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,477 @@
1
+ // M12 — Recovery & reconciliation: INTERPRETASI bukti durable, BUKAN authority.
2
+ //
3
+ // Kenapa berkas ini ada (P1 M12): jurnal M11 menyimpan history; seseorang harus
4
+ // memutuskan arti history itu (UNKNOWN? aman redispatch? butuh verifier?) TANPA
5
+ // menjadi lifecycle authority kedua. Modul ini adalah interpreter itu: membaca
6
+ // evidence (via API M11, tanpa SQL langsung), menghasilkan RecoveryResult/
7
+ // RecoveryPlan, dan (bila dibenarkan) membangun request Kernel yang divalidasi
8
+ // + di-commit Kernel — tak pernah mutasi langsung.
9
+ //
10
+ // Rantai yang dikunci (jangan dibalik tanpa ADR baru):
11
+ // Journal (evidence) → M12 interpretasi → decision/plan → Kernel request →
12
+ // Kernel validasi + commit. M12 TAK PERNAH menulis state, claim, schedule,
13
+ // journal, atau redispatch aktual (plan ≠ eksekusi).
14
+ // - UNKNOWN first-class: bukti kurang = UNKNOWN (bukan FAILED, bukan aman).
15
+ // - Predicate redispatch SATU (recovery-safety.ts): M9 konsumen mekanis, M12
16
+ // konsumen semantik — tanpa fork.
17
+ // - Terminal Kernel otoritatif: history terminal → NO_RECOVERY_REQUIRED;
18
+ // observasi telat tak pernah menyaingi (dicatat, bukan diputuskan).
19
+ // - Idempotensi recovery: incident key = executionId + frontier journal;
20
+ // history sama → hasil SAMA (tanpa rencana ganda); konkuren sync → deterministik.
21
+ // - Plan basi: validity snapshot (version/frontier/authority/budget/deadline);
22
+ // berubah = stale (bukan perintah irevokabel).
23
+ // - Anak: attached mewarisi interpretasi cancel parent; detached dilestarikan
24
+ // (owner/TTL/kill milik M7); failure anak ≠ terminal parent.
25
+ // - BUKAN: replay/rebuild/reconcile-engineredispatch-actual/scheduler-bridge/
26
+ // persistence/timer/worker/queue. Tanpa import SQLite/scheduler/TaskStore/UI/CLI.
27
+
28
+ import { isTerminalEventType } from "./execution-events.ts"
29
+ import { allocateExecutionId } from "./execution-id.ts"
30
+ import type { JournalRecord } from "./execution-journal.ts"
31
+ import type { TransitionRequest } from "./execution-kernel.ts"
32
+ import { hasDedupeProof, isRedispatchAllowed, type RedispatchSafety } from "./recovery-safety.ts"
33
+
34
+ export type RecoveryInterpretation =
35
+ | "NO_RECOVERY_REQUIRED"
36
+ | "STALE"
37
+ | "RECOVERABLE"
38
+ | "UNKNOWN"
39
+ | "UNCORRELATED"
40
+ | "ORPHAN"
41
+ | "REDISPATCH_SAFE"
42
+ | "REDISPATCH_UNSAFE"
43
+ | "REQUIRES_VERIFIER"
44
+ | "REQUIRES_OPERATOR"
45
+ | "RECOVERY_BLOCKED"
46
+ | "NOT_RECOVERABLE"
47
+
48
+ export type EvidenceStrength =
49
+ | "AUTHORITATIVE"
50
+ | "DURABLE"
51
+ | "OBSERVED"
52
+ | "REQUESTED"
53
+ | "INFERRED"
54
+ | "UNKNOWN"
55
+
56
+ export type VerifierResult = "CONFIRMED_EXECUTED" | "CONFIRMED_NOT_EXECUTED" | "UNKNOWN"
57
+
58
+ /** Penyedia bukti eksternal. Verifier = evidence provider (tak menyentuh kernel). */
59
+ export interface Verifier {
60
+ verify(input: { executionId: string }): VerifierResult
61
+ }
62
+
63
+ export type RecoveryNextAction =
64
+ | "NONE"
65
+ | "REQUEST_CANCEL"
66
+ | "AWAIT_EVIDENCE"
67
+ | "REQUEST_VERIFIER"
68
+ | "PLAN_REDISPATCH"
69
+ | "ESCALATE_OPERATOR"
70
+
71
+ export interface RecoveryProvenance {
72
+ readonly rule: string
73
+ readonly at: number
74
+ readonly journalFrontier: number
75
+ readonly observedExecutionVersion: number | null
76
+ }
77
+
78
+ export interface RedispatchPlan {
79
+ readonly newExecutionId: string
80
+ readonly attempt: number
81
+ readonly generation: number
82
+ readonly supersedes: string
83
+ readonly lineageRootId: string
84
+ readonly parentExecutionId?: string
85
+ readonly validity: {
86
+ readonly observedExecutionVersion: number | null
87
+ readonly journalFrontier: number
88
+ readonly authorityHeld: boolean
89
+ readonly budgetRemaining: number | null
90
+ readonly deadlineRemainingMs: number | null
91
+ }
92
+ }
93
+
94
+ export interface RecoveryResult {
95
+ readonly executionId: string
96
+ readonly interpretation: RecoveryInterpretation
97
+ readonly evidenceStrength: EvidenceStrength
98
+ readonly reasons: readonly string[]
99
+ readonly evidenceRefs: readonly number[]
100
+ readonly nextAction: RecoveryNextAction
101
+ readonly redispatchPlan: RedispatchPlan | null
102
+ readonly requiresVerifier: boolean
103
+ readonly provenance: RecoveryProvenance
104
+ }
105
+
106
+ export interface RecoveryContext {
107
+ readonly authorityHeld: boolean
108
+ readonly budgetRemaining: number | null
109
+ readonly deadlineRemainingMs: number | null
110
+ readonly idempotent: boolean
111
+ readonly dedupeKeyPresent: boolean
112
+ readonly dedupeCheckPass: boolean
113
+ /** Hasil verifier yang SUDAH dijalankan caller (M12 tak menjalankan verifier). */
114
+ readonly verifierResult?: VerifierResult | null
115
+ /** Jalur verifier tersedia (bila ya, UNKNOWN boleh menjadi REQUIRES_VERIFIER). */
116
+ readonly verifierAvailable?: boolean
117
+ /** Bukti konkret efek tak-pernah-mulai (admission-gagal/backend-lapor/gate). */
118
+ readonly notStartedEvidence?:
119
+ | "admission-failed"
120
+ | "backend-reported"
121
+ | "no-intent-with-gate"
122
+ | null
123
+ /** Proses restart diketahui (marker basi) — syarat klasifikasi STALE. */
124
+ readonly processRestarted?: boolean
125
+ /** Ketidakpastian daya tahan dari flush (M11 uncertain). */
126
+ readonly durabilityUncertain?: boolean
127
+ /** Orphan terdeteksi M9 (handle hilang tanpa terminal). */
128
+ readonly orphanSuspected?: boolean
129
+ /** Parent terminal diketahui (attached mewarisi interpretasi cancel). */
130
+ readonly parentTerminal?: boolean
131
+ /** Child detached: parent-terminal TAK mewarisi cancel (kontrak M7). */
132
+ readonly detachedChild?: boolean
133
+ /** Korupsi jurnal dilaporkan M11. */
134
+ readonly journalCorrupt?: boolean
135
+ /**
136
+ * [Fase 2 / LOOP-INV-07] Bukti bahwa hasil tool berstatus UNKNOWN
137
+ * (tag `[TOOL_OUTCOME state=UNKNOWN …]` di terminal). Menolak redispatch
138
+ * otomatis sampai verifier memberi jawaban.
139
+ */
140
+ readonly toolOutcomeUnknown?: boolean
141
+ /** Record warisan tanpa provenance memadai. */
142
+ readonly uncorrelated?: boolean
143
+ /** attempt/generation saat ini (untuk rencana redispatch). */
144
+ readonly attempt?: number
145
+ readonly generation?: number
146
+ readonly parentExecutionId?: string
147
+ readonly lineageRootId?: string
148
+ }
149
+
150
+ // [P1 M16] Tidak ada daftar terminal LOKAL di sini: taksonomi event milik M10
151
+ // (`isTerminalEventType`). Salinan kedua pernah hidup di baris ini dan akan
152
+ // gagal diam-diam begitu M10 menambah terminal baru.
153
+ interface Aggregated {
154
+ hasTerminal: boolean
155
+ terminalTypes: string[]
156
+ hasIntent: boolean
157
+ backendCompleted: boolean
158
+ backendFailed: boolean
159
+ backendObserved: boolean
160
+ maxVersion: number | null
161
+ frontier: number
162
+ refs: number[]
163
+ }
164
+
165
+ function aggregate(records: readonly JournalRecord[]): Aggregated {
166
+ const agg: Aggregated = {
167
+ hasTerminal: false,
168
+ terminalTypes: [],
169
+ hasIntent: false,
170
+ backendCompleted: false,
171
+ backendFailed: false,
172
+ backendObserved: false,
173
+ maxVersion: null,
174
+ frontier: 0,
175
+ refs: [],
176
+ }
177
+ for (const r of records) {
178
+ if (!r || typeof r.journalSequence !== "number") continue
179
+ agg.frontier = Math.max(agg.frontier, r.journalSequence)
180
+ agg.refs.push(r.journalSequence)
181
+ if (r.kind === "intent") {
182
+ agg.hasIntent = true
183
+ continue
184
+ }
185
+ if (r.kind !== "event") continue
186
+ if (isTerminalEventType(r.eventType)) {
187
+ agg.hasTerminal = true
188
+ if (!agg.terminalTypes.includes(r.eventType)) agg.terminalTypes.push(r.eventType)
189
+ }
190
+ if (r.eventType === "backend.observed") {
191
+ agg.backendObserved = true
192
+ if (r.state === "COMPLETED") agg.backendCompleted = true
193
+ if (r.state === "FAILED") agg.backendFailed = true
194
+ }
195
+ if (typeof r.executionVersion === "number") {
196
+ agg.maxVersion =
197
+ agg.maxVersion === null ? r.executionVersion : Math.max(agg.maxVersion, r.executionVersion)
198
+ }
199
+ }
200
+ return agg
201
+ }
202
+
203
+ function buildSafety(ctx: RecoveryContext, notStarted: boolean): RedispatchSafety {
204
+ return {
205
+ authorityHeld: ctx.authorityHeld,
206
+ budgetRemaining: ctx.budgetRemaining,
207
+ deadlineRemainingMs: ctx.deadlineRemainingMs,
208
+ effectDefinitelyNotStarted: notStarted,
209
+ idempotent: ctx.idempotent,
210
+ dedupeKeyPresent: ctx.dedupeKeyPresent,
211
+ dedupeCheckPass: ctx.dedupeCheckPass,
212
+ verifierConfirmedNotExecuted: ctx.verifierResult === "CONFIRMED_NOT_EXECUTED",
213
+ evidenceRecorded: ctx.verifierResult !== undefined && ctx.verifierResult !== null,
214
+ unknownToolOutcome: ctx.toolOutcomeUnknown === true,
215
+ }
216
+ }
217
+
218
+ export interface RecoveryEngine {
219
+ recoverExecution(
220
+ executionId: string,
221
+ records: readonly JournalRecord[],
222
+ ctx: RecoveryContext,
223
+ ): RecoveryResult
224
+ isPlanCurrent(
225
+ plan: RedispatchPlan,
226
+ current: {
227
+ version: number | null
228
+ frontier: number
229
+ authorityHeld: boolean
230
+ budgetRemaining: number | null
231
+ deadlineRemainingMs: number | null
232
+ },
233
+ ): boolean
234
+ buildCancelRequest(executionId: string, reason: string): TransitionRequest
235
+ metrics(): { recoveries: number; redispatchPlanned: number; suppressed: number }
236
+ }
237
+
238
+ export function createRecoveryEngine(): RecoveryEngine {
239
+ // Idempotensi recovery: incident = executionId + frontier journal.
240
+ // History sama → objek hasil SAMA (tanpa rencana ganda). Single-runtime;
241
+ // konkuren sync → deterministik (tanpa lock terdistribusi — batas tercatat).
242
+ const cache = new Map<string, RecoveryResult>()
243
+ const m = { recoveries: 0, redispatchPlanned: 0, suppressed: 0 }
244
+
245
+ const decide = (
246
+ executionId: string,
247
+ agg: Aggregated,
248
+ ctx: RecoveryContext,
249
+ at: number,
250
+ ): RecoveryResult => {
251
+ const reasons: string[] = []
252
+ // Attached + parent terminal → warisan observasi cancel (nextAction saja;
253
+ // interpretasi/state tak diubah; detached = preserve). M7 §29.
254
+ const inheritParentCancel = (action: RecoveryNextAction): RecoveryNextAction => {
255
+ if (
256
+ ctx.parentTerminal === true &&
257
+ ctx.detachedChild !== true &&
258
+ action === "AWAIT_EVIDENCE"
259
+ ) {
260
+ reasons.push("parent terminal (attached): cancel interpretation inherited")
261
+ return "REQUEST_CANCEL"
262
+ }
263
+ return action
264
+ }
265
+ const base = {
266
+ executionId,
267
+ evidenceRefs: Object.freeze([...agg.refs].sort((a, b) => a - b)),
268
+ provenance: Object.freeze({
269
+ rule: "",
270
+ at,
271
+ journalFrontier: agg.frontier,
272
+ observedExecutionVersion: agg.maxVersion,
273
+ }),
274
+ }
275
+ const finish = (
276
+ interpretation: RecoveryInterpretation,
277
+ evidenceStrength: EvidenceStrength,
278
+ nextAction: RecoveryNextAction,
279
+ extra: Partial<Pick<RecoveryResult, "redispatchPlan" | "requiresVerifier">> & {
280
+ rule: string
281
+ },
282
+ ): RecoveryResult =>
283
+ Object.freeze({
284
+ ...base,
285
+ interpretation,
286
+ evidenceStrength,
287
+ reasons: Object.freeze(reasons),
288
+ nextAction,
289
+ redispatchPlan: extra.redispatchPlan ?? null,
290
+ requiresVerifier: extra.requiresVerifier ?? false,
291
+ provenance: Object.freeze({ ...base.provenance, rule: extra.rule }),
292
+ })
293
+
294
+ // 1. Korupsi: blokir inferensi tak aman (bukan tebak).
295
+ if (ctx.journalCorrupt) {
296
+ reasons.push("journal corruption reported: history incomplete, no safe inference")
297
+ return finish("RECOVERY_BLOCKED", "UNKNOWN", "ESCALATE_OPERATOR", {
298
+ rule: "corruption-blocks",
299
+ })
300
+ }
301
+ // 2. Warisan tanpa provenance: UNCORRELATED (bukan lineage fabrikasi).
302
+ if (ctx.uncorrelated) {
303
+ reasons.push("legacy record without stable provenance")
304
+ return finish("UNCORRELATED", "UNKNOWN", "AWAIT_EVIDENCE", { rule: "legacy-uncorrelated" })
305
+ }
306
+ // 3. Terminal otoritatif: tak ada recovery; observasi telat dicatat.
307
+ if (agg.hasTerminal) {
308
+ reasons.push(`terminal history authoritative: ${agg.terminalTypes.join(",")}`)
309
+ if (agg.terminalTypes.length > 1)
310
+ reasons.push("late conflicting observation noted (kernel truth stands)")
311
+ return finish("NO_RECOVERY_REQUIRED", "AUTHORITATIVE", "NONE", {
312
+ rule: "terminal-authoritative",
313
+ })
314
+ }
315
+ // 4-6. Infrastruktur: authority/budget/deadline (tak pernah dihidupkan ulang).
316
+ if (!ctx.authorityHeld) {
317
+ reasons.push("authority not held")
318
+ return finish("RECOVERY_BLOCKED", "DURABLE", "ESCALATE_OPERATOR", {
319
+ rule: "authority-required",
320
+ })
321
+ }
322
+ if (ctx.budgetRemaining !== null && ctx.budgetRemaining <= 0) {
323
+ reasons.push("budget exhausted")
324
+ return finish("RECOVERY_BLOCKED", "DURABLE", "ESCALATE_OPERATOR", { rule: "budget-required" })
325
+ }
326
+ if (ctx.deadlineRemainingMs !== null && ctx.deadlineRemainingMs <= 0) {
327
+ reasons.push("deadline expired")
328
+ return finish("RECOVERY_BLOCKED", "DURABLE", "ESCALATE_OPERATOR", {
329
+ rule: "deadline-required",
330
+ })
331
+ }
332
+ // 7. Predicate kanonis tunggal (M9 mekanis / M12 semantis — satu definisi).
333
+ const safety = buildSafety(ctx, ctx.notStartedEvidence != null)
334
+ if (isRedispatchAllowed(safety)) {
335
+ const attempt = ctx.attempt ?? 1
336
+ const generation = ctx.generation ?? 1
337
+ const plan: RedispatchPlan = Object.freeze({
338
+ newExecutionId: allocateExecutionId(),
339
+ attempt: attempt + 1,
340
+ generation: generation + 1,
341
+ supersedes: executionId,
342
+ lineageRootId: ctx.lineageRootId ?? executionId,
343
+ ...(ctx.parentExecutionId ? { parentExecutionId: ctx.parentExecutionId } : {}),
344
+ validity: Object.freeze({
345
+ observedExecutionVersion: agg.maxVersion,
346
+ journalFrontier: agg.frontier,
347
+ authorityHeld: ctx.authorityHeld,
348
+ budgetRemaining: ctx.budgetRemaining,
349
+ deadlineRemainingMs: ctx.deadlineRemainingMs,
350
+ }),
351
+ })
352
+ m.redispatchPlanned++
353
+ reasons.push("redispatch predicate satisfied")
354
+ return finish("REDISPATCH_SAFE", "DURABLE", "PLAN_REDISPATCH", {
355
+ rule: "predicate-allow",
356
+ redispatchPlan: plan,
357
+ })
358
+ }
359
+ // 8. Efek terkonfirmasi terjadi: tak ada yang perlu di-recovery (bukan error).
360
+ if (ctx.verifierResult === "CONFIRMED_EXECUTED") {
361
+ reasons.push("effect confirmed executed by verifier")
362
+ return finish("NOT_RECOVERABLE", "OBSERVED", "NONE", { rule: "effect-done" })
363
+ }
364
+ // 9. Bahaya positif: efek mungkin terjadi (completed/gagal-parsial) +
365
+ // non-idempotent tanpa clearance → UNSAFE (fakta melarang, bukan kurang bukti).
366
+ const effectMaybeHappened = agg.backendCompleted || agg.backendFailed
367
+ if (effectMaybeHappened && !hasDedupeProof(ctx)) {
368
+ m.suppressed++
369
+ reasons.push("non-idempotent effect possibly happened without proof of non-execution")
370
+ return finish("REDISPATCH_UNSAFE", "OBSERVED", "REQUEST_VERIFIER", {
371
+ rule: "unsafe-non-idempotent",
372
+ requiresVerifier: true,
373
+ })
374
+ }
375
+ // 10. Orphan: handle hilang tanpa terminal (observasi dilestarikan).
376
+ if (ctx.orphanSuspected) {
377
+ reasons.push("orphan suspected: ownership expected, backend relationship untrustworthy")
378
+ if (ctx.verifierAvailable) {
379
+ return finish("ORPHAN", "OBSERVED", inheritParentCancel("REQUEST_VERIFIER"), {
380
+ rule: "orphan-needs-verifier",
381
+ requiresVerifier: true,
382
+ })
383
+ }
384
+ return finish("ORPHAN", "OBSERVED", inheritParentCancel("AWAIT_EVIDENCE"), {
385
+ rule: "orphan-unknown",
386
+ })
387
+ }
388
+ // 11. Tak cukup bukti + jalur verifier ada → minta verifier.
389
+ if (ctx.verifierAvailable) {
390
+ reasons.push("insufficient evidence; verifier path available")
391
+ return finish("REQUIRES_VERIFIER", "UNKNOWN", "REQUEST_VERIFIER", {
392
+ rule: "needs-verifier",
393
+ requiresVerifier: true,
394
+ })
395
+ }
396
+ // 12. STALE: restart diketahui + history live non-terminal (bukan vonis gagal).
397
+ if (ctx.processRestarted && (agg.hasIntent || agg.backendObserved || agg.maxVersion !== null)) {
398
+ reasons.push("stale live history after restart (no failure assumed)")
399
+ return finish("STALE", "DURABLE", inheritParentCancel("AWAIT_EVIDENCE"), {
400
+ rule: "stale-live",
401
+ })
402
+ }
403
+ reasons.push("insufficient evidence (no terminal, no safety, no verifier path)")
404
+ return finish("UNKNOWN", "UNKNOWN", inheritParentCancel("AWAIT_EVIDENCE"), {
405
+ rule: "unknown-default",
406
+ })
407
+ }
408
+
409
+ return {
410
+ recoverExecution(
411
+ executionId: string,
412
+ records: readonly JournalRecord[],
413
+ ctx: RecoveryContext,
414
+ ): RecoveryResult {
415
+ const agg = aggregate(records.filter((r) => recordBelongsTo(r, executionId)))
416
+ // Kunci insiden = history (frontier) + SELURUH konteks keputusan. Tanpa
417
+ // ini, konteks berbeda pada history sama mengembalikan hasil basi
418
+ // (defect nyata yang ditangkap test: budget-0 vs budget-null berbagi key).
419
+ const ctxKey = stableCtxKey(ctx)
420
+ const key = `${executionId}:${agg.frontier}:${ctxKey}`
421
+ const hit = cache.get(key)
422
+ if (hit) return hit
423
+ m.recoveries++
424
+ const result = decide(executionId, agg, ctx, Date.now())
425
+ cache.set(key, result)
426
+ return result
427
+ },
428
+
429
+ isPlanCurrent(plan, current): boolean {
430
+ // Konservatif: versi SAMA + frontier SAMA + authority/budget/deadline
431
+ // masih valid. Perubahan apa pun = stale (rencana bukan perintah irevokabel).
432
+ // [P1 Hygiene F2] Nilai non-finite (NaN/±Infinity) = stale, bukan current:
433
+ // `NaN > 0` false memang sudah stale, tapi +Infinity akan lolos sebagai
434
+ // "available" tanpa guard eksplisit — dan pagu tak-berhingga bukan bukti.
435
+ return (
436
+ current.version === plan.validity.observedExecutionVersion &&
437
+ current.frontier === plan.validity.journalFrontier &&
438
+ current.authorityHeld === plan.validity.authorityHeld &&
439
+ current.authorityHeld === true &&
440
+ (plan.validity.budgetRemaining === null ||
441
+ (current.budgetRemaining !== null &&
442
+ Number.isFinite(current.budgetRemaining) &&
443
+ current.budgetRemaining > 0)) &&
444
+ (plan.validity.deadlineRemainingMs === null ||
445
+ (current.deadlineRemainingMs !== null &&
446
+ Number.isFinite(current.deadlineRemainingMs) &&
447
+ current.deadlineRemainingMs > 0))
448
+ )
449
+ },
450
+
451
+ buildCancelRequest(executionId: string, reason: string): TransitionRequest {
452
+ // Data inert untuk caller teruskan ke kernel (engine tak memanggil kernel).
453
+ return { executionId, to: "CANCELLING", reason, source: "supervisor" }
454
+ },
455
+
456
+ metrics() {
457
+ // Catatan: suppressed dihitung di decide (UNSAFE path).
458
+ return {
459
+ recoveries: m.recoveries,
460
+ redispatchPlanned: m.redispatchPlanned,
461
+ suppressed: m.suppressed,
462
+ }
463
+ },
464
+ }
465
+ }
466
+
467
+ function recordBelongsTo(r: JournalRecord, executionId: string): boolean {
468
+ return !!r && (r as { executionId?: unknown }).executionId === executionId
469
+ }
470
+
471
+ /** Kunci konteks deterministik (sorted-keys; ctx hanya primitif JSON-safe). */
472
+ function stableCtxKey(ctx: RecoveryContext): string {
473
+ const keys = Object.keys(ctx).sort()
474
+ return keys
475
+ .map((k) => `${k}=${JSON.stringify((ctx as unknown as Record<string, unknown>)[k])}`)
476
+ .join(";")
477
+ }
@@ -0,0 +1,179 @@
1
+ // P13.1 — Deklarasi kapabilitas runtime: SATU sumber kebenaran.
2
+ //
3
+ // Kenapa berkas ini ada: kapabilitas yang DIKLAIM harus berasal dari deklarasi
4
+ // eksplisit di lapisan runtime, dibaca daemon DAN CLI lewat simbol yang sama.
5
+ // Dua daftar = dua jawaban = bug yang tak terlihat (persis kelas dual-authority
6
+ // yang sudah dikejar di lapisan lain repo ini).
7
+ //
8
+ // BEDA dari M6 (`src/runtime/capability.ts`): M6 adalah izin EKSEKUSI per
9
+ // eksekusi (request → grant → approval, anak ⊆ parent). Yang di sini adalah
10
+ // pernyataan KETERSEDIAAN runtime — "apakah lapisan ini bisa doingkat SEKARANG",
11
+ // bukan "apakah operasi ini diizinkan". Mencampur keduanya menghasilkan
12
+ // "runtime punya kapabilitas" yang sebenarnya "eksekusi ini diizinkan".
13
+ //
14
+ // Batas yang disengaja (P13.1):
15
+ // - `process-supervision` ADA di kosakata tapi TIDAK boleh diiklankan. Supervisor
16
+ // sekarang hanya dipakai untuk pembatalan eksekusi (`production-execution.ts`),
17
+ // BELUM supervising proses anak (restart/retry/escalation) — itu milestone
18
+ // P13.2. Mengiklankan sebelum attach = janji yang tak bisa dibuktikan.
19
+ // - TaskStore & Scheduler milik lapisan task (`src/task/`). Kapabilitas di sini
20
+ // adalah PERNYATAAN KETERSEDIAAN, bukan klaim kepemilikan: otoritas task tetap
21
+ // milik TaskStore, dan runtime tak pernah menulis task state sendiri.
22
+
23
+ /**
24
+ * Kapabilitas runtime. Kosakata KANONIK: nilai di sini adalah satu-satunya
25
+ * yang boleh dipakai di wire, di log, dan di status.
26
+ */
27
+ export type RuntimeCapability =
28
+ /** Jurnal eksekusi durable tersedia (history tak hilang saat restart). */
29
+ | "durable-journal"
30
+ /** TaskStore (otoritas task) terbuka dan bisa dipakai runtime ini. */
31
+ | "durable-task-store"
32
+ /** Scheduler terpasang — sumber dispatch kerja durable. */
33
+ | "task-scheduler"
34
+ /** Supervisor proses terpasang (P13.2+; belum diiklankan di P13.1). */
35
+ | "process-supervision"
36
+
37
+ /** Semua kapabilitas yang MAYAKINI dikenal (bukan berarti semuanya diiklankan). */
38
+ export const RUNTIME_CAPABILITIES: readonly RuntimeCapability[] = [
39
+ "durable-journal",
40
+ "durable-task-store",
41
+ "task-scheduler",
42
+ "process-supervision",
43
+ ] as const
44
+
45
+ /**
46
+ * Fakta PEMASANGAN (bukan flag niaga): apa yang benar-benar terpasang pada
47
+ * runtime ini. Dipasok composition root dari handle nyata.
48
+ *
49
+ * `supervisor` sengaja `false` di P13.1 — tak ada yang memasang supervisor ke
50
+ * jalur produksi, jadi mengiklankannya akan jadi kebohongan yang tak teruji.
51
+ */
52
+ export interface RuntimeAttachment {
53
+ /** Runtime dibangun dengan jurnal durable. */
54
+ readonly journal: boolean
55
+ /** TaskStore otoritas task tersedia untuk runtime ini. */
56
+ readonly taskStore: boolean
57
+ /** Scheduler terpasang. */
58
+ readonly scheduler: boolean
59
+ /** Supervisor proses terpasang (P13.2+). */
60
+ readonly supervisor: boolean
61
+ }
62
+
63
+ /**
64
+ * Bukti KETERSEDIAAN per kapabilitas.
65
+ *
66
+ * Tri-state dipakai sengaja: `true` = terverifikasi ada, `false` = terverifikasi
67
+ * tidak ada, `null` = belum diketahui. `null` tak pernah dihitung sebagai
68
+ * "boleh" — ketidakpastian bukti harus fail-closed, bukan di optimismakan.
69
+ */
70
+ export interface RuntimeCapabilityEvidence {
71
+ /** Jurnal durable terbuka dan tak ada append gagal pada incarnation ini. */
72
+ readonly journalWritable: boolean | null
73
+ /** TaskStore otoritas task bisa dibuka. */
74
+ readonly storeOpen: boolean | null
75
+ /** Scheduler terpasang. */
76
+ readonly schedulerAttached: boolean | null
77
+ /** Supervisor terpasang (null = belum ada kemampuan diklaim, P13.2). */
78
+ readonly supervisorAttached: boolean | null
79
+ }
80
+
81
+ /**
82
+ * Kapabilitas yang runtime ini DIKLAIM.
83
+ *
84
+ * Iklan berasal dari fakta pemasangan nyata, bukan dari daftar statis: begitu
85
+ * proses supervision benar-benar terpasang (P13.2), ia masuk otomatis — dan
86
+ * selama belum, tidak pernah muncul.
87
+ */
88
+ export function advertisedRuntimeCapabilities(
89
+ attachment: RuntimeAttachment,
90
+ ): readonly RuntimeCapability[] {
91
+ const out: RuntimeCapability[] = []
92
+ if (attachment.journal) out.push("durable-journal")
93
+ if (attachment.taskStore) out.push("durable-task-store")
94
+ if (attachment.scheduler) out.push("task-scheduler")
95
+ if (attachment.supervisor) out.push("process-supervision")
96
+ return out
97
+ }
98
+
99
+ /**
100
+ * Apakah kapabilitas itu SEDANG tersedia?
101
+ *
102
+ * Fail-closed: `null` (belum diketahui) = TIDAK tersedia. Bukti yang tak ada
103
+ * tak pernah diartikan sebagai izin.
104
+ */
105
+ export function capabilityAvailable(
106
+ capability: RuntimeCapability,
107
+ evidence: RuntimeCapabilityEvidence,
108
+ ): boolean {
109
+ switch (capability) {
110
+ case "durable-journal":
111
+ return evidence.journalWritable === true
112
+ case "durable-task-store":
113
+ return evidence.storeOpen === true
114
+ case "task-scheduler":
115
+ return evidence.schedulerAttached === true
116
+ case "process-supervision":
117
+ return evidence.supervisorAttached === true
118
+ }
119
+ }
120
+
121
+ // ── Peta eksplisit jenis kerja durable → kapabilitas yang dibutuhkan ─────────
122
+ //
123
+ // Kenapa peta, bukan nama: nama jenis kerja bukan bukti. "work-kind-x" tak
124
+ // pernah berarti "punya akses ke jurnal" — mengira begitu adalah inferensi
125
+ // yang salah arah (allowlist dari nama = kelas bug yang berulang). Pemetaan
126
+ // hanya sah bila DITULIS eksplisit dan diuji.
127
+
128
+ /** Kebutuhan satu jenis kerja durable terhadap kapabilitas runtime. */
129
+ export interface DurableWorkRequirement {
130
+ /** Pengenal jenis kerja (dipakai sebagai kunci peta, BUKAN sebagai bukti). */
131
+ readonly workKind: string
132
+ /** Kapabilitas yang WAJIB tersedia agar jenis kerja ini boleh jalan. */
133
+ readonly requiredCapabilities: readonly RuntimeCapability[]
134
+ }
135
+
136
+ /** Peta kebutuhan: jenis kerja → kebutuhan kapabilitas. */
137
+ export type DurableWorkRequirementMap = ReadonlyMap<string, DurableWorkRequirement>
138
+
139
+ /**
140
+ * Peta kosong — DEFAULT produksi P13.1.
141
+ *
142
+ * P13.1 tidak mendeklarasikan kelas kerja produksi: kelas kerja nyata adalah
143
+ * keputusan P13.2 (tergantung bentuk dispatch yang benar-benar dipakai). Ships
144
+ * kosong ⇒ admission durable work = REFUSE sampai peta sah didaftarkan. Itu
145
+ * fail-closed yang jujur, bukan placeholder yang menyesatkan.
146
+ */
147
+ export const EMPTY_REQUIREMENT_MAP: DurableWorkRequirementMap = new Map<
148
+ string,
149
+ DurableWorkRequirement
150
+ >()
151
+
152
+ /** Bangun peta kebutuhan dari daftar eksplisit (duplikat = entri terakhir). */
153
+ export function createRequirementMap(
154
+ entries: readonly DurableWorkRequirement[],
155
+ ): DurableWorkRequirementMap {
156
+ const map = new Map<string, DurableWorkRequirement>()
157
+ for (const entry of entries) {
158
+ if (!entry || typeof entry.workKind !== "string" || entry.workKind.length === 0) continue
159
+ map.set(entry.workKind, {
160
+ workKind: entry.workKind,
161
+ requiredCapabilities: [...entry.requiredCapabilities],
162
+ })
163
+ }
164
+ return map
165
+ }
166
+
167
+ /**
168
+ * Ambil kebutuhan untuk satu jenis kerja.
169
+ *
170
+ * `null` = tak ada peta eksplisit. Pemanggil WAJIB memperlakukan `null` sebagai
171
+ * "tolak" (fail-closed), bukan "boleh".
172
+ */
173
+ export function requirementFor(
174
+ map: DurableWorkRequirementMap,
175
+ workKind: string,
176
+ ): DurableWorkRequirement | null {
177
+ if (!map || typeof workKind !== "string" || workKind.length === 0) return null
178
+ return map.get(workKind) ?? null
179
+ }