minicode-ai 0.11.1 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (221) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/LICENSE +21 -21
  3. package/README.md +4 -4
  4. package/cli/args.ts +46 -0
  5. package/cli/commands/acp.ts +163 -10
  6. package/cli/commands/config.ts +33 -18
  7. package/cli/commands/daemon.ts +515 -0
  8. package/cli/commands/exec.ts +145 -53
  9. package/cli/commands/openwork.ts +986 -0
  10. package/cli/commands/sessions.ts +4 -1
  11. package/cli/commands/stats.ts +34 -4
  12. package/cli/commands.ts +217 -2
  13. package/cli/index.ts +146 -14
  14. package/cli/recovery-warning.ts +115 -0
  15. package/cli/router.ts +32 -1
  16. package/cli/setup.ts +2332 -171
  17. package/cli/tui.ts +113 -7
  18. package/docs/OUTPUT_ARCHITECTURE_AUDIT.md +489 -0
  19. package/docs/OUTPUT_EVENT_MODEL.md +289 -0
  20. package/docs/OUTPUT_IMPLEMENTATION_PLAN.md +391 -0
  21. package/docs/OUTPUT_PROTOCOL_SPEC.md +285 -0
  22. package/docs/OUTPUT_RENDERING_SPEC.md +248 -0
  23. package/docs/OUTPUT_UX_RULES.md +449 -0
  24. package/docs/PLAN_UIUX_V6.md +2 -2
  25. package/docs/README.md +4 -3
  26. package/docs/TERMINAL_CONTRACT.md +278 -71
  27. package/docs/architecture.md +89 -7
  28. package/docs/changelog.md +1 -1
  29. package/docs/choosing-mode.md +2 -2
  30. package/docs/cli.md +9 -5
  31. package/docs/concepts.md +1 -1
  32. package/docs/contributing.md +9 -2
  33. package/docs/environment.md +6 -2
  34. package/docs/exec.md +46 -5
  35. package/docs/memory-sessions.md +2 -0
  36. package/docs/policy-sandbox.md +1 -1
  37. package/docs/pricing-budget.md +1 -1
  38. package/docs/quickstart.md +2 -2
  39. package/docs/repl.md +6 -2
  40. package/docs/security-model.md +1 -1
  41. package/docs/security.md +1 -1
  42. package/docs/skills.md +2 -2
  43. package/docs/terminal.md +9 -5
  44. package/docs/tools.md +1 -1
  45. package/package.json +35 -5
  46. package/src/app/session.ts +261 -15
  47. package/src/app/tool-layer.ts +94 -7
  48. package/src/daemon/approvals.ts +361 -0
  49. package/src/daemon/capability.ts +145 -0
  50. package/src/daemon/children.ts +142 -0
  51. package/src/daemon/client.ts +267 -0
  52. package/src/daemon/control.ts +350 -0
  53. package/src/daemon/discovery.ts +234 -0
  54. package/src/daemon/feed.ts +155 -0
  55. package/src/daemon/framing.ts +94 -0
  56. package/src/daemon/host.ts +316 -0
  57. package/src/daemon/protocol.ts +217 -0
  58. package/src/daemon/resource.ts +170 -0
  59. package/src/daemon/sanitize.ts +57 -0
  60. package/src/daemon/server.ts +627 -0
  61. package/src/daemon/store.ts +317 -0
  62. package/src/daemon/subscription.ts +270 -0
  63. package/src/daemon/telemetry.ts +81 -0
  64. package/src/hooks/run.ts +12 -1
  65. package/src/lib/atomic-write.ts +29 -3
  66. package/src/lib/db-path.ts +26 -0
  67. package/src/lib/keystore.ts +544 -42
  68. package/src/lib/net.ts +43 -1
  69. package/src/lib/safe-open.ts +116 -1
  70. package/src/lib/session-id.ts +15 -0
  71. package/src/lsp/client.ts +123 -5
  72. package/src/mcp/client.ts +139 -17
  73. package/src/mcp/server.ts +177 -50
  74. package/src/mcp/transport.ts +16 -19
  75. package/src/memory/vector.ts +770 -55
  76. package/src/policy/allowlist.ts +14 -2
  77. package/src/policy/bash-guard.ts +105 -10
  78. package/src/policy/compaction.ts +82 -5
  79. package/src/policy/consequence-engine.ts +220 -0
  80. package/src/policy/context.ts +132 -0
  81. package/src/policy/executor.ts +187 -121
  82. package/src/policy/no-progress.ts +559 -0
  83. package/src/policy/permission.ts +4 -8
  84. package/src/policy/pricing.ts +17 -3
  85. package/src/policy/scrub.ts +69 -2
  86. package/src/policy/tool-contract.ts +515 -0
  87. package/src/policy/usage.ts +310 -24
  88. package/src/policy/verifier.ts +6 -3
  89. package/src/policy/work-mode.ts +182 -0
  90. package/src/presentation/adapter.ts +533 -26
  91. package/src/presentation/events.ts +151 -0
  92. package/src/presentation/model.ts +180 -27
  93. package/src/presentation/projection.ts +858 -0
  94. package/src/presentation/reducer.ts +645 -310
  95. package/src/presentation/store.ts +12 -7
  96. package/src/providers/anthropic.ts +18 -10
  97. package/src/providers/responses.ts +2 -2
  98. package/src/runtime/capability.ts +409 -0
  99. package/src/runtime/child-execution.ts +274 -0
  100. package/src/runtime/composition.ts +958 -0
  101. package/src/runtime/dispatch.ts +591 -0
  102. package/src/runtime/execution-backend.ts +632 -0
  103. package/src/runtime/execution-events.ts +272 -0
  104. package/src/runtime/execution-id.ts +230 -0
  105. package/src/runtime/execution-journal.ts +926 -0
  106. package/src/runtime/execution-kernel.ts +456 -0
  107. package/src/runtime/execution-registry.ts +379 -0
  108. package/src/runtime/process-supervision.ts +276 -0
  109. package/src/runtime/production-execution.ts +551 -0
  110. package/src/runtime/production-runtime.ts +217 -0
  111. package/src/runtime/recovery-safety.ts +70 -0
  112. package/src/runtime/recovery.ts +477 -0
  113. package/src/runtime/runtime-capabilities.ts +179 -0
  114. package/src/runtime/runtime-diagnostics.ts +141 -0
  115. package/src/runtime/runtime-host.ts +365 -0
  116. package/src/runtime/runtime-status-facts.ts +222 -0
  117. package/src/runtime/runtime-status-provider.ts +74 -0
  118. package/src/runtime/runtime-status.ts +459 -0
  119. package/src/runtime/runtime-task-admission.ts +101 -0
  120. package/src/runtime/supervisor.ts +444 -0
  121. package/src/session/authority.ts +168 -0
  122. package/src/session/checkpoint.ts +88 -1
  123. package/src/session/context-adapter.ts +251 -0
  124. package/src/session/context-assembly.ts +242 -0
  125. package/src/session/context-identity.ts +389 -0
  126. package/src/session/context-projection.ts +248 -0
  127. package/src/session/context-selector.ts +500 -0
  128. package/src/session/cross-session-adoption.ts +249 -0
  129. package/src/session/full-history-fold.ts +171 -0
  130. package/src/session/identity.ts +192 -0
  131. package/src/session/journal.ts +805 -102
  132. package/src/session/open-work-intent.ts +732 -0
  133. package/src/session/open-work.ts +767 -0
  134. package/src/session/pending-tools.ts +94 -0
  135. package/src/session/persistence.ts +3569 -127
  136. package/src/session/runtime-header.ts +208 -0
  137. package/src/session/shadow-git.ts +13 -5
  138. package/src/session/verification.ts +1623 -0
  139. package/src/task/assignment.ts +136 -0
  140. package/src/task/autonomous-adapter.ts +168 -0
  141. package/src/task/autonomous-context.ts +630 -0
  142. package/src/task/autonomous-policy.ts +490 -0
  143. package/src/task/continuity.ts +179 -0
  144. package/src/task/execution-cancellation.ts +165 -0
  145. package/src/task/graph-validate.ts +379 -0
  146. package/src/task/graph.ts +305 -0
  147. package/src/task/identity.ts +230 -0
  148. package/src/task/model.ts +417 -0
  149. package/src/task/production-scheduler.ts +293 -0
  150. package/src/task/readiness.ts +229 -0
  151. package/src/task/scheduler-observability.ts +387 -0
  152. package/src/task/scheduler.ts +1197 -0
  153. package/src/task/scheduling-policy.ts +165 -0
  154. package/src/task/session-authority.ts +148 -0
  155. package/src/task/session-ownership.ts +211 -0
  156. package/src/task/store.ts +2887 -0
  157. package/src/task/sync.ts +343 -0
  158. package/src/task/trigger.ts +260 -0
  159. package/src/tools/bash.ts +377 -211
  160. package/src/tools/code_run.ts +1 -1
  161. package/src/tools/delete_file.ts +1 -1
  162. package/src/tools/edit.ts +33 -6
  163. package/src/tools/evidence.ts +30 -0
  164. package/src/tools/git.ts +4 -4
  165. package/src/tools/glob.ts +12 -3
  166. package/src/tools/grep.ts +1 -1
  167. package/src/tools/lsp.ts +4 -4
  168. package/src/tools/mcp_call.ts +11 -4
  169. package/src/tools/memory.ts +153 -18
  170. package/src/tools/move_file.ts +1 -1
  171. package/src/tools/patch.ts +1 -1
  172. package/src/tools/read_file.ts +1 -1
  173. package/src/tools/read_image.ts +1 -1
  174. package/src/tools/submit_result.ts +1 -1
  175. package/src/tools/task.ts +437 -41
  176. package/src/tools/todo.ts +662 -35
  177. package/src/tools/web_fetch.ts +4 -2
  178. package/src/tools/web_search.ts +9 -3
  179. package/src/tools/write_file.ts +1 -1
  180. package/src/ui/assistant/simple.ts +123 -50
  181. package/src/ui/assistant/turn-status.ts +17 -3
  182. package/src/ui/contract.ts +184 -0
  183. package/src/ui/footer.ts +52 -19
  184. package/src/ui/i18n/en.ts +58 -6
  185. package/src/ui/i18n/id.ts +58 -6
  186. package/src/ui/input/prompt-engine.ts +120 -25
  187. package/src/ui/render/errors.ts +39 -1
  188. package/src/ui/render/markdown-table.ts +455 -0
  189. package/src/ui/render/markdown.ts +22 -1
  190. package/src/ui/render/table-grid.ts +184 -0
  191. package/src/ui/render/table.ts +15 -76
  192. package/src/ui/runtime/screen.ts +7 -2
  193. package/src/ui/runtime/statusline.ts +25 -6
  194. package/src/ui/tui/app.ts +507 -169
  195. package/src/ui/tui/transcript.ts +531 -89
  196. package/vendor/minicore/VENDOR.md +1 -1
  197. package/vendor/minicore/src/core/budget.ts +25 -25
  198. package/vendor/minicore/src/core/compact.ts +75 -75
  199. package/vendor/minicore/src/core/errors.ts +59 -59
  200. package/vendor/minicore/src/core/events.ts +73 -73
  201. package/vendor/minicore/src/core/executor.ts +139 -139
  202. package/vendor/minicore/src/core/history.ts +31 -31
  203. package/vendor/minicore/src/core/index.ts +41 -41
  204. package/vendor/minicore/src/core/loop.ts +355 -355
  205. package/vendor/minicore/src/core/permission.ts +22 -22
  206. package/vendor/minicore/src/core/provider.ts +39 -39
  207. package/vendor/minicore/src/core/recovery.ts +35 -35
  208. package/vendor/minicore/src/core/session.ts +327 -327
  209. package/vendor/minicore/src/core/snapshot.ts +146 -146
  210. package/vendor/minicore/src/core/tokens.ts +107 -107
  211. package/vendor/minicore/src/core/tool.ts +115 -115
  212. package/vendor/minicore/src/core/types.ts +50 -50
  213. package/vendor/minicore/src/providers/openai-compat.ts +417 -417
  214. package/AGENTS.md +0 -45
  215. package/PLAN.md +0 -491
  216. package/docs/ARCHITECTURE.html +0 -1248
  217. package/docs/CONTROL-PLANE-MAP.md +0 -139
  218. package/docs/HARNESS.md +0 -150
  219. package/docs/SUMMARY.md +0 -52
  220. package/docs/UI_RENDER_PIPELINE.md +0 -169
  221. package/docs/USAGE.md +0 -11
@@ -0,0 +1,272 @@
1
+ // M10 — Execution event plane: observasi kanonis, BUKAN authority.
2
+ //
3
+ // Kenapa berkas ini ada (P1 M10): lifecycle Kernel (M8), aksi supervisor (M9),
4
+ // dan observasi backend (M5) butuh satu aliran observasi yang koheren untuk
5
+ // diagnosis — tanpa menjadikan aliran itu penulis lifecycle, store durable,
6
+ // atau jembatan scheduler. Sebelum M10, observasi tersebar per-subsystem.
7
+ //
8
+ // Prinsip yang dikunci (jangan dilonggarkan tanpa ADR baru):
9
+ // Kernel decides (commit) → Event Plane observes (emit) → observers/metrics/M11.
10
+ // TAK PERNAH sebaliknya. Commit sukses + emit gagal = tetap committed.
11
+ // Event ≠ durable (persistensi = M11). Event ≠ replay/recovery (M12).
12
+ // - Tiga domain sequence TERPISAH: executionVersion (versi state otoritatif
13
+ // Kernel, diobservasi) ≠ eventSequence (urutan emit dalam plane ini) ≠
14
+ // journalSequence (TIDAK ADA di M10 — milik M11).
15
+ // - eventId (`evt_<uuid>`) ≠ executionId (satu execution → banyak event).
16
+ // - Ordering = per-plane monotonic; BUKAN global; timestamp tak pernah
17
+ // difabrikasi menjadi order (ts sama + sequence beda = legal).
18
+ // - Observer terisolasi (throw dihitung, commit/sink tak terpengaruh), tanpa
19
+ // worker/timer/queue tersembunyi; nested emit sinkron diizinkan dengan
20
+ // guard kedalaman (anti-deadlock/stack-blowup), bukan dilarang diam-diam.
21
+ // - Event frozen snapshot (tanpa referensi mutable ke Execution); metadata
22
+ // hanya korelasi (tanpa secret/prompt/history/output —boundary diuji).
23
+ // - Tak ada import scheduler/TaskStore/persistence/journal/UI/CLI/backend-spawn.
24
+ // Tak ada API: setState/mutate/complete/fail/cancel/admit/persist/recover/claim.
25
+
26
+ import { randomUUID } from "node:crypto"
27
+
28
+ /** Taksonomi M10: lifecycle (dari commit Kernel) + observasi mekanis. */
29
+ export type ExecutionEventType =
30
+ | "execution.created"
31
+ | "execution.state-changed"
32
+ | "execution.completed"
33
+ | "execution.failed"
34
+ | "execution.cancelled"
35
+ | "execution.timed-out"
36
+ | "execution.budget-exceeded"
37
+ | "execution.authority-lost"
38
+ | "execution.resource-exceeded"
39
+ | "execution.orphaned"
40
+ | "backend.observed"
41
+ | "backend.action-requested"
42
+ | "supervisor.observed"
43
+ | "supervisor.action"
44
+ | "supervisor.redispatch-planned"
45
+
46
+ /** Lifecycle terminal → tipe event (satu-ke-satu, tanpa collapse). */
47
+ const TERMINAL_EVENT: Record<string, ExecutionEventType> = {
48
+ COMPLETED: "execution.completed",
49
+ FAILED: "execution.failed",
50
+ CANCELLED: "execution.cancelled",
51
+ TIMED_OUT: "execution.timed-out",
52
+ BUDGET_EXCEEDED: "execution.budget-exceeded",
53
+ AUTHORITY_LOST: "execution.authority-lost",
54
+ RESOURCE_EXCEEDED: "execution.resource-exceeded",
55
+ }
56
+
57
+ export function terminalEventFor(state: string): ExecutionEventType | null {
58
+ return TERMINAL_EVENT[state] ?? null
59
+ }
60
+
61
+ /**
62
+ * [P1 M16] Satu-satunya definisi "event ini terminal".
63
+ *
64
+ * Sebelumnya M12 menyalin daftar tujuh tipe terminal ke modulnya sendiri; begitu
65
+ * suatu state terminal baru ditambah, M12 akan diam-diam gagal mengenali bukti
66
+ * terminal dan menafsirkannya sebagai `UNKNOWN`. Satu taksonomi, satu predicate —
67
+ * dan konsumennya (M12) memakai yang ini, bukan daftarnya sendiri.
68
+ */
69
+ const TERMINAL_EVENT_VALUES: ReadonlySet<string> = new Set(Object.values(TERMINAL_EVENT))
70
+
71
+ export function isTerminalEventType(type: unknown): type is ExecutionEventType {
72
+ return typeof type === "string" && TERMINAL_EVENT_VALUES.has(type)
73
+ }
74
+
75
+ /** Sumber provenance. Label asal observasi — BUKAN klaim authority. */
76
+ export type EventSource =
77
+ | "kernel"
78
+ | "supervisor"
79
+ | "backend"
80
+ | "host"
81
+ | "user"
82
+ | "agent"
83
+ | "scheduler"
84
+ | "test"
85
+
86
+ export interface ExecutionEvent {
87
+ readonly eventId: string
88
+ readonly eventType: ExecutionEventType
89
+ readonly executionId: string
90
+ readonly parentExecutionId?: string
91
+ readonly lineageRootId: string
92
+ /** ms epoch (observasi; BUKAN ordering authority). */
93
+ readonly timestamp: number
94
+ /** Urutan emit dalam plane ini (monotonik per-plane; BUKAN global). */
95
+ readonly eventSequence: number
96
+ /** Versi state otoritatif yang diobservasi (domain Kernel; ≠ eventSequence). */
97
+ readonly executionVersion: number
98
+ readonly source: EventSource
99
+ readonly causality?: string
100
+ readonly reason?: string
101
+ readonly state?: string
102
+ readonly previousState?: string
103
+ readonly attempt?: number
104
+ readonly generation?: number
105
+ readonly supersedes?: string
106
+ /** Metadata korelasi tambahan TANPA secret/prompt/history/output. */
107
+ readonly metadata?: Readonly<Record<string, string>>
108
+ }
109
+
110
+ export interface EventInput {
111
+ readonly eventType: ExecutionEventType
112
+ readonly executionId: string
113
+ readonly parentExecutionId?: string
114
+ readonly lineageRootId: string
115
+ readonly executionVersion: number
116
+ readonly source: EventSource
117
+ readonly causality?: string
118
+ readonly reason?: string
119
+ readonly state?: string
120
+ readonly previousState?: string
121
+ readonly attempt?: number
122
+ readonly generation?: number
123
+ readonly supersedes?: string
124
+ readonly metadata?: Record<string, string>
125
+ readonly timestamp?: number
126
+ }
127
+
128
+ export interface EventPlaneMetrics {
129
+ readonly emitted: number
130
+ readonly subscriberErrors: number
131
+ readonly nestedDrops: number
132
+ readonly subscribers: number
133
+ }
134
+
135
+ export type EventHandler = (event: ExecutionEvent) => void
136
+
137
+ /**
138
+ * Guard reentransi sinkron: nested emit diizinkan (deterministik, terurut),
139
+ * tetapi kedalaman dibatasi agar observer hostile tak meledakkan stack atau
140
+ * deadlock. Batas = safety valve terdokumentasi, bukan policy lifecycle.
141
+ */
142
+ export const MAX_EVENT_NESTING = 8
143
+
144
+ export interface EventPlane {
145
+ /** Bangun + emit event (frozen). Tak pernah melempar karena observer. */
146
+ emit(input: EventInput): ExecutionEvent
147
+ /** Langganan sinkron; kembalikan unsubscribe. */
148
+ subscribe(handler: EventHandler): () => void
149
+ metrics(): EventPlaneMetrics
150
+ }
151
+
152
+ function isValidEventId(value: unknown): boolean {
153
+ return (
154
+ typeof value === "string" &&
155
+ /^evt_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(value)
156
+ )
157
+ }
158
+
159
+ export function createEventPlane(): EventPlane {
160
+ const handlers = new Set<EventHandler>()
161
+ let sequence = 0
162
+ let nesting = 0
163
+ const m = { emitted: 0, subscriberErrors: 0, nestedDrops: 0 }
164
+
165
+ return {
166
+ emit(input: EventInput): ExecutionEvent {
167
+ if (!input || typeof input.executionId !== "string" || input.executionId.length === 0)
168
+ throw new Error("event-plane.emit: executionId is required")
169
+ if (!input.eventType || !input.lineageRootId || !input.source)
170
+ throw new Error("event-plane.emit: eventType + lineageRootId + source are required")
171
+ if (nesting >= MAX_EVENT_NESTING) {
172
+ m.nestedDrops++
173
+ throw new Error("event-plane.emit: nesting limit exceeded (hostile re-entrancy dropped)")
174
+ }
175
+ sequence++
176
+ const event: ExecutionEvent = Object.freeze({
177
+ eventId: `evt_${randomUUID()}`,
178
+ eventType: input.eventType,
179
+ executionId: input.executionId,
180
+ ...(input.parentExecutionId ? { parentExecutionId: input.parentExecutionId } : {}),
181
+ lineageRootId: input.lineageRootId,
182
+ timestamp: input.timestamp ?? Date.now(),
183
+ eventSequence: sequence,
184
+ executionVersion: input.executionVersion,
185
+ source: input.source,
186
+ ...(input.causality !== undefined ? { causality: input.causality } : {}),
187
+ ...(input.reason !== undefined ? { reason: input.reason } : {}),
188
+ ...(input.state !== undefined ? { state: input.state } : {}),
189
+ ...(input.previousState !== undefined ? { previousState: input.previousState } : {}),
190
+ ...(input.attempt !== undefined ? { attempt: input.attempt } : {}),
191
+ ...(input.generation !== undefined ? { generation: input.generation } : {}),
192
+ ...(input.supersedes !== undefined ? { supersedes: input.supersedes } : {}),
193
+ ...(input.metadata ? { metadata: Object.freeze({ ...input.metadata }) } : {}),
194
+ })
195
+ m.emitted++
196
+ nesting++
197
+ try {
198
+ for (const h of [...handlers]) {
199
+ try {
200
+ h(event)
201
+ } catch {
202
+ // Isolasi observer: satu gagal, lainnya tetap jalan; emit tak gagal.
203
+ m.subscriberErrors++
204
+ }
205
+ }
206
+ } finally {
207
+ nesting--
208
+ }
209
+ return event
210
+ },
211
+
212
+ subscribe(handler: EventHandler): () => void {
213
+ handlers.add(handler)
214
+ return () => {
215
+ handlers.delete(handler)
216
+ }
217
+ },
218
+
219
+ metrics(): EventPlaneMetrics {
220
+ return {
221
+ emitted: m.emitted,
222
+ subscriberErrors: m.subscriberErrors,
223
+ nestedDrops: m.nestedDrops,
224
+ subscribers: handlers.size,
225
+ }
226
+ },
227
+ }
228
+ }
229
+
230
+ // ── Bridge Kernel → plane (observasi pasca-commit; TANPA keputusan validitas) ──
231
+
232
+ export interface KernelTransitionRecord {
233
+ readonly executionId: string
234
+ readonly parentExecutionId?: string
235
+ readonly rootExecutionId: string
236
+ readonly version: number
237
+ readonly from: string
238
+ readonly to: string
239
+ readonly reason: string
240
+ readonly source: string
241
+ readonly causality?: string
242
+ }
243
+
244
+ /**
245
+ * Terjemahkan SATU commit otoritatif menjadi SATU event observasi.
246
+ * Dipanggil SETELAH kernel commit sukses (oleh pemilik integrasi; M10 tak
247
+ * memasang hook sendiri ke kernel produksi — staging prepared-but-controlled).
248
+ * Terminal → tipe terminal spesifik; non-terminal → execution.state-changed.
249
+ * Tak pernah memutuskan validitas (itu sudah terjadi di kernel).
250
+ */
251
+ export function executionEventFromCommit(
252
+ plane: EventPlane,
253
+ commit: KernelTransitionRecord,
254
+ opts?: { source?: EventSource; timestamp?: number },
255
+ ): ExecutionEvent {
256
+ const terminal = terminalEventFor(commit.to)
257
+ return plane.emit({
258
+ eventType: terminal ?? "execution.state-changed",
259
+ executionId: commit.executionId,
260
+ ...(commit.parentExecutionId ? { parentExecutionId: commit.parentExecutionId } : {}),
261
+ lineageRootId: commit.rootExecutionId,
262
+ executionVersion: commit.version,
263
+ source: opts?.source ?? "kernel",
264
+ ...(commit.causality !== undefined ? { causality: commit.causality } : {}),
265
+ reason: commit.reason,
266
+ state: commit.to,
267
+ previousState: commit.from,
268
+ ...(opts?.timestamp !== undefined ? { timestamp: opts.timestamp } : {}),
269
+ })
270
+ }
271
+
272
+ export { isValidEventId }
@@ -0,0 +1,230 @@
1
+ // M1 — Execution correlator: SATU allocator + korelasi identitas.
2
+ //
3
+ // Kenapa berkas ini ada (P1 ADR-002, FINAL QA P1–P5): setiap execution harus
4
+ // punya SATU identitas korelasi yang stabil (same execution = same executionId),
5
+ // terpisah dari domain IDs (session/turn/task/toolCall/eventSeq). Sebelum M1,
6
+ // korelasi hanya implisit (sessionId ganda, approval counter reset, toolCallId
7
+ // milik provider) sehingga reload/restart dapat mengubah identitas diam-diam.
8
+ //
9
+ // BUKAN FSM, BUKAN registry authority, BUKAN recovery — hanya alokasi +
10
+ // korelasi + normalisasi legacy. Authority lifecycle tetap milik kernel (M8);
11
+ // registry otoritatif tetap milik durable (M2 hanya observasi).
12
+ //
13
+ // Aturan yang dikunci di sini (jangan dilonggarkan tanpa ADR baru):
14
+ // - `allocateExecutionId()` = SATU-SATUNYA allocator id acak (CSPRNG UUIDv4).
15
+ // Jangan sebar `crypto.randomUUID()` ke modul lain — panggil helper ini.
16
+ // - Format `exec_<uuid>`; prefix presentation-only, uniqueness dari 128-bit.
17
+ // - Correlation object di-freeze (immutable pasca-admission).
18
+ // - Id turunan legacy deterministik (SHA-256 locator) BERBEDA BENTUK dari id
19
+ // alokasi (32 hex tanpa strip vs UUID strip) agar tak tertukar authority.
20
+ // - Tanpa locator stabil = uncorrelated group, BUKAN UUID baru per load.
21
+
22
+ import { createHash, randomUUID } from "node:crypto"
23
+
24
+ /** Prefix presentation-only. BUKAN sumber uniqueness. */
25
+ export const EXECUTION_ID_PREFIX = "exec_"
26
+
27
+ /** Kind datar M1 — metadata, bukan hierarchy class (M7/M8 yang memakai). */
28
+ export type ExecutionKind = "turn" | "tool_call" | "task" | "child" | "background"
29
+
30
+ /**
31
+ * Korelasi execution M1. Kontrak memory (BUKAN nullable shortcut):
32
+ * executionId/kind/ownerId/rootExecutionId WAJIB; parentExecutionId opsional
33
+ * hanya karena root tidak punya parent. Dibuat via constructor di bawah yang
34
+ * mem-freeze object (immutable pasca-admission).
35
+ */
36
+ export interface ExecutionCorrelation {
37
+ readonly executionId: string
38
+ readonly kind: ExecutionKind
39
+ readonly ownerId: string
40
+ readonly rootExecutionId: string
41
+ readonly parentExecutionId?: string
42
+ /** True = diturunkan deterministik dari locator legacy (bukan alokasi). */
43
+ readonly derived?: true
44
+ }
45
+
46
+ /** Pola UUIDv4 lowercase (randomUUID Node) — authority alokasi acak. */
47
+ const ALLOCATED_RE = /^exec_[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
48
+ /** Pola turunan deterministik: 32 hex tanpa strip (SHA-256 slice). */
49
+ const DERIVED_RE = /^exec_[0-9a-f]{32}$/
50
+
51
+ /** True untuk kedua bentuk (alokasi + turunan). Bukan validasi authority. */
52
+ export function isExecutionId(value: unknown): value is string {
53
+ return typeof value === "string" && (ALLOCATED_RE.test(value) || DERIVED_RE.test(value))
54
+ }
55
+
56
+ /** True hanya untuk id alokasi acak (otoritas allocator M1). */
57
+ export function isAllocatedExecutionId(value: unknown): value is string {
58
+ return typeof value === "string" && ALLOCATED_RE.test(value)
59
+ }
60
+
61
+ /** True hanya untuk id turunan deterministik legacy (bukan authority baru). */
62
+ export function isDerivedExecutionId(value: unknown): value is string {
63
+ return typeof value === "string" && DERIVED_RE.test(value)
64
+ }
65
+
66
+ // ── Observability minimal M1 (bukan canonical event system — itu M10) ──
67
+
68
+ export interface ExecutionIdMetrics {
69
+ allocated: number
70
+ derived: number
71
+ uncorrelated: number
72
+ collisions: number
73
+ }
74
+
75
+ const metrics: ExecutionIdMetrics = { allocated: 0, derived: 0, uncorrelated: 0, collisions: 0 }
76
+
77
+ /** Snapshot copy (bukan live view) agar observer tak memutasi counter. */
78
+ export function getExecutionIdMetrics(): ExecutionIdMetrics {
79
+ return { ...metrics }
80
+ }
81
+
82
+ // ── Allocator: SATU-SATUNYA sumber id acak (jangan panggil randomUUID langsung) ──
83
+
84
+ /**
85
+ * Alokasi id execution baru: `exec_<UUIDv4 CSPRNG 128-bit>`.
86
+ * Authority = Runtime Host / runtime allocator (M1: helper ini; Host formal M3).
87
+ * User input TIDAK BOLEH menjadi authority — allocator tak menerima id dari luar.
88
+ * Retry/re-dispatch TIDAK BOLEH memanggil ini untuk execution yang sudah ada
89
+ * (attempt baru = execution baru; execution lama immutable).
90
+ */
91
+ export function allocateExecutionId(): string {
92
+ const id = `${EXECUTION_ID_PREFIX}${randomUUID()}`
93
+ metrics.allocated++
94
+ return id
95
+ }
96
+
97
+ /**
98
+ * Alokasi anti-tabrakan terhadap himpunan yang dikenal (admission guard M1).
99
+ * Bila stub/generator menghasilkan duplikat: JANGAN overwrite/merge — catat
100
+ * collision, coba lagi dengan nilai baru. Mengembalikan id yang tidak ada di
101
+ * `known`. Registry otoritatif (M2/M8) memakai helper ini saat admission.
102
+ */
103
+ export function allocateUniqueExecutionId(
104
+ known: { has(id: string): boolean },
105
+ random: () => string = allocateExecutionId,
106
+ maxAttempts = 100,
107
+ ): string {
108
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
109
+ const id = random()
110
+ if (!known.has(id)) return id
111
+ metrics.collisions++
112
+ }
113
+ throw new Error("allocateUniqueExecutionId: collision persists (refusing to overwrite)")
114
+ }
115
+
116
+ // ── Constructor korelasi (frozen; root/parent rule dikunci) ──
117
+
118
+ function assertCorrelationInput(kind: unknown, ownerId: unknown): void {
119
+ if (typeof kind !== "string" || kind.length === 0)
120
+ throw new Error("ExecutionCorrelation: kind is required")
121
+ if (typeof ownerId !== "string" || ownerId.length === 0)
122
+ throw new Error("ExecutionCorrelation: ownerId is required (never user-controlled authority)")
123
+ }
124
+
125
+ /**
126
+ * Korelasi root: rootExecutionId = executionId, tanpa parent.
127
+ * ownerId = identitas owner menurut arsitektur kini (session/task id),
128
+ * BUKAN klaim dari user input (otorisasi tetap via policy/permission).
129
+ */
130
+ export function createRootCorrelation(kind: ExecutionKind, ownerId: string): ExecutionCorrelation {
131
+ assertCorrelationInput(kind, ownerId)
132
+ const executionId = allocateExecutionId()
133
+ return Object.freeze({
134
+ executionId,
135
+ kind,
136
+ ownerId,
137
+ rootExecutionId: executionId,
138
+ })
139
+ }
140
+
141
+ /**
142
+ * Korelasi child: id BARU (child ≠ parent), parentExecutionId = parent id,
143
+ * rootExecutionId = parent root (diwariskan TANPA rewrite — retry/detach penuh
144
+ * ditangani M7 dengan lineage_root vs cancel_scope terpisah).
145
+ * Parent tak valid (tanpa required fields) = throw, bukan tebak.
146
+ */
147
+ export function createChildCorrelation(
148
+ parent: Pick<ExecutionCorrelation, "executionId" | "rootExecutionId">,
149
+ kind: ExecutionKind,
150
+ ownerId: string,
151
+ ): ExecutionCorrelation {
152
+ assertCorrelationInput(kind, ownerId)
153
+ if (!parent || !isExecutionId(parent.executionId) || !isExecutionId(parent.rootExecutionId))
154
+ throw new Error("createChildCorrelation: valid parent correlation is required (no guessing)")
155
+ return Object.freeze({
156
+ executionId: allocateExecutionId(),
157
+ kind,
158
+ ownerId,
159
+ rootExecutionId: parent.rootExecutionId,
160
+ parentExecutionId: parent.executionId,
161
+ })
162
+ }
163
+
164
+ // ── Legacy normalization (stabil, tanpa tulis-ulang riwayat) ──
165
+
166
+ /** Namespace derivasi (ganti bila skema locator berubah → id baru eksplisit). */
167
+ const DERIVE_NAMESPACE = "m1-legacy-v1:"
168
+
169
+ /**
170
+ * Turunkan id stabil deterministik dari locator key.
171
+ * BUKAN alokasi: tidak menambah `allocated`, tidak menjadi authority baru,
172
+ * dibedakan bentuk (32 hex tanpa strip) + flag `derived:true` oleh pemanggil.
173
+ * Sama locator = sama id pada setiap load/restart/concurrent — tanpa storage.
174
+ */
175
+ export function deriveStableExecutionId(locatorKey: string): string {
176
+ if (!locatorKey) throw new Error("deriveStableExecutionId: locatorKey is required")
177
+ const digest = createHash("sha256")
178
+ .update(DERIVE_NAMESPACE + locatorKey)
179
+ .digest("hex")
180
+ .slice(0, 32)
181
+ const id = `${EXECUTION_ID_PREFIX}${digest}`
182
+ metrics.derived++
183
+ return id
184
+ }
185
+
186
+ /** Kunci locator stabil — HANYA dari basis yang terbukti di repository. */
187
+ export const legacyLocatorKeys = {
188
+ /** Journal: identitas utama `${session}:${seq}`, seq monotonik per-file. */
189
+ journal: (session: string, seq: number): string => `journal:${session}:${seq}`,
190
+ /** Messages: PK (session_id, seq). */
191
+ message: (sessionId: string, seq: number): string => `message:${sessionId}:${seq}`,
192
+ /** Presentation events: PK (session_id, event_seq). */
193
+ presentationEvent: (sessionId: string, eventSeq: number): string =>
194
+ `event:${sessionId}:${eventSeq}`,
195
+ /** Turn: session + turn index. */
196
+ turn: (sessionId: string, turnIdx: number): string => `turn:${sessionId}:${turnIdx}`,
197
+ /** Claim/attempt: taskId + revision + generation (+incarnation bila ada). */
198
+ claim: (taskId: string, revision: number, generation: number, incarnation?: string): string =>
199
+ `claim:${taskId}:r${revision}:g${generation}${incarnation ? `:${incarnation}` : ""}`,
200
+ } as const
201
+
202
+ export type LegacyNormalization =
203
+ | { status: "correlated"; executionId: string }
204
+ | { status: "stable-locator"; locatorKey: string; executionId: string }
205
+ | { status: "uncorrelated"; group: string; uncorrelated: true }
206
+
207
+ /**
208
+ * Normalisasi SATU arah (load-time, tanpa mutasi storage):
209
+ * - record sudah bawa executionId valid → pakai itu (jangan regenerate);
210
+ * - locator stabil ada → id turunan deterministik (stabil lintas load);
211
+ * - selain itu → uncorrelated group (BUKAN UUID baru per load; tanpa
212
+ * individual cancel/retry/re-dispatch — hanya agregat observasi).
213
+ */
214
+ export function normalizeLegacyIdentity(input: {
215
+ executionId?: unknown
216
+ locatorKey?: string
217
+ fallbackGroup: string
218
+ }): LegacyNormalization {
219
+ if (isExecutionId(input.executionId))
220
+ return { status: "correlated", executionId: input.executionId }
221
+ if (input.locatorKey) {
222
+ return {
223
+ status: "stable-locator",
224
+ locatorKey: input.locatorKey,
225
+ executionId: deriveStableExecutionId(input.locatorKey),
226
+ }
227
+ }
228
+ metrics.uncorrelated++
229
+ return { status: "uncorrelated", group: input.fallbackGroup, uncorrelated: true as const }
230
+ }