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.
- package/CHANGELOG.md +98 -0
- package/LICENSE +21 -21
- package/README.md +4 -4
- package/cli/args.ts +46 -0
- package/cli/commands/acp.ts +163 -10
- package/cli/commands/config.ts +33 -18
- package/cli/commands/daemon.ts +515 -0
- package/cli/commands/exec.ts +145 -53
- package/cli/commands/openwork.ts +986 -0
- package/cli/commands/sessions.ts +4 -1
- package/cli/commands/stats.ts +34 -4
- package/cli/commands.ts +217 -2
- package/cli/index.ts +146 -14
- package/cli/recovery-warning.ts +115 -0
- package/cli/router.ts +32 -1
- package/cli/setup.ts +2332 -171
- package/cli/tui.ts +113 -7
- package/docs/OUTPUT_ARCHITECTURE_AUDIT.md +489 -0
- package/docs/OUTPUT_EVENT_MODEL.md +289 -0
- package/docs/OUTPUT_IMPLEMENTATION_PLAN.md +391 -0
- package/docs/OUTPUT_PROTOCOL_SPEC.md +285 -0
- package/docs/OUTPUT_RENDERING_SPEC.md +248 -0
- package/docs/OUTPUT_UX_RULES.md +449 -0
- package/docs/PLAN_UIUX_V6.md +2 -2
- package/docs/README.md +4 -3
- package/docs/TERMINAL_CONTRACT.md +278 -66
- package/docs/architecture.md +89 -7
- package/docs/changelog.md +1 -1
- package/docs/choosing-mode.md +2 -2
- package/docs/cli.md +9 -5
- package/docs/concepts.md +1 -1
- package/docs/contributing.md +9 -2
- package/docs/environment.md +6 -2
- package/docs/exec.md +46 -5
- package/docs/memory-sessions.md +2 -0
- package/docs/policy-sandbox.md +1 -1
- package/docs/pricing-budget.md +1 -1
- package/docs/quickstart.md +2 -2
- package/docs/repl.md +6 -2
- package/docs/security-model.md +1 -1
- package/docs/security.md +1 -1
- package/docs/skills.md +2 -2
- package/docs/terminal.md +9 -5
- package/docs/tools.md +1 -1
- package/package.json +35 -5
- package/src/app/session.ts +261 -15
- package/src/app/tool-layer.ts +94 -7
- package/src/daemon/approvals.ts +361 -0
- package/src/daemon/capability.ts +145 -0
- package/src/daemon/children.ts +142 -0
- package/src/daemon/client.ts +267 -0
- package/src/daemon/control.ts +350 -0
- package/src/daemon/discovery.ts +234 -0
- package/src/daemon/feed.ts +155 -0
- package/src/daemon/framing.ts +94 -0
- package/src/daemon/host.ts +316 -0
- package/src/daemon/protocol.ts +217 -0
- package/src/daemon/resource.ts +170 -0
- package/src/daemon/sanitize.ts +57 -0
- package/src/daemon/server.ts +627 -0
- package/src/daemon/store.ts +317 -0
- package/src/daemon/subscription.ts +270 -0
- package/src/daemon/telemetry.ts +81 -0
- package/src/hooks/run.ts +12 -1
- package/src/lib/atomic-write.ts +29 -3
- package/src/lib/db-path.ts +26 -0
- package/src/lib/keystore.ts +544 -42
- package/src/lib/net.ts +43 -1
- package/src/lib/safe-open.ts +116 -1
- package/src/lib/session-id.ts +15 -0
- package/src/lsp/client.ts +123 -5
- package/src/mcp/client.ts +139 -17
- package/src/mcp/server.ts +177 -50
- package/src/mcp/transport.ts +16 -19
- package/src/memory/vector.ts +770 -55
- package/src/policy/allowlist.ts +14 -2
- package/src/policy/bash-guard.ts +105 -10
- package/src/policy/compaction.ts +82 -5
- package/src/policy/consequence-engine.ts +220 -0
- package/src/policy/context.ts +132 -0
- package/src/policy/executor.ts +187 -121
- package/src/policy/no-progress.ts +559 -0
- package/src/policy/permission.ts +4 -8
- package/src/policy/pricing.ts +17 -3
- package/src/policy/scrub.ts +69 -2
- package/src/policy/tool-contract.ts +515 -0
- package/src/policy/usage.ts +310 -24
- package/src/policy/verifier.ts +6 -3
- package/src/policy/work-mode.ts +182 -0
- package/src/presentation/adapter.ts +533 -26
- package/src/presentation/events.ts +151 -0
- package/src/presentation/model.ts +180 -27
- package/src/presentation/projection.ts +858 -0
- package/src/presentation/reducer.ts +645 -310
- package/src/presentation/store.ts +12 -7
- package/src/providers/anthropic.ts +18 -10
- package/src/providers/responses.ts +17 -7
- package/src/runtime/capability.ts +409 -0
- package/src/runtime/child-execution.ts +274 -0
- package/src/runtime/composition.ts +958 -0
- package/src/runtime/dispatch.ts +591 -0
- package/src/runtime/execution-backend.ts +632 -0
- package/src/runtime/execution-events.ts +272 -0
- package/src/runtime/execution-id.ts +230 -0
- package/src/runtime/execution-journal.ts +926 -0
- package/src/runtime/execution-kernel.ts +456 -0
- package/src/runtime/execution-registry.ts +379 -0
- package/src/runtime/process-supervision.ts +276 -0
- package/src/runtime/production-execution.ts +551 -0
- package/src/runtime/production-runtime.ts +217 -0
- package/src/runtime/recovery-safety.ts +70 -0
- package/src/runtime/recovery.ts +477 -0
- package/src/runtime/runtime-capabilities.ts +179 -0
- package/src/runtime/runtime-diagnostics.ts +141 -0
- package/src/runtime/runtime-host.ts +365 -0
- package/src/runtime/runtime-status-facts.ts +222 -0
- package/src/runtime/runtime-status-provider.ts +74 -0
- package/src/runtime/runtime-status.ts +459 -0
- package/src/runtime/runtime-task-admission.ts +101 -0
- package/src/runtime/supervisor.ts +444 -0
- package/src/session/authority.ts +168 -0
- package/src/session/checkpoint.ts +88 -1
- package/src/session/context-adapter.ts +251 -0
- package/src/session/context-assembly.ts +242 -0
- package/src/session/context-identity.ts +389 -0
- package/src/session/context-projection.ts +248 -0
- package/src/session/context-selector.ts +500 -0
- package/src/session/cross-session-adoption.ts +249 -0
- package/src/session/full-history-fold.ts +171 -0
- package/src/session/identity.ts +192 -0
- package/src/session/journal.ts +805 -102
- package/src/session/open-work-intent.ts +732 -0
- package/src/session/open-work.ts +767 -0
- package/src/session/pending-tools.ts +94 -0
- package/src/session/persistence.ts +3569 -127
- package/src/session/runtime-header.ts +208 -0
- package/src/session/shadow-git.ts +13 -5
- package/src/session/verification.ts +1623 -0
- package/src/task/assignment.ts +136 -0
- package/src/task/autonomous-adapter.ts +168 -0
- package/src/task/autonomous-context.ts +630 -0
- package/src/task/autonomous-policy.ts +490 -0
- package/src/task/continuity.ts +179 -0
- package/src/task/execution-cancellation.ts +165 -0
- package/src/task/graph-validate.ts +379 -0
- package/src/task/graph.ts +305 -0
- package/src/task/identity.ts +230 -0
- package/src/task/model.ts +417 -0
- package/src/task/production-scheduler.ts +293 -0
- package/src/task/readiness.ts +229 -0
- package/src/task/scheduler-observability.ts +387 -0
- package/src/task/scheduler.ts +1197 -0
- package/src/task/scheduling-policy.ts +165 -0
- package/src/task/session-authority.ts +148 -0
- package/src/task/session-ownership.ts +211 -0
- package/src/task/store.ts +2887 -0
- package/src/task/sync.ts +343 -0
- package/src/task/trigger.ts +260 -0
- package/src/tools/bash.ts +377 -211
- package/src/tools/code_run.ts +1 -1
- package/src/tools/delete_file.ts +1 -1
- package/src/tools/edit.ts +33 -6
- package/src/tools/evidence.ts +30 -0
- package/src/tools/git.ts +4 -4
- package/src/tools/glob.ts +12 -3
- package/src/tools/grep.ts +1 -1
- package/src/tools/lsp.ts +4 -4
- package/src/tools/mcp_call.ts +11 -4
- package/src/tools/memory.ts +153 -18
- package/src/tools/move_file.ts +1 -1
- package/src/tools/patch.ts +1 -1
- package/src/tools/read_file.ts +1 -1
- package/src/tools/read_image.ts +1 -1
- package/src/tools/submit_result.ts +1 -1
- package/src/tools/task.ts +437 -41
- package/src/tools/todo.ts +662 -35
- package/src/tools/web_fetch.ts +4 -2
- package/src/tools/web_search.ts +9 -3
- package/src/tools/write_file.ts +1 -1
- package/src/ui/assistant/simple.ts +123 -50
- package/src/ui/assistant/turn-status.ts +17 -3
- package/src/ui/contract.ts +184 -0
- package/src/ui/footer.ts +54 -18
- package/src/ui/i18n/en.ts +62 -6
- package/src/ui/i18n/id.ts +62 -6
- package/src/ui/input/prompt-engine.ts +120 -25
- package/src/ui/render/errors.ts +39 -1
- package/src/ui/render/markdown-table.ts +455 -0
- package/src/ui/render/markdown.ts +22 -1
- package/src/ui/render/table-grid.ts +184 -0
- package/src/ui/render/table.ts +15 -76
- package/src/ui/runtime/screen.ts +7 -2
- package/src/ui/runtime/statusline.ts +25 -6
- package/src/ui/tui/app.ts +598 -133
- package/src/ui/tui/transcript.ts +531 -89
- package/vendor/minicore/VENDOR.md +1 -1
- package/vendor/minicore/src/core/budget.ts +25 -25
- package/vendor/minicore/src/core/compact.ts +75 -75
- package/vendor/minicore/src/core/errors.ts +59 -59
- package/vendor/minicore/src/core/events.ts +73 -73
- package/vendor/minicore/src/core/executor.ts +139 -139
- package/vendor/minicore/src/core/history.ts +31 -31
- package/vendor/minicore/src/core/index.ts +41 -41
- package/vendor/minicore/src/core/loop.ts +355 -355
- package/vendor/minicore/src/core/permission.ts +22 -22
- package/vendor/minicore/src/core/provider.ts +39 -39
- package/vendor/minicore/src/core/recovery.ts +35 -35
- package/vendor/minicore/src/core/session.ts +327 -327
- package/vendor/minicore/src/core/snapshot.ts +146 -146
- package/vendor/minicore/src/core/tokens.ts +107 -107
- package/vendor/minicore/src/core/tool.ts +115 -115
- package/vendor/minicore/src/core/types.ts +50 -50
- package/vendor/minicore/src/providers/openai-compat.ts +417 -417
- package/AGENTS.md +0 -45
- package/PLAN.md +0 -491
- package/docs/ARCHITECTURE.html +0 -1248
- package/docs/CONTROL-PLANE-MAP.md +0 -139
- package/docs/HARNESS.md +0 -150
- package/docs/SUMMARY.md +0 -52
- package/docs/UI_RENDER_PIPELINE.md +0 -165
- package/docs/USAGE.md +0 -11
|
@@ -0,0 +1,958 @@
|
|
|
1
|
+
// M14 — Runtime composition root: BUILD + WIRE, bukan decide/mutate/recover.
|
|
2
|
+
//
|
|
3
|
+
// Kenapa berkas ini ada (P1 M14): M1–M13 dibangun per-modul dan "prepared but
|
|
4
|
+
// controlled" — lengkap + teruji, tapi belum dirangkai menjadi SATU runtime.
|
|
5
|
+
// Modul ini adalah rangkaiannya: satu host, satu kernel, satu plane, satu
|
|
6
|
+
// journal, satu supervisor, satu bridge, satu recovery — dirangkai dengan
|
|
7
|
+
// kepemilikan eksplisit, tanpa otoritas kedua dan tanpa mengubah siapa pun.
|
|
8
|
+
//
|
|
9
|
+
// Batas yang dikunci (jangan dilonggarkan tanpa ADR baru):
|
|
10
|
+
// - Composition = construct + connect. Ia TIDAK memutuskan, TIDAK memutasi
|
|
11
|
+
// lifecycle di luar port yang sudah ada, TIDAK menafsirkan recovery, TIDAK
|
|
12
|
+
// mengeksekusi backend, TIDAK menyentuh policy/scheduler/task/session/UI.
|
|
13
|
+
// Semua keputusan tetap milik modul asalnya (M8/M9/M12/M13/M5).
|
|
14
|
+
// - Session != Runtime Host != Execution. Modul ini tidak punya konsep sesi
|
|
15
|
+
// yang bisa mengubah state sesi; ia hanya membawa sessionId sebagai label.
|
|
16
|
+
// - SATU komposisi = SATU dunia. Tidak ada singleton global, tidak ada state
|
|
17
|
+
// mutable di module scope: dua komposisi (session/workspace berbeda) tidak
|
|
18
|
+
// mungkin saling melihat event, jurnal, atau dispatch satu sama lain.
|
|
19
|
+
// - Journal path EKSPLISIT dari caller. Tidak ada default global dan tidak ada
|
|
20
|
+
// penoran dari acak: resume berarti caller memberikan path yang SAMA.
|
|
21
|
+
// - Journal wajib secara default (fail-closed): open gagal = konstruksi gagal.
|
|
22
|
+
// "Tak ada jurnal" hanya boleh terjadi bila mode non-durable diminta eksplisit.
|
|
23
|
+
//
|
|
24
|
+
// === MODEL SHUTDOWN (satu-satunya urutan; lihat runShutdown) ===
|
|
25
|
+
//
|
|
26
|
+
// admission latch -> host.shutdown() -> execution drain
|
|
27
|
+
// -> event delivery drain -> journal.flush() -> journal.close()
|
|
28
|
+
// -> host.close() -> (pemanggil: session/UI detach)
|
|
29
|
+
//
|
|
30
|
+
// Kenapa urutan itu, berdasarkan kepemilikan yang BENAR-BENAR ada (bukan nama):
|
|
31
|
+
// - Latch admission milik composition (satu boolean monoton). Port admission
|
|
32
|
+
// mengeceknya LEBIH DALAM dari hostState M13, jadi penolakan tetap deterministik
|
|
33
|
+
// walau host masih READY (jeda antara latch dan host.shutdown() adalah async).
|
|
34
|
+
// - host.shutdown() = latch admitting/run + hook onShutdown milik PEMILIK. Hook
|
|
35
|
+
// itu adalah tempat owner menghentikan produsen event; karena itu hook berjalan
|
|
36
|
+
// SEBELUM drain/flush, bukan sesudah.
|
|
37
|
+
// - Execution drain = menunggu kerja in-flight yang DIDAFTARKAN runtime (track())
|
|
38
|
+
// (track()). Executions non-terminal yang TIDAK dilacak TIDAK ditulis ulang:
|
|
39
|
+
// shutdown tak pernah mengarang COMPLETED; ia melapor, dan M12 yang menafsirkan.
|
|
40
|
+
// - Event delivery drain: M10 emit() sepenuhnya sinkron (tak ada antrean), jadi
|
|
41
|
+
// satu-satunya pengiriman async adalah append M11. Drain menunggu append yang
|
|
42
|
+
// masih jalan, termasuk yang muncul selama drain itu sendiri.
|
|
43
|
+
// - journal.flush() setelah drain: inilah batas durability. Setelah flush, hook
|
|
44
|
+
// berhenti append (barrier) — sehingga tak ada append SETELAH flush, dan
|
|
45
|
+
// Pastinya tak ada reopen yang diam-diam.
|
|
46
|
+
// - journal.close() sesudah flush: bukti durable sudah dicatat; gagalnya close
|
|
47
|
+
// tak boleh membatalkan bukti itu.
|
|
48
|
+
// - host.close() TERAKHIR: host tak memegang jurnal, jadi menutupnya lebih dulu
|
|
49
|
+
// hanya menambah cara kegagalan membatalkan batas durability. Hook onClose yang
|
|
50
|
+
// melempar dilaporkan eksplisit (tidak ditelan) lewat RuntimeShutdownResult.
|
|
51
|
+
//
|
|
52
|
+
// BUKAN FSM kedua: composition tak punya state machine lifecycle. Authority
|
|
53
|
+
// lifecycle tetap RuntimeHost (CREATED/STARTING/READY/DRAINING/CLOSING/CLOSED);
|
|
54
|
+
// latch composition cuma menjawab satu pertanyaan monoton: "admission masih
|
|
55
|
+
// dibuka?" — true lalu false, tak pernah kembali true.
|
|
56
|
+
//
|
|
57
|
+
// drainTimeoutMs = batas DRAIN saja (tak memaksa hasil jadi "sukses"): drain
|
|
58
|
+
// yang tak tuntas dilaporkan sebagai "uncertain", bukan dipoles jadi hijau.
|
|
59
|
+
|
|
60
|
+
import {
|
|
61
|
+
createDispatchBridge,
|
|
62
|
+
type DispatchBridge,
|
|
63
|
+
type DispatchMetrics,
|
|
64
|
+
type DispatchRefresh,
|
|
65
|
+
type DispatchRequest,
|
|
66
|
+
} from "./dispatch.ts"
|
|
67
|
+
import { BACKEND_FACTORIES, type BackendKind, type ExecutionBackend } from "./execution-backend.ts"
|
|
68
|
+
import {
|
|
69
|
+
createEventPlane,
|
|
70
|
+
type EventPlane,
|
|
71
|
+
type EventPlaneMetrics,
|
|
72
|
+
type EventSource,
|
|
73
|
+
executionEventFromCommit,
|
|
74
|
+
} from "./execution-events.ts"
|
|
75
|
+
import {
|
|
76
|
+
type CheckpointResult,
|
|
77
|
+
type ExecutionJournal,
|
|
78
|
+
type FlushResult,
|
|
79
|
+
type JournalMetrics,
|
|
80
|
+
type JournalRecord,
|
|
81
|
+
openExecutionJournal,
|
|
82
|
+
} from "./execution-journal.ts"
|
|
83
|
+
import {
|
|
84
|
+
createExecutionKernel,
|
|
85
|
+
type ExecutionKernel,
|
|
86
|
+
type ExecutionState,
|
|
87
|
+
isExecutionTerminalState,
|
|
88
|
+
type KernelMetrics,
|
|
89
|
+
type TransitionRequestSource,
|
|
90
|
+
} from "./execution-kernel.ts"
|
|
91
|
+
import {
|
|
92
|
+
createProcessSupervision,
|
|
93
|
+
type ProcessSupervision,
|
|
94
|
+
type ProcessSupervisionStatus,
|
|
95
|
+
} from "./process-supervision.ts"
|
|
96
|
+
import {
|
|
97
|
+
createRecoveryEngine,
|
|
98
|
+
type RecoveryContext,
|
|
99
|
+
type RecoveryEngine,
|
|
100
|
+
type RecoveryResult,
|
|
101
|
+
} from "./recovery.ts"
|
|
102
|
+
import {
|
|
103
|
+
createRuntimeHost,
|
|
104
|
+
type HostLifecycleState,
|
|
105
|
+
type RuntimeHost,
|
|
106
|
+
type RuntimeHostOptions,
|
|
107
|
+
} from "./runtime-host.ts"
|
|
108
|
+
import {
|
|
109
|
+
type RuntimeFacts,
|
|
110
|
+
type RuntimeFlushReport,
|
|
111
|
+
runtimeFactsFrom,
|
|
112
|
+
type TaskLayerFacts,
|
|
113
|
+
} from "./runtime-status-facts.ts"
|
|
114
|
+
|
|
115
|
+
// Bentuk hasil drain milik modul netral (runtime-status-facts.ts) supaya
|
|
116
|
+
// `runtime-status.ts` tak perlu mengimpor composition.ts — graf src/runtime/**
|
|
117
|
+
// bebas siklus (guard m16 G1). Re-export supaya pemanggil lama tak berubah.
|
|
118
|
+
export type { RuntimeFlushReport } from "./runtime-status-facts.ts"
|
|
119
|
+
|
|
120
|
+
import { createSupervisor, type SupervisionPolicy, type Supervisor } from "./supervisor.ts"
|
|
121
|
+
|
|
122
|
+
export interface RuntimeCompositionOptions {
|
|
123
|
+
/**
|
|
124
|
+
* Label identitas sesi. Diteruskan apa adanya — TIDAK PERNAH diturunkan dari
|
|
125
|
+
* acak di sini: identitas itu milik caller, dan resume harus memakai identitas
|
|
126
|
+
* lama, bukan identitas pengganti.
|
|
127
|
+
*/
|
|
128
|
+
readonly sessionId: string
|
|
129
|
+
/** Workspace tempat runtime ini hidup (informasi; batas tetap milik policy). */
|
|
130
|
+
readonly workspaceCwd: string
|
|
131
|
+
/**
|
|
132
|
+
* Path jurnal durable. WAJIB eksplisit: caller yang tahu storage-nya
|
|
133
|
+
* (resume = path yang sama; sesi baru = path sendiri per workspace).
|
|
134
|
+
*/
|
|
135
|
+
readonly journalPath: string
|
|
136
|
+
/** Backend fisik (default "host" — backend yang sama dengan proses CLI). */
|
|
137
|
+
readonly backend?: BackendKind
|
|
138
|
+
/**
|
|
139
|
+
* Fail-closed bila jurnal tak bisa dibuka (default). `false` = mode
|
|
140
|
+
* non-durable eksplisit: TANPA jurnal, history restart hilang, dan
|
|
141
|
+
* `recover()` hanya bisa membaca apa yang ada di memori.
|
|
142
|
+
*/
|
|
143
|
+
readonly journalRequired?: boolean
|
|
144
|
+
/** Batas drain (ms; default 5000). Drain tak tuntas = "uncertain", bukan hijau. */
|
|
145
|
+
readonly drainTimeoutMs?: number
|
|
146
|
+
readonly supervisorPolicy?: SupervisionPolicy
|
|
147
|
+
/**
|
|
148
|
+
* Policy supervision proses (P13.2). Memakai policy M9 yang sama — tak ada
|
|
149
|
+
* ambang baru yang mengendap diam-diam.
|
|
150
|
+
*/
|
|
151
|
+
readonly processSupervisionPolicy?: SupervisionPolicy
|
|
152
|
+
/**
|
|
153
|
+
* Seam (P13.2): fabrikasi instance supervision proses. Default = instance
|
|
154
|
+
* standar. Disuntik HANYA untuk menguji kegagalan establishment — runtime
|
|
155
|
+
* harus degrade (bukan mengklaim sehat), bukan crash.
|
|
156
|
+
*/
|
|
157
|
+
readonly processSupervisionFactory?: () => ProcessSupervision
|
|
158
|
+
/**
|
|
159
|
+
* Fakta lapisan task (P13.3): scheduler terpasang? TaskStore otoritas task
|
|
160
|
+
* terbuka?
|
|
161
|
+
*
|
|
162
|
+
* Diberikan sebagai THUNK, bukan nilai: scheduler dibuat SESUDAH runtime, jadi
|
|
163
|
+
* faktanya baru diketahui saat dispatch. Thunk dibaca saat fakta dibutuhkan,
|
|
164
|
+
* bukan saat komposisi dibangun — nilai basi akan menyesatkan gerbang
|
|
165
|
+
* admission dengan alasan yang tak pernah benar.
|
|
166
|
+
*/
|
|
167
|
+
readonly taskLayerFacts?: () => TaskLayerFacts
|
|
168
|
+
readonly now?: () => number
|
|
169
|
+
/**
|
|
170
|
+
* Seam/test hook milik M3 (onShutdown/onClose). Composition tetap memanggil
|
|
171
|
+
* API publik host — tak ada mutasi state internal dari sini. Produksi tak
|
|
172
|
+
* mengeset ini; test memakainya untuk membuktikan fase drain dan kegagalan
|
|
173
|
+
* host.close() tidak merusak batas jurnal.
|
|
174
|
+
*/
|
|
175
|
+
readonly hostOptions?: RuntimeHostOptions
|
|
176
|
+
/**
|
|
177
|
+
* Seam checkpoint M11 (passthrough). M11 sendiri menandainya sebagai seam uji;
|
|
178
|
+
* di sini hanya diteruskan agar "durability-uncertain" bisa dibuktikan tanpa
|
|
179
|
+
* mencoret kontrak M11.
|
|
180
|
+
*/
|
|
181
|
+
readonly journalCheckpoint?: () => CheckpointResult
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Fase shutdown berurutan. Urutan = urutan eksekusi. */
|
|
185
|
+
export type RuntimeShutdownPhase =
|
|
186
|
+
| "admission-latch"
|
|
187
|
+
| "host-shutdown"
|
|
188
|
+
| "execution-drain"
|
|
189
|
+
| "process-cleanup"
|
|
190
|
+
| "event-drain"
|
|
191
|
+
| "journal-flush"
|
|
192
|
+
| "journal-close"
|
|
193
|
+
| "host-close"
|
|
194
|
+
|
|
195
|
+
/** Empat kondisi berbeda — tak semuanya "gagal", tak semuanya "sukses". */
|
|
196
|
+
export type RuntimeShutdownOutcome = "succeeded" | "uncertain" | "failed" | "skipped"
|
|
197
|
+
|
|
198
|
+
export interface RuntimeShutdownPhaseReport {
|
|
199
|
+
readonly phase: RuntimeShutdownPhase
|
|
200
|
+
readonly outcome: RuntimeShutdownOutcome
|
|
201
|
+
/** Detail ringkas untuk diagnosis (tanpa isi error yang bisa membocorkan data). */
|
|
202
|
+
readonly detail?: string
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
export interface RuntimeShutdownError {
|
|
206
|
+
readonly phase: RuntimeShutdownPhase
|
|
207
|
+
readonly error: unknown
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Eksekusi non-terminal milik runtime ini — dilaporkan, TAK PERNAH ditulis ulang. */
|
|
211
|
+
export interface OutstandingExecution {
|
|
212
|
+
readonly executionId: string
|
|
213
|
+
readonly state: ExecutionState
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export interface RuntimeShutdownResult {
|
|
217
|
+
/** True hanya bila tak ada fase "failed" (uncertain tetap.ok = true). */
|
|
218
|
+
readonly ok: boolean
|
|
219
|
+
readonly phases: readonly RuntimeShutdownPhaseReport[]
|
|
220
|
+
readonly errors: readonly RuntimeShutdownError[]
|
|
221
|
+
/** Latch admission sudah tertutup (monoton, tak pernah dibuka lagi). */
|
|
222
|
+
readonly admissionStopped: boolean
|
|
223
|
+
/** Non-terminal saat latch menutup (potret sebelum drain). */
|
|
224
|
+
readonly outstandingBefore: readonly OutstandingExecution[]
|
|
225
|
+
/** Non-terminal setelah barrier drain — inilah yang M12 tafsirkan nanti. */
|
|
226
|
+
readonly outstandingAfter: readonly OutstandingExecution[]
|
|
227
|
+
readonly trackedWork: {
|
|
228
|
+
readonly registered: number
|
|
229
|
+
readonly drained: number
|
|
230
|
+
readonly pending: number
|
|
231
|
+
}
|
|
232
|
+
readonly events: {
|
|
233
|
+
readonly drained: number
|
|
234
|
+
readonly pending: number
|
|
235
|
+
/** Event yang tiba SETELAH batas flush: ditolak eksplisit, tak pernah di-append. */
|
|
236
|
+
readonly rejectedAfterBarrier: number
|
|
237
|
+
}
|
|
238
|
+
readonly journal: {
|
|
239
|
+
readonly flush: FlushResult["status"] | "disabled"
|
|
240
|
+
readonly closed: boolean
|
|
241
|
+
}
|
|
242
|
+
readonly host: { readonly state: HostLifecycleState }
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
export interface RuntimeCompositionMetrics {
|
|
246
|
+
readonly closed: boolean
|
|
247
|
+
readonly admissionOpen: boolean
|
|
248
|
+
readonly host: ReturnType<RuntimeHost["metrics"]>
|
|
249
|
+
readonly kernel: KernelMetrics
|
|
250
|
+
readonly plane: EventPlaneMetrics
|
|
251
|
+
readonly journal: JournalMetrics | null
|
|
252
|
+
readonly bridge: DispatchMetrics
|
|
253
|
+
/** Append jurnal yang gagal/tidak terrekam (observasi, bukan keputusan). */
|
|
254
|
+
readonly journalAppendFailures: number
|
|
255
|
+
readonly pendingAppends: number
|
|
256
|
+
readonly trackedWork: number
|
|
257
|
+
readonly rejectedEventsAfterBarrier: number
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
export interface RuntimeComposition {
|
|
261
|
+
readonly sessionId: string
|
|
262
|
+
readonly workspaceCwd: string
|
|
263
|
+
/** Path yang diberikan caller; `journal` null berarti mode non-durable. */
|
|
264
|
+
readonly journalPath: string
|
|
265
|
+
readonly durable: boolean
|
|
266
|
+
readonly host: RuntimeHost
|
|
267
|
+
readonly kernel: ExecutionKernel
|
|
268
|
+
readonly plane: EventPlane
|
|
269
|
+
readonly journal: ExecutionJournal | null
|
|
270
|
+
readonly supervisor: Supervisor
|
|
271
|
+
/**
|
|
272
|
+
* Jalur ownership proses (P13.2). `null` = establishment GAGAL — runtime
|
|
273
|
+
* lalu degraded, bukan mengklaim sehat. Bukan "supervisi opsional diam-diam":
|
|
274
|
+
* kegagalan establishment terlihat di status runtime.
|
|
275
|
+
*/
|
|
276
|
+
readonly supervision: ProcessSupervision | null
|
|
277
|
+
/** Status supervision jujur (null = tak ada instance). */
|
|
278
|
+
supervisionStatus(): ProcessSupervisionStatus | null
|
|
279
|
+
/**
|
|
280
|
+
* [P13.3] Fakta kontrak runtime dari komposisi ini — SATU sumber untuk
|
|
281
|
+
* status surface DAN untuk gerbang admission.
|
|
282
|
+
*
|
|
283
|
+
* `taskLayer` menimpa fakta lapisan task bila pemanggil punya yang lebih
|
|
284
|
+
* baru (layer task tak bisa dibaca dari dalam komposisi).
|
|
285
|
+
*/
|
|
286
|
+
statusFacts(
|
|
287
|
+
taskLayer?: Partial<TaskLayerFacts> & { lastFlush?: RuntimeFlushReport | null },
|
|
288
|
+
): RuntimeFacts
|
|
289
|
+
readonly bridge: DispatchBridge
|
|
290
|
+
readonly recovery: RecoveryEngine
|
|
291
|
+
readonly backend: ExecutionBackend
|
|
292
|
+
/** Jalur admission tunggal: Scheduler/Recovery → M13 → composition ini. */
|
|
293
|
+
dispatch(
|
|
294
|
+
request: DispatchRequest,
|
|
295
|
+
refresh?: DispatchRefresh,
|
|
296
|
+
): ReturnType<DispatchBridge["dispatch"]>
|
|
297
|
+
/** Interpretasi evidence dari jurnal (M12); tidak menulis apa pun. */
|
|
298
|
+
recover(executionId: string, ctx: RecoveryContext): RecoveryResult
|
|
299
|
+
/**
|
|
300
|
+
* Daftarkan kerja in-flight milik runtime untuk eksekusi ini. Drain menunggu
|
|
301
|
+
* semua work terdaftar (bounded) sebelum event drain/flush. Wajib untuk execution
|
|
302
|
+
* yang boleh settle natural saat shutdown — tanpa ini, drain tak punya hak untuk menggantungkan diri (dan M12 yang menafsirkan
|
|
303
|
+
* eksekusi yang belum terminal). Returns untrack (idempoten).
|
|
304
|
+
*/
|
|
305
|
+
track(executionId: string, work: Promise<unknown>): () => void
|
|
306
|
+
/** Non-terminal milik runtime ini (observasi, bukan keputusan lifecycle). */
|
|
307
|
+
outstanding(): readonly OutstandingExecution[]
|
|
308
|
+
isAdmissionOpen(): boolean
|
|
309
|
+
flush(): Promise<RuntimeFlushReport>
|
|
310
|
+
/**
|
|
311
|
+
* Shutdown kanonik: admission latch → drain → flush → close, dengan hasil
|
|
312
|
+
* terstruktur. IDEMPOTEN dan CONCURRENCY-SAFE: panggilan kedua/menyejeng
|
|
313
|
+
* menerima promise & hasil yang SAMA (tak ada flush/close ganda).
|
|
314
|
+
*/
|
|
315
|
+
shutdown(): Promise<RuntimeShutdownResult>
|
|
316
|
+
/** Alias; hasil identik dengan shutdown() (satu lifecycle, bukan dua). */
|
|
317
|
+
close(): Promise<RuntimeShutdownResult>
|
|
318
|
+
/** Hasil shutdown terakhir, atau null bila belum ada. */
|
|
319
|
+
shutdownResult(): RuntimeShutdownResult | null
|
|
320
|
+
isClosed(): boolean
|
|
321
|
+
metrics(): RuntimeCompositionMetrics
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
const DEFAULT_DRAIN_TIMEOUT_MS = 5_000
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* [P1 M15] Intent id durable untuk satu keputusan dispatch.
|
|
328
|
+
*
|
|
329
|
+
* Satu fungsi, satu format — dipakai penulis (runner) DAN pembaca (dedupe M13),
|
|
330
|
+
* supaya "saya sudah menulis bukti" dan "saya melihat bukti itu" tak pernah
|
|
331
|
+
* berbeda definisi.
|
|
332
|
+
*/
|
|
333
|
+
export function dispatchIntentId(dispatchId: string): string {
|
|
334
|
+
return `dispatch:${dispatchId}`
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* Sumber kernel → label event M10. Pemetaan TIDAK bijective dan itu disengaja:
|
|
339
|
+
* label yang tak ada padanannya jatuh ke "kernel" (label committer yang benar)
|
|
340
|
+
* alih-alih mengarang label yang menyiratkan asal lain. Provenance asli tetap
|
|
341
|
+
* di record kernel + journal (lihat catatan di kepala berkas).
|
|
342
|
+
*/
|
|
343
|
+
function eventSourceFor(source: TransitionRequestSource): EventSource {
|
|
344
|
+
switch (source) {
|
|
345
|
+
case "host":
|
|
346
|
+
case "scheduler":
|
|
347
|
+
case "backend":
|
|
348
|
+
case "agent-loop":
|
|
349
|
+
case "supervisor":
|
|
350
|
+
case "test":
|
|
351
|
+
return source === "agent-loop" ? "agent" : source
|
|
352
|
+
default:
|
|
353
|
+
return "kernel"
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
interface TrackedWork {
|
|
358
|
+
readonly executionId: string
|
|
359
|
+
readonly promise: Promise<unknown>
|
|
360
|
+
settled: boolean
|
|
361
|
+
error: unknown
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
export function createRuntimeComposition(opts: RuntimeCompositionOptions): RuntimeComposition {
|
|
365
|
+
// ── validasi identitas (fail-closed; tak ada tebakan) ──────────────────────
|
|
366
|
+
if (!opts || typeof opts !== "object") throw new Error("composition: options object is required")
|
|
367
|
+
if (typeof opts.sessionId !== "string" || opts.sessionId.length === 0)
|
|
368
|
+
throw new Error("composition: sessionId is required and must not be derived here")
|
|
369
|
+
if (typeof opts.workspaceCwd !== "string" || opts.workspaceCwd.length === 0)
|
|
370
|
+
throw new Error("composition: workspaceCwd is required")
|
|
371
|
+
if (typeof opts.journalPath !== "string" || opts.journalPath.length === 0)
|
|
372
|
+
throw new Error("composition: journalPath is required (no global default)")
|
|
373
|
+
if (opts.journalPath.includes("\0"))
|
|
374
|
+
throw new Error("composition: journalPath must not contain NUL")
|
|
375
|
+
|
|
376
|
+
const journalRequired = opts.journalRequired !== false
|
|
377
|
+
const drainTimeoutMs =
|
|
378
|
+
typeof opts.drainTimeoutMs === "number" && opts.drainTimeoutMs >= 0
|
|
379
|
+
? opts.drainTimeoutMs
|
|
380
|
+
: DEFAULT_DRAIN_TIMEOUT_MS
|
|
381
|
+
const now = opts.now ?? Date.now
|
|
382
|
+
|
|
383
|
+
// ── konstruksi komponen (urutan = urutan ketergantungan) ──────────────────
|
|
384
|
+
const backendKind = opts.backend ?? "host"
|
|
385
|
+
const factory = BACKEND_FACTORIES[backendKind]
|
|
386
|
+
if (!factory) throw new Error(`composition: unknown backend "${String(backendKind)}"`)
|
|
387
|
+
const backend = factory()
|
|
388
|
+
const plane = createEventPlane()
|
|
389
|
+
const kernel = createExecutionKernel()
|
|
390
|
+
const supervisor = createSupervisor({
|
|
391
|
+
kernel,
|
|
392
|
+
backend,
|
|
393
|
+
...(opts.supervisorPolicy ? { policy: opts.supervisorPolicy } : {}),
|
|
394
|
+
now,
|
|
395
|
+
})
|
|
396
|
+
const recovery = createRecoveryEngine()
|
|
397
|
+
const host = createRuntimeHost(opts.hostOptions ?? {})
|
|
398
|
+
host.start()
|
|
399
|
+
|
|
400
|
+
// ── P13.2: jalur ownership proses ──────────────────────────────────────────
|
|
401
|
+
// Satu registry anak milik runtime ini. Kegagalan establishment TIDAK
|
|
402
|
+
// mematikan runtime (runtime tanpa supervisi masih berguna), TAPI ia
|
|
403
|
+
// menurunkan status runtime ke DEGRADED — jadi tak ada klaim "sehat" atau
|
|
404
|
+
// "disupervisi" yang tak benar.
|
|
405
|
+
let supervision: ProcessSupervision | null = null
|
|
406
|
+
let supervisionEstablishmentFailed = false
|
|
407
|
+
try {
|
|
408
|
+
const supervisionFactory =
|
|
409
|
+
opts.processSupervisionFactory ??
|
|
410
|
+
(() =>
|
|
411
|
+
createProcessSupervision({
|
|
412
|
+
...(opts.processSupervisionPolicy ? { policy: opts.processSupervisionPolicy } : {}),
|
|
413
|
+
now,
|
|
414
|
+
}))
|
|
415
|
+
supervision = supervisionFactory()
|
|
416
|
+
} catch {
|
|
417
|
+
supervision = null
|
|
418
|
+
supervisionEstablishmentFailed = true
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// ── journal (fail-closed) ──────────────────────────────────────────────────
|
|
422
|
+
let journal: ExecutionJournal | null = null
|
|
423
|
+
if (journalRequired) {
|
|
424
|
+
journal = openExecutionJournal(
|
|
425
|
+
opts.journalPath,
|
|
426
|
+
opts.journalCheckpoint ? { checkpoint: opts.journalCheckpoint } : {},
|
|
427
|
+
)
|
|
428
|
+
if (!journal.isOpen()) {
|
|
429
|
+
// Konstruksi gagal dan host tak boleh tertinggal READY di belakang objek
|
|
430
|
+
// yang tak pernah dikembalikan. Nutup dulu, baru lempar.
|
|
431
|
+
try {
|
|
432
|
+
void host.shutdown()
|
|
433
|
+
} catch {}
|
|
434
|
+
try {
|
|
435
|
+
void host.close()
|
|
436
|
+
} catch {}
|
|
437
|
+
throw new Error("composition: journal failed to open (fail-closed; no silent null journal)")
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
// ── latch + barrier (satu boolean monoton; BUKAN state machine) ────────────
|
|
442
|
+
let admissionOpen = true
|
|
443
|
+
/** true setelah flush terakhir: hook berhenti append (tak ada append pasca-flush). */
|
|
444
|
+
let durabilityBarrierPassed = false
|
|
445
|
+
let rejectedAfterBarrier = 0
|
|
446
|
+
|
|
447
|
+
/** Eksekusi yang runtime ini admit sendiri (satu-satunya lifecycle yang "dimiliki"). */
|
|
448
|
+
const ownedExecutions = new Set<string>()
|
|
449
|
+
const trackedWork = new Set<TrackedWork>()
|
|
450
|
+
|
|
451
|
+
// ── kernel commit → plane (observasi) + journal (history) ─────────────────
|
|
452
|
+
// Hook ini PASIF: ia tidak menolak, tidak memperbaiki, tidak memutar balik.
|
|
453
|
+
// Kegagalan append = metrik + durability-uncertain saat flush, tak pernah
|
|
454
|
+
// "hapus event supaya tampak bersih" (M11 yang memutuskan, bukan sini).
|
|
455
|
+
const pendingAppends = new Set<Promise<unknown>>()
|
|
456
|
+
// Penghitung eksplisit (bukan `pending.size`): urutan microtask `.finally`
|
|
457
|
+
// tak perlu ditebak untuk tahu berapa append yang benar-benar mendarat.
|
|
458
|
+
let settledAppends = 0
|
|
459
|
+
let appendFailures = 0
|
|
460
|
+
const unsubscribeKernel = kernel.onTransition((t) => {
|
|
461
|
+
try {
|
|
462
|
+
const record = kernel.get(t.executionId)
|
|
463
|
+
const event = executionEventFromCommit(
|
|
464
|
+
plane,
|
|
465
|
+
{
|
|
466
|
+
executionId: t.executionId,
|
|
467
|
+
...(record?.parentExecutionId ? { parentExecutionId: record.parentExecutionId } : {}),
|
|
468
|
+
rootExecutionId: record?.rootExecutionId ?? t.executionId,
|
|
469
|
+
version: record?.version ?? 0,
|
|
470
|
+
from: t.from,
|
|
471
|
+
to: t.to,
|
|
472
|
+
reason: t.reason,
|
|
473
|
+
source: t.source,
|
|
474
|
+
},
|
|
475
|
+
{ source: eventSourceFor(t.source), timestamp: t.at },
|
|
476
|
+
)
|
|
477
|
+
// Barrier durability: setelah flush terakhir, event TIDAK di-append dan
|
|
478
|
+
// jurnal tak pernah dibuka ulang. Dihitung eksplisit (bukan "hilang diam").
|
|
479
|
+
if (durabilityBarrierPassed) {
|
|
480
|
+
rejectedAfterBarrier++
|
|
481
|
+
return
|
|
482
|
+
}
|
|
483
|
+
if (!journal) return
|
|
484
|
+
const appended: Promise<unknown> = journal
|
|
485
|
+
.appendEvent(event)
|
|
486
|
+
.then((r) => {
|
|
487
|
+
if (r.status === "error") appendFailures++
|
|
488
|
+
})
|
|
489
|
+
.catch(() => {
|
|
490
|
+
appendFailures++
|
|
491
|
+
})
|
|
492
|
+
.then(() => {
|
|
493
|
+
settledAppends++
|
|
494
|
+
})
|
|
495
|
+
pendingAppends.add(appended)
|
|
496
|
+
void appended.finally(() => {
|
|
497
|
+
pendingAppends.delete(appended)
|
|
498
|
+
})
|
|
499
|
+
} catch {
|
|
500
|
+
// Observasi tak boleh menjatuhkan commit kernel yang sudah sah.
|
|
501
|
+
}
|
|
502
|
+
})
|
|
503
|
+
|
|
504
|
+
// ── admission: SATU-SATUNYA jalan dari bridge ke runtime ───────────────────
|
|
505
|
+
// admitted ⇔ kernel punya record ADMITTED. Gagal = reason jujur ke M13 supaya
|
|
506
|
+
// state dispatch-nya benar (BLOCKED/REJECTED), bukan "sukses".
|
|
507
|
+
// Latch diperiksa LEBIH DALAM dari hostState: jeda antara latch composition dan
|
|
508
|
+
// host.shutdown() itu async, jadi satu-satunya cara Deterministik menutup
|
|
509
|
+
// admission adalah memeriksa latch itu sendiri.
|
|
510
|
+
const bridge = createDispatchBridge({
|
|
511
|
+
admission: {
|
|
512
|
+
admit: (req) => {
|
|
513
|
+
if (!admissionOpen)
|
|
514
|
+
return { admitted: false, reason: "runtime admission closed (shutdown latch)" }
|
|
515
|
+
try {
|
|
516
|
+
const record = kernel.create({
|
|
517
|
+
executionId: req.executionId,
|
|
518
|
+
...(req.parentExecutionId ? { parentExecutionId: req.parentExecutionId } : {}),
|
|
519
|
+
rootExecutionId: req.lineageRootId,
|
|
520
|
+
kind: req.kind,
|
|
521
|
+
ownerId: req.ownerId,
|
|
522
|
+
})
|
|
523
|
+
const result = kernel.requestTransition({
|
|
524
|
+
executionId: record.executionId,
|
|
525
|
+
to: "ADMITTED",
|
|
526
|
+
reason: "dispatch-admission",
|
|
527
|
+
source: "host",
|
|
528
|
+
})
|
|
529
|
+
if (!result.committed)
|
|
530
|
+
return { admitted: false, reason: `kernel refused admission (${result.outcome})` }
|
|
531
|
+
ownedExecutions.add(record.executionId)
|
|
532
|
+
return { admitted: true, executionId: record.executionId }
|
|
533
|
+
} catch (e) {
|
|
534
|
+
return {
|
|
535
|
+
admitted: false,
|
|
536
|
+
reason: (e instanceof Error ? e.message : String(e)).slice(0, 120),
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
},
|
|
540
|
+
},
|
|
541
|
+
hostState: () => host.state(),
|
|
542
|
+
// [P1 M15] Bukti durable untuk dedupe lintas-restart: M13 hanya memakai
|
|
543
|
+
// jawaban "admitted" bila caller menyatakan redelivery (`redelivered: true`),
|
|
544
|
+
// dan JURNAL M11 adalah satu-satunya sumber kebenaran itu. Tanpa lookup →
|
|
545
|
+
// M13 jatuh ke UNCERTAIN_DUPLICATE (konservatif), bukan menebak.
|
|
546
|
+
historyLookup: (dispatchId: string) => {
|
|
547
|
+
if (!journal) return "unknown"
|
|
548
|
+
return journal
|
|
549
|
+
.readAll()
|
|
550
|
+
.some((r) => r.kind === "intent" && r.intentId === dispatchIntentId(dispatchId))
|
|
551
|
+
? ("admitted" as const)
|
|
552
|
+
: ("unknown" as const)
|
|
553
|
+
},
|
|
554
|
+
now,
|
|
555
|
+
})
|
|
556
|
+
|
|
557
|
+
let closed = false
|
|
558
|
+
let shutdownPromise: Promise<RuntimeShutdownResult> | null = null
|
|
559
|
+
let shutdownReport: RuntimeShutdownResult | null = null
|
|
560
|
+
|
|
561
|
+
function outstanding(): OutstandingExecution[] {
|
|
562
|
+
const out: OutstandingExecution[] = []
|
|
563
|
+
for (const executionId of ownedExecutions) {
|
|
564
|
+
const record = kernel.get(executionId)
|
|
565
|
+
if (record && !isExecutionTerminalState(record.state))
|
|
566
|
+
out.push({ executionId, state: record.state })
|
|
567
|
+
}
|
|
568
|
+
return out.sort((a, b) => (a.executionId < b.executionId ? -1 : 1))
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
/** Tunggu append yang jalan; ulangi bila append BARU muncul selama drain. */
|
|
572
|
+
async function drainAppends(budgetMs: number): Promise<{ drained: number; pending: number }> {
|
|
573
|
+
const settledBefore = settledAppends
|
|
574
|
+
const deadline = Date.now() + budgetMs
|
|
575
|
+
while (pendingAppends.size > 0) {
|
|
576
|
+
const remaining = deadline - Date.now()
|
|
577
|
+
if (remaining <= 0) break
|
|
578
|
+
const batch = [...pendingAppends]
|
|
579
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
580
|
+
const bounded = new Promise<void>((resolve) => {
|
|
581
|
+
timer = setTimeout(resolve, remaining)
|
|
582
|
+
timer.unref?.()
|
|
583
|
+
})
|
|
584
|
+
await Promise.race([Promise.allSettled(batch).then(() => undefined), bounded])
|
|
585
|
+
if (timer) clearTimeout(timer)
|
|
586
|
+
}
|
|
587
|
+
return { drained: settledAppends - settledBefore, pending: pendingAppends.size }
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
/** Tunggu kerja yang di-track runtime (bounded). Error kerja dikembalikan apa adanya. */
|
|
591
|
+
async function drainTrackedWork(budgetMs: number): Promise<{
|
|
592
|
+
registered: number
|
|
593
|
+
drained: number
|
|
594
|
+
pending: number
|
|
595
|
+
errors: unknown[]
|
|
596
|
+
}> {
|
|
597
|
+
const entries = [...trackedWork]
|
|
598
|
+
if (entries.length === 0) return { registered: 0, drained: 0, pending: 0, errors: [] }
|
|
599
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
600
|
+
const bounded = new Promise<void>((resolve) => {
|
|
601
|
+
timer = setTimeout(resolve, budgetMs)
|
|
602
|
+
timer.unref?.()
|
|
603
|
+
})
|
|
604
|
+
await Promise.race([
|
|
605
|
+
Promise.allSettled(entries.map((e) => e.promise)).then(() => undefined),
|
|
606
|
+
bounded,
|
|
607
|
+
])
|
|
608
|
+
if (timer) clearTimeout(timer)
|
|
609
|
+
const pendingEntries = entries.filter((e) => !e.settled)
|
|
610
|
+
return {
|
|
611
|
+
registered: entries.length,
|
|
612
|
+
drained: entries.length - pendingEntries.length,
|
|
613
|
+
pending: pendingEntries.length,
|
|
614
|
+
errors: entries.map((e) => e.error).filter((e) => e !== null && e !== undefined),
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
async function runShutdown(): Promise<RuntimeShutdownResult> {
|
|
619
|
+
const phases: RuntimeShutdownPhaseReport[] = []
|
|
620
|
+
const errors: RuntimeShutdownError[] = []
|
|
621
|
+
const phase = (
|
|
622
|
+
name: RuntimeShutdownPhase,
|
|
623
|
+
outcome: RuntimeShutdownOutcome,
|
|
624
|
+
detail?: string,
|
|
625
|
+
) => {
|
|
626
|
+
phases.push({ phase: name, outcome, ...(detail !== undefined ? { detail } : {}) })
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
// ── 1. admission latch (monoton; inline, sebelum semua yang async) ────────
|
|
630
|
+
admissionOpen = false
|
|
631
|
+
phase("admission-latch", "succeeded", "admission closed (monotonic)")
|
|
632
|
+
|
|
633
|
+
const outstandingBefore = outstanding()
|
|
634
|
+
|
|
635
|
+
// ── 2. host.shutdown(): latch admitting/run + hook onShutdown (owner stop) ─
|
|
636
|
+
const hookFailuresBefore = host.metrics().host.hookFailures
|
|
637
|
+
try {
|
|
638
|
+
await host.shutdown()
|
|
639
|
+
const degraded = host.metrics().host.hookFailures > hookFailuresBefore
|
|
640
|
+
phase(
|
|
641
|
+
"host-shutdown",
|
|
642
|
+
degraded ? "uncertain" : "succeeded",
|
|
643
|
+
degraded
|
|
644
|
+
? "onShutdown hook failed (host degraded, stays DRAINING; journal still handled)"
|
|
645
|
+
: `host=${host.state()}`,
|
|
646
|
+
)
|
|
647
|
+
} catch (e) {
|
|
648
|
+
phase("host-shutdown", "failed", (e instanceof Error ? e.message : String(e)).slice(0, 160))
|
|
649
|
+
errors.push({ phase: "host-shutdown", error: e })
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
// ── 3. execution drain: kerja in-flight yang di-track + barrier ────────────
|
|
653
|
+
// Eksekusi non-terminal TAK diubah state-nya di sini: shutdown tak pernah
|
|
654
|
+
// mengarang COMPLETED/CANCELLED. Yang draining adalah kerja in-flight-nya.
|
|
655
|
+
const tracked = await drainTrackedWork(drainTimeoutMs)
|
|
656
|
+
|
|
657
|
+
// R1 (P9.0): pembersihan record backend milik komposisi INI — satu-kali di
|
|
658
|
+
// shutdown, BUKAN sweeper (tanpa timer, tanpa siklus, tak menyentuh instance
|
|
659
|
+
// backend lain). Drain kerja terlacak sudah selesai, jadi tak ada konsumen
|
|
660
|
+
// sah yang masih menunggu hasil; record sisa (pemanggilnya tak pernah
|
|
661
|
+
// dispose) dibebaskan sekarang: kill best-effort anti-yatim untuk proses
|
|
662
|
+
// yang masih hidup + waiter in-flight diselesaikan jujur "disposed".
|
|
663
|
+
// Kepemilikan dispose per-handle TETAP di pemanggil yang memulai eksekusi —
|
|
664
|
+
// ini jaring pengaman batas-umur-proses di batas komposisi saja.
|
|
665
|
+
const backendDisposed = backend.disposeAll()
|
|
666
|
+
|
|
667
|
+
if (tracked.errors.length > 0) {
|
|
668
|
+
phase(
|
|
669
|
+
"execution-drain",
|
|
670
|
+
"failed",
|
|
671
|
+
`${tracked.errors.length} tracked work rejected · backendDisposed=${backendDisposed.disposed}`,
|
|
672
|
+
)
|
|
673
|
+
for (const error of tracked.errors) errors.push({ phase: "execution-drain", error })
|
|
674
|
+
} else if (tracked.pending > 0) {
|
|
675
|
+
phase(
|
|
676
|
+
"execution-drain",
|
|
677
|
+
"uncertain",
|
|
678
|
+
`${tracked.pending}/${tracked.registered} tracked work unfinished at ${drainTimeoutMs}ms · backendDisposed=${backendDisposed.disposed}`,
|
|
679
|
+
)
|
|
680
|
+
} else {
|
|
681
|
+
phase(
|
|
682
|
+
"execution-drain",
|
|
683
|
+
"succeeded",
|
|
684
|
+
`tracked=${tracked.registered} outstanding=${outstandingBefore.length} · backendDisposed=${backendDisposed.disposed}`,
|
|
685
|
+
)
|
|
686
|
+
}
|
|
687
|
+
const outstandingAfter = outstanding()
|
|
688
|
+
|
|
689
|
+
// ── 3b. process cleanup (P13.2): anak yang dikelola DIHENTIKAN dan
|
|
690
|
+
// ditunggu. Posisi: SESUDAH drain kerja terlacak (kerja in-flight tak
|
|
691
|
+
// diganggu) dan SEBELUM flush jurnal (kematian anak tercatat di history).
|
|
692
|
+
// "Tidak ada child yang terlepas" hanya bisa diklaim bila shutdown
|
|
693
|
+
// MENUNGGU anak berhenti — bukan hanya drop record.
|
|
694
|
+
if (supervision) {
|
|
695
|
+
try {
|
|
696
|
+
const cleaned = await supervision.shutdown()
|
|
697
|
+
phase(
|
|
698
|
+
"process-cleanup",
|
|
699
|
+
cleaned.failed > 0 ? "uncertain" : "succeeded",
|
|
700
|
+
`stopped=${cleaned.stopped} failed=${cleaned.failed}`,
|
|
701
|
+
)
|
|
702
|
+
} catch (e) {
|
|
703
|
+
phase(
|
|
704
|
+
"process-cleanup",
|
|
705
|
+
"failed",
|
|
706
|
+
(e instanceof Error ? e.message : String(e)).slice(0, 160),
|
|
707
|
+
)
|
|
708
|
+
errors.push({ phase: "process-cleanup", error: e })
|
|
709
|
+
}
|
|
710
|
+
} else {
|
|
711
|
+
phase(
|
|
712
|
+
"process-cleanup",
|
|
713
|
+
"skipped",
|
|
714
|
+
supervisionEstablishmentFailed
|
|
715
|
+
? "supervisi tak established (runtime degraded, bukan klaim sehat)"
|
|
716
|
+
: "tak ada supervisi terpasang",
|
|
717
|
+
)
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
// ── 4. event delivery drain (M10 sinkron; M11 append async) ──────────────
|
|
721
|
+
const events = await drainAppends(drainTimeoutMs)
|
|
722
|
+
phase(
|
|
723
|
+
"event-drain",
|
|
724
|
+
events.pending > 0 ? "uncertain" : "succeeded",
|
|
725
|
+
`drained=${events.drained} pending=${events.pending} rejectedAfterBarrier=${rejectedAfterBarrier}`,
|
|
726
|
+
)
|
|
727
|
+
|
|
728
|
+
// ── 5. barrier + journal flush = batas durability TERAKHIR ─────────────────
|
|
729
|
+
// BARRIER DULU, sebelum flush(): dari titik ini tak ada append baru yang
|
|
730
|
+
// mulai — sehingga mustahil ada event yang committed SETELAH batas
|
|
731
|
+
// durability (data pascabatas = klaim palsu "durable-confirmed"). Jeda
|
|
732
|
+
// antara drain dan baris ini sinkron, jadi tak ada user code yang bisa
|
|
733
|
+
// menyisipkan commit di antaranya.
|
|
734
|
+
durabilityBarrierPassed = true
|
|
735
|
+
let flushStatus: FlushResult["status"] | "disabled" = "disabled"
|
|
736
|
+
if (!journal) {
|
|
737
|
+
phase("journal-flush", "skipped", "non-durable mode (no journal)")
|
|
738
|
+
} else {
|
|
739
|
+
const flushed = journal.flush()
|
|
740
|
+
flushStatus = flushed.status
|
|
741
|
+
const outcome: RuntimeShutdownOutcome =
|
|
742
|
+
flushed.status === "durable-confirmed"
|
|
743
|
+
? "succeeded"
|
|
744
|
+
: flushed.status === "durability-uncertain"
|
|
745
|
+
? "uncertain"
|
|
746
|
+
: "failed"
|
|
747
|
+
phase("journal-flush", outcome, flushed.status)
|
|
748
|
+
if (flushed.status !== "durable-confirmed")
|
|
749
|
+
errors.push({ phase: "journal-flush", error: flushed })
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
// ── 6. journal close (SATU pemilik: composition) ─────────────────────────
|
|
753
|
+
let journalClosed = false
|
|
754
|
+
if (!journal) {
|
|
755
|
+
phase("journal-close", "skipped", "non-durable mode (no journal)")
|
|
756
|
+
} else {
|
|
757
|
+
try {
|
|
758
|
+
journal.close()
|
|
759
|
+
// M11 close() tak melempar (idempoten) → verifikasi via post-condition,
|
|
760
|
+
// bukan "tidak ada exception = sukses".
|
|
761
|
+
journalClosed = !journal.isOpen()
|
|
762
|
+
phase(
|
|
763
|
+
"journal-close",
|
|
764
|
+
journalClosed ? "succeeded" : "failed",
|
|
765
|
+
journalClosed ? "closed after flush" : "still open after close()",
|
|
766
|
+
)
|
|
767
|
+
if (!journalClosed)
|
|
768
|
+
errors.push({
|
|
769
|
+
phase: "journal-close",
|
|
770
|
+
error: new Error("journal still open after close"),
|
|
771
|
+
})
|
|
772
|
+
} catch (e) {
|
|
773
|
+
phase("journal-close", "failed", (e instanceof Error ? e.message : String(e)).slice(0, 160))
|
|
774
|
+
errors.push({ phase: "journal-close", error: e })
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
// ── 7. host close TERAKHIR (host tak memegang jurnal; durability sudah aman) ─
|
|
779
|
+
try {
|
|
780
|
+
await host.close()
|
|
781
|
+
phase(
|
|
782
|
+
"host-close",
|
|
783
|
+
host.state() === "CLOSED" ? "succeeded" : "failed",
|
|
784
|
+
`host=${host.state()}`,
|
|
785
|
+
)
|
|
786
|
+
if (host.state() !== "CLOSED")
|
|
787
|
+
errors.push({ phase: "host-close", error: new Error(`host not CLOSED (${host.state()})`) })
|
|
788
|
+
} catch (e) {
|
|
789
|
+
// Host M3 melempar bila hook onClose gagal — meski state sudah CLOSED.
|
|
790
|
+
phase("host-close", "failed", (e instanceof Error ? e.message : String(e)).slice(0, 160))
|
|
791
|
+
errors.push({ phase: "host-close", error: e })
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
closed = true
|
|
795
|
+
// Hook dilepas sebagai langkah TERAKHIR: commit selama drain tetap terekam
|
|
796
|
+
// (append-nya ikut ter-drain di fase 4), sementara commit yang datang
|
|
797
|
+
// sesudah barrier durability sudah ditolak eksplisit di atas (dihitung,
|
|
798
|
+
// bukan dibuang diam-diam).
|
|
799
|
+
try {
|
|
800
|
+
unsubscribeKernel()
|
|
801
|
+
} catch {}
|
|
802
|
+
const result: RuntimeShutdownResult = Object.freeze({
|
|
803
|
+
ok: !phases.some((p) => p.outcome === "failed"),
|
|
804
|
+
phases: Object.freeze(phases.slice()),
|
|
805
|
+
errors: Object.freeze(errors.slice()),
|
|
806
|
+
admissionStopped: true,
|
|
807
|
+
outstandingBefore: Object.freeze(outstandingBefore.slice()),
|
|
808
|
+
outstandingAfter: Object.freeze(outstandingAfter.slice()),
|
|
809
|
+
trackedWork: Object.freeze({
|
|
810
|
+
registered: tracked.registered,
|
|
811
|
+
drained: tracked.drained,
|
|
812
|
+
pending: tracked.pending,
|
|
813
|
+
}),
|
|
814
|
+
events: Object.freeze({ ...events, rejectedAfterBarrier }),
|
|
815
|
+
journal: Object.freeze({ flush: flushStatus, closed: journalClosed }),
|
|
816
|
+
host: Object.freeze({ state: host.state() }),
|
|
817
|
+
})
|
|
818
|
+
shutdownReport = result
|
|
819
|
+
return result
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
const api: RuntimeComposition = {
|
|
823
|
+
sessionId: opts.sessionId,
|
|
824
|
+
workspaceCwd: opts.workspaceCwd,
|
|
825
|
+
journalPath: opts.journalPath,
|
|
826
|
+
durable: journal !== null,
|
|
827
|
+
|
|
828
|
+
host,
|
|
829
|
+
kernel,
|
|
830
|
+
plane,
|
|
831
|
+
journal,
|
|
832
|
+
supervisor,
|
|
833
|
+
supervision,
|
|
834
|
+
bridge,
|
|
835
|
+
recovery,
|
|
836
|
+
backend,
|
|
837
|
+
|
|
838
|
+
supervisionStatus(): ProcessSupervisionStatus | null {
|
|
839
|
+
return supervision ? supervision.status() : null
|
|
840
|
+
},
|
|
841
|
+
|
|
842
|
+
statusFacts(
|
|
843
|
+
taskLayer?: Partial<TaskLayerFacts> & { lastFlush?: RuntimeFlushReport | null },
|
|
844
|
+
): RuntimeFacts {
|
|
845
|
+
const metrics = api.metrics()
|
|
846
|
+
const supervisionStatus = supervision ? supervision.status() : null
|
|
847
|
+
// Fakta lapisan task: argumen pemanggil menang (lebih baru), kalau tak ada
|
|
848
|
+
// argumen, thunk komposisi dibaca (nilai paling dekat ke saat dispatch).
|
|
849
|
+
const base = opts.taskLayerFacts?.() ?? null
|
|
850
|
+
return runtimeFactsFrom({
|
|
851
|
+
enabled: true,
|
|
852
|
+
constructed: true,
|
|
853
|
+
closed,
|
|
854
|
+
admissionOpen: admissionOpen,
|
|
855
|
+
durable: journal !== null,
|
|
856
|
+
journalAppendFailures: metrics.journalAppendFailures,
|
|
857
|
+
pendingJournalAppends: metrics.pendingAppends,
|
|
858
|
+
supervisionEstablished: supervisionStatus !== null,
|
|
859
|
+
supervisorAttached: supervisionStatus?.operational === true,
|
|
860
|
+
supervisedChildren: supervisionStatus?.managed ?? 0,
|
|
861
|
+
schedulerAttached: taskLayer?.schedulerAttached ?? base?.schedulerAttached ?? null,
|
|
862
|
+
storeOpen: taskLayer?.storeOpen ?? base?.storeOpen ?? null,
|
|
863
|
+
...(taskLayer?.lastFlush !== undefined ? { lastFlush: taskLayer.lastFlush } : {}),
|
|
864
|
+
})
|
|
865
|
+
},
|
|
866
|
+
|
|
867
|
+
dispatch(request, refresh) {
|
|
868
|
+
if (!admissionOpen)
|
|
869
|
+
throw new Error("composition: dispatch refused — admission latch closed (shutdown)")
|
|
870
|
+
return bridge.dispatch(request, refresh)
|
|
871
|
+
},
|
|
872
|
+
|
|
873
|
+
recover(executionId, ctx) {
|
|
874
|
+
// Bukti = history jurnal (M11), bukan state in-memory: interpretasi harus
|
|
875
|
+
// bisa dilakukan ulang setelah restart dengan hasil yang sama.
|
|
876
|
+
const records: readonly JournalRecord[] = journal
|
|
877
|
+
? journal.readExecutionHistory(executionId)
|
|
878
|
+
: []
|
|
879
|
+
return recovery.recoverExecution(executionId, records, ctx)
|
|
880
|
+
},
|
|
881
|
+
|
|
882
|
+
track(executionId: string, work: Promise<unknown>): () => void {
|
|
883
|
+
if (!admissionOpen)
|
|
884
|
+
throw new Error("composition: track() refused — admission latch closed (shutdown)")
|
|
885
|
+
if (typeof executionId !== "string" || executionId.length === 0)
|
|
886
|
+
throw new Error("composition: track() requires executionId")
|
|
887
|
+
if (!work || typeof (work as Promise<unknown>).then !== "function")
|
|
888
|
+
throw new Error("composition: track() requires a promise")
|
|
889
|
+
const entry: TrackedWork = {
|
|
890
|
+
executionId,
|
|
891
|
+
settled: false,
|
|
892
|
+
error: null,
|
|
893
|
+
promise: Promise.resolve(work).then(
|
|
894
|
+
() => {
|
|
895
|
+
entry.settled = true
|
|
896
|
+
},
|
|
897
|
+
(e) => {
|
|
898
|
+
entry.settled = true
|
|
899
|
+
entry.error = e
|
|
900
|
+
},
|
|
901
|
+
),
|
|
902
|
+
}
|
|
903
|
+
trackedWork.add(entry)
|
|
904
|
+
return () => {
|
|
905
|
+
trackedWork.delete(entry)
|
|
906
|
+
}
|
|
907
|
+
},
|
|
908
|
+
|
|
909
|
+
outstanding,
|
|
910
|
+
|
|
911
|
+
isAdmissionOpen: () => admissionOpen,
|
|
912
|
+
|
|
913
|
+
async flush(): Promise<RuntimeFlushReport> {
|
|
914
|
+
const drained = await drainAppends(drainTimeoutMs)
|
|
915
|
+
if (!journal)
|
|
916
|
+
return { journal: "disabled", drained: drained.drained, unfinished: drained.pending }
|
|
917
|
+
const flushed = journal.flush()
|
|
918
|
+
return {
|
|
919
|
+
journal: flushed.status,
|
|
920
|
+
drained: drained.drained,
|
|
921
|
+
unfinished: drained.pending,
|
|
922
|
+
}
|
|
923
|
+
},
|
|
924
|
+
|
|
925
|
+
shutdown(): Promise<RuntimeShutdownResult> {
|
|
926
|
+
// Idempoten + concurrency-safe: satu promise untuk semua pemanggil, dan
|
|
927
|
+
// tak ada flush/close kedua yang bisa balapan dengan yang pertama.
|
|
928
|
+
if (!shutdownPromise) shutdownPromise = runShutdown()
|
|
929
|
+
return shutdownPromise
|
|
930
|
+
},
|
|
931
|
+
|
|
932
|
+
close(): Promise<RuntimeShutdownResult> {
|
|
933
|
+
return api.shutdown()
|
|
934
|
+
},
|
|
935
|
+
|
|
936
|
+
shutdownResult(): RuntimeShutdownResult | null {
|
|
937
|
+
return shutdownReport
|
|
938
|
+
},
|
|
939
|
+
|
|
940
|
+
isClosed: () => closed,
|
|
941
|
+
|
|
942
|
+
metrics: () => ({
|
|
943
|
+
closed,
|
|
944
|
+
admissionOpen,
|
|
945
|
+
host: host.metrics(),
|
|
946
|
+
kernel: kernel.metrics(),
|
|
947
|
+
plane: plane.metrics(),
|
|
948
|
+
journal: journal ? journal.metrics() : null,
|
|
949
|
+
bridge: bridge.metrics(),
|
|
950
|
+
journalAppendFailures: appendFailures,
|
|
951
|
+
pendingAppends: pendingAppends.size,
|
|
952
|
+
trackedWork: trackedWork.size,
|
|
953
|
+
rejectedEventsAfterBarrier: rejectedAfterBarrier,
|
|
954
|
+
}),
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
return api
|
|
958
|
+
}
|