minicode-ai 0.14.2 → 0.14.4

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 (76) hide show
  1. package/README.md +34 -178
  2. package/cli/args.ts +10 -18
  3. package/cli/commands/acp.ts +20 -27
  4. package/cli/commands/daemon.ts +6 -7
  5. package/cli/commands/exec.ts +12 -10
  6. package/cli/commands.ts +6 -9
  7. package/cli/index.ts +30 -15
  8. package/cli/provider-manager.ts +1 -3
  9. package/cli/setup.ts +167 -143
  10. package/cli/tui.ts +15 -23
  11. package/docs/CONTROL-PLANE-MAP.md +145 -0
  12. package/docs/OUTPUT_EVENT_MODEL.md +1 -1
  13. package/docs/OUTPUT_PROTOCOL_SPEC.md +2 -2
  14. package/docs/OUTPUT_RENDERING_SPEC.md +7 -2
  15. package/docs/OUTPUT_UX_RULES.md +1 -1
  16. package/docs/README.md +14 -102
  17. package/docs/SUMMARY.md +53 -0
  18. package/docs/TERMINAL_CONTRACT.md +84 -51
  19. package/docs/UI_RENDER_PIPELINE.md +204 -0
  20. package/docs/agents.md +5 -5
  21. package/docs/architecture.md +23 -12
  22. package/docs/choosing-mode.md +7 -7
  23. package/docs/cli.md +22 -29
  24. package/docs/concepts.md +1 -1
  25. package/docs/config.md +10 -5
  26. package/docs/contributing.md +6 -6
  27. package/docs/environment.md +3 -1
  28. package/docs/exec.md +5 -5
  29. package/docs/glossary.md +8 -6
  30. package/docs/memory-sessions.md +7 -5
  31. package/docs/policy-sandbox.md +16 -14
  32. package/docs/quickstart.md +2 -2
  33. package/docs/repl.md +4 -3
  34. package/docs/security-model.md +14 -15
  35. package/docs/security.md +8 -29
  36. package/docs/skills.md +1 -1
  37. package/docs/tools.md +2 -2
  38. package/package.json +5 -3
  39. package/scripts/vendor-overlays/minicode-context.patch +109 -0
  40. package/src/app/provider-layer.ts +13 -1
  41. package/src/app/session.ts +216 -13
  42. package/src/config.ts +30 -3
  43. package/src/constants.ts +2 -0
  44. package/src/daemon/control.ts +1 -1
  45. package/src/mcp/server.ts +2 -3
  46. package/src/policy/compaction.ts +272 -16
  47. package/src/policy/context-window.ts +73 -0
  48. package/src/policy/context.ts +55 -3
  49. package/src/policy/ratelimit.ts +47 -18
  50. package/src/policy/usage.ts +15 -8
  51. package/src/policy/work-mode.ts +1 -1
  52. package/src/providers/guards.ts +61 -4
  53. package/src/providers/provision.ts +12 -3
  54. package/src/providers/router.ts +56 -23
  55. package/src/session/context-projection.ts +14 -0
  56. package/src/session/context-selector.ts +58 -20
  57. package/src/session/persistence.ts +1 -1
  58. package/src/task/model.ts +21 -70
  59. package/src/tools/task.ts +7 -0
  60. package/src/ui/footer.ts +131 -66
  61. package/src/ui/i18n/en.ts +0 -11
  62. package/src/ui/i18n/id.ts +0 -11
  63. package/src/ui/input/input.ts +2 -3
  64. package/src/ui/input/prompt-engine.ts +2 -5
  65. package/src/ui/screens/model-manager.ts +3 -10
  66. package/src/ui/screens/picker.ts +23 -40
  67. package/src/ui/screens/provider-manager.ts +12 -33
  68. package/src/ui/screens/wizard.ts +0 -1
  69. package/src/ui/tui/app.ts +10 -6
  70. package/src/ui/tui/transcript.ts +48 -8
  71. package/vendor/minicore/VENDOR.md +9 -5
  72. package/vendor/minicore/src/core/loop.ts +47 -12
  73. package/vendor/minicore/src/core/provider.ts +4 -0
  74. package/vendor/minicore/src/core/session.ts +14 -1
  75. package/docs/OUTPUT_ARCHITECTURE_AUDIT.md +0 -489
  76. package/docs/OUTPUT_IMPLEMENTATION_PLAN.md +0 -391
@@ -236,13 +236,15 @@ export function watchBudgetLimit(opts: {
236
236
  export function watchContextWindowLimit(opts: {
237
237
  bus: EventBus
238
238
  /** Batas window konteks (W). Bila 0/undefined → no-op. */
239
- windowTokens: number
239
+ windowTokens: number | (() => number)
240
240
  /** Snapshot token request provider aktif; window berlaku per request. */
241
241
  getRequestTokens: () => { inputTokens: number; outputTokens: number } | null
242
- onOver: (allowed: number, actual: number) => void
242
+ onOver: (allowed: number, actual: number, inputTokens?: number) => void
243
243
  }): () => void {
244
- const W = opts.windowTokens
245
- if (!Number.isFinite(W) || W <= 0) return () => {}
244
+ const readWindow = () =>
245
+ typeof opts.windowTokens === "function" ? opts.windowTokens() : opts.windowTokens
246
+ const initialWindow = readWindow()
247
+ if (!Number.isFinite(initialWindow) || initialWindow <= 0) return () => {}
246
248
  let fired = false
247
249
  const check = () => {
248
250
  if (fired) return
@@ -250,15 +252,20 @@ export function watchContextWindowLimit(opts: {
250
252
  // Belum ada usage untuk request aktif: jangan memakai snapshot request
251
253
  // sebelumnya atau total token kumulatif turn sebagai pengganti.
252
254
  if (!request) return
253
- const allowedOutput = Math.max(256, Math.floor(W - request.inputTokens))
255
+ const W = readWindow()
256
+ if (!Number.isFinite(W) || W <= 0) return
257
+ const allowedOutput = Math.max(0, Math.floor(W - request.inputTokens))
254
258
  const output = request.outputTokens
255
- if (output > allowedOutput) {
259
+ if (request.inputTokens > W || output > allowedOutput) {
256
260
  fired = true
257
- opts.onOver(allowedOutput, output)
261
+ opts.onOver(allowedOutput, output, request.inputTokens)
258
262
  }
259
263
  }
260
264
  const offExt = opts.bus.on("provider:extension", (e) => {
261
- if (e.kind === "usage") check()
265
+ if (e.kind === "usage") {
266
+ const data = e.data as { source?: unknown } | undefined
267
+ if (data?.source !== "compaction") check()
268
+ }
262
269
  })
263
270
  check()
264
271
  return () => {
@@ -30,7 +30,7 @@ export class VerifyWorkModeConflictError extends Error {
30
30
  readonly workMode: Exclude<WorkMode, "EXECUTE">
31
31
  constructor(workMode: Exclude<WorkMode, "EXECUTE">) {
32
32
  super(
33
- `[work-mode] --verify cannot be combined with WorkMode ${workMode} (verification runs shell commands and self-heal turns; use --work-mode EXECUTE or omit --verify)`,
33
+ `[work-mode] --verify cannot be combined with WorkMode ${workMode} (verification runs shell commands and self-heal turns; use --work-mode BUILD or omit --verify)`,
34
34
  )
35
35
  this.name = "VerifyWorkModeConflictError"
36
36
  this.workMode = workMode
@@ -25,7 +25,13 @@ export function withStreamGuards(
25
25
  maxTotalToolArgBytes?: number
26
26
  } = {},
27
27
  ): ModelProvider {
28
- const timeoutMs = opts.timeoutMs ?? LIMITS.PROVIDER_REQUEST_TIMEOUT_MS
28
+ const configuredTimeout = opts.timeoutMs
29
+ const timeoutMs =
30
+ typeof configuredTimeout === "number" &&
31
+ Number.isFinite(configuredTimeout) &&
32
+ configuredTimeout > 0
33
+ ? Math.min(LIMITS.MAX_TIMER_DELAY_MS, Math.max(1, Math.floor(configuredTimeout)))
34
+ : LIMITS.PROVIDER_REQUEST_TIMEOUT_MS
29
35
  const maxTextChars = opts.maxTextChars ?? LIMITS.PROVIDER_TEXT_MAX_CHARS
30
36
  // Reasoning = bukan bagian jawaban; cap agresif (2MB logis ≈ 500k token —
31
37
  // jauh di atas reasoning sah mana pun, jauh di bawah OOM).
@@ -61,8 +67,6 @@ export function withStreamGuards(
61
67
  timedOut = true
62
68
  ctl.abort(new Error(`provider request timed out after ${timeoutMs}ms`))
63
69
  }, timeoutMs)
64
- // Jangan menahan exit proses bila turn sudah selesai dari sisi lain.
65
- ;(timer as unknown as { unref?: () => void }).unref?.()
66
70
  let textChars = 0
67
71
  let reasonChars = 0
68
72
  let toolArgumentBytes = 0
@@ -71,8 +75,13 @@ export function withStreamGuards(
71
75
  let finishReason: "stop" | "tool_calls" | "length" | "abort" | "error" | undefined
72
76
  let hadVisibleOutput = false
73
77
  let invalidated = false
78
+ let iterator: AsyncIterator<ProviderEvent> | undefined
74
79
  try {
75
- for await (const ev of provider.stream(request, ctl.signal)) {
80
+ iterator = provider.stream(request, ctl.signal)[Symbol.asyncIterator]()
81
+ while (true) {
82
+ const next = await nextOrAbort(iterator, ctl.signal)
83
+ if (next.done) break
84
+ const ev = next.value
76
85
  if (
77
86
  finishReason !== undefined &&
78
87
  (ev.type === "text" || ev.type === "tool_call" || ev.type === "finish")
@@ -186,7 +195,55 @@ export function withStreamGuards(
186
195
  } finally {
187
196
  clearTimeout(timer)
188
197
  signal.removeEventListener("abort", onParentAbort)
198
+ if (!ctl.signal.aborted && finishReason !== "stop" && finishReason !== "tool_calls") {
199
+ ctl.abort(new DOMException("Provider stream closed", "AbortError"))
200
+ }
201
+ if (ctl.signal.aborted && iterator?.return) {
202
+ try {
203
+ void Promise.resolve(iterator.return()).catch(() => {})
204
+ } catch {}
205
+ }
189
206
  }
190
207
  },
191
208
  }
192
209
  }
210
+
211
+ function nextOrAbort<T>(
212
+ iterator: AsyncIterator<T>,
213
+ signal: AbortSignal,
214
+ ): Promise<IteratorResult<T>> {
215
+ if (signal.aborted)
216
+ return Promise.reject(signal.reason ?? new DOMException("Aborted", "AbortError"))
217
+ return new Promise((resolve, reject) => {
218
+ const onAbort = () => {
219
+ cleanup()
220
+ reject(signal.reason ?? new DOMException("Aborted", "AbortError"))
221
+ }
222
+ signal.addEventListener("abort", onAbort, { once: true })
223
+ if (signal.aborted) {
224
+ onAbort()
225
+ return
226
+ }
227
+ let next: Promise<IteratorResult<T>>
228
+ try {
229
+ next = Promise.resolve(iterator.next())
230
+ } catch (error) {
231
+ cleanup()
232
+ reject(error)
233
+ return
234
+ }
235
+ next.then(
236
+ (value) => {
237
+ cleanup()
238
+ resolve(value)
239
+ },
240
+ (error) => {
241
+ cleanup()
242
+ reject(error)
243
+ },
244
+ )
245
+ function cleanup() {
246
+ signal.removeEventListener("abort", onAbort)
247
+ }
248
+ })
249
+ }
@@ -62,8 +62,15 @@ export async function saveProvider(
62
62
  if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e
63
63
  }
64
64
  const idx = cfg.providers.findIndex((p) => p.id === entry.id)
65
- if (idx >= 0) cfg.providers[idx] = entry
66
- else cfg.providers.push(entry)
65
+ if (idx >= 0) {
66
+ const previous = cfg.providers[idx]!
67
+ cfg.providers[idx] = {
68
+ ...entry,
69
+ ...(entry.contextWindows === undefined && previous.contextWindows
70
+ ? { contextWindows: previous.contextWindows }
71
+ : {}),
72
+ }
73
+ } else cfg.providers.push(entry)
67
74
  await writeConfigAtomic(path, cfg)
68
75
  })
69
76
  }
@@ -149,13 +156,15 @@ export async function detectAndSave(
149
156
  const uniqId = deriveProviderId(baseUrl, existing, id)
150
157
  // Pertahankan knob user (thinking effort) bila provider sudah ada — tanpa
151
158
  // ini tiap add/edit me-reset effort ke default diam-diam ("hilang").
152
- const prevEffort = prevCfg.providers.find((p) => p.id === uniqId)?.reasoningEffort
159
+ const previous = prevCfg.providers.find((p) => p.id === uniqId)
160
+ const prevEffort = previous?.reasoningEffort
153
161
  const entry: ProviderEntry = {
154
162
  id: uniqId,
155
163
  baseUrl,
156
164
  apiKey,
157
165
  models: detected.models,
158
166
  providerHint: detected.providerHint,
167
+ ...(previous?.contextWindows ? { contextWindows: previous.contextWindows } : {}),
159
168
  ...(prevEffort ? { reasoningEffort: prevEffort } : {}),
160
169
  }
161
170
  await saveProvider(entry, opts)
@@ -3,17 +3,25 @@ import { ProviderError } from "#minicore/core/errors.ts"
3
3
  import type { ModelProvider, ProviderEvent, StreamRequest } from "#minicore/core/provider.ts"
4
4
  import type { Message } from "#minicore/core/types.ts"
5
5
  import { LIMITS } from "../constants.ts"
6
- import type { RateLimiter } from "../policy/ratelimit.ts"
6
+ import { DEFAULT_FALLBACK_CONTEXT_WINDOW_TOKENS } from "../policy/context-window.ts"
7
+ import { type RateLimiter, waitAbortable } from "../policy/ratelimit.ts"
7
8
 
8
9
  export interface RouterConfig {
9
10
  providers: ModelProvider[]
10
11
  defaultProviderId?: string
12
+ contextWindowTokensForModel?: (model?: string) => number
11
13
  // P2 cap
12
14
  maxRetryAfterMs?: number // default LIMITS.RETRY_AFTER_MAX_MS
13
15
  // Token bucket rate limiter (opsional) — cegah request beruntun kena 429
14
16
  limiter?: RateLimiter
15
17
  }
16
18
 
19
+ export type RouterProvider = ModelProvider & {
20
+ updateProviders: (list: ModelProvider[]) => void
21
+ updateContextWindowResolver: (resolver: (model?: string) => number) => void
22
+ contextModelIdentity: (model?: string) => string | undefined
23
+ }
24
+
17
25
  // C4 fix: convert Uint8Array tool content to base64 before an openai-compat
18
26
  // provider sees it. Anthropic handles Uint8Array natively (image →
19
27
  // source.base64 + media_type in toAnthropicMessages) — converting up-front
@@ -75,15 +83,21 @@ function requestFor(
75
83
  return { req: fixed, substituted: false }
76
84
  }
77
85
 
78
- export function createRouterProvider(config: RouterConfig): ModelProvider {
79
- const maxRetry = config.maxRetryAfterMs ?? LIMITS.RETRY_AFTER_MAX_MS
86
+ export function createRouterProvider(config: RouterConfig): RouterProvider {
87
+ const configuredMaxRetry = config.maxRetryAfterMs
88
+ const maxRetry =
89
+ typeof configuredMaxRetry === "number" &&
90
+ Number.isSafeInteger(configuredMaxRetry) &&
91
+ configuredMaxRetry >= 0
92
+ ? configuredMaxRetry
93
+ : LIMITS.RETRY_AFTER_MAX_MS
80
94
  // byId dan defaultId dihitung per-stream agar provider yang baru ditambah via /provider
81
95
  // langsung dikenali tanpa restart. Provider list bisa berubah mid-session.
82
96
  const getById = () => new Map(config.providers.map((p) => [p.id, p]))
83
97
  const getDefaultId = () => config.defaultProviderId ?? config.providers[0]?.id ?? "router"
84
98
  const getModels = () => config.providers.flatMap((p) => [...p.models])
85
99
 
86
- const router: ModelProvider & { updateProviders: (list: ModelProvider[]) => void } = {
100
+ const router: RouterProvider = {
87
101
  id: "router",
88
102
  get models() {
89
103
  return getModels()
@@ -91,6 +105,21 @@ export function createRouterProvider(config: RouterConfig): ModelProvider {
91
105
  updateProviders(list: ModelProvider[]) {
92
106
  config.providers.splice(0, config.providers.length, ...list)
93
107
  },
108
+ updateContextWindowResolver(resolver) {
109
+ config.contextWindowTokensForModel = resolver
110
+ },
111
+ contextWindowTokensForModel(model?: string) {
112
+ return config.contextWindowTokensForModel?.(model) ?? DEFAULT_FALLBACK_CONTEXT_WINDOW_TOKENS
113
+ },
114
+ contextModelIdentity(model?: string) {
115
+ if (model?.includes("::")) return model
116
+ let provider = model
117
+ ? config.providers.find((entry) => entry.models.includes(model))
118
+ : (getById().get(getDefaultId()) ?? config.providers[0])
119
+ provider ??= getById().get(getDefaultId()) ?? config.providers[0]
120
+ const effectiveModel = model && provider?.models.includes(model) ? model : provider?.models[0]
121
+ return provider && effectiveModel ? `${provider.id}::${effectiveModel}` : effectiveModel
122
+ },
94
123
  async *stream(request: StreamRequest, signal: AbortSignal): AsyncIterable<ProviderEvent> {
95
124
  // route by model name — first match wins (default/daftar urutan provider)
96
125
  // Format "providerId::modelName" = PIN eksplisit (kontrak): provider itu
@@ -144,7 +173,7 @@ export function createRouterProvider(config: RouterConfig): ModelProvider {
144
173
  let hasYieldedContent = false
145
174
  try {
146
175
  // rate limit: tunggu token bucket sebelum tiap request
147
- if (config.limiter) await config.limiter.acquire()
176
+ if (config.limiter) await config.limiter.acquire(signal)
148
177
  const fixed = needsBinaryFix(current) ? fixRequest(request) : request
149
178
  const withSys = needsSystemMessage(current) ? withSystemMessage(fixed) : fixed
150
179
  const { req, effectiveModel, substituted } = requestFor(current, { ...withSys, model })
@@ -180,7 +209,19 @@ export function createRouterProvider(config: RouterConfig): ModelProvider {
180
209
  ) {
181
210
  hasYieldedContent = true
182
211
  }
183
- yield ev
212
+ if (ev.type === "extension" && ev.kind === "usage") {
213
+ const data = ev.data && typeof ev.data === "object" ? ev.data : {}
214
+ yield {
215
+ ...ev,
216
+ data: {
217
+ ...(data as Record<string, unknown>),
218
+ model: req.model ?? model,
219
+ provider: current.id,
220
+ },
221
+ }
222
+ } else {
223
+ yield ev
224
+ }
184
225
  }
185
226
  return
186
227
  } catch (e) {
@@ -189,8 +230,13 @@ export function createRouterProvider(config: RouterConfig): ModelProvider {
189
230
  if (hasYieldedContent) throw e
190
231
  // cap retryAfter without mutating original
191
232
  let err: ProviderError = e
192
- if (e.retryAfterMs != null && e.retryAfterMs > maxRetry) {
193
- err = new ProviderError(e.category, e.message, maxRetry)
233
+ if (
234
+ e.retryAfterMs != null &&
235
+ (!Number.isFinite(e.retryAfterMs) || e.retryAfterMs < 0)
236
+ ) {
237
+ err = new ProviderError(e.category, e.message, undefined, e.cause)
238
+ } else if (e.retryAfterMs != null && e.retryAfterMs > maxRetry) {
239
+ err = new ProviderError(e.category, e.message, maxRetry, e.cause)
194
240
  }
195
241
  // P11 P1.3 — honori retry-after. Audit #14: fallback DULU bila ada
196
242
  // alternatif — jangan bakar sleep (maks 30 dtk) saat provider
@@ -212,20 +258,7 @@ export function createRouterProvider(config: RouterConfig): ModelProvider {
212
258
  }
213
259
  }
214
260
  const waitMs = Math.min(err.retryAfterMs, maxRetry)
215
- if (signal.aborted) throw new DOMException("Aborted", "AbortError")
216
- let onAbort: (() => void) | undefined
217
- try {
218
- await Promise.race([
219
- Bun.sleep(waitMs),
220
- new Promise<void>((_, rej) => {
221
- onAbort = () => rej(new DOMException("Aborted", "AbortError"))
222
- if (signal.aborted) onAbort()
223
- else signal.addEventListener("abort", onAbort, { once: true })
224
- }),
225
- ])
226
- } finally {
227
- if (onAbort) signal.removeEventListener("abort", onAbort)
228
- }
261
+ await waitAbortable(waitMs, signal)
229
262
  // Pin: tetap di provider yang dipilih (tunggu lalu ulangi di
230
263
  // tempat) — jangan pindah ke provider lain.
231
264
  if (pinned) continue
@@ -256,5 +289,5 @@ export function createRouterProvider(config: RouterConfig): ModelProvider {
256
289
  }
257
290
  },
258
291
  }
259
- return router as ModelProvider
292
+ return router
260
293
  }
@@ -29,6 +29,7 @@
29
29
 
30
30
  import { ContextStore, mechanicalCompaction } from "#minicore"
31
31
  import type { Message } from "#minicore/core/types.ts"
32
+ import { LIMITS } from "../constants.ts"
32
33
  import { renderFullHistoryFold } from "./full-history-fold.ts"
33
34
  import {
34
35
  buildProjection,
@@ -100,6 +101,18 @@ export function deriveSummaryFromCanonical(
100
101
  return { summaryText, baseSeq }
101
102
  }
102
103
 
104
+ function boundProjectionSummary(text: string): string {
105
+ const cap = LIMITS.COMPACTION_SUMMARY_MAX_CHARS
106
+ if (text.length <= cap) return text
107
+ const marker = "\n[projection summary truncated; older details may be missing]"
108
+ let head = text.slice(0, Math.max(0, cap - marker.length))
109
+ if (head.length > 0) {
110
+ const code = head.charCodeAt(head.length - 1)
111
+ if (code >= 0xd800 && code <= 0xdbff) head = head.slice(0, -1)
112
+ }
113
+ return `${head}${marker}`
114
+ }
115
+
103
116
  /**
104
117
  * Bungkus P3.7 `renderFullHistoryFold` untuk seam produsen: ubah baris thread
105
118
  * menjadi input renderer, dan ubah `FoldError` (cakupan tak-terbukti) menjadi
@@ -182,6 +195,7 @@ export function produceSummaryProjection(
182
195
  if (baseSeq === undefined || baseSeq <= 0) {
183
196
  return { produced: false, detail: "no explicit/derivable baseSeq — refusing empty projection" }
184
197
  }
198
+ summaryText = boundProjectionSummary(summaryText)
185
199
  // Tulis lewat primitif P2.7 (epoch-fenced, satu txn, delete+insert, sumber
186
200
  // kanonik UTUH). Satu-satunya efek tulis produsen = history_projections.
187
201
  const row = buildProjection(sessionId, threadId, summaryText, cwd, {
@@ -315,7 +315,7 @@ function selectionFreshness(
315
315
  *
316
316
  * Urutan strategi (audit §7):
317
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)
318
+ * 2. fallback-unknown — histori kanonik berlabel jujur bila muat
319
319
  * 3. full-history — histori kanonik penuh bila muat budget
320
320
  * 4. budget-tail — ekor kanonik terbaru yang muat budget
321
321
  */
@@ -359,36 +359,75 @@ export function selectContext(input: SelectContextInput): ContextSelection {
359
359
  const summaryText = input.projection.summaryText
360
360
  if (b > 0 && typeof summaryText === "string" && summaryText.length > 0) {
361
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
- })
362
+ const makeProjectionSelection = (text: string, truncated: boolean): ContextSelection => {
363
+ const synthetic = syntheticSummaryMessage(text, b)
364
+ const msgs: Message[] = [synthetic, ...tail]
365
+ const artifact: ContextOnlyArtifact = { role: "user", content: synthetic.content as string }
366
+ return Object.freeze({
367
+ sessionId: input.sessionId,
368
+ threadId: input.threadId,
369
+ frontier,
370
+ messages: msgs,
371
+ source: "projection" as ContextSource,
372
+ coveredSeq: b,
373
+ selectionBasis: "summary-plus-tail" as SelectionBasis,
374
+ freshness: selectionFreshness(frontier, input.canonicalFrontier),
375
+ budget: report(msgs),
376
+ detail: truncated
377
+ ? `durable summary covers [0,${b}) + canonical tail [${b},${headSeq}]; summary tail truncated to fit budget`
378
+ : `durable summary covers [0,${b}) + canonical tail [${b},${headSeq}]`,
379
+ contextOnly: artifact,
380
+ })
381
+ }
382
+ const complete = makeProjectionSelection(summaryText, false)
383
+ if (complete.budget.fits) return complete
384
+
385
+ // Projection texts can grow independently of the model window. Keep the
386
+ // most recent portion of the old summary and preserve the canonical tail
387
+ // only when the resulting pair fits; otherwise continue to budget-tail.
388
+ const marker = "[older projection prefix omitted for context budget]\n"
389
+ const tailTokens = sumTokens(tail, est)
390
+ if (tailTokens < limit) {
391
+ let low = 0
392
+ let high = summaryText.length
393
+ let best: ContextSelection | undefined
394
+ while (low <= high) {
395
+ const keep = Math.floor((low + high) / 2)
396
+ let suffix = summaryText.slice(summaryText.length - keep)
397
+ if (suffix.length > 0) {
398
+ const code = suffix.charCodeAt(0)
399
+ if (code >= 0xdc00 && code <= 0xdfff) suffix = suffix.slice(1)
400
+ }
401
+ const text = `${marker}${suffix}`
402
+ const candidate = makeProjectionSelection(text, true)
403
+ if (candidate.budget.fits) {
404
+ best = candidate
405
+ low = keep + 1
406
+ } else {
407
+ high = keep - 1
408
+ }
409
+ }
410
+ if (best) return best
411
+ }
378
412
  }
379
413
  // batas tak aman / ringkasan kosong → lanjut sebagai histori kanonik penuh.
380
414
  }
381
415
 
382
416
  const full = coverageOf(input, rows, 0)
383
417
  const fullFreshness = selectionFreshness(full.frontier, input.canonicalFrontier)
418
+ const fullTokens = sumTokens(full.messages, est)
384
419
 
385
420
  // ── Strategi 2: fallback-unknown (STALE/DIVERGED/UNKNOWN) ──────────────────
386
421
  // N3: baris BASI (view di belakang kanonis) TIDAK boleh dilabeli
387
422
  // "full-history" — label itu menyiratkan representasi kanonik yang trusted,
388
423
  // padahal view ini tak memutakhirkan diri ke head kanonis. Pakai
389
- // `fallback-unknown` (state yang sudah ada; bukan basis kelima yang baru).
424
+ // `fallback-unknown` bila histori penuh muat; bila tidak, teruskan ke
425
+ // budget-tail dengan status freshness tetap dihitung dari frontier terpilih.
390
426
  // Coverage completeness (semua baris tersedia diikutkan) ≠ freshness/trust.
391
- if (fullFreshness === "unknown" || fullFreshness === "diverged" || fullFreshness === "stale") {
427
+ if (
428
+ (fullFreshness === "unknown" || fullFreshness === "diverged" || fullFreshness === "stale") &&
429
+ fullTokens <= limit
430
+ ) {
392
431
  return Object.freeze({
393
432
  sessionId: input.sessionId,
394
433
  threadId: input.threadId,
@@ -404,7 +443,6 @@ export function selectContext(input: SelectContextInput): ContextSelection {
404
443
  }
405
444
 
406
445
  // ── Strategi 3: full-history (muat budget) ─────────────────────────────────
407
- const fullTokens = sumTokens(full.messages, est)
408
446
  if (fullTokens <= limit) {
409
447
  return Object.freeze({
410
448
  sessionId: input.sessionId,
@@ -217,7 +217,7 @@ function open(cwd?: string, local = false): Database {
217
217
  db.exec("ALTER TABLE sessions ADD COLUMN parent_run_id TEXT NULL")
218
218
  }
219
219
  // P0.2 (Q5): persistensi WorkMode di metadata sesi lintas `--resume`.
220
- // NULL = sesi legacy pra-P0.2 (resume fallback ke default EXECUTE).
220
+ // NULL = sesi legacy tanpa WorkMode tersimpan (resume fallback DISCUSS).
221
221
  if (!cols.some((c) => c.name === "work_mode")) {
222
222
  db.exec("ALTER TABLE sessions ADD COLUMN work_mode TEXT NULL")
223
223
  }
package/src/task/model.ts CHANGED
@@ -1,46 +1,14 @@
1
- // Task model types — the *domain* half of Phase 1.
2
- //
3
- // EVIDENCE NOTE. This file did NOT survive the wipe: there is no
4
- // `model.orig.ts` artifact and no `src/task/` in the recovered baseline. It is
5
- // reconstructed from the only two surviving sources of truth about it:
6
- //
7
- // 1. `store.orig.ts` — the actual pre-wipe implementation. Every field below
8
- // is pinned by `TaskRow` + `rowToTask()` + the construction sites in
9
- // `synchronizeTasks()`. Where the artifact *uses* a field, that field is
10
- // PROVEN, not guessed.
11
- // 2. `docs/TASK_IDENTITY_SPEC.md` + `docs/TASK_STATE_MACHINE_SPEC.md` —
12
- // in-repo design docs committed at baseline HEAD (`aa76dfb`).
13
- //
14
- // The two sources DISAGREE, and the disagreement is recorded rather than
15
- // smoothed over:
16
- //
17
- // | aspect | design doc | store.orig.ts (ACTUAL) |
18
- // |---------------|-------------------------------|------------------------|
19
- // | status casing | lowercase ("pending") | UPPERCASE ("PENDING") |
20
- // | blocker | `blocker: TaskBlocker` object | `blockedReason: string`|
21
- // | timestamps | `createdAt: number` | `createdAt: string` ISO|
22
- // | verification | `at: number` | `checkedAt: string` |
23
- // | provenance | `{source, actor, at}` | `{origin, source}` |
24
- // | titleKey | present | ABSENT |
25
- // | revision | ABSENT | present |
26
- //
27
- // The artifact wins. It is later evidence and it is the code that actually
28
- // ran. The doc is DESIGN-mode and predates the implementation.
29
- //
30
- // Every inference below is tagged `[INFERRED]`. Everything untagged is proven
31
- // by `store.orig.ts`.
1
+ // Domain types shared by TaskStore, TaskGraph, and scheduler code. Runtime
2
+ // invariants live in the current validators and persistence implementation.
32
3
 
33
4
  /**
34
5
  * Task lifecycle states.
35
6
  *
36
- * PROVEN by artifact usage: `PENDING` (the `rowToTask` fallback), `BLOCKED`
37
- * (the only status compared in `validate()`), `CANCELLED` (named in the
38
- * `deleteTask` comment as the sanctioned alternative to deletion).
7
+ * These values are persisted and validated by the task store. Producers may
8
+ * support only a subset of the declared lifecycle.
39
9
  *
40
- * [INFERRED] the remaining five, from `docs/TASK_STATE_MACHINE_SPEC.md` which
41
- * states the enum is "diperluas dari 5 ke 8" and lists them lowercase. Uppercased
42
- * to match the artifact's casing convention. None is ever written by the store
43
- * itself; they only widen what `isTaskStatus` accepts.
10
+ * The union includes lifecycle states accepted by the task domain. A type
11
+ * member alone does not imply that each producer currently emits that state.
44
12
  */
45
13
  export type TaskStatus =
46
14
  | "PENDING"
@@ -63,7 +31,7 @@ const TASK_STATUSES: readonly TaskStatus[] = [
63
31
  "CANCELLED",
64
32
  ]
65
33
 
66
- /** PROVEN: `rowToTask` calls this to decide whether a stored status is valid. */
34
+ /** Check whether a persisted status belongs to the task domain. */
67
35
  export function isTaskStatus(value: unknown): value is TaskStatus {
68
36
  return typeof value === "string" && TASK_STATUSES.includes(value as TaskStatus)
69
37
  }
@@ -180,33 +148,25 @@ export function isLegalTaskTransition(from: TaskStatus, to: TaskStatus): boolean
180
148
  * its running max at `0` and returns `taskIdFromIndex(max)`, so for an EMPTY
181
149
  * session (max = 0) the very first id must be `t1` — therefore the index is
182
150
  * 1-based and the mapping is `n -> t(n+1)`. This also reproduces the
183
- * artifact's own worked example: `t1,t2,t5` -> max 5 -> `t6`, not `t3`.
151
+ * store example: `t1,t2,t5` -> max 5 -> `t6`, not `t3`.
184
152
  */
185
153
  export function taskIdFromIndex(index: number): string {
186
154
  return `t${index + 1}`
187
155
  }
188
156
 
189
157
  /**
190
- * [INFERRED] Strict guard for a canonical id. `docs/TASK_IDENTITY_SPEC.md` fixes
191
- * the form as `t<n>` starting at 1, so `t0`, `t01` and `t-1` are all rejected.
192
- * `store.orig.ts` relies on this to reject model-supplied ids before they can
193
- * reach SQL, and `nextId()` re-parses with `Number(id.slice(1))`, which only
194
- * round-trips cleanly for `^t[1-9][0-9]*$`.
158
+ * Canonical task IDs use a positive, unpadded session-local integer. Reject
159
+ * values that cannot round-trip through the store's next-ID calculation.
195
160
  */
196
161
  const TASK_ID_RE = /^t[1-9][0-9]*$/
197
162
 
198
- /** PROVEN: guard used by `getTask`, `patchTask`, `deleteTask`. */
163
+ /** Guard canonical IDs at task-store entry points. */
199
164
  export function isTaskId(value: unknown): value is string {
200
165
  return typeof value === "string" && TASK_ID_RE.test(value)
201
166
  }
202
167
 
203
168
  /**
204
- * Verification record attached to a task.
205
- *
206
- * PROVEN from the artifact's only construction site
207
- * (`synchronizeTasks`): `{ verdict, detail?, checkedAt }` where `checkedAt` is
208
- * an ISO string from `nowIso()`. Note the field is `checkedAt`, NOT the
209
- * `at: number` the design doc proposed — artifact wins.
169
+ * Verification record persisted with a task. `checkedAt` is an ISO timestamp.
210
170
  */
211
171
  export interface TaskVerification {
212
172
  verdict: "passed" | "failed" | "unverified"
@@ -219,12 +179,8 @@ export type TaskEvidenceKind = "completion" | "receipt" | "test" | "verify" | "c
219
179
  /**
220
180
  * Evidence record appended on every synchronization.
221
181
  *
222
- * PROVEN from the artifact's construction site: `{ kind: "completion", detail,
223
- * at }` with `at` an ISO string.
224
- *
225
- * [INFERRED] the wider kind union, from `docs/TASK_STATE_MACHINE_SPEC.md`
226
- * (`EvidenceKind`). The store only ever writes `"completion"`; the rest exist so
227
- * a later phase can name evidence without another migration.
182
+ * Evidence kinds describe the source of a task completion claim or related
183
+ * verification record.
228
184
  */
229
185
  export interface TaskEvidence {
230
186
  kind: TaskEvidenceKind
@@ -235,18 +191,15 @@ export interface TaskEvidence {
235
191
  /**
236
192
  * [INFERRED] Acceptance criteria.
237
193
  *
238
- * UNRECOVERABLE SHAPE: the artifact stores and returns this value but never
239
- * reads a field from it and never constructs a non-null one, so its real shape
240
- * is unrecoverable. Modelled as an opaque record — the store round-trips it
241
- * verbatim via JSON and deliberately interprets nothing. Guessing concrete
242
- * fields here would be pure invention with no behavioural consequence.
194
+ * The store round-trips this opaque JSON value and does not interpret its
195
+ * fields. Keep the shape open until a concrete consumer is introduced.
243
196
  */
244
197
  export type TaskAcceptance = Record<string, unknown>
245
198
 
246
199
  /**
247
200
  * Where a task came from.
248
201
  *
249
- * PROVEN from the artifact: the `rowToTask` default is
202
+ * The `rowToTask` default is
250
203
  * `{ origin: "runtime", source: "unknown" }` and `synchronizeTasks` writes
251
204
  * `{ origin: "model", source: "todo_write" }`. So `origin` is a closed
252
205
  * two-value union and `source` is an open string.
@@ -259,11 +212,9 @@ export interface TaskProvenance {
259
212
  /**
260
213
  * One durable task row.
261
214
  *
262
- * PROVEN field-for-field by `rowToTask()`, which is the authoritative
215
+ * Projected field-for-field by `rowToTask()`, which is the authoritative
263
216
  * projection: the DB column set and this object are in 1:1 correspondence.
264
- * `sessionId` and `revision` do not appear in the design doc at all — they
265
- * exist only in the artifact, and `revision` is the stale-write substrate
266
- * Phase 1 must preserve.
217
+ * `revision` is the stale-write substrate and must be preserved.
267
218
  */
268
219
  export interface Task {
269
220
  /** Stable, canonical `t<n>`, allocated by the store. Never reused. */
@@ -288,13 +239,13 @@ export interface Task {
288
239
  revision: number
289
240
  }
290
241
 
291
- /** PROVEN: `getSnapshot()` returns exactly this. */
242
+ /** Snapshot returned by `getSnapshot()`. */
292
243
  export interface TaskSnapshot {
293
244
  sessionId: string
294
245
  tasks: Task[]
295
246
  }
296
247
 
297
- /** Error codes the artifact actually raises, plus nothing invented. */
248
+ /** Error codes emitted by the task store. */
298
249
  export type TaskErrorCode =
299
250
  | "TASK_DB_INIT_FAILURE"
300
251
  | "TASK_INVALID_ID"