minicode-ai 0.11.1 → 0.13.1

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 (222) hide show
  1. package/CHANGELOG.md +95 -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/minicode.js +6 -0
  15. package/cli/recovery-warning.ts +115 -0
  16. package/cli/router.ts +32 -1
  17. package/cli/setup.ts +2332 -171
  18. package/cli/tui.ts +113 -7
  19. package/docs/OUTPUT_ARCHITECTURE_AUDIT.md +489 -0
  20. package/docs/OUTPUT_EVENT_MODEL.md +289 -0
  21. package/docs/OUTPUT_IMPLEMENTATION_PLAN.md +391 -0
  22. package/docs/OUTPUT_PROTOCOL_SPEC.md +285 -0
  23. package/docs/OUTPUT_RENDERING_SPEC.md +248 -0
  24. package/docs/OUTPUT_UX_RULES.md +449 -0
  25. package/docs/PLAN_UIUX_V6.md +2 -2
  26. package/docs/README.md +4 -3
  27. package/docs/TERMINAL_CONTRACT.md +278 -71
  28. package/docs/architecture.md +89 -7
  29. package/docs/changelog.md +1 -1
  30. package/docs/choosing-mode.md +2 -2
  31. package/docs/cli.md +9 -5
  32. package/docs/concepts.md +1 -1
  33. package/docs/contributing.md +9 -2
  34. package/docs/environment.md +6 -2
  35. package/docs/exec.md +46 -5
  36. package/docs/memory-sessions.md +2 -0
  37. package/docs/policy-sandbox.md +1 -1
  38. package/docs/pricing-budget.md +1 -1
  39. package/docs/quickstart.md +2 -2
  40. package/docs/repl.md +6 -2
  41. package/docs/security-model.md +1 -1
  42. package/docs/security.md +1 -1
  43. package/docs/skills.md +2 -2
  44. package/docs/terminal.md +9 -5
  45. package/docs/tools.md +1 -1
  46. package/package.json +36 -6
  47. package/src/app/session.ts +261 -15
  48. package/src/app/tool-layer.ts +94 -7
  49. package/src/daemon/approvals.ts +361 -0
  50. package/src/daemon/capability.ts +145 -0
  51. package/src/daemon/children.ts +142 -0
  52. package/src/daemon/client.ts +267 -0
  53. package/src/daemon/control.ts +350 -0
  54. package/src/daemon/discovery.ts +234 -0
  55. package/src/daemon/feed.ts +155 -0
  56. package/src/daemon/framing.ts +94 -0
  57. package/src/daemon/host.ts +316 -0
  58. package/src/daemon/protocol.ts +217 -0
  59. package/src/daemon/resource.ts +170 -0
  60. package/src/daemon/sanitize.ts +57 -0
  61. package/src/daemon/server.ts +627 -0
  62. package/src/daemon/store.ts +317 -0
  63. package/src/daemon/subscription.ts +270 -0
  64. package/src/daemon/telemetry.ts +81 -0
  65. package/src/hooks/run.ts +12 -1
  66. package/src/lib/atomic-write.ts +29 -3
  67. package/src/lib/db-path.ts +26 -0
  68. package/src/lib/keystore.ts +544 -42
  69. package/src/lib/net.ts +43 -1
  70. package/src/lib/safe-open.ts +116 -1
  71. package/src/lib/session-id.ts +15 -0
  72. package/src/lsp/client.ts +123 -5
  73. package/src/mcp/client.ts +139 -17
  74. package/src/mcp/server.ts +177 -50
  75. package/src/mcp/transport.ts +16 -19
  76. package/src/memory/vector.ts +770 -55
  77. package/src/policy/allowlist.ts +14 -2
  78. package/src/policy/bash-guard.ts +105 -10
  79. package/src/policy/compaction.ts +82 -5
  80. package/src/policy/consequence-engine.ts +220 -0
  81. package/src/policy/context.ts +132 -0
  82. package/src/policy/executor.ts +187 -121
  83. package/src/policy/no-progress.ts +559 -0
  84. package/src/policy/permission.ts +4 -8
  85. package/src/policy/pricing.ts +17 -3
  86. package/src/policy/scrub.ts +69 -2
  87. package/src/policy/tool-contract.ts +515 -0
  88. package/src/policy/usage.ts +310 -24
  89. package/src/policy/verifier.ts +6 -3
  90. package/src/policy/work-mode.ts +182 -0
  91. package/src/presentation/adapter.ts +533 -26
  92. package/src/presentation/events.ts +151 -0
  93. package/src/presentation/model.ts +180 -27
  94. package/src/presentation/projection.ts +858 -0
  95. package/src/presentation/reducer.ts +645 -310
  96. package/src/presentation/store.ts +12 -7
  97. package/src/providers/anthropic.ts +18 -10
  98. package/src/providers/responses.ts +2 -2
  99. package/src/runtime/capability.ts +409 -0
  100. package/src/runtime/child-execution.ts +274 -0
  101. package/src/runtime/composition.ts +958 -0
  102. package/src/runtime/dispatch.ts +591 -0
  103. package/src/runtime/execution-backend.ts +632 -0
  104. package/src/runtime/execution-events.ts +272 -0
  105. package/src/runtime/execution-id.ts +230 -0
  106. package/src/runtime/execution-journal.ts +926 -0
  107. package/src/runtime/execution-kernel.ts +456 -0
  108. package/src/runtime/execution-registry.ts +379 -0
  109. package/src/runtime/process-supervision.ts +276 -0
  110. package/src/runtime/production-execution.ts +551 -0
  111. package/src/runtime/production-runtime.ts +217 -0
  112. package/src/runtime/recovery-safety.ts +70 -0
  113. package/src/runtime/recovery.ts +477 -0
  114. package/src/runtime/runtime-capabilities.ts +179 -0
  115. package/src/runtime/runtime-diagnostics.ts +141 -0
  116. package/src/runtime/runtime-host.ts +365 -0
  117. package/src/runtime/runtime-status-facts.ts +222 -0
  118. package/src/runtime/runtime-status-provider.ts +74 -0
  119. package/src/runtime/runtime-status.ts +459 -0
  120. package/src/runtime/runtime-task-admission.ts +101 -0
  121. package/src/runtime/supervisor.ts +444 -0
  122. package/src/session/authority.ts +168 -0
  123. package/src/session/checkpoint.ts +88 -1
  124. package/src/session/context-adapter.ts +251 -0
  125. package/src/session/context-assembly.ts +242 -0
  126. package/src/session/context-identity.ts +389 -0
  127. package/src/session/context-projection.ts +248 -0
  128. package/src/session/context-selector.ts +500 -0
  129. package/src/session/cross-session-adoption.ts +249 -0
  130. package/src/session/full-history-fold.ts +171 -0
  131. package/src/session/identity.ts +192 -0
  132. package/src/session/journal.ts +805 -102
  133. package/src/session/open-work-intent.ts +732 -0
  134. package/src/session/open-work.ts +767 -0
  135. package/src/session/pending-tools.ts +94 -0
  136. package/src/session/persistence.ts +3569 -127
  137. package/src/session/runtime-header.ts +208 -0
  138. package/src/session/shadow-git.ts +13 -5
  139. package/src/session/verification.ts +1623 -0
  140. package/src/task/assignment.ts +136 -0
  141. package/src/task/autonomous-adapter.ts +168 -0
  142. package/src/task/autonomous-context.ts +630 -0
  143. package/src/task/autonomous-policy.ts +490 -0
  144. package/src/task/continuity.ts +179 -0
  145. package/src/task/execution-cancellation.ts +165 -0
  146. package/src/task/graph-validate.ts +379 -0
  147. package/src/task/graph.ts +305 -0
  148. package/src/task/identity.ts +230 -0
  149. package/src/task/model.ts +417 -0
  150. package/src/task/production-scheduler.ts +293 -0
  151. package/src/task/readiness.ts +229 -0
  152. package/src/task/scheduler-observability.ts +387 -0
  153. package/src/task/scheduler.ts +1197 -0
  154. package/src/task/scheduling-policy.ts +165 -0
  155. package/src/task/session-authority.ts +148 -0
  156. package/src/task/session-ownership.ts +211 -0
  157. package/src/task/store.ts +2887 -0
  158. package/src/task/sync.ts +343 -0
  159. package/src/task/trigger.ts +260 -0
  160. package/src/tools/bash.ts +377 -211
  161. package/src/tools/code_run.ts +1 -1
  162. package/src/tools/delete_file.ts +1 -1
  163. package/src/tools/edit.ts +33 -6
  164. package/src/tools/evidence.ts +30 -0
  165. package/src/tools/git.ts +4 -4
  166. package/src/tools/glob.ts +12 -3
  167. package/src/tools/grep.ts +1 -1
  168. package/src/tools/lsp.ts +4 -4
  169. package/src/tools/mcp_call.ts +11 -4
  170. package/src/tools/memory.ts +153 -18
  171. package/src/tools/move_file.ts +1 -1
  172. package/src/tools/patch.ts +1 -1
  173. package/src/tools/read_file.ts +1 -1
  174. package/src/tools/read_image.ts +1 -1
  175. package/src/tools/submit_result.ts +1 -1
  176. package/src/tools/task.ts +437 -41
  177. package/src/tools/todo.ts +662 -35
  178. package/src/tools/web_fetch.ts +4 -2
  179. package/src/tools/web_search.ts +9 -3
  180. package/src/tools/write_file.ts +1 -1
  181. package/src/ui/assistant/simple.ts +123 -50
  182. package/src/ui/assistant/turn-status.ts +17 -3
  183. package/src/ui/contract.ts +184 -0
  184. package/src/ui/footer.ts +52 -19
  185. package/src/ui/i18n/en.ts +58 -6
  186. package/src/ui/i18n/id.ts +58 -6
  187. package/src/ui/input/prompt-engine.ts +120 -25
  188. package/src/ui/render/errors.ts +39 -1
  189. package/src/ui/render/markdown-table.ts +455 -0
  190. package/src/ui/render/markdown.ts +22 -1
  191. package/src/ui/render/table-grid.ts +184 -0
  192. package/src/ui/render/table.ts +15 -76
  193. package/src/ui/runtime/screen.ts +7 -2
  194. package/src/ui/runtime/statusline.ts +25 -6
  195. package/src/ui/tui/app.ts +507 -169
  196. package/src/ui/tui/transcript.ts +531 -89
  197. package/vendor/minicore/VENDOR.md +1 -1
  198. package/vendor/minicore/src/core/budget.ts +25 -25
  199. package/vendor/minicore/src/core/compact.ts +75 -75
  200. package/vendor/minicore/src/core/errors.ts +59 -59
  201. package/vendor/minicore/src/core/events.ts +73 -73
  202. package/vendor/minicore/src/core/executor.ts +139 -139
  203. package/vendor/minicore/src/core/history.ts +31 -31
  204. package/vendor/minicore/src/core/index.ts +41 -41
  205. package/vendor/minicore/src/core/loop.ts +355 -355
  206. package/vendor/minicore/src/core/permission.ts +22 -22
  207. package/vendor/minicore/src/core/provider.ts +39 -39
  208. package/vendor/minicore/src/core/recovery.ts +35 -35
  209. package/vendor/minicore/src/core/session.ts +327 -327
  210. package/vendor/minicore/src/core/snapshot.ts +146 -146
  211. package/vendor/minicore/src/core/tokens.ts +107 -107
  212. package/vendor/minicore/src/core/tool.ts +115 -115
  213. package/vendor/minicore/src/core/types.ts +50 -50
  214. package/vendor/minicore/src/providers/openai-compat.ts +417 -417
  215. package/AGENTS.md +0 -45
  216. package/PLAN.md +0 -491
  217. package/docs/ARCHITECTURE.html +0 -1248
  218. package/docs/CONTROL-PLANE-MAP.md +0 -139
  219. package/docs/HARNESS.md +0 -150
  220. package/docs/SUMMARY.md +0 -52
  221. package/docs/UI_RENDER_PIPELINE.md +0 -169
  222. package/docs/USAGE.md +0 -11
@@ -0,0 +1,591 @@
1
+ // M13 — Dispatch bridge: validasi/terjemah/teruskan WHAT/WHEN → CAN/HOW.
2
+ //
3
+ // Kenapa berkas ini ada (P1 M13): scheduler (WHAT/WHEN) dan runtime (CAN/HOW)
4
+ // tak boleh saling memanggil langsung — scheduler tak boleh menulis lifecycle,
5
+ // runtime tak boleh memutuskan jadwal. Bridge ini adalah batas terjemahan:
6
+ // validasi authority/budget/deadline/capability/parent-child, revalidasi plan
7
+ // M12, dedupe dispatch-id, teruskan SATU admission request ke AdmissionPort
8
+ // (milik Host/Kernel di produksi; fake-diuji di sini). BUKAN scheduler kedua,
9
+ // BUKAN execution engine kedua.
10
+ //
11
+ // BUKAN: lifecycle authority (Kernel), state transition (M8), supervisor
12
+ // (M9), recovery interpretation (M12 — hanya konsumsi plan), persistence
13
+ // (M11), capability enforcement (M6/M5), agent reasoning, scheduler policy,
14
+ // TaskStore claims, timer/queue/worker. Aturan yang dikunci:
15
+ // - dispatchId ≠ executionId ≠ taskId (namespace dsp_*; stabil per logical occurrence).
16
+ // - Dispatch FSM ≠ Execution FSM (PLANNED/VALIDATING/READY/ADMITTING/ADMITTED +
17
+ // REJECTED/EXPIRED/AUTHORITY_LOST/BLOCKED/FAILED; tanpa COMPLETED).
18
+ // - planned ≠ admitted: id dialokasi ≠ eksekusi ada (tanpa ghost execution).
19
+ // - Predicate redispatch SATU (recovery-safety, via hasil M12 — tanpa fork).
20
+ // - Authority race jujur: snapshot lokal + revalidasi saat admit; tanpa itu
21
+ // TOCTOU dinyatakan (tanpa distributed lock di fase ini).
22
+ // - Tanpa import scheduler/TaskStore/SQLite/spawn/UI/CLI; tanpa timer.
23
+
24
+ import { randomUUID } from "node:crypto"
25
+ import {
26
+ type Capability,
27
+ type CapabilityGrant,
28
+ isCapabilitySubset,
29
+ isPathWithin,
30
+ } from "./capability.ts"
31
+ import { allocateExecutionId } from "./execution-id.ts"
32
+ import { createRecoveryEngine, type RedispatchPlan } from "./recovery.ts"
33
+
34
+ /** Engine M12 untuk isPlanCurrent SAJA (tanpa recoverExecution di sini). */
35
+ const planValidator = createRecoveryEngine()
36
+
37
+ /** Namespace dispatch id (stabil per logical occurrence; BUKAN executionId). */
38
+ export const DISPATCH_ID_PREFIX = "dsp_"
39
+
40
+ export function createDispatchId(): string {
41
+ return `${DISPATCH_ID_PREFIX}${randomUUID().replace(/-/g, "").slice(0, 12)}`
42
+ }
43
+
44
+ export function isDispatchId(value: unknown): value is string {
45
+ return (
46
+ typeof value === "string" &&
47
+ value.length > 4 &&
48
+ value.length <= 128 &&
49
+ /^dsp_[A-Za-z0-9_-]+$/.test(value)
50
+ )
51
+ }
52
+
53
+ export type DispatchState =
54
+ | "PLANNED"
55
+ | "VALIDATING"
56
+ | "READY"
57
+ | "ADMITTING"
58
+ | "ADMITTED"
59
+ | "REJECTED"
60
+ | "EXPIRED"
61
+ | "AUTHORITY_LOST"
62
+ | "BLOCKED"
63
+ | "FAILED"
64
+ | "STALE"
65
+ | "CAPABILITY_DENIED"
66
+ | "BUDGET_EXCEEDED"
67
+ | "DUPLICATE"
68
+ | "UNCERTAIN_DUPLICATE"
69
+
70
+ export type DispatchOutcome = DispatchState
71
+
72
+ export interface DispatchRequest {
73
+ readonly dispatchId: string
74
+ readonly schedulerSource: string
75
+ readonly taskId?: string
76
+ readonly claimRevision?: number
77
+ readonly claimGeneration?: number
78
+ readonly incarnation?: string
79
+ readonly authorityHeld: boolean
80
+ readonly executionId?: string
81
+ readonly intentId?: string
82
+ readonly parentExecutionId?: string
83
+ readonly lineageRootId?: string
84
+ /** Kind eksekusi yang diminta (default "turn" bila absen). */
85
+ readonly kind?: AdmissionRequest["kind"]
86
+ /** Owner lifecycle/resource (fallback: taskId, lalu schedulerSource — eksplisit). */
87
+ readonly ownerId?: string
88
+ readonly priority?: number
89
+ readonly scheduledAt?: number
90
+ readonly deadlineAt?: number | null
91
+ readonly budget?: number | null
92
+ readonly requestedCapabilities?: readonly Capability[]
93
+ readonly parentGrant?: CapabilityGrant
94
+ readonly workspace?: string
95
+ readonly parentWorkspace?: string
96
+ readonly modelRouting?: string
97
+ readonly backendHint?: string
98
+ readonly recoveryPlan?: RedispatchPlan
99
+ readonly attempt?: number
100
+ readonly generation?: number
101
+ readonly supersedes?: string
102
+ readonly parentTerminal?: boolean
103
+ readonly detached?: { ownerId: string; ttlMs: number; killPath: string }
104
+ readonly parentDeadlineRemainingMs?: number | null
105
+ readonly parentBudgetRemainingMs?: number | null
106
+ readonly provenance: { requestedBy: string; reason: string }
107
+ readonly metadata?: Record<string, string>
108
+ }
109
+
110
+ export interface AdmissionRequest {
111
+ readonly executionId: string
112
+ readonly parentExecutionId?: string
113
+ readonly lineageRootId: string
114
+ readonly kind: "turn" | "task" | "child" | "background"
115
+ readonly ownerId: string
116
+ readonly attempt?: number
117
+ readonly generation?: number
118
+ readonly supersedes?: string
119
+ readonly workspace?: string
120
+ readonly backendHint?: string
121
+ }
122
+
123
+ export type AdmissionResult =
124
+ | { readonly admitted: true; readonly executionId: string }
125
+ | { readonly admitted: false; readonly reason: string }
126
+
127
+ /** Batas admission milik Host/Kernel di produksi; fake-diuji di sini. */
128
+ export interface AdmissionPort {
129
+ admit(request: AdmissionRequest): AdmissionResult
130
+ }
131
+
132
+ export interface DispatchRecord {
133
+ readonly dispatchId: string
134
+ readonly state: DispatchState
135
+ readonly schedulerSource: string
136
+ readonly executionId?: string
137
+ readonly taskId?: string
138
+ readonly attempt?: number
139
+ readonly generation?: number
140
+ readonly supersedes?: string
141
+ readonly reason: string
142
+ readonly authorityAtAdmit?: boolean
143
+ readonly duplicateOf?: string
144
+ readonly history: readonly { state: DispatchState; at: number; reason: string }[]
145
+ }
146
+
147
+ export interface DispatchObservation {
148
+ readonly dispatchId: string
149
+ readonly state: DispatchState
150
+ readonly at: number
151
+ readonly executionId?: string
152
+ readonly reason: string
153
+ }
154
+
155
+ export interface DispatchMetrics {
156
+ readonly planned: number
157
+ readonly admitted: number
158
+ readonly rejected: number
159
+ readonly duplicates: number
160
+ readonly stale: number
161
+ readonly entries: number
162
+ }
163
+
164
+ export interface DispatchBridgeDeps {
165
+ readonly admission: AdmissionPort
166
+ /** Status host untuk pre-check (READY sajamelanjutkan; absen = lewati cek). */
167
+ readonly hostState?: () => string
168
+ /** Riwayat durable untuk cross-restart (absen = DUPLICATE_UNCERTAIN jujur). */
169
+ readonly historyLookup?: (dispatchId: string) => "admitted" | "unknown"
170
+ /** Revalidator plan M12 (default: logika validitas bawaan tanpa engine). */
171
+ readonly now?: () => number
172
+ /** Sink observasi opsional (terisolasi; bukan taksonomi M10). */
173
+ readonly onDispatchEvent?: (event: DispatchObservation) => void
174
+ }
175
+
176
+ function isValidDispatchId(value: unknown): value is string {
177
+ return isDispatchId(value)
178
+ }
179
+
180
+ function invalidReason(req: Partial<DispatchRequest>): string | null {
181
+ if (!req || typeof req !== "object") return "malformed request"
182
+ if (!isValidDispatchId(req.dispatchId)) return "malformed dispatchId"
183
+ if (typeof req.schedulerSource !== "string" || req.schedulerSource.length === 0)
184
+ return "malformed schedulerSource"
185
+ if (typeof req.authorityHeld !== "boolean") return "malformed authorityHeld"
186
+ if (
187
+ req.provenance === undefined ||
188
+ typeof req.provenance.requestedBy !== "string" ||
189
+ typeof req.provenance.reason !== "string"
190
+ )
191
+ return "malformed provenance"
192
+ for (const [k, v] of [
193
+ ["priority", req.priority],
194
+ ["attempt", req.attempt],
195
+ ["generation", req.generation],
196
+ ["budget", req.budget],
197
+ ] as const) {
198
+ if (v !== undefined && !Number.isFinite(v as number)) return `malformed ${k}`
199
+ }
200
+ if (req.metadata !== undefined) {
201
+ if (typeof req.metadata !== "object" || req.metadata === null) return "malformed metadata"
202
+ for (const [k, v] of Object.entries(req.metadata)) {
203
+ if (typeof v !== "string" || v.length > 4096) return "malformed metadata value"
204
+ void k
205
+ }
206
+ }
207
+ if (req.workspace !== undefined) {
208
+ if (
209
+ typeof req.workspace !== "string" ||
210
+ req.workspace.length === 0 ||
211
+ req.workspace.includes("\0")
212
+ )
213
+ return "malformed workspace"
214
+ }
215
+ return null
216
+ }
217
+
218
+ function checkPlanFreshness(
219
+ plan: RedispatchPlan,
220
+ now: number,
221
+ ctx: {
222
+ version: number | null
223
+ frontier: number
224
+ authorityHeld: boolean
225
+ budgetRemaining: number | null
226
+ deadlineRemainingMs: number | null
227
+ },
228
+ ): string | null {
229
+ // Revalidasi via SATU-SATUNYA check M12 (tanpa reinterpretasi evidence di sini).
230
+ // Alasan drift diuraikan lokal hanya untuk diagnostik (bukan predicate kedua).
231
+ const current = {
232
+ version: ctx.version,
233
+ frontier: ctx.frontier,
234
+ authorityHeld: ctx.authorityHeld,
235
+ budgetRemaining: ctx.budgetRemaining,
236
+ deadlineRemainingMs: ctx.deadlineRemainingMs,
237
+ }
238
+ if (planValidator.isPlanCurrent(plan, current)) {
239
+ void now
240
+ return null
241
+ }
242
+ if (ctx.version !== plan.validity.observedExecutionVersion) return "execution version drifted"
243
+ if (ctx.frontier !== plan.validity.journalFrontier) return "journal frontier moved"
244
+ if (!ctx.authorityHeld || ctx.authorityHeld !== plan.validity.authorityHeld)
245
+ return "authority changed"
246
+ if (
247
+ plan.validity.budgetRemaining !== null &&
248
+ (ctx.budgetRemaining === null || ctx.budgetRemaining <= 0)
249
+ )
250
+ return "budget drifted"
251
+ if (
252
+ plan.validity.deadlineRemainingMs !== null &&
253
+ (ctx.deadlineRemainingMs === null || ctx.deadlineRemainingMs <= 0)
254
+ )
255
+ return "deadline drifted"
256
+ return "plan no longer current"
257
+ }
258
+
259
+ export interface DispatchRefresh {
260
+ readonly authorityHeld?: boolean
261
+ readonly version?: number | null
262
+ readonly frontier?: number
263
+ readonly budgetRemaining?: number | null
264
+ readonly deadlineRemainingMs?: number | null
265
+ /** True bila request ini redelivery pasca-restart (bukan intent baru). */
266
+ readonly redelivered?: boolean
267
+ }
268
+
269
+ export interface DispatchBridge {
270
+ dispatch(request: DispatchRequest, refresh?: DispatchRefresh): DispatchRecord
271
+ get(dispatchId: string): DispatchRecord | undefined
272
+ metrics(): DispatchMetrics
273
+ }
274
+
275
+ interface StoredDispatch {
276
+ record: DispatchRecord
277
+ }
278
+
279
+ export function createDispatchBridge(deps: DispatchBridgeDeps): DispatchBridge {
280
+ const store = new Map<string, StoredDispatch>()
281
+ const m = { planned: 0, admitted: 0, rejected: 0, duplicates: 0, stale: 0 }
282
+ const now = deps.now ?? Date.now
283
+ const emit = (record: DispatchRecord): void => {
284
+ try {
285
+ deps.onDispatchEvent?.({
286
+ dispatchId: record.dispatchId,
287
+ state: record.state,
288
+ at: Date.now(),
289
+ ...(record.executionId ? { executionId: record.executionId } : {}),
290
+ reason: record.reason,
291
+ })
292
+ } catch {}
293
+ }
294
+ const save = (
295
+ dispatchId: string,
296
+ partial: Omit<DispatchRecord, "dispatchId" | "history" | "state" | "reason"> & {
297
+ history?: DispatchRecord["history"]
298
+ },
299
+ transition: { state: DispatchState; reason: string },
300
+ ): DispatchRecord => {
301
+ const prev = store.get(dispatchId)
302
+ const entry = { state: transition.state, at: now(), reason: transition.reason }
303
+ const record: DispatchRecord = Object.freeze({
304
+ dispatchId,
305
+ state: transition.state,
306
+ schedulerSource: partial.schedulerSource,
307
+ ...(partial.executionId ? { executionId: partial.executionId } : {}),
308
+ ...(partial.taskId ? { taskId: partial.taskId } : {}),
309
+ ...(partial.attempt !== undefined ? { attempt: partial.attempt } : {}),
310
+ ...(partial.generation !== undefined ? { generation: partial.generation } : {}),
311
+ ...(partial.supersedes ? { supersedes: partial.supersedes } : {}),
312
+ reason: transition.reason,
313
+ history: Object.freeze([...(prev?.record.history ?? []), entry]),
314
+ })
315
+ store.set(dispatchId, { record })
316
+ emit(record)
317
+ return record
318
+ }
319
+
320
+ const fail = (
321
+ dispatchId: string,
322
+ base: Omit<DispatchRecord, "dispatchId" | "history" | "state" | "reason"> & { reason?: string },
323
+ state: DispatchState,
324
+ reason: string,
325
+ ): DispatchRecord => {
326
+ m.rejected++
327
+ return save(dispatchId, { ...base, schedulerSource: base.schedulerSource }, { state, reason })
328
+ }
329
+
330
+ return {
331
+ dispatch(request: DispatchRequest, refresh?: DispatchRefresh): DispatchRecord {
332
+ const t0 = now()
333
+ void t0
334
+ // 1. Bentuk (malformed ≠ retryable sebagai valid).
335
+ const malformed = invalidReason(request)
336
+ // 2. Dedupe stabil SEBELUM validasi mahal — kecuali malformed.
337
+ const seen = store.get(request.dispatchId)
338
+ if (malformed) {
339
+ // Malformed tetap dicatat (observasi) tanpa execution.
340
+ m.rejected++
341
+ return save(
342
+ request.dispatchId,
343
+ {
344
+ schedulerSource:
345
+ typeof request.schedulerSource === "string" ? request.schedulerSource : "unknown",
346
+ },
347
+ { state: "REJECTED", reason: malformed },
348
+ )
349
+ }
350
+ if (seen) {
351
+ // Idempoten: acknowledgement SAMA tanpa menumbuhkan history tersimpan
352
+ // (tanpa E baru, tanpa mutasi). Stored record tak berubah.
353
+ m.duplicates++
354
+ const dup: DispatchRecord = Object.freeze({
355
+ ...seen.record,
356
+ state: "DUPLICATE" as const,
357
+ duplicateOf: seen.record.state,
358
+ reason: `duplicate of ${seen.record.state}`,
359
+ })
360
+ emit(dup)
361
+ return dup
362
+ }
363
+ // 2b. Redelivery pasca-restart tanpa memori lokal: JANGAN buta buat E2.
364
+ // Cross-restart hanya aman bila bukti durable tersedia; selain itu
365
+ // UNCERTAIN eksplisit yang konservatif (tidak admit, tidak tolak final).
366
+ if (refresh?.redelivered === true) {
367
+ const known = deps.historyLookup ? deps.historyLookup(request.dispatchId) : "unknown"
368
+ if (known === "admitted") {
369
+ m.duplicates++
370
+ const dup: DispatchRecord = Object.freeze({
371
+ dispatchId: request.dispatchId,
372
+ state: "DUPLICATE" as const,
373
+ schedulerSource: request.schedulerSource,
374
+ reason: "duplicate confirmed by durable evidence",
375
+ duplicateOf: "ADMITTED" as const,
376
+ history: Object.freeze([
377
+ {
378
+ state: "DUPLICATE" as const,
379
+ at: now(),
380
+ reason: "duplicate confirmed by durable evidence",
381
+ },
382
+ ]),
383
+ })
384
+ store.set(request.dispatchId, { record: dup })
385
+ emit(dup)
386
+ return dup
387
+ }
388
+ return save(
389
+ request.dispatchId,
390
+ { schedulerSource: request.schedulerSource },
391
+ {
392
+ state: "UNCERTAIN_DUPLICATE",
393
+ reason: "redelivered after restart without durable evidence",
394
+ },
395
+ )
396
+ }
397
+ const base = {
398
+ schedulerSource: request.schedulerSource,
399
+ ...(request.taskId ? { taskId: request.taskId } : {}),
400
+ ...(request.attempt !== undefined ? { attempt: request.attempt } : {}),
401
+ ...(request.generation !== undefined ? { generation: request.generation } : {}),
402
+ ...(request.supersedes ? { supersedes: request.supersedes } : {}),
403
+ }
404
+ // 3. Authority snapshot lokal (TOCTOU jujur: dicek ulang saat admit).
405
+ const authorityNow = refresh?.authorityHeld ?? request.authorityHeld
406
+ if (!request.authorityHeld || !authorityNow) {
407
+ return fail(
408
+ request.dispatchId,
409
+ base,
410
+ "AUTHORITY_LOST",
411
+ "scheduler authority absent at dispatch",
412
+ )
413
+ }
414
+ // 4. Schedule timing: masa lalu-kedaluwarsa vs belum-due (bridge tak menjadwal).
415
+ if (
416
+ request.deadlineAt !== undefined &&
417
+ request.deadlineAt !== null &&
418
+ now() >= request.deadlineAt
419
+ ) {
420
+ return fail(request.dispatchId, base, "EXPIRED", "deadline already passed")
421
+ }
422
+ if (request.scheduledAt !== undefined && request.scheduledAt > now()) {
423
+ return fail(
424
+ request.dispatchId,
425
+ base,
426
+ "REJECTED",
427
+ "not-due (bridge holds no schedule queue)",
428
+ )
429
+ }
430
+ // 5. Budget: tak ada mint, tak ada reset, tak ada double-count di sini.
431
+ if (request.budget !== undefined && request.budget !== null && request.budget <= 0) {
432
+ return fail(request.dispatchId, base, "BLOCKED", "budget exhausted")
433
+ }
434
+ // 6. Capability: subset terhadap parent grant bila keduanya ada (M6 reuse).
435
+ if (request.requestedCapabilities && request.parentGrant) {
436
+ for (const cap of request.requestedCapabilities) {
437
+ const covered = request.parentGrant.capabilities.some((p) => isCapabilitySubset(cap, p))
438
+ if (!covered) {
439
+ return fail(
440
+ request.dispatchId,
441
+ base,
442
+ "CAPABILITY_DENIED",
443
+ "requested capability exceeds parent grant",
444
+ )
445
+ }
446
+ }
447
+ }
448
+ // 7. Workspace: di dalam parent bila keduanya ada (M6 reuse; enforcement milik jail).
449
+ if (request.workspace && request.parentWorkspace) {
450
+ let inside = false
451
+ try {
452
+ inside = isPathWithin(request.parentWorkspace, request.workspace)
453
+ } catch {
454
+ inside = false
455
+ }
456
+ if (!inside)
457
+ return fail(
458
+ request.dispatchId,
459
+ base,
460
+ "CAPABILITY_DENIED",
461
+ "workspace outside parent scope",
462
+ )
463
+ }
464
+ // 8. Parent/child: terminal parent + attached → tolak (detached butuh kontrak penuh).
465
+ if (request.parentExecutionId && request.parentTerminal === true && !request.detached) {
466
+ return fail(
467
+ request.dispatchId,
468
+ base,
469
+ "REJECTED",
470
+ "parent terminal (attached child dispatch rejected)",
471
+ )
472
+ }
473
+ if (request.detached) {
474
+ const d = request.detached
475
+ if (!d.ownerId || !Number.isFinite(d.ttlMs) || d.ttlMs <= 0 || !d.killPath) {
476
+ return fail(request.dispatchId, base, "REJECTED", "detached requires owner+ttl+killPath")
477
+ }
478
+ }
479
+ // 9. Recovery plan: revalidasi TANPA reinterpretasi (M12 punya makna).
480
+ let lineageExecutionId: string | undefined
481
+ let lineage = {
482
+ attempt: request.attempt,
483
+ generation: request.generation,
484
+ supersedes: request.supersedes,
485
+ }
486
+ if (request.recoveryPlan) {
487
+ const plan = request.recoveryPlan
488
+ const stale = checkPlanFreshness(plan, now(), {
489
+ version: refresh?.version ?? null,
490
+ frontier: refresh?.frontier ?? -1,
491
+ authorityHeld: authorityNow,
492
+ budgetRemaining: refresh?.budgetRemaining ?? request.budget ?? null,
493
+ deadlineRemainingMs:
494
+ refresh?.deadlineRemainingMs ??
495
+ (request.deadlineAt != null ? request.deadlineAt - now() : null),
496
+ })
497
+ if (stale) {
498
+ m.stale++
499
+ return fail(request.dispatchId, base, "STALE", `recovery plan stale: ${stale}`)
500
+ }
501
+ lineageExecutionId = plan.newExecutionId
502
+ lineage = {
503
+ attempt: plan.attempt,
504
+ generation: plan.generation,
505
+ supersedes: plan.supersedes,
506
+ }
507
+ }
508
+ // 10. Host pre-check (bila disediakan): hanya READY yang lanjut.
509
+ if (deps.hostState) {
510
+ const hs = deps.hostState()
511
+ if (hs !== "READY") {
512
+ return fail(request.dispatchId, base, "BLOCKED", `host not accepting (${hs})`)
513
+ }
514
+ }
515
+ // 11. Admission via port (SATU-SATUNYA jalan ke runtime). ExecutionId:
516
+ // plan (redispatch lineage) atau mint baru M1 — tak pernah reuse E lama.
517
+ // Owner: eksplisit → taskId → schedulerSource (rantai fallback eksplisit).
518
+ // lineageRoot: request eksplisit → plan (redispatch P13) → E baru.
519
+ // admissionBase TANPA executionId dipakai untuk jalur gagal (planned ≠
520
+ // admitted: id yang tak pernah diadmit tak boleh menempel di record).
521
+ const executionId = lineageExecutionId ?? allocateExecutionId()
522
+ const admissionOwner = request.ownerId ?? request.taskId ?? request.schedulerSource
523
+ const admissionRoot =
524
+ request.lineageRootId ?? request.recoveryPlan?.lineageRootId ?? executionId
525
+ const admissionBase = {
526
+ ...base,
527
+ executionId,
528
+ ...(lineage.attempt !== undefined ? { attempt: lineage.attempt } : {}),
529
+ ...(lineage.generation !== undefined ? { generation: lineage.generation } : {}),
530
+ ...(lineage.supersedes ? { supersedes: lineage.supersedes } : {}),
531
+ }
532
+ m.planned++
533
+ const admitting = save(request.dispatchId, admissionBase, {
534
+ state: "ADMITTING",
535
+ reason: "forwarding to admission port",
536
+ })
537
+ void admitting
538
+ let admitted: AdmissionResult
539
+ try {
540
+ admitted = deps.admission.admit({
541
+ executionId,
542
+ ...(request.parentExecutionId ? { parentExecutionId: request.parentExecutionId } : {}),
543
+ lineageRootId: admissionRoot,
544
+ kind: request.kind ?? "turn",
545
+ ownerId: admissionOwner,
546
+ ...(lineage.attempt !== undefined ? { attempt: lineage.attempt } : {}),
547
+ ...(lineage.generation !== undefined ? { generation: lineage.generation } : {}),
548
+ ...(lineage.supersedes ? { supersedes: lineage.supersedes } : {}),
549
+ ...(request.workspace ? { workspace: request.workspace } : {}),
550
+ ...(request.backendHint ? { backendHint: request.backendHint } : {}),
551
+ })
552
+ } catch (e) {
553
+ return fail(
554
+ request.dispatchId,
555
+ base,
556
+ "FAILED",
557
+ `admission port threw: ${(e instanceof Error ? e.message : String(e)).slice(0, 120)}`,
558
+ )
559
+ }
560
+ if (!admitted.admitted) {
561
+ const reason = admitted.reason
562
+ const state = /drain|clos|shut/i.test(reason)
563
+ ? "BLOCKED"
564
+ : /author/i.test(reason)
565
+ ? "AUTHORITY_LOST"
566
+ : "BLOCKED"
567
+ return fail(request.dispatchId, base, state as DispatchState, reason)
568
+ }
569
+ m.admitted++
570
+ return save(request.dispatchId, admissionBase, {
571
+ state: "ADMITTED",
572
+ reason: "admitted by runtime boundary",
573
+ })
574
+ },
575
+
576
+ get(dispatchId: string): DispatchRecord | undefined {
577
+ return store.get(dispatchId)?.record
578
+ },
579
+
580
+ metrics(): DispatchMetrics {
581
+ return {
582
+ planned: m.planned,
583
+ admitted: m.admitted,
584
+ rejected: m.rejected,
585
+ duplicates: m.duplicates,
586
+ stale: m.stale,
587
+ entries: store.size,
588
+ }
589
+ },
590
+ }
591
+ }