minicode-ai 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (221) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/LICENSE +21 -21
  3. package/README.md +4 -4
  4. package/cli/args.ts +46 -0
  5. package/cli/commands/acp.ts +163 -10
  6. package/cli/commands/config.ts +33 -18
  7. package/cli/commands/daemon.ts +515 -0
  8. package/cli/commands/exec.ts +145 -53
  9. package/cli/commands/openwork.ts +986 -0
  10. package/cli/commands/sessions.ts +4 -1
  11. package/cli/commands/stats.ts +34 -4
  12. package/cli/commands.ts +217 -2
  13. package/cli/index.ts +146 -14
  14. package/cli/recovery-warning.ts +115 -0
  15. package/cli/router.ts +32 -1
  16. package/cli/setup.ts +2332 -171
  17. package/cli/tui.ts +113 -7
  18. package/docs/OUTPUT_ARCHITECTURE_AUDIT.md +489 -0
  19. package/docs/OUTPUT_EVENT_MODEL.md +289 -0
  20. package/docs/OUTPUT_IMPLEMENTATION_PLAN.md +391 -0
  21. package/docs/OUTPUT_PROTOCOL_SPEC.md +285 -0
  22. package/docs/OUTPUT_RENDERING_SPEC.md +248 -0
  23. package/docs/OUTPUT_UX_RULES.md +449 -0
  24. package/docs/PLAN_UIUX_V6.md +2 -2
  25. package/docs/README.md +4 -3
  26. package/docs/TERMINAL_CONTRACT.md +278 -66
  27. package/docs/architecture.md +89 -7
  28. package/docs/changelog.md +1 -1
  29. package/docs/choosing-mode.md +2 -2
  30. package/docs/cli.md +9 -5
  31. package/docs/concepts.md +1 -1
  32. package/docs/contributing.md +9 -2
  33. package/docs/environment.md +6 -2
  34. package/docs/exec.md +46 -5
  35. package/docs/memory-sessions.md +2 -0
  36. package/docs/policy-sandbox.md +1 -1
  37. package/docs/pricing-budget.md +1 -1
  38. package/docs/quickstart.md +2 -2
  39. package/docs/repl.md +6 -2
  40. package/docs/security-model.md +1 -1
  41. package/docs/security.md +1 -1
  42. package/docs/skills.md +2 -2
  43. package/docs/terminal.md +9 -5
  44. package/docs/tools.md +1 -1
  45. package/package.json +35 -5
  46. package/src/app/session.ts +261 -15
  47. package/src/app/tool-layer.ts +94 -7
  48. package/src/daemon/approvals.ts +361 -0
  49. package/src/daemon/capability.ts +145 -0
  50. package/src/daemon/children.ts +142 -0
  51. package/src/daemon/client.ts +267 -0
  52. package/src/daemon/control.ts +350 -0
  53. package/src/daemon/discovery.ts +234 -0
  54. package/src/daemon/feed.ts +155 -0
  55. package/src/daemon/framing.ts +94 -0
  56. package/src/daemon/host.ts +316 -0
  57. package/src/daemon/protocol.ts +217 -0
  58. package/src/daemon/resource.ts +170 -0
  59. package/src/daemon/sanitize.ts +57 -0
  60. package/src/daemon/server.ts +627 -0
  61. package/src/daemon/store.ts +317 -0
  62. package/src/daemon/subscription.ts +270 -0
  63. package/src/daemon/telemetry.ts +81 -0
  64. package/src/hooks/run.ts +12 -1
  65. package/src/lib/atomic-write.ts +29 -3
  66. package/src/lib/db-path.ts +26 -0
  67. package/src/lib/keystore.ts +544 -42
  68. package/src/lib/net.ts +43 -1
  69. package/src/lib/safe-open.ts +116 -1
  70. package/src/lib/session-id.ts +15 -0
  71. package/src/lsp/client.ts +123 -5
  72. package/src/mcp/client.ts +139 -17
  73. package/src/mcp/server.ts +177 -50
  74. package/src/mcp/transport.ts +16 -19
  75. package/src/memory/vector.ts +770 -55
  76. package/src/policy/allowlist.ts +14 -2
  77. package/src/policy/bash-guard.ts +105 -10
  78. package/src/policy/compaction.ts +82 -5
  79. package/src/policy/consequence-engine.ts +220 -0
  80. package/src/policy/context.ts +132 -0
  81. package/src/policy/executor.ts +187 -121
  82. package/src/policy/no-progress.ts +559 -0
  83. package/src/policy/permission.ts +4 -8
  84. package/src/policy/pricing.ts +17 -3
  85. package/src/policy/scrub.ts +69 -2
  86. package/src/policy/tool-contract.ts +515 -0
  87. package/src/policy/usage.ts +310 -24
  88. package/src/policy/verifier.ts +6 -3
  89. package/src/policy/work-mode.ts +182 -0
  90. package/src/presentation/adapter.ts +533 -26
  91. package/src/presentation/events.ts +151 -0
  92. package/src/presentation/model.ts +180 -27
  93. package/src/presentation/projection.ts +858 -0
  94. package/src/presentation/reducer.ts +645 -310
  95. package/src/presentation/store.ts +12 -7
  96. package/src/providers/anthropic.ts +18 -10
  97. package/src/providers/responses.ts +17 -7
  98. package/src/runtime/capability.ts +409 -0
  99. package/src/runtime/child-execution.ts +274 -0
  100. package/src/runtime/composition.ts +958 -0
  101. package/src/runtime/dispatch.ts +591 -0
  102. package/src/runtime/execution-backend.ts +632 -0
  103. package/src/runtime/execution-events.ts +272 -0
  104. package/src/runtime/execution-id.ts +230 -0
  105. package/src/runtime/execution-journal.ts +926 -0
  106. package/src/runtime/execution-kernel.ts +456 -0
  107. package/src/runtime/execution-registry.ts +379 -0
  108. package/src/runtime/process-supervision.ts +276 -0
  109. package/src/runtime/production-execution.ts +551 -0
  110. package/src/runtime/production-runtime.ts +217 -0
  111. package/src/runtime/recovery-safety.ts +70 -0
  112. package/src/runtime/recovery.ts +477 -0
  113. package/src/runtime/runtime-capabilities.ts +179 -0
  114. package/src/runtime/runtime-diagnostics.ts +141 -0
  115. package/src/runtime/runtime-host.ts +365 -0
  116. package/src/runtime/runtime-status-facts.ts +222 -0
  117. package/src/runtime/runtime-status-provider.ts +74 -0
  118. package/src/runtime/runtime-status.ts +459 -0
  119. package/src/runtime/runtime-task-admission.ts +101 -0
  120. package/src/runtime/supervisor.ts +444 -0
  121. package/src/session/authority.ts +168 -0
  122. package/src/session/checkpoint.ts +88 -1
  123. package/src/session/context-adapter.ts +251 -0
  124. package/src/session/context-assembly.ts +242 -0
  125. package/src/session/context-identity.ts +389 -0
  126. package/src/session/context-projection.ts +248 -0
  127. package/src/session/context-selector.ts +500 -0
  128. package/src/session/cross-session-adoption.ts +249 -0
  129. package/src/session/full-history-fold.ts +171 -0
  130. package/src/session/identity.ts +192 -0
  131. package/src/session/journal.ts +805 -102
  132. package/src/session/open-work-intent.ts +732 -0
  133. package/src/session/open-work.ts +767 -0
  134. package/src/session/pending-tools.ts +94 -0
  135. package/src/session/persistence.ts +3569 -127
  136. package/src/session/runtime-header.ts +208 -0
  137. package/src/session/shadow-git.ts +13 -5
  138. package/src/session/verification.ts +1623 -0
  139. package/src/task/assignment.ts +136 -0
  140. package/src/task/autonomous-adapter.ts +168 -0
  141. package/src/task/autonomous-context.ts +630 -0
  142. package/src/task/autonomous-policy.ts +490 -0
  143. package/src/task/continuity.ts +179 -0
  144. package/src/task/execution-cancellation.ts +165 -0
  145. package/src/task/graph-validate.ts +379 -0
  146. package/src/task/graph.ts +305 -0
  147. package/src/task/identity.ts +230 -0
  148. package/src/task/model.ts +417 -0
  149. package/src/task/production-scheduler.ts +293 -0
  150. package/src/task/readiness.ts +229 -0
  151. package/src/task/scheduler-observability.ts +387 -0
  152. package/src/task/scheduler.ts +1197 -0
  153. package/src/task/scheduling-policy.ts +165 -0
  154. package/src/task/session-authority.ts +148 -0
  155. package/src/task/session-ownership.ts +211 -0
  156. package/src/task/store.ts +2887 -0
  157. package/src/task/sync.ts +343 -0
  158. package/src/task/trigger.ts +260 -0
  159. package/src/tools/bash.ts +377 -211
  160. package/src/tools/code_run.ts +1 -1
  161. package/src/tools/delete_file.ts +1 -1
  162. package/src/tools/edit.ts +33 -6
  163. package/src/tools/evidence.ts +30 -0
  164. package/src/tools/git.ts +4 -4
  165. package/src/tools/glob.ts +12 -3
  166. package/src/tools/grep.ts +1 -1
  167. package/src/tools/lsp.ts +4 -4
  168. package/src/tools/mcp_call.ts +11 -4
  169. package/src/tools/memory.ts +153 -18
  170. package/src/tools/move_file.ts +1 -1
  171. package/src/tools/patch.ts +1 -1
  172. package/src/tools/read_file.ts +1 -1
  173. package/src/tools/read_image.ts +1 -1
  174. package/src/tools/submit_result.ts +1 -1
  175. package/src/tools/task.ts +437 -41
  176. package/src/tools/todo.ts +662 -35
  177. package/src/tools/web_fetch.ts +4 -2
  178. package/src/tools/web_search.ts +9 -3
  179. package/src/tools/write_file.ts +1 -1
  180. package/src/ui/assistant/simple.ts +123 -50
  181. package/src/ui/assistant/turn-status.ts +17 -3
  182. package/src/ui/contract.ts +184 -0
  183. package/src/ui/footer.ts +54 -18
  184. package/src/ui/i18n/en.ts +62 -6
  185. package/src/ui/i18n/id.ts +62 -6
  186. package/src/ui/input/prompt-engine.ts +120 -25
  187. package/src/ui/render/errors.ts +39 -1
  188. package/src/ui/render/markdown-table.ts +455 -0
  189. package/src/ui/render/markdown.ts +22 -1
  190. package/src/ui/render/table-grid.ts +184 -0
  191. package/src/ui/render/table.ts +15 -76
  192. package/src/ui/runtime/screen.ts +7 -2
  193. package/src/ui/runtime/statusline.ts +25 -6
  194. package/src/ui/tui/app.ts +598 -133
  195. package/src/ui/tui/transcript.ts +531 -89
  196. package/vendor/minicore/VENDOR.md +1 -1
  197. package/vendor/minicore/src/core/budget.ts +25 -25
  198. package/vendor/minicore/src/core/compact.ts +75 -75
  199. package/vendor/minicore/src/core/errors.ts +59 -59
  200. package/vendor/minicore/src/core/events.ts +73 -73
  201. package/vendor/minicore/src/core/executor.ts +139 -139
  202. package/vendor/minicore/src/core/history.ts +31 -31
  203. package/vendor/minicore/src/core/index.ts +41 -41
  204. package/vendor/minicore/src/core/loop.ts +355 -355
  205. package/vendor/minicore/src/core/permission.ts +22 -22
  206. package/vendor/minicore/src/core/provider.ts +39 -39
  207. package/vendor/minicore/src/core/recovery.ts +35 -35
  208. package/vendor/minicore/src/core/session.ts +327 -327
  209. package/vendor/minicore/src/core/snapshot.ts +146 -146
  210. package/vendor/minicore/src/core/tokens.ts +107 -107
  211. package/vendor/minicore/src/core/tool.ts +115 -115
  212. package/vendor/minicore/src/core/types.ts +50 -50
  213. package/vendor/minicore/src/providers/openai-compat.ts +417 -417
  214. package/AGENTS.md +0 -45
  215. package/PLAN.md +0 -491
  216. package/docs/ARCHITECTURE.html +0 -1248
  217. package/docs/CONTROL-PLANE-MAP.md +0 -139
  218. package/docs/HARNESS.md +0 -150
  219. package/docs/SUMMARY.md +0 -52
  220. package/docs/UI_RENDER_PIPELINE.md +0 -165
  221. package/docs/USAGE.md +0 -11
@@ -0,0 +1,500 @@
1
+ // P3.3 — Canonical Context Selector (derived, read-only, deterministic).
2
+ //
3
+ // Jawaban SATU pertanyaan: "Dari canonical state yang mana, dan dengan policy
4
+ // apa, view konteks runtime ini dibangun?" — tanpa menjadi otoritas baru.
5
+ //
6
+ // Model yang dikunci (mengikuti P3.3 architecture audit):
7
+ //
8
+ // Canonical History (messages; AUTHORITY: persistence.ts)
9
+ // │ read-only (rows SUDAH dimuat pemanggil; modul ini TANPA IO)
10
+ // ▼
11
+ // P3.2 Identity / Frontier / Freshness (context-identity.ts — DESKRIPTIF)
12
+ // │
13
+ // ▼
14
+ // P3.3 Selector (modul ini — DERIVED, murni, deterministik)
15
+ // │
16
+ // ▼
17
+ // ContextSelection (RAM-only, provenance-bound)
18
+ // │
19
+ // ▼
20
+ // Runtime Context (ContextStore) [EXECUTION-LOCAL]
21
+ // │
22
+ // └─ publication → P3.1 decision + P2.7 safety (saveSession) → canonical
23
+ //
24
+ // Batas keras modul ini:
25
+ // - TANPA IO. Tanpa SQLite/fs/jaringan, tanpa Date.now, tanpa random, tanpa
26
+ // state modul yang memengaruhi hasil. Input = data yang sudah dimuat +
27
+ // policy + budget; output = nilai murni.
28
+ // - BACA-SAJA secara struktural: modul ini TIDAK mengimpor persistence.ts,
29
+ // jadi ia tak mungkin menulis kanonik. Ia hanya mengimpor fungsi MURNI dari
30
+ // context-identity.ts (P3.2) dan helper murni dari context-assembly.ts (P2.8).
31
+ // - TIDAK ada store/cache/sidecar/DB milik selector (dilarang audit).
32
+ // - TIDAK ada ranking semantik/embedding/LLM/jaringan (infrastructure, bukan
33
+ // intelligence — audit §3).
34
+ // - BUKAN decider: putusan publikasi tetap di saveSession (P2.7). Selector
35
+ // MENYELEKSI & MENJELASKAN ("describe/project"), tidak "decide".
36
+ //
37
+ // Generalisasi seam P2.8 (assembleContext) menjadi selector sadar-budget yang
38
+ // membawa provenance, TANPA menduplikasi logika P2.8 (berbagi primitive).
39
+
40
+ import { estimateMessage, type TokenEstimator } from "#minicore/core/tokens.ts"
41
+ import type { Message } from "#minicore/core/types.ts"
42
+ import {
43
+ boundaryIsSafe,
44
+ type ContextOnlyArtifact,
45
+ type ContextSource,
46
+ syntheticSummaryMessage,
47
+ } from "./context-assembly.ts"
48
+ import {
49
+ assessContextFreshness,
50
+ type CanonicalEventRef,
51
+ type ContextFreshness,
52
+ type ContextFrontier,
53
+ deriveContextFrontier,
54
+ deriveHistoryCommit,
55
+ } from "./context-identity.ts"
56
+
57
+ /**
58
+ * Basis pemilihan view — kontrak semantik (BUKAN string bebas). Persis satu
59
+ * nilai per seleksi; menjelaskan ATAS DASAR APA view dibangun.
60
+ *
61
+ * - full-history : seluruh baris kanonik muat budget; tanpa fold.
62
+ * - summary-plus-tail: ringkasan proyeksi durable CURRENT atas [0,baseSeq) +
63
+ * ekor kanonik [baseSeq, head].
64
+ * - budget-tail : ekor kanonik kontigu terbaru yang muat budget; prefix
65
+ * lama DIJATUHKAN (tanpa ringkasan) — context-window
66
+ * eviction, BUKAN fold/kompaksi.
67
+ * - fallback-unknown : kesegaran/cakupan tak dapat dipastikan; view aman-terlebar
68
+ * (histori kanonik penuh) + freshness eksplisit.
69
+ */
70
+ export type SelectionBasis =
71
+ | "full-history"
72
+ | "summary-plus-tail"
73
+ | "budget-tail"
74
+ | "fallback-unknown"
75
+
76
+ const SELECTION_BASES: readonly SelectionBasis[] = [
77
+ "full-history",
78
+ "summary-plus-tail",
79
+ "budget-tail",
80
+ "fallback-unknown",
81
+ ]
82
+
83
+ /** True bila string adalah SelectionBasis yang well-formed. */
84
+ export function isSelectionBasis(value: unknown): value is SelectionBasis {
85
+ return typeof value === "string" && (SELECTION_BASES as readonly string[]).includes(value)
86
+ }
87
+
88
+ /** Semua nilai basis (beku) — dipakai test/validasi. */
89
+ export const ALL_SELECTION_BASES: readonly SelectionBasis[] = Object.freeze([...SELECTION_BASES])
90
+
91
+ /** Baris kanonik yang sudah dimuat (bentuk SAMA dengan P2.8 `loadThreadHistory`). */
92
+ export interface SelectableRow {
93
+ readonly seq: number
94
+ readonly message: unknown
95
+ }
96
+
97
+ /**
98
+ * Adaptasi baris → ref kanonik P3.2 (menambahkan `seq` yang dibutuhkan hashing).
99
+ * `message` dari loadThreadHistoryWithSeq adalah kernel Message (role/content/
100
+ * toolCalls/reasoning/…); ref kanonik HANYA mengambil field durable yang mengikat
101
+ * identitas — persis bentuk yang dipakai guard P3.1 `refsFromRows`.
102
+ */
103
+ function toRef(row: SelectableRow): CanonicalEventRef {
104
+ const m = (row.message ?? {}) as {
105
+ role?: unknown
106
+ content?: unknown
107
+ toolCalls?: unknown
108
+ toolCallId?: unknown
109
+ name?: unknown
110
+ reasoning?: unknown
111
+ isError?: unknown
112
+ }
113
+ const content = typeof m.content === "string" ? m.content : JSON.stringify(m.content ?? null)
114
+ const ref: {
115
+ seq: number
116
+ role: string
117
+ content: string
118
+ toolCalls?: string | null
119
+ toolCallId?: string | null
120
+ name?: string | null
121
+ reasoning?: string | null
122
+ isError?: number | boolean | null
123
+ } = {
124
+ seq: row.seq,
125
+ role: typeof m.role === "string" ? m.role : "user",
126
+ content,
127
+ }
128
+ if (m.toolCalls !== undefined) ref.toolCalls = JSON.stringify(m.toolCalls ?? null)
129
+ if (m.toolCallId !== undefined) ref.toolCallId = (m.toolCallId as string | null) ?? null
130
+ if (m.name !== undefined) ref.name = (m.name as string | null) ?? null
131
+ if (m.reasoning !== undefined) ref.reasoning = (m.reasoning as string | null) ?? null
132
+ if (m.isError !== undefined) ref.isError = m.isError as boolean | number | null
133
+ return ref
134
+ }
135
+
136
+ /**
137
+ * Publik: adaptasi baris selector → ref kanonik P3.2. Diekspor agar pemanggil
138
+ * (composition root) bisa menurunkan frontier kanonis dari baris yang SAMA
139
+ * untuk diteruskan sebagai `canonicalFrontier` — SATU adapter, tanpa duplikasi.
140
+ */
141
+ export function rowsToCanonicalRefs(rows: readonly SelectableRow[]): CanonicalEventRef[] {
142
+ return rows.map(toRef)
143
+ }
144
+
145
+ /**
146
+ * Ringkasan proyeksi durable yang boleh dipakai selector. Pemanggil membacanya
147
+ * (persistence.ts getProjection/getProjectionStatus) dan menyerahkannya HANYA
148
+ * bila status CURRENT + boundary aman — selector TIDAK membaca DB sendiri.
149
+ */
150
+ export interface ProjectionSummary {
151
+ /** Cakupan eksklusif [0, baseSeq) yang diringkas. baseSeq > 0. */
152
+ readonly baseSeq: number
153
+ /** Teks ringkasan durable (bukan hasil generate selector). */
154
+ readonly summaryText: string
155
+ }
156
+
157
+ /**
158
+ * Kebijakan seleksi — input deterministik, tanpa state mutable. `budgetTokens`
159
+ * adalah pagu token untuk BAGIAN PESAN saja (system+tools sudah dikurangkan
160
+ * pemanggil; lihat `reservedForSystemAndTools` di output untuk transparansi).
161
+ */
162
+ export interface SelectionPolicy {
163
+ /** Pagu token untuk pesan terpilih (>= 0). */
164
+ readonly budgetTokens: number
165
+ /** Estimator token injeksi (default kernel chars/4) — sumber tunggal. */
166
+ readonly estimator?: TokenEstimator
167
+ /** Berapa token yang sudah dipesan untuk system+tools (bukti/diagnostik). */
168
+ readonly reservedForSystemAndTools?: number
169
+ }
170
+
171
+ /**
172
+ * Input selector — data kanonik yang SUDAH dimuat + policy + budget. Sengaja
173
+ * TIDAK membawa handle persistence, session object, ContextStore, run, atau
174
+ * epoch (modul ini murni & tak menyentuh state eksekusi).
175
+ */
176
+ export interface SelectContextInput {
177
+ readonly sessionId: string
178
+ readonly threadId: string
179
+ /** Baris kanonik thread ini (dari loadThreadHistoryWithSeq), urut seq. */
180
+ readonly rows: readonly SelectableRow[]
181
+ /** Revisi kanonis = cacah durable `context.compacted` (P3.2). */
182
+ readonly revision: number
183
+ /** Ringkasan proyeksi durable (opsional; hanya bila CURRENT + boundary aman). */
184
+ readonly projection?: ProjectionSummary
185
+ /** Kebijakan seleksi. */
186
+ readonly policy: SelectionPolicy
187
+ /**
188
+ * Frontier kanonis SAAT INI (opsional) untuk menilai kesegaran view. Bila
189
+ * `undefined` → view baru dinilai FRESH (dibangun dari kanonik saat ini).
190
+ * Bila eksplisit `null` → UNKNOWN (kanonik tak dapat dibuktikan).
191
+ */
192
+ readonly canonicalFrontier?: ContextFrontier | null
193
+ }
194
+
195
+ /**
196
+ * Akuntansi budget — LAPORAN, bukan keputusan. Memisahkan "benar" (selection
197
+ * correctness) dari "muat" (budget feasibility).
198
+ */
199
+ export interface SelectionBudgetReport {
200
+ /** Pagu token untuk pesan (dari policy). */
201
+ readonly limitTokens: number
202
+ /** Estimasi token pesan terpilih. */
203
+ readonly estimatedTokens: number
204
+ /** Token yang pemanggil pesan untuk system+tools (diteruskan apa adanya). */
205
+ readonly reservedForSystemAndTools: number
206
+ /** True bila pesan terpilih muat dalam pagu. */
207
+ readonly fits: boolean
208
+ }
209
+
210
+ /**
211
+ * Hasil seleksi — nilai RAM murni (seperti ContextView P2.8: tak pernah
212
+ * diserialisasi, tak pernah jadi otoritas resume). Membawa provenance yang
213
+ * mengikat view ke isi kanonik eksak via `frontier.historyCommit`.
214
+ */
215
+ export interface ContextSelection {
216
+ /** Referensi identitas kanonik (bukan salinan). */
217
+ readonly sessionId: string
218
+ readonly threadId: string
219
+ /**
220
+ * Frontier view terpilih — mengikat cakupan + isi. `baseSeq` menandai batas
221
+ * cakupan: 0 = histori penuh; > 0 = parsial. `null` hanya bila tak ada baris
222
+ * kanonik (frontier kosong = UNKNOWN).
223
+ */
224
+ readonly frontier: ContextFrontier | null
225
+ /** Materialisasi untuk di-seed ke ContextStore (appendAll). RAM-only. */
226
+ readonly messages: Message[]
227
+ /** Asal isi: "projection" (ada ringkasan) atau "messages" (murni kanonik). */
228
+ readonly source: ContextSource
229
+ /** Cakupan eksklusif yang diwakili ringkasan; 0 bila tak ada ringkasan. */
230
+ readonly coveredSeq: number
231
+ /** Basis pemilihan (kontrak semantik). */
232
+ readonly selectionBasis: SelectionBasis
233
+ /** Kesegaran view ini terhadap frontier kanonis (P3.2, deskriptif). */
234
+ readonly freshness: ContextFreshness
235
+ /** Materialisasi token/budget. */
236
+ readonly budget: SelectionBudgetReport
237
+ /** Kenapa basis ini dipilih / kenapa fallback. Diagnostik, bukan otoritas. */
238
+ readonly detail: string
239
+ /**
240
+ * Artefak context-only (bila summary dipakai) yang WAJIB dibuang jalur persist
241
+ * sebelum menulis kanonik (fingerprint P2.8; diteruskan apa adanya).
242
+ */
243
+ readonly contextOnly?: ContextOnlyArtifact
244
+ }
245
+
246
+ /** Estimator default = kernel chars/4, dipakai bila policy tak menyediakan. */
247
+ const defaultEstimator: TokenEstimator = (text: string) => Math.ceil(text.length / 4)
248
+
249
+ function sumTokens(messages: readonly Message[], est: TokenEstimator): number {
250
+ let total = 0
251
+ for (const m of messages) total += estimateMessage(m, est)
252
+ return total
253
+ }
254
+
255
+ /**
256
+ * Batas cakupan parsial yang aman: mulai `rawBaseSeq`, geser NAIK sampai batas
257
+ * aman (tidak memisahkan pasangan assistant(toolCalls)/tool-result). Batas sah
258
+ * ada di [1, head] — P3.2 `deriveContextFrontier` menolak baseSeq > head
259
+ * ("view is never inverted"), jadi cakupan PENUH P2.8 (base_seq == head+1)
260
+ * DICAP ke head (ringkasan [0,head) + ekor [head]; tetap valid & lengkap).
261
+ * Deterministis; tanpa heuristik.
262
+ *
263
+ * Mengembalikan baseSeq final; 0 = cakupan penuh (mundur aman-terlebar bila
264
+ * tak ada batas aman). rawBaseSeq <= 0 juga 0.
265
+ */
266
+ export function safeBaseSeq(rows: readonly SelectableRow[], rawBaseSeq: number): number {
267
+ if (rawBaseSeq <= 0) return 0
268
+ if (rows.length === 0) return 0
269
+ const head = rows[rows.length - 1]!.seq
270
+ // Cap ke head: base_seq == head+1 (cakupan penuh P2.8) tetap representable
271
+ // sebagai ringkasan [0,head) + ekor [head].
272
+ let boundary = Math.min(rawBaseSeq, head)
273
+ while (boundary >= 1 && boundary <= head) {
274
+ if (boundaryIsSafe(rows as { seq: number; message: unknown }[], boundary)) return boundary
275
+ boundary++
276
+ }
277
+ return 0
278
+ }
279
+
280
+ /** Bangun frontier + materialisasi atas cakupan [baseSeq, head]. */
281
+ function coverageOf(
282
+ input: SelectContextInput,
283
+ rows: readonly SelectableRow[],
284
+ baseSeq: number,
285
+ ): { frontier: ContextFrontier; messages: Message[] } {
286
+ const covered = baseSeq <= 0 ? rows : rows.filter((r) => r.seq >= baseSeq)
287
+ const headRow = rows[rows.length - 1]!
288
+ const frontier = deriveContextFrontier({
289
+ sessionId: input.sessionId,
290
+ threadId: input.threadId,
291
+ baseSeq,
292
+ head: toRef(headRow),
293
+ revision: input.revision,
294
+ historyCommit: deriveHistoryCommit(covered.map(toRef)),
295
+ })
296
+ return { frontier, messages: covered.map((r) => r.message as Message) }
297
+ }
298
+
299
+ /**
300
+ * Kesegaran view terhadap frontier kanonis. Bila pemanggil tak memberi frontier
301
+ * (`undefined`), view yang baru dibangun dari kanonik saat ini = FRESH. Bila
302
+ * eksplisit `null` → UNKNOWN. Selain itu delegasi ke semantik P3.2.
303
+ */
304
+ function selectionFreshness(
305
+ view: ContextFrontier,
306
+ canonical: ContextFrontier | null | undefined,
307
+ ): ContextFreshness {
308
+ if (canonical === undefined) return "fresh"
309
+ if (canonical === null) return "unknown"
310
+ return assessContextFreshness(view, canonical)
311
+ }
312
+
313
+ /**
314
+ * SELECTOR INTI. MURNI + DETERMINISTIK: input tak dimutasi, tanpa IO.
315
+ *
316
+ * Urutan strategi (audit §7):
317
+ * 1. summary-plus-tail — ringkasan durable [0,B) + ekor [B, head] (bila aman)
318
+ * 2. fallback-unknown — view kanonik penuh + label jujur (DIVERGED/UNKNOWN)
319
+ * 3. full-history — histori kanonik penuh bila muat budget
320
+ * 4. budget-tail — ekor kanonik terbaru yang muat budget
321
+ */
322
+ export function selectContext(input: SelectContextInput): ContextSelection {
323
+ const est = input.policy.estimator ?? defaultEstimator
324
+ const reserved = input.policy.reservedForSystemAndTools ?? 0
325
+ const limit = Math.max(0, Math.floor(input.policy.budgetTokens))
326
+ const rows = input.rows
327
+
328
+ const report = (msgs: readonly Message[]): SelectionBudgetReport => {
329
+ const estimated = sumTokens(msgs, est)
330
+ return {
331
+ limitTokens: limit,
332
+ estimatedTokens: estimated,
333
+ reservedForSystemAndTools: reserved,
334
+ fits: estimated <= limit,
335
+ }
336
+ }
337
+
338
+ // ── Kosong: frontier null = UNKNOWN (P3.2) ─────────────────────────────────
339
+ if (rows.length === 0) {
340
+ return Object.freeze({
341
+ sessionId: input.sessionId,
342
+ threadId: input.threadId,
343
+ frontier: null,
344
+ messages: [] as Message[],
345
+ source: "messages" as ContextSource,
346
+ coveredSeq: 0,
347
+ selectionBasis: "fallback-unknown" as SelectionBasis,
348
+ freshness: "unknown" as ContextFreshness,
349
+ budget: report([]),
350
+ detail: "empty canonical history (no rows); frontier null = UNKNOWN",
351
+ })
352
+ }
353
+
354
+ const headSeq = rows[rows.length - 1]!.seq
355
+
356
+ // ── Strategi 1: summary-plus-tail ──────────────────────────────────────────
357
+ if (input.projection && input.projection.baseSeq > 0) {
358
+ const b = safeBaseSeq(rows, input.projection.baseSeq)
359
+ const summaryText = input.projection.summaryText
360
+ if (b > 0 && typeof summaryText === "string" && summaryText.length > 0) {
361
+ const { frontier, messages: tail } = coverageOf(input, rows, b)
362
+ const synthetic = syntheticSummaryMessage(summaryText, b)
363
+ const msgs: Message[] = [synthetic, ...tail]
364
+ const artifact: ContextOnlyArtifact = { role: "user", content: synthetic.content as string }
365
+ return Object.freeze({
366
+ sessionId: input.sessionId,
367
+ threadId: input.threadId,
368
+ frontier,
369
+ messages: msgs,
370
+ source: "projection" as ContextSource,
371
+ coveredSeq: b,
372
+ selectionBasis: "summary-plus-tail" as SelectionBasis,
373
+ freshness: selectionFreshness(frontier, input.canonicalFrontier),
374
+ budget: report(msgs),
375
+ detail: `durable summary covers [0,${b}) + canonical tail [${b},${headSeq}]`,
376
+ contextOnly: artifact,
377
+ })
378
+ }
379
+ // batas tak aman / ringkasan kosong → lanjut sebagai histori kanonik penuh.
380
+ }
381
+
382
+ const full = coverageOf(input, rows, 0)
383
+ const fullFreshness = selectionFreshness(full.frontier, input.canonicalFrontier)
384
+
385
+ // ── Strategi 2: fallback-unknown (STALE/DIVERGED/UNKNOWN) ──────────────────
386
+ // N3: baris BASI (view di belakang kanonis) TIDAK boleh dilabeli
387
+ // "full-history" — label itu menyiratkan representasi kanonik yang trusted,
388
+ // padahal view ini tak memutakhirkan diri ke head kanonis. Pakai
389
+ // `fallback-unknown` (state yang sudah ada; bukan basis kelima yang baru).
390
+ // Coverage completeness (semua baris tersedia diikutkan) ≠ freshness/trust.
391
+ if (fullFreshness === "unknown" || fullFreshness === "diverged" || fullFreshness === "stale") {
392
+ return Object.freeze({
393
+ sessionId: input.sessionId,
394
+ threadId: input.threadId,
395
+ frontier: full.frontier,
396
+ messages: full.messages,
397
+ source: "messages" as ContextSource,
398
+ coveredSeq: 0,
399
+ selectionBasis: "fallback-unknown" as SelectionBasis,
400
+ freshness: fullFreshness,
401
+ budget: report(full.messages),
402
+ detail: `canonical freshness vs supplied frontier = ${fullFreshness}; full rows present but labeled untrusted (not full-history)`,
403
+ })
404
+ }
405
+
406
+ // ── Strategi 3: full-history (muat budget) ─────────────────────────────────
407
+ const fullTokens = sumTokens(full.messages, est)
408
+ if (fullTokens <= limit) {
409
+ return Object.freeze({
410
+ sessionId: input.sessionId,
411
+ threadId: input.threadId,
412
+ frontier: full.frontier,
413
+ messages: full.messages,
414
+ source: "messages" as ContextSource,
415
+ coveredSeq: 0,
416
+ selectionBasis: "full-history" as SelectionBasis,
417
+ freshness: fullFreshness,
418
+ budget: report(full.messages),
419
+ detail: `full canonical history fits budget (${fullTokens} <= ${limit})`,
420
+ })
421
+ }
422
+
423
+ // ── Strategi 4: budget-tail (ekor kontigu terbaru yang muat) ────────────────
424
+ const boundaryRows = rows as unknown as { seq: number; message: unknown }[]
425
+ let acc = 0
426
+ let firstKeptIdx = rows.length // tak ada yang muat
427
+ for (let i = rows.length - 1; i >= 0; i--) {
428
+ const one = estimateMessage(rows[i]!.message as Message, est)
429
+ if (acc + one > limit) break
430
+ acc += one
431
+ firstKeptIdx = i
432
+ }
433
+ if (firstKeptIdx >= rows.length) {
434
+ return Object.freeze({
435
+ sessionId: input.sessionId,
436
+ threadId: input.threadId,
437
+ frontier: full.frontier,
438
+ messages: [] as Message[],
439
+ source: "messages" as ContextSource,
440
+ coveredSeq: 0,
441
+ selectionBasis: "budget-tail" as SelectionBasis,
442
+ freshness: fullFreshness,
443
+ budget: {
444
+ limitTokens: limit,
445
+ estimatedTokens: 0,
446
+ reservedForSystemAndTools: reserved,
447
+ // Bahkan satu pesan tak muat: view kosong, namun konten yang
448
+ // diminta TIDAK muat → fits=false (jujur; ini eviction, bukan sukses).
449
+ fits: false,
450
+ },
451
+ detail: `insufficient budget: even one message exceeds ${limit} tokens; empty view (honest)`,
452
+ })
453
+ }
454
+ // Batas aman: geser NAIK hanya MENYUSUT segmen (tetap <= budget).
455
+ let safeBase = rows[firstKeptIdx]!.seq
456
+ while (safeBase <= headSeq) {
457
+ if (boundaryIsSafe(boundaryRows, safeBase)) break
458
+ safeBase++
459
+ }
460
+ const selectedRows = safeBase > headSeq ? [] : rows.filter((r) => r.seq >= safeBase)
461
+ const tailMsgs = selectedRows.map((r) => r.message as Message)
462
+ const baseForFrontier = safeBase > headSeq ? headSeq : safeBase
463
+ const frontier = coverageOf(input, rows, baseForFrontier).frontier
464
+ const fresh = selectionFreshness(frontier, input.canonicalFrontier)
465
+ // N2: bila batas-aman menggeser segmen sampai KOSONG (segmen budget tak dapat
466
+ // diwakili tanpa memisahkan pasangan tool), view kosong TIDAK boleh melaporkan
467
+ // fits=true — konten yang diminta tidak dapat direpresentasikan. `fits=false`
468
+ // (eviction jujur, sejalan dengan cabang insufficient-budget di atas).
469
+ if (tailMsgs.length === 0) {
470
+ return Object.freeze({
471
+ sessionId: input.sessionId,
472
+ threadId: input.threadId,
473
+ frontier,
474
+ messages: [] as Message[],
475
+ source: "messages" as ContextSource,
476
+ coveredSeq: 0,
477
+ selectionBasis: "budget-tail" as SelectionBasis,
478
+ freshness: fresh,
479
+ budget: {
480
+ limitTokens: limit,
481
+ estimatedTokens: 0,
482
+ reservedForSystemAndTools: reserved,
483
+ fits: false,
484
+ },
485
+ detail: `budget-tail empty: safe boundary shift left no representable segment (${limit} tokens); eviction, NOT a fold`,
486
+ })
487
+ }
488
+ return Object.freeze({
489
+ sessionId: input.sessionId,
490
+ threadId: input.threadId,
491
+ frontier,
492
+ messages: tailMsgs,
493
+ source: "messages" as ContextSource,
494
+ coveredSeq: 0,
495
+ selectionBasis: "budget-tail" as SelectionBasis,
496
+ freshness: fresh,
497
+ budget: report(tailMsgs),
498
+ detail: `budget-tail from seq ${baseForFrontier} (${sumTokens(tailMsgs, est)} <= ${limit}); prefix dropped = eviction, NOT a fold`,
499
+ })
500
+ }