@aiwayds/dsh-topics-memory 0.22.0 → 0.23.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.
@@ -0,0 +1,294 @@
1
+ /**
2
+ * Local embedding client (ollama) — the semantic layer behind the nearFloor
3
+ * reranker (A4 决议 2, spec §3.1).
4
+ *
5
+ * Semantics (mirror of jev/client's outcome mode):
6
+ * - every failure returns as a structured {ok:false, outcome} result, NEVER
7
+ * a throw — the caller degrades explicitly to the pure-lexical path;
8
+ * - one AbortSignal.timeout per request, NO retry (query 2s / batch 30s);
9
+ * - localhost only in v1 (ADR 0017 local exception). Remote providers do
10
+ * not exist here by design: a remote embedding may only ever enter a
11
+ * slow-lane/offline path, never the fast lane (red line ①).
12
+ *
13
+ * @module embedding
14
+ */
15
+
16
+ import { execFileSync } from 'node:child_process'
17
+
18
+ /** Default ollama bind (the plugin's own default; OLLAMA_HOST overrides). */
19
+ export const DEFAULT_EMBED_HOST = 'http://127.0.0.1:11434'
20
+
21
+ /** Provider default model when embeddingModel is the '' sentinel
22
+ * (spec §7: ollama → nomic-embed-text, 768 dims, A1 §5 measured). */
23
+ export const DEFAULT_EMBED_MODEL = 'nomic-embed-text'
24
+
25
+ /** Query-side timeout — the reranker sits in the spliced hot path; a slow
26
+ * ollama must lose the race, not the injection. */
27
+ export const EMBED_QUERY_TIMEOUT_MS = 2000
28
+ /** Batch-side timeout (index rebuild: A1 measured ~9.5s for 137 topics). */
29
+ export const EMBED_BATCH_TIMEOUT_MS = 30_000
30
+
31
+ /** Per-text byte cap before anything leaves the process (query端 p50=153 tok
32
+ * ~ well under this; the cap only bites on paste pollution). */
33
+ export const MAX_TEXT_BYTES = 2048
34
+
35
+ /** The only provider v1 speaks. Anything else is an explicit
36
+ * unsupported_provider outcome, not a silent attempt. */
37
+ export const SUPPORTED_PROVIDER = 'ollama'
38
+
39
+ /** The config slice the embed functions need (pass straight from
40
+ * TopicsConfigValue). '' sentinels: provider off / provider default model. */
41
+ export interface EmbeddingConfig {
42
+ provider?: string
43
+ model?: string
44
+ /** Explicit host; absent → OLLAMA_HOST env → DEFAULT_EMBED_HOST. */
45
+ host?: string
46
+ }
47
+
48
+ /** Resolve the ollama base URL: explicit arg wins, then OLLAMA_HOST, then
49
+ * the localhost default. Bare `host:port` values get the http:// prefix
50
+ * (ollama's own OLLAMA_HOST convention); trailing slashes are trimmed. */
51
+ export function resolveEmbedHost(explicit?: string): string {
52
+ const raw = (explicit ?? process.env.OLLAMA_HOST ?? '').trim()
53
+ const withScheme = raw === '' ? DEFAULT_EMBED_HOST : /^https?:\/\//.test(raw) ? raw : `http://${raw.replace(/^tcp:\/\//, '')}`
54
+ return withScheme.replace(/\/+$/, '')
55
+ }
56
+
57
+ /** '' sentinel → provider default model. */
58
+ export function resolveEmbedModel(model?: string): string {
59
+ const m = (model ?? '').trim()
60
+ return m === '' ? DEFAULT_EMBED_MODEL : m
61
+ }
62
+
63
+ /** Truncate a string to ≤ maxBytes UTF-8 bytes WITHOUT splitting a multibyte
64
+ * character: cut at the byte cap, then back off over any continuation bytes
65
+ * (0b10xxxxxx) so the decoded tail is never a replacement char. */
66
+ export function truncateUtf8(text: string, maxBytes: number = MAX_TEXT_BYTES): string {
67
+ if (maxBytes <= 0) return ''
68
+ const buf = Buffer.from(text, 'utf8')
69
+ if (buf.length <= maxBytes) return text
70
+ let end = maxBytes
71
+ while (end > 0 && (buf[end]! & 0xc0) === 0x80) end -= 1
72
+ return buf.subarray(0, end).toString('utf8')
73
+ }
74
+
75
+ // ---------------------------------------------------------------------------
76
+ // Outcomes — the explicit-degradation vocabulary. Callers branch on `ok`;
77
+ // `outcome` is the human/queryable why (降级状态可查, spec §3.1).
78
+ // ---------------------------------------------------------------------------
79
+
80
+ export type EmbeddingFailureOutcome =
81
+ | 'provider_off' // config provider is the '' sentinel — semantic layer off
82
+ | 'unsupported_provider' // configured, but not a v1 provider (no remote!)
83
+ | 'empty_input' // nothing to embed — refused before any network activity
84
+ | 'network' // connect refused / DNS / socket — ollama not serving
85
+ | 'timeout' // the one AbortSignal fired
86
+ | 'model_missing' // ollama answered 404: model not pulled
87
+ | 'http_4xx'
88
+ | 'http_5xx'
89
+ | 'bad_json'
90
+ | 'bad_shape' // 200 but the embeddings array is malformed / dims disagree
91
+
92
+ export interface EmbedBatchOk {
93
+ ok: true
94
+ /** Vectors aligned 1:1 with the (truncated) input texts. */
95
+ vectors: number[][]
96
+ model: string
97
+ dim: number
98
+ latencyMs: number
99
+ }
100
+
101
+ export interface EmbedQueryOk {
102
+ ok: true
103
+ vector: number[]
104
+ model: string
105
+ dim: number
106
+ latencyMs: number
107
+ }
108
+
109
+ export interface EmbedFailure {
110
+ ok: false
111
+ outcome: EmbeddingFailureOutcome
112
+ message: string
113
+ host: string
114
+ model: string
115
+ latencyMs: number
116
+ }
117
+
118
+ export type EmbedResult = EmbedBatchOk | EmbedFailure
119
+ export type EmbedQueryResult = EmbedQueryOk | EmbedFailure
120
+ export type ProbeResult = { ok: true; host: string; model: string; dim: number; latencyMs: number } | EmbedFailure
121
+
122
+ function isPlainObject(v: unknown): v is Record<string, unknown> {
123
+ return typeof v === 'object' && v !== null && !Array.isArray(v)
124
+ }
125
+
126
+ /** Shared request path: POST {host}/api/embed, outcome-mode failures only. */
127
+ async function embedRequest(
128
+ texts: readonly string[],
129
+ config: EmbeddingConfig,
130
+ timeoutMs: number,
131
+ ): Promise<EmbedResult> {
132
+ const provider = (config.provider ?? '').trim()
133
+ if (provider === '') {
134
+ return { ok: false, outcome: 'provider_off', message: "embeddingProvider is '' — the semantic layer is off (pure lexical).", host: resolveEmbedHost(config.host), model: resolveEmbedModel(config.model), latencyMs: 0 }
135
+ }
136
+ if (provider !== SUPPORTED_PROVIDER) {
137
+ return { ok: false, outcome: 'unsupported_provider', message: `embeddingProvider '${provider}' is not supported in v1 (only '${SUPPORTED_PROVIDER}'); remote providers may not enter the fast lane.`, host: resolveEmbedHost(config.host), model: resolveEmbedModel(config.model), latencyMs: 0 }
138
+ }
139
+ if (texts.length === 0) {
140
+ return { ok: false, outcome: 'empty_input', message: 'no texts to embed.', host: resolveEmbedHost(config.host), model: resolveEmbedModel(config.model), latencyMs: 0 }
141
+ }
142
+ const host = resolveEmbedHost(config.host)
143
+ const model = resolveEmbedModel(config.model)
144
+ const started = Date.now()
145
+ let res: Response
146
+ try {
147
+ res = await fetch(`${host}/api/embed`, {
148
+ method: 'POST',
149
+ headers: { 'content-type': 'application/json' },
150
+ body: JSON.stringify({ model, input: texts.map((t) => truncateUtf8(t)) }),
151
+ signal: AbortSignal.timeout(timeoutMs),
152
+ })
153
+ } catch (err) {
154
+ const outcome: EmbeddingFailureOutcome =
155
+ err instanceof Error && (err.name === 'TimeoutError' || err.name === 'AbortError') ? 'timeout' : 'network'
156
+ return { ok: false, outcome, message: `${outcome}: ${err instanceof Error ? err.message : String(err)}`, host, model, latencyMs: Date.now() - started }
157
+ }
158
+ if (!res.ok) {
159
+ const text = (await res.text().catch(() => '')).slice(0, 300)
160
+ // ollama answers 404 {"error":"model \"…\" not found, try pulling it first"}
161
+ const outcome: EmbeddingFailureOutcome = res.status === 404 ? 'model_missing' : res.status >= 500 ? 'http_5xx' : 'http_4xx'
162
+ return { ok: false, outcome, message: `ollama responded ${res.status}: ${text}`, host, model, latencyMs: Date.now() - started }
163
+ }
164
+ let json: unknown
165
+ try {
166
+ json = await res.json()
167
+ } catch (err) {
168
+ return { ok: false, outcome: 'bad_json', message: `non-JSON body: ${err instanceof Error ? err.message : String(err)}`, host, model, latencyMs: Date.now() - started }
169
+ }
170
+ const vectors = isPlainObject(json) ? json.embeddings : undefined
171
+ if (
172
+ !Array.isArray(vectors) ||
173
+ vectors.length !== texts.length ||
174
+ !vectors.every((v) => Array.isArray(v) && v.length > 0 && v.every((n) => typeof n === 'number' && Number.isFinite(n))) ||
175
+ new Set(vectors.map((v) => (v as number[]).length)).size !== 1
176
+ ) {
177
+ return { ok: false, outcome: 'bad_shape', message: 'embeddings must be a rectangular [texts.length][dim] array of finite numbers.', host, model, latencyMs: Date.now() - started }
178
+ }
179
+ return { ok: true, vectors: vectors as number[][], model, dim: (vectors[0] as number[]).length, latencyMs: Date.now() - started }
180
+ }
181
+
182
+ /** Batch-embed texts (index build/rebuild path). Vectors align 1:1 with the
183
+ * input order; each text is truncated to MAX_TEXT_BYTES first. */
184
+ export async function embedTexts(
185
+ texts: readonly string[],
186
+ config: EmbeddingConfig = {},
187
+ opts: { timeoutMs?: number } = {},
188
+ ): Promise<EmbedResult> {
189
+ const timeoutMs = Number(opts.timeoutMs) > 0 ? Number(opts.timeoutMs) : EMBED_BATCH_TIMEOUT_MS
190
+ return embedRequest(texts, config, timeoutMs)
191
+ }
192
+
193
+ /** Embed one query (reranker hot path, 2s budget). Empty/whitespace queries
194
+ * fail locally with 'empty_input' — nothing leaves the process. */
195
+ export async function embedQuery(
196
+ query: string,
197
+ config: EmbeddingConfig = {},
198
+ opts: { timeoutMs?: number } = {},
199
+ ): Promise<EmbedQueryResult> {
200
+ if ((query ?? '').trim() === '') {
201
+ return { ok: false, outcome: 'empty_input', message: 'empty query.', host: resolveEmbedHost(config.host), model: resolveEmbedModel(config.model), latencyMs: 0 }
202
+ }
203
+ const timeoutMs = Number(opts.timeoutMs) > 0 ? Number(opts.timeoutMs) : EMBED_QUERY_TIMEOUT_MS
204
+ const r = await embedRequest([query], config, timeoutMs)
205
+ if (!r.ok) return r
206
+ return { ok: true, vector: r.vectors[0]!, model: r.model, dim: r.dim, latencyMs: r.latencyMs }
207
+ }
208
+
209
+ /**
210
+ * Probe: is the server there, is the model pulled? One micro embed call —
211
+ * unlike a /api/tags listing it validates the FULL path (server + model +
212
+ * response shape) and yields the vector dim for index validation, at the
213
+ * same 15-30ms cost (A1 §5). Structured result; never throws.
214
+ */
215
+ export async function probeEmbedding(config: EmbeddingConfig = {}, opts: { timeoutMs?: number } = {}): Promise<ProbeResult> {
216
+ const timeoutMs = Number(opts.timeoutMs) > 0 ? Number(opts.timeoutMs) : EMBED_QUERY_TIMEOUT_MS
217
+ const r = await embedRequest(['dsh-topics-memory semantic layer probe'], config, timeoutMs)
218
+ if (!r.ok) return r
219
+ return { ok: true, host: resolveEmbedHost(config.host), model: resolveEmbedModel(config.model), dim: r.dim, latencyMs: r.latencyMs }
220
+ }
221
+
222
+ /**
223
+ * Build an embedder handle for retrieval's `ensureIndexFresh` — a callable
224
+ * embedTexts bound to this config, carrying the RESOLVED model identity the
225
+ * index must match. ensureIndexFresh reads `.model` only; the actual
226
+ * rebuild stays with the caller.
227
+ */
228
+ export function embedderWith(
229
+ config: EmbeddingConfig,
230
+ ): ((texts: readonly string[]) => Promise<EmbedResult>) & { model: string } {
231
+ const fn = (texts: readonly string[]) => embedTexts(texts, config)
232
+ return Object.assign(fn, { model: resolveEmbedModel(config.model) })
233
+ }
234
+
235
+ // --- Sync query embed (Phase-2 wiring) --------------------------------------
236
+ // The spliced hot path is synchronous (the chancelu lesson): retrieveSync
237
+ // cannot await. A local ollama query is 15-30ms steady state (A1 §5), so a
238
+ // bounded SYNC subprocess call keeps the reranker on the hot lane inside the
239
+ // ADR 0017 local exception — hard-capped so a wedged ollama loses the race,
240
+ // never the injection. curl ships with the host OS; node has no sync HTTP.
241
+
242
+ /** Hard sync budget for the hot-lane query embed. Generous over the measured
243
+ * 15-30ms, merciless for a wedged server. */
244
+ export const EMBED_QUERY_SYNC_TIMEOUT_MS = 250
245
+
246
+ export function embedQuerySync(query: string, config: EmbeddingConfig = {}): EmbedQueryResult {
247
+ const provider = (config.provider ?? '').trim()
248
+ if (provider === '') {
249
+ return { ok: false, outcome: 'provider_off', message: "embeddingProvider is '' — the semantic layer is off.", host: resolveEmbedHost(config.host), model: resolveEmbedModel(config.model), latencyMs: 0 }
250
+ }
251
+ if (provider !== SUPPORTED_PROVIDER) {
252
+ return { ok: false, outcome: 'unsupported_provider', message: `embeddingProvider '${provider}' is not supported in v1.`, host: resolveEmbedHost(config.host), model: resolveEmbedModel(config.model), latencyMs: 0 }
253
+ }
254
+ if ((query ?? '').trim() === '') {
255
+ return { ok: false, outcome: 'empty_input', message: 'empty query.', host: resolveEmbedHost(config.host), model: resolveEmbedModel(config.model), latencyMs: 0 }
256
+ }
257
+ const host = resolveEmbedHost(config.host)
258
+ const model = resolveEmbedModel(config.model)
259
+ const started = Date.now()
260
+ let raw: string
261
+ try {
262
+ raw = execFileSync(
263
+ 'curl',
264
+ [
265
+ '-sS',
266
+ '--max-time', String(Math.ceil(EMBED_QUERY_SYNC_TIMEOUT_MS / 1000)),
267
+ '-X', 'POST', `${host}/api/embed`,
268
+ '-H', 'content-type: application/json',
269
+ '-d', JSON.stringify({ model, input: [truncateUtf8(query)] }),
270
+ ],
271
+ { timeout: EMBED_QUERY_SYNC_TIMEOUT_MS, encoding: 'utf8', maxBuffer: 8 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] },
272
+ )
273
+ } catch (err) {
274
+ const message = err instanceof Error ? err.message : String(err)
275
+ const outcome: EmbeddingFailureOutcome = /timed out|ETIMEDOUT|maxTime/i.test(message) ? 'timeout' : 'network'
276
+ return { ok: false, outcome, message: `${outcome}: ${message}`, host, model, latencyMs: Date.now() - started }
277
+ }
278
+ let json: unknown
279
+ try {
280
+ json = JSON.parse(raw)
281
+ } catch {
282
+ return { ok: false, outcome: 'bad_json', message: 'ollama returned non-JSON (sync path).', host, model, latencyMs: Date.now() - started }
283
+ }
284
+ const embeddings = isPlainObject(json) ? (json as Record<string, unknown>).embeddings : undefined
285
+ const first = Array.isArray(embeddings) && embeddings.length > 0 ? embeddings[0] : undefined
286
+ if (!Array.isArray(first)) {
287
+ return { ok: false, outcome: 'bad_shape', message: 'ollama response has no embeddings[0] array (sync path).', host, model, latencyMs: Date.now() - started }
288
+ }
289
+ const vector = (first as unknown[]).filter((n): n is number => typeof n === 'number')
290
+ if (vector.length === 0 || vector.length !== (first as unknown[]).length) {
291
+ return { ok: false, outcome: 'bad_shape', message: 'embeddings[0] malformed (sync path).', host, model, latencyMs: Date.now() - started }
292
+ }
293
+ return { ok: true, vector, model, dim: vector.length, latencyMs: Date.now() - started }
294
+ }
package/src/ilog.ts CHANGED
@@ -27,6 +27,14 @@ export interface SlowItem {
27
27
  why: string
28
28
  }
29
29
 
30
+ /**
31
+ * Slow-lane full-lifecycle outcome (A4 决议 3, spec §3.2): where a slow-lane
32
+ * run (or round with a slow-lane stake) ended. Precedent = decisions.jsonl's
33
+ * outcome enum — a closed vocabulary so 「没跑」(no-run/no-claim) and 「跑了
34
+ * 全败」(llm-error/timeout) are finally distinguishable in the log.
35
+ */
36
+ export type SlowOutcome = 'no-run' | 'no-claim' | 'no-candidates' | 'llm-error' | 'timeout' | 'delivered' | 'expired'
37
+
30
38
  export interface InjectionRecord {
31
39
  at: string
32
40
  sessionId?: string
@@ -60,6 +68,15 @@ export interface InjectionRecord {
60
68
  slowMs?: number
61
69
  /** Slow-lane pointers this round, in delivery order. */
62
70
  slow?: SlowItem[]
71
+ /**
72
+ * Slow-lane disposition for this round (A4 决议 3, spec §8.2): `delivered`
73
+ * when a pending was consumed and packed, `expired` at its hard bounds, and
74
+ * the producing run's failure point (no-run/no-claim/no-candidates/
75
+ * llm-error/timeout) when a spliced arrived with no pending. Optional —
76
+ * older lines predate the field and pure fast-lane rounds may omit it.
77
+ * Written once with the record, never backfilled (ilog append-only).
78
+ */
79
+ slowOutcome?: SlowOutcome
63
80
  }
64
81
 
65
82
  /**
package/src/index.ts CHANGED
@@ -501,8 +501,9 @@ export async function apply(ctx: Context, config: TopicsRuntimeConfig = {}): Pro
501
501
  if (cfg.autoInject) {
502
502
  const consumed = slowLane.consume(sessionId, observer.turnCountOf(sessionId))
503
503
  if (consumed !== undefined) {
504
- if ('pending' in consumed) slow = consumed.pending
505
- else slowExpired = consumed.expired
504
+ if ('pending' in consumed) {
505
+ slow = { ...consumed.pending, outcome: consumed.pending.outcome }
506
+ } else slowExpired = consumed.expired
506
507
  }
507
508
  }
508
509
  const r = service.retrieveSync(query, sessionId, seen === undefined && echo === undefined ? undefined : { exclude: seen, echo }, slow, slowExpired)
@@ -708,7 +709,10 @@ export async function apply(ctx: Context, config: TopicsRuntimeConfig = {}): Pro
708
709
  // and its own settle hook does the release.
709
710
  const run = distiller.request(sessionId, reason)
710
711
  if (run !== undefined) {
711
- void run.finally(() => releaseSessionLlm(sessionId)).catch(() => undefined)
712
+ void run
713
+ .finally(() => releaseSessionLlm(sessionId))
714
+ .then(() => service.refreshEmbeddingIndex())
715
+ .catch(() => undefined)
712
716
  }
713
717
  })
714
718
 
@@ -916,7 +920,11 @@ export async function apply(ctx: Context, config: TopicsRuntimeConfig = {}): Pro
916
920
  // no-adapter detail instead
917
921
  }
918
922
  const run = distiller.request(sessionId, 'boot-replay')
919
- if (run !== undefined) void run.catch(() => undefined)
923
+ if (run !== undefined) {
924
+ void run
925
+ .then(() => service.refreshEmbeddingIndex())
926
+ .catch(() => undefined)
927
+ }
920
928
  })
921
929
  .catch(() => undefined)
922
930
  // Consolidation cadence check — after the pull (freshest pool),
@@ -951,6 +959,9 @@ export async function apply(ctx: Context, config: TopicsRuntimeConfig = {}): Pro
951
959
  })
952
960
  .catch(() => undefined)
953
961
  }
962
+ // Embedding index maintenance (A4/A6, spec §3): boot-time freshness
963
+ // check + incremental rebuild — provider '' / packageMode off = no-op.
964
+ void service.refreshEmbeddingIndex().catch(() => undefined)
954
965
  })
955
966
  .catch((error: unknown) => {
956
967
  warn(`dsh-topics-memory 启动链失败(不影响会话启动):${error instanceof Error ? error.message : String(error)}`)
@@ -1075,7 +1086,11 @@ export async function apply(ctx: Context, config: TopicsRuntimeConfig = {}): Pro
1075
1086
  ? { ok: false, reason: 'in-flight', created: [], updated: [], marked: 0 }
1076
1087
  : { ok: false, reason: 'no-model', created: [], updated: [], marked: 0 }
1077
1088
  }
1078
- return run.finally(() => releaseSessionLlm(sessionId))
1089
+ void run
1090
+ .finally(() => releaseSessionLlm(sessionId))
1091
+ .then(() => service.refreshEmbeddingIndex())
1092
+ .catch(() => undefined)
1093
+ return run
1079
1094
  }
1080
1095
  // Manual /topics consolidate trigger: same lane as the cadence path, same
1081
1096
  // trigger-time llm capture and in-flight guard (the command runs inside a
@@ -1146,6 +1161,9 @@ const DEFAULTS: TopicsConfigValue = {
1146
1161
  distillMaxModelCalls: 8,
1147
1162
  consolidateCadence: 'daily',
1148
1163
  deprecatedTtlDays: 15,
1164
+ embeddingProvider: '',
1165
+ embeddingModel: '',
1166
+ packageMode: 'off',
1149
1167
  usageBoost: 0.15,
1150
1168
  pushDebounceSeconds: 45,
1151
1169
  }
@@ -0,0 +1,132 @@
1
+ /**
2
+ * meta/pipeline-events.jsonl — the pipeline-level anomaly ledger (spec §8.1,
3
+ * A2/A6 BL-1 revised: the "记 wtf 账" mechanism never existed, this IS the
4
+ * explicit ledger). One line JSON per event; always on, no config key
5
+ * (恒开无键 — observability is not a gray-release feature).
6
+ *
7
+ * Discipline = decisions.jsonl (src/jev/log.ts) verbatim: field-whitelist
8
+ * copy on write (extra caller fields cannot leak in, detail values must be
9
+ * scalar), 512KB auto-compaction keeping the most recent quarter, and write
10
+ * failures swallowed silently — a broken sink must never break the pipeline.
11
+ * Unlike jev/log this writer takes the bundle root explicitly (callers like
12
+ * the slow lane already hold it; tests point it at a tmp dir).
13
+ *
14
+ * @module pipeline-events
15
+ */
16
+
17
+ import { appendFile, mkdir, readFile, rename, writeFile } from 'node:fs/promises'
18
+ import { randomUUID } from 'node:crypto'
19
+ import { dirname, join } from 'node:path'
20
+ import { metaDir } from './paths.ts'
21
+
22
+ /** Closed vocabulary, spec §8.1 + W-C wave start set. `slow-lane-outcome` is
23
+ * the slow lane's per-run disposition row (quality.ts); the distill/link
24
+ * kinds are the A2/A6 producers' contract — they import this module. */
25
+ export type PipelineEventKind = 'slow-lane-outcome' | 'distill-op-invalid' | 'distill-op-retry-exhausted' | 'link-ref-rejected'
26
+
27
+ /** File NAME inside the bundle's meta dir (path via pipelineEventsFile). */
28
+ export const PIPELINE_EVENTS_FILE = 'pipeline-events.jsonl'
29
+
30
+ export interface PipelineEvent {
31
+ at: string
32
+ kind: PipelineEventKind
33
+ /** Bounded scalar metadata only — never conversation or conclusion text. */
34
+ detail?: Record<string, string | number | boolean>
35
+ }
36
+
37
+ const COMPACT_LIMIT = 512 * 1024 // ~512KB cap, same as the decisions/ilog sidecars
38
+ /** Whitelist copy bounds: detail entries and their values stay metadata-sized. */
39
+ const DETAIL_MAX_ENTRIES = 16
40
+ const DETAIL_KEY_MAX_CHARS = 64
41
+ const DETAIL_VALUE_MAX_CHARS = 256
42
+
43
+ /** Runtime mirror of PipelineEventKind — the closed vocabulary is enforced
44
+ * at the write gate too (a JS caller cannot smuggle an unknown kind in). */
45
+ const KNOWN_KINDS: ReadonlySet<string> = new Set<string>([
46
+ 'slow-lane-outcome',
47
+ 'distill-op-invalid',
48
+ 'distill-op-retry-exhausted',
49
+ 'link-ref-rejected',
50
+ ])
51
+
52
+ export function pipelineEventsFile(bundleDir: string): string {
53
+ return join(metaDir(bundleDir), PIPELINE_EVENTS_FILE)
54
+ }
55
+
56
+ // Serialized like jev/log: single-record appends are line-atomic anyway, but
57
+ // the compaction rewrite must not interleave with an append.
58
+ let queue: Promise<unknown> = Promise.resolve()
59
+
60
+ function enqueue<T>(op: () => Promise<T>): Promise<T> {
61
+ const run = queue.then(op, op)
62
+ queue = run.catch(() => undefined)
63
+ return run
64
+ }
65
+
66
+ /** All write failures die HERE — never upstream. */
67
+ async function appendJsonl(file: string, lines: readonly string[]): Promise<void> {
68
+ await enqueue(async () => {
69
+ try {
70
+ await mkdir(dirname(file), { recursive: true })
71
+ await appendFile(file, lines.map((l) => `${l}\n`).join(''), 'utf8')
72
+ await compactIfNeeded(file)
73
+ } catch {
74
+ // fail-open: a broken ledger must never break the pipeline (§8.1)
75
+ }
76
+ })
77
+ }
78
+
79
+ // jev/log compactIfNeeded pattern: ~512KB cap; keep the most recent quarter
80
+ // when exceeded (headroom for the next window).
81
+ async function compactIfNeeded(file: string): Promise<void> {
82
+ let raw: string
83
+ try {
84
+ raw = await readFile(file, 'utf8')
85
+ } catch {
86
+ return
87
+ }
88
+ if (raw.length <= COMPACT_LIMIT) return
89
+ const lines = raw.split('\n').filter((l) => l.trim() !== '')
90
+ const keep = lines.slice(-Math.max(1, Math.floor(lines.length / 4)))
91
+ const tmp = `${file}.tmp-${randomUUID()}`
92
+ try {
93
+ await writeFile(tmp, keep.map((l) => `${l}\n`).join(''), 'utf8')
94
+ await rename(tmp, file)
95
+ } catch {
96
+ // swallow — the next append retries the compaction
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Copy one event through the field whitelist onto the ledger. Only `at`,
102
+ * `kind` and a scalar-valued `detail` map can pass; non-scalar detail values
103
+ * (objects/arrays/null/NaN), surplus entries and over-long keys/values are
104
+ * dropped here so no unbounded content can ride in. Write failures are
105
+ * swallowed downstream — this never rejects and never throws.
106
+ */
107
+ export async function recordPipelineEvent(bundleDir: string, event: PipelineEvent): Promise<void> {
108
+ if (bundleDir === '' || typeof bundleDir !== 'string') return
109
+ if (event === null || typeof event !== 'object') return
110
+ if (typeof event.kind !== 'string' || !KNOWN_KINDS.has(event.kind)) return
111
+ const detail: Record<string, string | number | boolean> = {}
112
+ if (event.detail !== undefined && typeof event.detail === 'object') {
113
+ for (const [key, value] of Object.entries(event.detail)) {
114
+ if (Object.keys(detail).length >= DETAIL_MAX_ENTRIES) break
115
+ const t = typeof value
116
+ if (t === 'string') {
117
+ if ((value as string) !== '') detail[key.slice(0, DETAIL_KEY_MAX_CHARS)] = (value as string).slice(0, DETAIL_VALUE_MAX_CHARS)
118
+ } else if (t === 'number') {
119
+ if (Number.isFinite(value)) detail[key.slice(0, DETAIL_KEY_MAX_CHARS)] = value
120
+ } else if (t === 'boolean') {
121
+ detail[key.slice(0, DETAIL_KEY_MAX_CHARS)] = value
122
+ }
123
+ // objects/arrays/null/undefined never pass the whitelist
124
+ }
125
+ }
126
+ const at = typeof event.at === 'string' && event.at !== '' ? event.at : new Date().toISOString()
127
+ const row =
128
+ Object.keys(detail).length === 0
129
+ ? { at, kind: event.kind }
130
+ : { at, kind: event.kind, detail }
131
+ await appendJsonl(pipelineEventsFile(bundleDir), [JSON.stringify(row)])
132
+ }