minicode-ai 0.11.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +98 -0
- package/LICENSE +21 -21
- package/README.md +4 -4
- package/cli/args.ts +46 -0
- package/cli/commands/acp.ts +163 -10
- package/cli/commands/config.ts +33 -18
- package/cli/commands/daemon.ts +515 -0
- package/cli/commands/exec.ts +145 -53
- package/cli/commands/openwork.ts +986 -0
- package/cli/commands/sessions.ts +4 -1
- package/cli/commands/stats.ts +34 -4
- package/cli/commands.ts +217 -2
- package/cli/index.ts +146 -14
- package/cli/recovery-warning.ts +115 -0
- package/cli/router.ts +32 -1
- package/cli/setup.ts +2332 -171
- package/cli/tui.ts +113 -7
- package/docs/OUTPUT_ARCHITECTURE_AUDIT.md +489 -0
- package/docs/OUTPUT_EVENT_MODEL.md +289 -0
- package/docs/OUTPUT_IMPLEMENTATION_PLAN.md +391 -0
- package/docs/OUTPUT_PROTOCOL_SPEC.md +285 -0
- package/docs/OUTPUT_RENDERING_SPEC.md +248 -0
- package/docs/OUTPUT_UX_RULES.md +449 -0
- package/docs/PLAN_UIUX_V6.md +2 -2
- package/docs/README.md +4 -3
- package/docs/TERMINAL_CONTRACT.md +278 -66
- package/docs/architecture.md +89 -7
- package/docs/changelog.md +1 -1
- package/docs/choosing-mode.md +2 -2
- package/docs/cli.md +9 -5
- package/docs/concepts.md +1 -1
- package/docs/contributing.md +9 -2
- package/docs/environment.md +6 -2
- package/docs/exec.md +46 -5
- package/docs/memory-sessions.md +2 -0
- package/docs/policy-sandbox.md +1 -1
- package/docs/pricing-budget.md +1 -1
- package/docs/quickstart.md +2 -2
- package/docs/repl.md +6 -2
- package/docs/security-model.md +1 -1
- package/docs/security.md +1 -1
- package/docs/skills.md +2 -2
- package/docs/terminal.md +9 -5
- package/docs/tools.md +1 -1
- package/package.json +35 -5
- package/src/app/session.ts +261 -15
- package/src/app/tool-layer.ts +94 -7
- package/src/daemon/approvals.ts +361 -0
- package/src/daemon/capability.ts +145 -0
- package/src/daemon/children.ts +142 -0
- package/src/daemon/client.ts +267 -0
- package/src/daemon/control.ts +350 -0
- package/src/daemon/discovery.ts +234 -0
- package/src/daemon/feed.ts +155 -0
- package/src/daemon/framing.ts +94 -0
- package/src/daemon/host.ts +316 -0
- package/src/daemon/protocol.ts +217 -0
- package/src/daemon/resource.ts +170 -0
- package/src/daemon/sanitize.ts +57 -0
- package/src/daemon/server.ts +627 -0
- package/src/daemon/store.ts +317 -0
- package/src/daemon/subscription.ts +270 -0
- package/src/daemon/telemetry.ts +81 -0
- package/src/hooks/run.ts +12 -1
- package/src/lib/atomic-write.ts +29 -3
- package/src/lib/db-path.ts +26 -0
- package/src/lib/keystore.ts +544 -42
- package/src/lib/net.ts +43 -1
- package/src/lib/safe-open.ts +116 -1
- package/src/lib/session-id.ts +15 -0
- package/src/lsp/client.ts +123 -5
- package/src/mcp/client.ts +139 -17
- package/src/mcp/server.ts +177 -50
- package/src/mcp/transport.ts +16 -19
- package/src/memory/vector.ts +770 -55
- package/src/policy/allowlist.ts +14 -2
- package/src/policy/bash-guard.ts +105 -10
- package/src/policy/compaction.ts +82 -5
- package/src/policy/consequence-engine.ts +220 -0
- package/src/policy/context.ts +132 -0
- package/src/policy/executor.ts +187 -121
- package/src/policy/no-progress.ts +559 -0
- package/src/policy/permission.ts +4 -8
- package/src/policy/pricing.ts +17 -3
- package/src/policy/scrub.ts +69 -2
- package/src/policy/tool-contract.ts +515 -0
- package/src/policy/usage.ts +310 -24
- package/src/policy/verifier.ts +6 -3
- package/src/policy/work-mode.ts +182 -0
- package/src/presentation/adapter.ts +533 -26
- package/src/presentation/events.ts +151 -0
- package/src/presentation/model.ts +180 -27
- package/src/presentation/projection.ts +858 -0
- package/src/presentation/reducer.ts +645 -310
- package/src/presentation/store.ts +12 -7
- package/src/providers/anthropic.ts +18 -10
- package/src/providers/responses.ts +17 -7
- package/src/runtime/capability.ts +409 -0
- package/src/runtime/child-execution.ts +274 -0
- package/src/runtime/composition.ts +958 -0
- package/src/runtime/dispatch.ts +591 -0
- package/src/runtime/execution-backend.ts +632 -0
- package/src/runtime/execution-events.ts +272 -0
- package/src/runtime/execution-id.ts +230 -0
- package/src/runtime/execution-journal.ts +926 -0
- package/src/runtime/execution-kernel.ts +456 -0
- package/src/runtime/execution-registry.ts +379 -0
- package/src/runtime/process-supervision.ts +276 -0
- package/src/runtime/production-execution.ts +551 -0
- package/src/runtime/production-runtime.ts +217 -0
- package/src/runtime/recovery-safety.ts +70 -0
- package/src/runtime/recovery.ts +477 -0
- package/src/runtime/runtime-capabilities.ts +179 -0
- package/src/runtime/runtime-diagnostics.ts +141 -0
- package/src/runtime/runtime-host.ts +365 -0
- package/src/runtime/runtime-status-facts.ts +222 -0
- package/src/runtime/runtime-status-provider.ts +74 -0
- package/src/runtime/runtime-status.ts +459 -0
- package/src/runtime/runtime-task-admission.ts +101 -0
- package/src/runtime/supervisor.ts +444 -0
- package/src/session/authority.ts +168 -0
- package/src/session/checkpoint.ts +88 -1
- package/src/session/context-adapter.ts +251 -0
- package/src/session/context-assembly.ts +242 -0
- package/src/session/context-identity.ts +389 -0
- package/src/session/context-projection.ts +248 -0
- package/src/session/context-selector.ts +500 -0
- package/src/session/cross-session-adoption.ts +249 -0
- package/src/session/full-history-fold.ts +171 -0
- package/src/session/identity.ts +192 -0
- package/src/session/journal.ts +805 -102
- package/src/session/open-work-intent.ts +732 -0
- package/src/session/open-work.ts +767 -0
- package/src/session/pending-tools.ts +94 -0
- package/src/session/persistence.ts +3569 -127
- package/src/session/runtime-header.ts +208 -0
- package/src/session/shadow-git.ts +13 -5
- package/src/session/verification.ts +1623 -0
- package/src/task/assignment.ts +136 -0
- package/src/task/autonomous-adapter.ts +168 -0
- package/src/task/autonomous-context.ts +630 -0
- package/src/task/autonomous-policy.ts +490 -0
- package/src/task/continuity.ts +179 -0
- package/src/task/execution-cancellation.ts +165 -0
- package/src/task/graph-validate.ts +379 -0
- package/src/task/graph.ts +305 -0
- package/src/task/identity.ts +230 -0
- package/src/task/model.ts +417 -0
- package/src/task/production-scheduler.ts +293 -0
- package/src/task/readiness.ts +229 -0
- package/src/task/scheduler-observability.ts +387 -0
- package/src/task/scheduler.ts +1197 -0
- package/src/task/scheduling-policy.ts +165 -0
- package/src/task/session-authority.ts +148 -0
- package/src/task/session-ownership.ts +211 -0
- package/src/task/store.ts +2887 -0
- package/src/task/sync.ts +343 -0
- package/src/task/trigger.ts +260 -0
- package/src/tools/bash.ts +377 -211
- package/src/tools/code_run.ts +1 -1
- package/src/tools/delete_file.ts +1 -1
- package/src/tools/edit.ts +33 -6
- package/src/tools/evidence.ts +30 -0
- package/src/tools/git.ts +4 -4
- package/src/tools/glob.ts +12 -3
- package/src/tools/grep.ts +1 -1
- package/src/tools/lsp.ts +4 -4
- package/src/tools/mcp_call.ts +11 -4
- package/src/tools/memory.ts +153 -18
- package/src/tools/move_file.ts +1 -1
- package/src/tools/patch.ts +1 -1
- package/src/tools/read_file.ts +1 -1
- package/src/tools/read_image.ts +1 -1
- package/src/tools/submit_result.ts +1 -1
- package/src/tools/task.ts +437 -41
- package/src/tools/todo.ts +662 -35
- package/src/tools/web_fetch.ts +4 -2
- package/src/tools/web_search.ts +9 -3
- package/src/tools/write_file.ts +1 -1
- package/src/ui/assistant/simple.ts +123 -50
- package/src/ui/assistant/turn-status.ts +17 -3
- package/src/ui/contract.ts +184 -0
- package/src/ui/footer.ts +54 -18
- package/src/ui/i18n/en.ts +62 -6
- package/src/ui/i18n/id.ts +62 -6
- package/src/ui/input/prompt-engine.ts +120 -25
- package/src/ui/render/errors.ts +39 -1
- package/src/ui/render/markdown-table.ts +455 -0
- package/src/ui/render/markdown.ts +22 -1
- package/src/ui/render/table-grid.ts +184 -0
- package/src/ui/render/table.ts +15 -76
- package/src/ui/runtime/screen.ts +7 -2
- package/src/ui/runtime/statusline.ts +25 -6
- package/src/ui/tui/app.ts +598 -133
- package/src/ui/tui/transcript.ts +531 -89
- package/vendor/minicore/VENDOR.md +1 -1
- package/vendor/minicore/src/core/budget.ts +25 -25
- package/vendor/minicore/src/core/compact.ts +75 -75
- package/vendor/minicore/src/core/errors.ts +59 -59
- package/vendor/minicore/src/core/events.ts +73 -73
- package/vendor/minicore/src/core/executor.ts +139 -139
- package/vendor/minicore/src/core/history.ts +31 -31
- package/vendor/minicore/src/core/index.ts +41 -41
- package/vendor/minicore/src/core/loop.ts +355 -355
- package/vendor/minicore/src/core/permission.ts +22 -22
- package/vendor/minicore/src/core/provider.ts +39 -39
- package/vendor/minicore/src/core/recovery.ts +35 -35
- package/vendor/minicore/src/core/session.ts +327 -327
- package/vendor/minicore/src/core/snapshot.ts +146 -146
- package/vendor/minicore/src/core/tokens.ts +107 -107
- package/vendor/minicore/src/core/tool.ts +115 -115
- package/vendor/minicore/src/core/types.ts +50 -50
- package/vendor/minicore/src/providers/openai-compat.ts +417 -417
- package/AGENTS.md +0 -45
- package/PLAN.md +0 -491
- package/docs/ARCHITECTURE.html +0 -1248
- package/docs/CONTROL-PLANE-MAP.md +0 -139
- package/docs/HARNESS.md +0 -150
- package/docs/SUMMARY.md +0 -52
- package/docs/UI_RENDER_PIPELINE.md +0 -165
- package/docs/USAGE.md +0 -11
|
@@ -0,0 +1,389 @@
|
|
|
1
|
+
// P3.2 — Context Identity + Frontier: formal, deterministik, terekonstruksi.
|
|
2
|
+
//
|
|
3
|
+
// Menjawab SATU pertanyaan: "Context ini adalah view dari canonical state
|
|
4
|
+
// yang mana?" — tanpa menjadikan Context authority baru. Model yang dikunci:
|
|
5
|
+
//
|
|
6
|
+
// SESSION = durable canonical reality (SQLite messages/turns +
|
|
7
|
+
// presentation_events + jurnal; PK (session_id, seq))
|
|
8
|
+
// CONTEXT = deterministic view/query terhadap canonical reality
|
|
9
|
+
// MODEL = temporary consumer
|
|
10
|
+
//
|
|
11
|
+
// Modul ini MURNI (tanpa IO, tanpa Date.now, tanpa random, tanpa state
|
|
12
|
+
// modul yang memengaruhi hasil): canonical facts yang sama + selector yang
|
|
13
|
+
// sama + revisi yang sama = identity/frontier yang sama, di proses mana pun.
|
|
14
|
+
//
|
|
15
|
+
// Yang SENGAJA tidak ada di sini (batas scope P3.2):
|
|
16
|
+
// - second persistence store / sidecar / cache kanonis baru (dilarang);
|
|
17
|
+
// - selector P3.3, projection cache P3.4, adapter runtime P3.5, resume P3.6,
|
|
18
|
+
// compaction P3.7, paging P3.8, branch/fork penuh P3.9, RAG P3.11;
|
|
19
|
+
// - run_id / model / provider / prompt fingerprint / RAG hit / buffer runtime
|
|
20
|
+
// di dalam identity (eksplisit ditolak — lihat AGENT_PRESENTATION_
|
|
21
|
+
// ARCHITECTURE_V2_1.md: run_id redundan dengan (sessionId, turnId)).
|
|
22
|
+
//
|
|
23
|
+
// Lapisan: src/session (host). Tidak mengimpor src/ui, cli, atau #minicore,
|
|
24
|
+
// tidak menyentuh vendor — ContextStore kernel tetap satu-satunya buffer
|
|
25
|
+
// runtime, modul ini hanya menurunkannya secara deterministik.
|
|
26
|
+
|
|
27
|
+
import { createHash } from "node:crypto"
|
|
28
|
+
|
|
29
|
+
/** Prefix anchor event. BUKAN uniqueness source; hanya namespace tampilan. */
|
|
30
|
+
export const CONTEXT_ANCHOR_PREFIX = "ctxev_"
|
|
31
|
+
|
|
32
|
+
/** Thread default sebelum semantik branch/fork penuh (P3.9). */
|
|
33
|
+
export const MAIN_THREAD_ID = "main"
|
|
34
|
+
|
|
35
|
+
/** Status kesegaran context terhadap canonical frontier. BUKAN boolean. */
|
|
36
|
+
export type ContextFreshness = "fresh" | "stale" | "diverged" | "unknown"
|
|
37
|
+
|
|
38
|
+
/** Hasil perbandingan dua frontier. Tanpa timestamp, tanpa run_id. */
|
|
39
|
+
export type ContextFrontierRelation = "EQUAL" | "A_AHEAD" | "B_AHEAD" | "DIVERGED" | "UNKNOWN"
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Referensi event kanonis — bentuk baris durable `messages` (lihat
|
|
43
|
+
* loadSession di persistence.ts:656-685). `content` di sini adalah nilai
|
|
44
|
+
* TERSIMPAN (sudah safeContent/scrub/cap saat tulis), bukan objek runtime:
|
|
45
|
+
* hanya dari sanalah anchor stabil lintas replay/restart.
|
|
46
|
+
*/
|
|
47
|
+
export interface CanonicalEventRef {
|
|
48
|
+
seq: number
|
|
49
|
+
role: string
|
|
50
|
+
content: string
|
|
51
|
+
toolCalls?: string | null
|
|
52
|
+
toolCallId?: string | null
|
|
53
|
+
name?: string | null
|
|
54
|
+
reasoning?: string | null
|
|
55
|
+
isError?: number | boolean | null
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* IDENTITY — "view dari canonical state yang mana".
|
|
60
|
+
* session_id + thread_id + base_seq + anchor_event_id. TANPA run_id, model,
|
|
61
|
+
* provider, fingerprint, RAG hit, atau buffer runtime.
|
|
62
|
+
*/
|
|
63
|
+
export interface ContextIdentity {
|
|
64
|
+
readonly sessionId: string
|
|
65
|
+
readonly threadId: string
|
|
66
|
+
readonly baseSeq: number
|
|
67
|
+
readonly anchorEventId: string
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* FRONTIER — posisi deterministik view di dalam canonical history.
|
|
72
|
+
* baseSeq/headSeq = cakupan view; anchorEventId = jangkar konten di head;
|
|
73
|
+
* lastSeen* = frontier kanonis saat view dibangun (pada selector penuh =
|
|
74
|
+
* head; pada selector parsial P3.3 nanti bisa berbeda — dibedakan eksplisit,
|
|
75
|
+
* bukan dua nama untuk hal yang sama); revision = ruang-sekuens kanonis
|
|
76
|
+
* (jumlah durable `context.compacted`; naik tepat saat canonical ditulis
|
|
77
|
+
* ulang oleh kompaksi — lihat D3); historyCommit = komitmen atas SELURUH
|
|
78
|
+
* isi yang dicakup view (bukan hanya head — tanpa ini, rewrite tengah
|
|
79
|
+
* N→N panjang-sama ala bug F-05 tak terdeteksi: endpoint sama, isi beda).
|
|
80
|
+
*/
|
|
81
|
+
export interface ContextFrontier extends ContextIdentity {
|
|
82
|
+
readonly headSeq: number
|
|
83
|
+
readonly lastSeenSeq: number
|
|
84
|
+
readonly lastSeenEventId: string
|
|
85
|
+
readonly revision: number
|
|
86
|
+
readonly historyCommit: string
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Namespace derivasi (ganti bila skema anchor berubah → id baru eksplisit). */
|
|
90
|
+
const ANCHOR_NAMESPACE = "p32-context-anchor-v1:"
|
|
91
|
+
|
|
92
|
+
/** Pola anchor valid: prefix + 32 hex (berbeda bentuk dari id alokasi M1). */
|
|
93
|
+
const ANCHOR_RE = /^ctxev_[0-9a-f]{32}$/
|
|
94
|
+
|
|
95
|
+
/** Pola komitmen histori valid: namespace sendiri, bukan event id. */
|
|
96
|
+
const HISTORY_COMMIT_RE = /^ctxhist_[0-9a-f]{32}$/
|
|
97
|
+
|
|
98
|
+
/** True bila string adalah anchor event P3.2 yang well-formed. */
|
|
99
|
+
export function isAnchorEventId(value: unknown): value is string {
|
|
100
|
+
return typeof value === "string" && ANCHOR_RE.test(value)
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** True bila string adalah komitmen histori P3.2 yang well-formed. */
|
|
104
|
+
export function isHistoryCommit(value: unknown): value is string {
|
|
105
|
+
return typeof value === "string" && HISTORY_COMMIT_RE.test(value)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function assertSeq(seq: unknown, field: string): asserts seq is number {
|
|
109
|
+
if (typeof seq !== "number" || !Number.isInteger(seq) || seq < 0)
|
|
110
|
+
throw new Error(
|
|
111
|
+
`context-identity: ${field} must be a non-negative integer (got ${String(seq)})`,
|
|
112
|
+
)
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function assertNonEmptyString(value: unknown, field: string): asserts value is string {
|
|
116
|
+
if (typeof value !== "string" || value.length === 0)
|
|
117
|
+
throw new Error(`context-identity: ${field} is required (never guess identity)`)
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Serialisasi kanonis SATU baris durable untuk hashing. Urutan field tetap
|
|
122
|
+
* dan null dinormalisasi eksplisit supaya baris yang "sama secara kanonis"
|
|
123
|
+
* selalu menghasilkan string yang sama (Replay stability / test C).
|
|
124
|
+
*/
|
|
125
|
+
function canonicalEventKey(ref: CanonicalEventRef): string {
|
|
126
|
+
assertSeq(ref.seq, "ref.seq")
|
|
127
|
+
if (typeof ref.role !== "string" || typeof ref.content !== "string")
|
|
128
|
+
throw new Error("context-identity: ref.role and ref.content must be strings (durable form)")
|
|
129
|
+
return JSON.stringify([
|
|
130
|
+
ref.seq,
|
|
131
|
+
ref.role,
|
|
132
|
+
ref.content,
|
|
133
|
+
ref.toolCalls ?? null,
|
|
134
|
+
ref.toolCallId ?? null,
|
|
135
|
+
ref.name ?? null,
|
|
136
|
+
ref.reasoning ?? null,
|
|
137
|
+
ref.isError == null ? null : ref.isError === true || ref.isError === 1 ? 1 : 0,
|
|
138
|
+
])
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Turunkan anchor stabil untuk SATU event kanonis. Mengikat session + thread
|
|
143
|
+
* + seq + ISI kanonis: seq sama tapi isi/session/thread berbeda = anchor
|
|
144
|
+
* berbeda (Identity != Sequence). Sama canonical = sama anchor pada setiap
|
|
145
|
+
* load/restart/replay — tanpa storage, tanpa runtime state.
|
|
146
|
+
*/
|
|
147
|
+
export function deriveAnchorEventId(
|
|
148
|
+
sessionId: string,
|
|
149
|
+
threadId: string,
|
|
150
|
+
ref: CanonicalEventRef,
|
|
151
|
+
): string {
|
|
152
|
+
assertNonEmptyString(sessionId, "sessionId")
|
|
153
|
+
assertNonEmptyString(threadId, "threadId")
|
|
154
|
+
const digest = createHash("sha256")
|
|
155
|
+
.update(`${ANCHOR_NAMESPACE}${sessionId}:${threadId}:${canonicalEventKey(ref)}`)
|
|
156
|
+
.digest("hex")
|
|
157
|
+
.slice(0, 32)
|
|
158
|
+
return `${CONTEXT_ANCHOR_PREFIX}${digest}`
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Turunkan identity view dari posisi base + event jangkar di head. */
|
|
162
|
+
export function deriveContextIdentity(input: {
|
|
163
|
+
sessionId: string
|
|
164
|
+
threadId?: string
|
|
165
|
+
baseSeq: number
|
|
166
|
+
head: CanonicalEventRef
|
|
167
|
+
}): ContextIdentity {
|
|
168
|
+
assertNonEmptyString(input.sessionId, "sessionId")
|
|
169
|
+
const threadId = input.threadId ?? MAIN_THREAD_ID
|
|
170
|
+
assertNonEmptyString(threadId, "threadId")
|
|
171
|
+
assertSeq(input.baseSeq, "baseSeq")
|
|
172
|
+
if (input.baseSeq > input.head.seq)
|
|
173
|
+
throw new Error("context-identity: baseSeq must not exceed head seq (view is never inverted)")
|
|
174
|
+
return Object.freeze({
|
|
175
|
+
sessionId: input.sessionId,
|
|
176
|
+
threadId,
|
|
177
|
+
baseSeq: input.baseSeq,
|
|
178
|
+
anchorEventId: deriveAnchorEventId(input.sessionId, threadId, input.head),
|
|
179
|
+
})
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Komitmen deterministik atas SELURUH baris yang dicakup satu view, dalam
|
|
184
|
+
* urutan seq. Mengikat isi (via canonicalEventKey per baris yang sudah
|
|
185
|
+
* mengikat session+thread+seq+isi), bukan hanya endpoint: dua canonical yang
|
|
186
|
+
* berbeda di tengah (rewrite N→N) menghasilkan commit berbeda walau base,
|
|
187
|
+
* head, dan anchor head-nya sama. Input kosong → throw (canonical kosong
|
|
188
|
+
* direpresentasikan sebagai frontier null, bukan commit kosong).
|
|
189
|
+
*/
|
|
190
|
+
export function deriveHistoryCommit(rows: readonly CanonicalEventRef[]): string {
|
|
191
|
+
if (rows.length === 0)
|
|
192
|
+
throw new Error("context-identity: cannot commit to an empty history (use null frontier)")
|
|
193
|
+
const hash = createHash("sha256")
|
|
194
|
+
hash.update("p32-context-history-v1:")
|
|
195
|
+
const sorted = [...rows].sort((a, b) => a.seq - b.seq)
|
|
196
|
+
for (let i = 1; i < sorted.length; i++) {
|
|
197
|
+
if (sorted[i]!.seq <= sorted[i - 1]!.seq)
|
|
198
|
+
throw new Error(
|
|
199
|
+
`context-identity: duplicate/non-monotonic seq ${sorted[i]!.seq} (canonical corrupt — refusing to guess)`,
|
|
200
|
+
)
|
|
201
|
+
}
|
|
202
|
+
for (const r of sorted) hash.update(`|${canonicalEventKey(r)}`)
|
|
203
|
+
return `ctxhist_${hash.digest("hex").slice(0, 32)}`
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** Turunkan frontier lengkap: cakupan view + last-seen + revisi kanonis. */
|
|
207
|
+
export function deriveContextFrontier(input: {
|
|
208
|
+
sessionId: string
|
|
209
|
+
threadId?: string
|
|
210
|
+
baseSeq: number
|
|
211
|
+
head: CanonicalEventRef
|
|
212
|
+
lastSeen?: CanonicalEventRef
|
|
213
|
+
revision: number
|
|
214
|
+
/** Komitmen isi cakupan view (deriveHistoryCommit atas baris yang dicakup). */
|
|
215
|
+
historyCommit: string
|
|
216
|
+
}): ContextFrontier {
|
|
217
|
+
const identity = deriveContextIdentity(input)
|
|
218
|
+
assertSeq(input.head.seq, "head.seq")
|
|
219
|
+
if (typeof input.revision !== "number" || !Number.isInteger(input.revision) || input.revision < 0)
|
|
220
|
+
throw new Error("context-identity: revision must be a non-negative integer (compaction count)")
|
|
221
|
+
if (!isHistoryCommit(input.historyCommit))
|
|
222
|
+
throw new Error("context-identity: historyCommit is required (never guess content)")
|
|
223
|
+
const lastSeen = input.lastSeen ?? input.head
|
|
224
|
+
return Object.freeze({
|
|
225
|
+
...identity,
|
|
226
|
+
headSeq: input.head.seq,
|
|
227
|
+
lastSeenSeq: lastSeen.seq,
|
|
228
|
+
lastSeenEventId: deriveAnchorEventId(identity.sessionId, identity.threadId, lastSeen),
|
|
229
|
+
revision: input.revision,
|
|
230
|
+
historyCommit: input.historyCommit,
|
|
231
|
+
})
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Rekonstruksi frontier dari durable rows saja (tanpa ContextStore runtime,
|
|
236
|
+
* tanpa memori proses, tanpa invocasi model). Rows boleh tak terurut —
|
|
237
|
+
* diurutkan stabil berdasarkan seq; seq duplikat = canonical korup → throw
|
|
238
|
+
* (fail-closed, jangan tebak). Rows kosong → null (belum ada jangkar;
|
|
239
|
+
* pemanggil memperlakukannya sebagai UNKNOWN, bukan error).
|
|
240
|
+
*/
|
|
241
|
+
export function deriveFrontierFromDurable(input: {
|
|
242
|
+
sessionId: string
|
|
243
|
+
threadId?: string
|
|
244
|
+
rows: readonly CanonicalEventRef[]
|
|
245
|
+
revision: number
|
|
246
|
+
}): ContextFrontier | null {
|
|
247
|
+
assertNonEmptyString(input.sessionId, "sessionId")
|
|
248
|
+
if (input.rows.length === 0) return null
|
|
249
|
+
const sorted = [...input.rows].sort((a, b) => a.seq - b.seq)
|
|
250
|
+
for (let i = 1; i < sorted.length; i++) {
|
|
251
|
+
if (sorted[i]!.seq <= sorted[i - 1]!.seq)
|
|
252
|
+
throw new Error(
|
|
253
|
+
`context-identity: duplicate/non-monotonic seq ${sorted[i]!.seq} (canonical corrupt — refusing to guess)`,
|
|
254
|
+
)
|
|
255
|
+
}
|
|
256
|
+
const base = sorted[0]!
|
|
257
|
+
const head = sorted[sorted.length - 1]!
|
|
258
|
+
return deriveContextFrontier({
|
|
259
|
+
sessionId: input.sessionId,
|
|
260
|
+
threadId: input.threadId,
|
|
261
|
+
baseSeq: base.seq,
|
|
262
|
+
head,
|
|
263
|
+
revision: input.revision,
|
|
264
|
+
historyCommit: deriveHistoryCommit(sorted),
|
|
265
|
+
})
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** Type guard untuk frontier dari sumber tak terpercaya (mis. JSON). */
|
|
269
|
+
export function isContextFrontier(value: unknown): value is ContextFrontier {
|
|
270
|
+
if (typeof value !== "object" || value === null) return false
|
|
271
|
+
const v = value as Record<string, unknown>
|
|
272
|
+
return (
|
|
273
|
+
typeof v.sessionId === "string" &&
|
|
274
|
+
v.sessionId.length > 0 &&
|
|
275
|
+
typeof v.threadId === "string" &&
|
|
276
|
+
v.threadId.length > 0 &&
|
|
277
|
+
typeof v.baseSeq === "number" &&
|
|
278
|
+
Number.isInteger(v.baseSeq) &&
|
|
279
|
+
v.baseSeq >= 0 &&
|
|
280
|
+
isAnchorEventId(v.anchorEventId) &&
|
|
281
|
+
typeof v.headSeq === "number" &&
|
|
282
|
+
Number.isInteger(v.headSeq) &&
|
|
283
|
+
v.headSeq >= 0 &&
|
|
284
|
+
typeof v.lastSeenSeq === "number" &&
|
|
285
|
+
Number.isInteger(v.lastSeenSeq) &&
|
|
286
|
+
v.lastSeenSeq >= 0 &&
|
|
287
|
+
isAnchorEventId(v.lastSeenEventId) &&
|
|
288
|
+
typeof v.revision === "number" &&
|
|
289
|
+
Number.isInteger(v.revision) &&
|
|
290
|
+
(v.revision as number) >= 0 &&
|
|
291
|
+
isHistoryCommit(v.historyCommit)
|
|
292
|
+
)
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Perbandingan frontier deterministik — TANPA timestamp, TANPA
|
|
297
|
+
* Date.now/object-identity/index-array/posisi-prompt/run_id.
|
|
298
|
+
* - session berbeda = UNKNOWN (tak ada basis bersama);
|
|
299
|
+
* - thread berbeda dalam session sama = DIVERGED (tabrakan terdeteksi);
|
|
300
|
+
* - revisi berbeda = DIVERGED (ruang sekuens ditulis ulang — kompaksi;
|
|
301
|
+
* perbandingan posisional tak bermakna, jangan diam-diam reconcile);
|
|
302
|
+
* - revisi sama: semua sama (termasuk historyCommit) = EQUAL; head beda =
|
|
303
|
+
* A_AHEAD/B_AHEAD; head sama tapi identitas/isi beda = DIVERGED (posisi
|
|
304
|
+
* sama, event berbeda — termasuk base view berbeda pada head yang sama:
|
|
305
|
+
* view parsial tak pernah disamakan dengan view penuh — dan termasuk
|
|
306
|
+
* rewrite tengah N→N: commit beda walau endpoint sama).
|
|
307
|
+
*/
|
|
308
|
+
export function compareContextFrontier(
|
|
309
|
+
a: ContextFrontier | null | undefined,
|
|
310
|
+
b: ContextFrontier | null | undefined,
|
|
311
|
+
): ContextFrontierRelation {
|
|
312
|
+
if (!isContextFrontier(a) || !isContextFrontier(b)) return "UNKNOWN"
|
|
313
|
+
if (a.sessionId !== b.sessionId) return "UNKNOWN"
|
|
314
|
+
if (a.threadId !== b.threadId) return "DIVERGED"
|
|
315
|
+
if (a.revision !== b.revision) return "DIVERGED"
|
|
316
|
+
if (
|
|
317
|
+
a.baseSeq === b.baseSeq &&
|
|
318
|
+
a.headSeq === b.headSeq &&
|
|
319
|
+
a.anchorEventId === b.anchorEventId &&
|
|
320
|
+
a.historyCommit === b.historyCommit
|
|
321
|
+
)
|
|
322
|
+
return "EQUAL"
|
|
323
|
+
if (a.headSeq !== b.headSeq) return a.headSeq > b.headSeq ? "A_AHEAD" : "B_AHEAD"
|
|
324
|
+
return "DIVERGED"
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* Status kesegaran SATU context terhadap frontier kanonis saat ini.
|
|
329
|
+
* Context TIDAK PERNAH otomatis menjadi kanonis hanya karena stale:
|
|
330
|
+
* STALE = pemanggil harus membangun ulang dari canonical; DIVERGED/UNKNOWN
|
|
331
|
+
* = dilarang menulis diam-diam maupun reconcile diam-diam.
|
|
332
|
+
* - revisi context < kanonis = DIVERGED (canonical ditulis ulang di bawahnya);
|
|
333
|
+
* - revisi context > kanonis = UNKNOWN (klaim dari masa depan — invalid);
|
|
334
|
+
* - revisi sama: head+anchor sama = FRESH bila isi cakupan SAMA terbukti
|
|
335
|
+
* (base sama + historyCommit sama) atau bila base berbeda (perbedaan
|
|
336
|
+
* selector P3.3 — kesegaran soal head, bukan cakupan); base sama tapi
|
|
337
|
+
* historyCommit beda = DIVERGED (rewrite tengah tanpa revisi — anomali
|
|
338
|
+
* tulis yang tak boleh dibaca sebagai fresh);
|
|
339
|
+
* canonical di depan = STALE; context melampaui canonical = UNKNOWN;
|
|
340
|
+
* head sama anchor beda = DIVERGED.
|
|
341
|
+
*/
|
|
342
|
+
export function assessContextFreshness(
|
|
343
|
+
context: ContextFrontier | null | undefined,
|
|
344
|
+
canonical: ContextFrontier | null | undefined,
|
|
345
|
+
): ContextFreshness {
|
|
346
|
+
if (!isContextFrontier(context) || !isContextFrontier(canonical)) return "unknown"
|
|
347
|
+
if (context.sessionId !== canonical.sessionId || context.threadId !== canonical.threadId)
|
|
348
|
+
return "unknown"
|
|
349
|
+
if (context.revision < canonical.revision) return "diverged"
|
|
350
|
+
if (context.revision > canonical.revision) return "unknown"
|
|
351
|
+
if (context.headSeq === canonical.headSeq) {
|
|
352
|
+
if (context.anchorEventId !== canonical.anchorEventId) return "diverged"
|
|
353
|
+
if (context.baseSeq === canonical.baseSeq && context.historyCommit !== canonical.historyCommit)
|
|
354
|
+
return "diverged"
|
|
355
|
+
return "fresh"
|
|
356
|
+
}
|
|
357
|
+
return context.headSeq < canonical.headSeq ? "stale" : "unknown"
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* Derivasikan revisi kanonis dari daftar event durable: jumlah event
|
|
362
|
+
* `context.compacted` yang durable+replayable (events.ts DURABILITY).
|
|
363
|
+
* Jembatan kernel `context:compacted` → durable `context.compacted` ada di
|
|
364
|
+
* adapter.ts:951-957, jadi setiap kompaksi loop/recovery meninggalkan satu
|
|
365
|
+
* marker durable — kecuali jalur yang tak memasang adapter (headless tanpa
|
|
366
|
+
* presentation): revisi undercount di sana adalah seam P3.5, bukan angka
|
|
367
|
+
* yang boleh ditebak di sini (fail-closed: hitung yang durable saja).
|
|
368
|
+
*/
|
|
369
|
+
export function countDurableCompactions(events: readonly { readonly type: string }[]): number {
|
|
370
|
+
let count = 0
|
|
371
|
+
for (const e of events) {
|
|
372
|
+
if (e.type === "context.compacted") count++
|
|
373
|
+
}
|
|
374
|
+
return count
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* Provenance minimal untuk model-visible context (kontrak Fase 10 — TIPE
|
|
379
|
+
* SAJA, tanpa assembly: assembly penuh = P3.3 selector + P3.11 RAG).
|
|
380
|
+
* selectionBasis mendokumentasikan ATAS DASAR APA view dipilih
|
|
381
|
+
* ("full-history" hari ini; P3.3 merumuskan sisanya); projectionRevision
|
|
382
|
+
* hanya diisi bila proyeksi berversi benar-benar ada (jangan dikarang).
|
|
383
|
+
*/
|
|
384
|
+
export interface ModelContextProvenance {
|
|
385
|
+
readonly contextIdentity: ContextIdentity
|
|
386
|
+
readonly canonicalFrontier: ContextFrontier
|
|
387
|
+
readonly selectionBasis: string
|
|
388
|
+
readonly projectionRevision?: number
|
|
389
|
+
}
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
// P3.4 — Durable Context Projection Producer (Projection Cache lifecycle).
|
|
2
|
+
//
|
|
3
|
+
// Menutup celah yang diidentifikasi audit P3.4: substrate `history_projections`
|
|
4
|
+
// (cache derived durable) SUDAH ada dan bisa DIBACA (P2.8 assembly + P3.3
|
|
5
|
+
// selector), tetapi TIDAK ADA jalur produksi yang membangunnya di jalur otomatis
|
|
6
|
+
// (`buildProjection`/`rebuildProjection` hanya dipakai test). Akibatnya basis
|
|
7
|
+
// seleksi `summary-plus-tail` tak pernah terjadi di produksi.
|
|
8
|
+
//
|
|
9
|
+
// Modul ini = PRODUSEN: membangun/menyegarkan baris proyeksi dari state kanonik
|
|
10
|
+
// lewat primitif yang SUDAH ADA (`buildProjection`, berpagar epoch). Batas keras:
|
|
11
|
+
// - SUMBER = histori kanonik (baca-saja via loadThreadHistoryWithSeq). Bukan
|
|
12
|
+
// buffer runtime, bukan state eksekusi.
|
|
13
|
+
// - TULIS = HANYA `history_projections` (derived). NEVER `messages`/head/run.
|
|
14
|
+
// - Bukan otoritas: proyeksi tetap cache; `saveSession` tetap satu-satunya
|
|
15
|
+
// penulis kanonik.
|
|
16
|
+
// - Ringkasan = render fold kernel yang SUDAH ADA (`mechanicalCompaction`) atas
|
|
17
|
+
// PREFIX kanonik [0, baseSeq); ekor [baseSeq, head] tetap verbatim. BUKAN
|
|
18
|
+
// algoritma A+C lanjutan (P3.7), bukan LLM/embedding/network.
|
|
19
|
+
// - Deterministik: urutan kanonik, tanpa Date.now/random di jalur derivasi
|
|
20
|
+
// (built_at diisi primitif P2.7, bukan klaim cakupan).
|
|
21
|
+
//
|
|
22
|
+
// Cakupan: proyeksi yang diproduksi adalah PARSIAL (base_seq < head+1) —
|
|
23
|
+
// "ringkasan prefix + ekor kanonik". P2.8 `assembleContext` hanya memakai
|
|
24
|
+
// proyeksi CURRENT (cakupan penuh); konsumen yang boleh menerima cakupan-parsial
|
|
25
|
+
// yang tetap VALID (jangkar utuh) adalah P3.3 selector (basis `summary-plus-tail`),
|
|
26
|
+
// sesuai P3.0 §8 D6 ("pembaca menerima coverage-valid, bukan hanya CURRENT").
|
|
27
|
+
//
|
|
28
|
+
// Runtime adapter / revision bridge ke runtime = P3.5 (di luar modul ini).
|
|
29
|
+
|
|
30
|
+
import { ContextStore, mechanicalCompaction } from "#minicore"
|
|
31
|
+
import type { Message } from "#minicore/core/types.ts"
|
|
32
|
+
import { renderFullHistoryFold } from "./full-history-fold.ts"
|
|
33
|
+
import {
|
|
34
|
+
buildProjection,
|
|
35
|
+
DEFAULT_THREAD_ID,
|
|
36
|
+
getProjection,
|
|
37
|
+
getProjectionStatus,
|
|
38
|
+
loadThreadHistoryWithSeq,
|
|
39
|
+
PROJECTION_STALE_HEAD_ADVANCED_DETAIL,
|
|
40
|
+
type ProjectionRow,
|
|
41
|
+
type ProjectionState,
|
|
42
|
+
SUMMARY_PROJECTION_ID,
|
|
43
|
+
} from "./persistence.ts"
|
|
44
|
+
|
|
45
|
+
/** Kebijakan produsen — input deterministik, tanpa state mutable. */
|
|
46
|
+
export interface ProjectionProducePolicy {
|
|
47
|
+
/**
|
|
48
|
+
* Berapa turn terakhir dipertahankan verbatim sebagai ekor; prefix di atasnya
|
|
49
|
+
* diringkas (render fold kernel yang SUDAH ADA). Harus >= 1 agar ada prefix.
|
|
50
|
+
* Diabaikan bila `fold: "full-history"` (cakupan selalu penuh).
|
|
51
|
+
*/
|
|
52
|
+
readonly keepRecentTurns: number
|
|
53
|
+
/**
|
|
54
|
+
* P3.7 — strategi fold. `"mechanical"` (default) = perilaku P3.4 yang sudah
|
|
55
|
+
* ada (prefix parsial via kernel). `"full-history"` = renderer P3.7
|
|
56
|
+
* (cakupan penuh [0, N), CURRENT-capable). Default eksplisit menjaga perilaku
|
|
57
|
+
* lama bila field absen.
|
|
58
|
+
*/
|
|
59
|
+
readonly fold?: "mechanical" | "full-history"
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Hasil produksi — laporan, bukan otoritas. */
|
|
63
|
+
export interface ProjectionProduceResult {
|
|
64
|
+
/** True bila sebuah baris proyeksi dituliskan (ada prefix untuk diringkas). */
|
|
65
|
+
readonly produced: boolean
|
|
66
|
+
/** Baris proyeksi yang ditulis (bila produced). */
|
|
67
|
+
readonly row?: ProjectionRow
|
|
68
|
+
/** Cakupan eksklusif [0, baseSeq) yang diringkas (bila produced). */
|
|
69
|
+
readonly baseSeq?: number
|
|
70
|
+
/** Kenapa produced / tidak. Diagnostik. */
|
|
71
|
+
readonly detail: string
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Derivasi DETERMINISTIK {summaryText, baseSeq} dari baris kanonik memakai render
|
|
76
|
+
* fold kernel yang SUDAH ADA (`mechanicalCompaction`). MURNI (tak menyentuh DB,
|
|
77
|
+
* tak memutasi input). Mengembalikan null bila tak ada prefix untuk diringkas.
|
|
78
|
+
*
|
|
79
|
+
* base_seq = jumlah baris prefix yang diringkas = total - |ekor verbatim|.
|
|
80
|
+
*/
|
|
81
|
+
export function deriveSummaryFromCanonical(
|
|
82
|
+
messages: readonly Message[],
|
|
83
|
+
policy: ProjectionProducePolicy,
|
|
84
|
+
): { summaryText: string; baseSeq: number } | null {
|
|
85
|
+
if (messages.length === 0) return null
|
|
86
|
+
const keep =
|
|
87
|
+
Number.isInteger(policy.keepRecentTurns) && policy.keepRecentTurns >= 1
|
|
88
|
+
? policy.keepRecentTurns
|
|
89
|
+
: 1
|
|
90
|
+
const store = new ContextStore()
|
|
91
|
+
store.appendAll(messages)
|
|
92
|
+
const folded = mechanicalCompaction.compact(store, { keepRecentTurns: keep })
|
|
93
|
+
// Tak ada fold (prefix kosong) → tak ada cakupan untuk proyeksi.
|
|
94
|
+
if (folded.length >= messages.length) return null
|
|
95
|
+
const kept = folded.length - 1
|
|
96
|
+
const baseSeq = messages.length - kept
|
|
97
|
+
const summaryMsg = folded[0] as { role?: unknown; content?: unknown } | undefined
|
|
98
|
+
const summaryText = summaryMsg && typeof summaryMsg.content === "string" ? summaryMsg.content : ""
|
|
99
|
+
if (baseSeq <= 0 || summaryText.length === 0) return null
|
|
100
|
+
return { summaryText, baseSeq }
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Bungkus P3.7 `renderFullHistoryFold` untuk seam produsen: ubah baris thread
|
|
105
|
+
* menjadi input renderer, dan ubah `FoldError` (cakupan tak-terbukti) menjadi
|
|
106
|
+
* no-op jujur (null) — pemanggil tak boleh menebak cakupan.
|
|
107
|
+
*/
|
|
108
|
+
function foldFullHistory(
|
|
109
|
+
rows: readonly { seq: number; message: unknown }[],
|
|
110
|
+
): { summaryText: string; baseSeq: number } | null {
|
|
111
|
+
try {
|
|
112
|
+
const folded = renderFullHistoryFold(rows)
|
|
113
|
+
if (folded.baseSeq !== rows.length) return null
|
|
114
|
+
return { summaryText: folded.summaryText, baseSeq: folded.baseSeq }
|
|
115
|
+
} catch {
|
|
116
|
+
return null
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* PRODUSEN PRODUKSI. Membangun/menyegarkan proyeksi ringkasan durable dari state
|
|
122
|
+
* kanonik. Berpagar epoch (reuse `buildProjection`). TIDAK menyentuh `messages`.
|
|
123
|
+
*
|
|
124
|
+
* Cakupan = PARSIAL bila `policy.keepRecentTurns` menyisakan ekor; base_seq =
|
|
125
|
+
* jumlah baris prefix. `summaryText` opsional: bila pemanggil sudah memegang teks
|
|
126
|
+
* ringkasan (mis. dari jalur kompaksi kernel), ia tidak dihitung ulang.
|
|
127
|
+
*
|
|
128
|
+
* Idempoten secara semantik: sumber sama + policy/ringkasan sama → baris ekuivalen
|
|
129
|
+
* (base_seq + summary_text + anchor sama; built_at boleh beda — stempel waktu).
|
|
130
|
+
* Kegagalan build TIDAK pernah mengubah kanonik.
|
|
131
|
+
*/
|
|
132
|
+
export function produceSummaryProjection(
|
|
133
|
+
sessionId: string,
|
|
134
|
+
cwd: string | undefined,
|
|
135
|
+
opts: {
|
|
136
|
+
expectedEpoch: number
|
|
137
|
+
policy: ProjectionProducePolicy
|
|
138
|
+
threadId?: string
|
|
139
|
+
/** Teks ringkasan yang sudah diproduksi jalur kompaksi (opsional). */
|
|
140
|
+
summaryText?: string
|
|
141
|
+
/** base_seq eksplisit (dipakai bersama summaryText); absen = diturunkan. */
|
|
142
|
+
baseSeq?: number
|
|
143
|
+
},
|
|
144
|
+
): ProjectionProduceResult {
|
|
145
|
+
const threadId = opts.threadId ?? DEFAULT_THREAD_ID
|
|
146
|
+
const rows = loadThreadHistoryWithSeq(sessionId, threadId, cwd)
|
|
147
|
+
if (rows.length === 0) {
|
|
148
|
+
return { produced: false, detail: "empty canonical history — no projection" }
|
|
149
|
+
}
|
|
150
|
+
let summaryText = opts.summaryText
|
|
151
|
+
let baseSeq = opts.baseSeq
|
|
152
|
+
if (typeof summaryText !== "string" || summaryText.length === 0) {
|
|
153
|
+
if (opts.policy.fold === "full-history") {
|
|
154
|
+
// P3.7 — fold cakupan-penuh deterministik atas SELURUH baris kanonik.
|
|
155
|
+
// baseSeq SELALU == rows.length ([0, N) penuh, CURRENT-capable). Gagal
|
|
156
|
+
// derivasi (baris kosong/tak-kontinyu/bentuk tak-didukung) → no-op jujur,
|
|
157
|
+
// BUKAN klaim parsial sebagai penuh.
|
|
158
|
+
const folded: { summaryText: string; baseSeq: number } | null = foldFullHistory(rows)
|
|
159
|
+
if (!folded) {
|
|
160
|
+
return {
|
|
161
|
+
produced: false,
|
|
162
|
+
detail: `full-history fold refused (rows=${rows.length}) — see fold detail`,
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
summaryText = folded.summaryText
|
|
166
|
+
baseSeq = folded.baseSeq
|
|
167
|
+
} else {
|
|
168
|
+
const derived = deriveSummaryFromCanonical(
|
|
169
|
+
rows.map((r) => r.message as Message),
|
|
170
|
+
opts.policy,
|
|
171
|
+
)
|
|
172
|
+
if (!derived) {
|
|
173
|
+
return {
|
|
174
|
+
produced: false,
|
|
175
|
+
detail: `no foldable prefix (rows=${rows.length}, keepRecentTurns=${opts.policy.keepRecentTurns})`,
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
summaryText = derived.summaryText
|
|
179
|
+
baseSeq = derived.baseSeq
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
if (baseSeq === undefined || baseSeq <= 0) {
|
|
183
|
+
return { produced: false, detail: "no explicit/derivable baseSeq — refusing empty projection" }
|
|
184
|
+
}
|
|
185
|
+
// Tulis lewat primitif P2.7 (epoch-fenced, satu txn, delete+insert, sumber
|
|
186
|
+
// kanonik UTUH). Satu-satunya efek tulis produsen = history_projections.
|
|
187
|
+
const row = buildProjection(sessionId, threadId, summaryText, cwd, {
|
|
188
|
+
expectedEpoch: opts.expectedEpoch,
|
|
189
|
+
baseSeq,
|
|
190
|
+
projectionId: SUMMARY_PROJECTION_ID,
|
|
191
|
+
})
|
|
192
|
+
return {
|
|
193
|
+
produced: true,
|
|
194
|
+
row,
|
|
195
|
+
baseSeq: row.base_seq,
|
|
196
|
+
detail:
|
|
197
|
+
row.base_seq >= rows.length
|
|
198
|
+
? `projection covers [0,${row.base_seq}) of ${rows.length} rows (full: full-history fold, CURRENT-capable)`
|
|
199
|
+
: `projection covers [0,${row.base_seq}) of ${rows.length} rows (partial: prefix summary + canonical tail)`,
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** Status proyeksi ringkasan terkini (baca-saja). */
|
|
204
|
+
export function summaryProjectionStatus(
|
|
205
|
+
sessionId: string,
|
|
206
|
+
cwd?: string,
|
|
207
|
+
threadId?: string,
|
|
208
|
+
): { state: ProjectionState; detail: string } {
|
|
209
|
+
return getProjectionStatus(sessionId, threadId ?? DEFAULT_THREAD_ID, SUMMARY_PROJECTION_ID, cwd)
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Baca proyeksi ringkasan yang dapat dikonsumsi SELECTOR: baris ada + VALID
|
|
214
|
+
* (jangkar utuh & cakupan kanonik; STALE-dengan-jangkar-utuh DITERIMA sebagai
|
|
215
|
+
* coverage-valid per P3.0 §8 D6). CORRUPT/UNKNOWN/absen → null (fallback kanonik).
|
|
216
|
+
*
|
|
217
|
+
* Pembedaan STALE (N1): STALE-rule-8 (head maju, JANGKAR UTUH) = consumable;
|
|
218
|
+
* STALE-rule-7 (jangkar patah / batas berubah) = TIDAK consumable — ringkasan
|
|
219
|
+
* tak lagi mewakili prefix kanonik. Detail status (bukan cek jangkar ulang)
|
|
220
|
+
* dipakai, agar tidak menduplikasi validasi di lapisan lain.
|
|
221
|
+
*
|
|
222
|
+
* Mengembalikan { summaryText, baseSeq } untuk diteruskan ke `selectContext`
|
|
223
|
+
* sebagai `projection`. Baca-saja; tak menulis apa pun.
|
|
224
|
+
*/
|
|
225
|
+
export function readConsumableSummaryProjection(
|
|
226
|
+
sessionId: string,
|
|
227
|
+
cwd?: string,
|
|
228
|
+
threadId?: string,
|
|
229
|
+
): { summaryText: string; baseSeq: number } | null {
|
|
230
|
+
const tid = threadId ?? DEFAULT_THREAD_ID
|
|
231
|
+
const status = getProjectionStatus(sessionId, tid, SUMMARY_PROJECTION_ID, cwd)
|
|
232
|
+
// CURRENT = cakupan penuh, consumable. STALE = HANYA sub-kasus rule-8
|
|
233
|
+
// (detail "head advanced beyond coverage") yang consumable; STALE-rule-7
|
|
234
|
+
// (detail lain, jangkar patah) → null. CORRUPT/INCOMPLETE/UNKNOWN/absen → null.
|
|
235
|
+
if (status.state === "CURRENT") {
|
|
236
|
+
// lanjut ke pembacaan baris di bawah
|
|
237
|
+
} else if (status.state === "STALE" && status.detail === PROJECTION_STALE_HEAD_ADVANCED_DETAIL) {
|
|
238
|
+
// rule-8: coverage-valid, consumable sebagai sumber ringkasan turunan
|
|
239
|
+
} else {
|
|
240
|
+
return null
|
|
241
|
+
}
|
|
242
|
+
const row = getProjection(sessionId, tid, SUMMARY_PROJECTION_ID, cwd)
|
|
243
|
+
if (!row) return null
|
|
244
|
+
if (row.base_seq <= 0 || typeof row.summary_text !== "string" || row.summary_text.length === 0) {
|
|
245
|
+
return null
|
|
246
|
+
}
|
|
247
|
+
return { summaryText: row.summary_text, baseSeq: row.base_seq }
|
|
248
|
+
}
|