dsh-memvault 0.10.0 → 0.11.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/lib/index.js CHANGED
@@ -19,8 +19,8 @@
19
19
  * Configuration is described once in `config.js`; `schema.js` turns that same
20
20
  * description into the Config schema DSH validates and the Plugins page renders.
21
21
  */
22
- import { readFileSync, statSync } from 'node:fs'
23
- import { formatCoreBlocks, readCoreBlocks } from './blocks.js'
22
+ import { existsSync, readFileSync, statSync } from 'node:fs'
23
+ import { formatCoreBlocksDetailed, readCoreBlocks } from './blocks.js'
24
24
  import {
25
25
  createEventBuffer,
26
26
  loadState,
@@ -31,11 +31,15 @@ import {
31
31
  } from './extract.js'
32
32
  import {
33
33
  BLOCKS_PATH,
34
+ DOMAIN_PATH,
35
+ KNOWLEDGE_PATH,
36
+ TIMELINE_PATH,
34
37
  FLAG_PATH,
35
38
  REINDEX_PATH,
36
39
  FLUSH_PATH,
37
40
  MEMORIES_PATH,
38
41
  MEMORY_PATH,
42
+ PROPOSALS_PATH,
39
43
  REFRESH_PATH,
40
44
  REPLAY_PATH,
41
45
  REVIEW_PATH,
@@ -50,6 +54,14 @@ import { CoreStore } from './core/store.js'
50
54
  import { DEFAULT_CORE_DB } from './core/host.js'
51
55
  import { buildPipeline, resolvePipeline, runCoreExtraction } from './core/pipeline.js'
52
56
  import { runBlockActionCore } from './core/block-write.js'
57
+ import { knowledgeEvents, knowledgeStats, rememberKnowledge } from './core/knowledge.js'
58
+ import { decideProposal as decideProposalCore, listProposals, proposalSummary } from './core/proposals.js'
59
+ import { promoteKnowledge } from './core/promotion.js'
60
+ import {
61
+ computeDomainSegment, createDomainState, createSignalRing, registerDomainTools,
62
+ } from './domain-host.js'
63
+ import { listDomains, setDomainStatus, upsertDomain } from './domain.js'
64
+ import { gateGuard } from './gate.js'
53
65
  import { backfillEmbeddings } from './core/backfill.js'
54
66
  import { flaggedIds, normalizeFlags, setFlag } from './flags.js'
55
67
  import {
@@ -95,6 +107,30 @@ export function dbFileInfo(dbPath) {
95
107
  }
96
108
  }
97
109
 
110
+ /**
111
+ * Best-effort text of one session event, for the domain signal ring.
112
+ *
113
+ * Domain scoring only needs "what has been said or touched lately", so this is
114
+ * deliberately forgiving: an event shape we do not recognise contributes an empty
115
+ * string instead of throwing inside the session observer.
116
+ */
117
+ export function eventText(event) {
118
+ const data = event?.data ?? {}
119
+ const content = data.content ?? data.message?.content ?? data.arguments ?? data.args ?? data.query ?? ''
120
+ if (typeof content === 'string') return content
121
+ if (Array.isArray(content)) {
122
+ return content
123
+ .map((part) => (typeof part === 'string' ? part : (part?.text ?? part?.content ?? '')))
124
+ .filter((part) => typeof part === 'string')
125
+ .join(' ')
126
+ }
127
+ try {
128
+ return JSON.stringify(content ?? '')
129
+ } catch {
130
+ return ''
131
+ }
132
+ }
133
+
98
134
  /**
99
135
  * Do the configured paths actually resolve?
100
136
  *
@@ -254,12 +290,15 @@ export function apply(ctx, config = {}) {
254
290
  * Keeping `blocks` beside `text` costs nothing (the read produced them anyway)
255
291
  * and is what the panel renders: the browser cannot read the store itself.
256
292
  */
257
- let cache = { text: '', at: 0, blocks: [], error: null }
293
+ let cache = { text: '', at: 0, blocks: [], dropped: 0, error: null }
258
294
 
259
295
  /** One read: blocks, then the rendered prompt text. Throws if the store is unreadable. */
260
296
  function readNow() {
261
297
  const blocks = readCoreBlocks({ dbPath: coreDbPath, scopes, labels })
262
- return { blocks, text: formatCoreBlocks(blocks, { maxChars }) }
298
+ const rendered = formatCoreBlocksDetailed(blocks, { maxChars })
299
+ // `dropped` travels with the text so the panel can say "the budget squeezed
300
+ // N blocks out" instead of leaving the reader to notice the omission note.
301
+ return { blocks, text: rendered.text, dropped: rendered.dropped }
263
302
  }
264
303
 
265
304
  /**
@@ -312,6 +351,11 @@ export function apply(ctx, config = {}) {
312
351
 
313
352
  // ── half 2: turn/end → MemVault write pipeline ─────────────────────────────
314
353
  const extract = settings.extract
354
+ // The knowledge channel has its own budget and switches; extract.enabled gates
355
+ // both (no turn/end handler, no window), so an install with extraction off also
356
+ // has no knowledge capture.
357
+ const knowledgeSettings = extract.knowledge ?? {}
358
+ let lastKnowledge = null
315
359
 
316
360
  // ── the in-plugin store (JS kernel) ──────────────────────────────────────
317
361
  // Opened lazily so a read-only composition never creates a database file.
@@ -348,6 +392,139 @@ export function apply(ctx, config = {}) {
348
392
  agentId: scopes.find((scope) => scope.type === 'agent')?.id ?? null,
349
393
  runId: null,
350
394
  }
395
+
396
+ // ── domain packs (0.11 P2): a second, optional context segment ─────────────
397
+ //
398
+ // Separate contribution rather than more text in the core one: the core is human
399
+ // approved and small, the domain segment is workspace-dependent and may be empty.
400
+ // Its own name also means `suppressRuntimeContext()` decisions stay legible —
401
+ // though both are registered `required` because a gate that vanishes silently is
402
+ // worse than no gate.
403
+ const domainSettings = { ...(settings.domain ?? {}) }
404
+ // The config surface keeps whole numbers (every numeric knob in this plugin is an
405
+ // integer so the schema stays one shape); the scorer wants a 0–5 float.
406
+ if (Number.isFinite(domainSettings.thresholdPct)) domainSettings.threshold = domainSettings.thresholdPct / 100
407
+ const domainGateSettings = { ...(domainSettings.gate ?? {}) }
408
+ const domainState = createDomainState()
409
+ const domainSignals = createSignalRing()
410
+ let domainCache = { text: '', at: 0, dir: '' }
411
+
412
+ /**
413
+ * The domain segment for this step, refreshed on its own TTL.
414
+ *
415
+ * Fail-soft for the same reason as the core read: a workspace probe that throws
416
+ * must not fail the turn, and serving the last known segment is better than
417
+ * dropping the rules mid-task.
418
+ */
419
+ function domainSegment() {
420
+ const now = Date.now()
421
+ const dir = domainSettings.probeDir ?? ''
422
+ const ttl = domainSettings.refreshMs ?? 10_000
423
+ if (domainCache.at !== 0 && now - domainCache.at < ttl && domainCache.dir === dir) return domainCache.text
424
+ try {
425
+ // Same promise as the panel: never create the file just to render, but read
426
+ // an existing store even when nothing else has opened it yet.
427
+ const store = core !== null || existsSync(coreDbPath) ? coreStore() : null
428
+ if (store === null) {
429
+ domainCache = { text: '', at: now, dir }
430
+ return ''
431
+ }
432
+ const out = computeDomainSegment({
433
+ store,
434
+ state: domainState,
435
+ settings: domainSettings,
436
+ signals: domainSignals.snapshot(),
437
+ now,
438
+ })
439
+ domainCache = { text: out.text, at: now, dir }
440
+ return out.text
441
+ } catch (error) {
442
+ warnOnce('domain', 'domain segment unavailable; serving the last known text', error)
443
+ return domainCache.text
444
+ }
445
+ }
446
+
447
+ if (domainSettings.enabled !== false) {
448
+ ctx.effect(() => ctx.systemPrompt.context({
449
+ name: domainSettings.name ?? 'memvault:domain',
450
+ order: domainSettings.order ?? 215,
451
+ text: () => domainSegment(),
452
+ // Same two reasons as the core segment: pack text is prose (interpolation
453
+ // could throw during assemble) and an invisible gate is worse than none.
454
+ interpolate: false,
455
+ required: true,
456
+ }), 'dsh-memvault: domain context')
457
+ }
458
+
459
+ /**
460
+ * The knowledge flow, newest first: what was captured, proposed, decided,
461
+ * activated and retrieved.
462
+ *
463
+ * Built by merging four tables that already record timestamps, rather than by
464
+ * writing a fifth event log: a timeline that needs its own bookkeeping drifts from
465
+ * the data it claims to describe. `retrievals` is sampled (last few) because a
466
+ * busy search would otherwise drown every other event.
467
+ */
468
+ function readTimeline({ limit = 60, retrievalSample = 8 } = {}) {
469
+ const store = core ?? (existsSync(coreDbPath) ? coreStore() : null)
470
+ if (store === null) return { events: [], unavailable: true }
471
+ const events = []
472
+ const push = (at, kind, label, detail = '') => {
473
+ if (!at) return
474
+ events.push({ at: String(at), kind, label: String(label ?? ''), detail: String(detail ?? '') })
475
+ }
476
+ try {
477
+ for (const row of store.db.prepare(
478
+ 'SELECT label, change_kind, proposer, status, created_at, decided_at, decided_by FROM block_proposals',
479
+ ).all()) {
480
+ push(row.created_at, 'proposal', row.label, `${row.change_kind} · ${row.proposer}`)
481
+ if (row.decided_at) push(row.decided_at, 'decision', row.label, `${row.status}${row.decided_by ? ` · ${row.decided_by}` : ''}`)
482
+ }
483
+ for (const row of store.db.prepare('SELECT domain_id, kind, at, detail FROM domain_events').all()) {
484
+ let detail = ''
485
+ try {
486
+ const parsed = JSON.parse(String(row.detail ?? '{}'))
487
+ if (parsed.reasons?.length) detail = parsed.reasons.join(',')
488
+ else if (parsed.note) detail = String(parsed.note).slice(0, 60)
489
+ } catch { /* a malformed detail is not worth failing the timeline */ }
490
+ push(row.at, `domain:${row.kind}`, row.domain_id, detail)
491
+ }
492
+ for (const row of store.db.prepare(
493
+ 'SELECT k.kind, m.text, k.created_at FROM knowledge k JOIN memories m ON m.id = k.memory_id',
494
+ ).all()) {
495
+ push(row.created_at, 'knowledge', row.kind, String(row.text ?? '').slice(0, 80))
496
+ }
497
+ for (const row of store.db.prepare(
498
+ 'SELECT query, hit, at FROM retrievals ORDER BY at DESC LIMIT ?',
499
+ ).all(retrievalSample)) {
500
+ push(row.at, 'retrieval', String(row.query ?? '').slice(0, 40), row.hit ? 'hit' : 'miss')
501
+ }
502
+ } catch (error) {
503
+ return { events: [], error: String(error?.message ?? error) }
504
+ }
505
+ events.sort((a, b) => String(b.at).localeCompare(String(a.at)))
506
+ return { events: events.slice(0, Math.max(1, Math.min(200, Number(limit) || 60))) }
507
+ }
508
+
509
+ /** Status view: which packs exist, which are approved, which are injected now. */
510
+ function domainSnapshot() {
511
+ try {
512
+ const store = core ?? (existsSync(coreDbPath) ? coreStore() : null)
513
+ if (store === null) return null
514
+ const packs = listDomains(store, { status: 'all' })
515
+ return {
516
+ packs: packs.length,
517
+ approved: packs.filter((pack) => pack.status === 'active').length,
518
+ active: [...domainState.active],
519
+ shadow: domainState.shadow.map((entry) => entry.domainId),
520
+ probeDir: domainSettings.probeDir ?? '',
521
+ reasons: [...domainState.reasons.entries()].map(([domainId, reasons]) => ({ domainId, reasons })),
522
+ }
523
+ } catch {
524
+ return null
525
+ }
526
+ }
527
+
351
528
  // Loaded even when extraction is off: the panel reports the history, and
352
529
  // "extraction is off" is exactly the state a reader needs to be able to see.
353
530
  const state = loadState(extract.statePath)
@@ -417,9 +594,19 @@ let pendingStats = () => null
417
594
  refreshMs,
418
595
  cacheAgeMs: cache.at === 0 ? null : Date.now() - cache.at,
419
596
  renderedChars: cache.text.length,
597
+ // Blocks the character budget pushed out of this render. Zero is the
598
+ // normal case; anything else means the configured blocks no longer fit.
599
+ droppedBlocks: cache.dropped ?? 0,
420
600
  error: cache.error,
421
601
  },
422
602
  blocks: cache.blocks,
603
+ // Waiting proposals. Counting does not create the file (that is the one
604
+ // promise a read-only composition gets), but it does open an existing one:
605
+ // after a restart the queue is real even though nothing has opened it yet.
606
+ proposals: core === null && !existsSync(coreDbPath) ? null : proposalSummary(coreStore()),
607
+ // Which domain packs are injected right now. Counted from the same lazy-read
608
+ // rule: an existing store is read, a missing one is not created.
609
+ domain: domainSnapshot(),
423
610
  // Whether the configured store file is actually there, and how big. The panel
424
611
  // shows this at setup time: "the path exists but nothing is in it" and "the
425
612
  // path is wrong" look identical in a row count alone.
@@ -506,6 +693,67 @@ let pendingStats = () => null
506
693
  return { ok: true, report: { ...report, applied: true } }
507
694
  }
508
695
  : null,
696
+ /**
697
+ * The core-block proposal queue.
698
+ *
699
+ * Reading is always available (it opens the store only if something already
700
+ * did — a read-only composition must not create the file just to report an
701
+ * empty queue). Deciding needs the write half, because approving writes a
702
+ * block; the panel is told that through `writable`/403 rather than silently
703
+ * accepting a decision it cannot apply.
704
+ */
705
+ readProposals: ({ status = 'pending', limit = 20 } = {}) => {
706
+ // Read the queue whenever the store already exists on disk. Reporting
707
+ // "unavailable" merely because nothing has opened it yet was wrong: after
708
+ // a restart the panel showed an empty-grey tab while the proposals were
709
+ // sitting right there. The promise being kept is narrower — a read-only
710
+ // composition must not *create* the file.
711
+ const store = core ?? (existsSync(coreDbPath) ? coreStore() : null)
712
+ if (store === null) return { items: [], summary: { pending: 0, stale: 0, applied: 0, oldestAgeMs: null }, unavailable: true }
713
+ return listProposals(store, { status, limit })
714
+ },
715
+ decideProposal: panelWrites
716
+ ? async (input) => {
717
+ const out = decideProposalCore(coreStore(), input)
718
+ // An applied proposal changed a block, so the next assemble must not
719
+ // serve a render that predates it (same rule as a panel block write).
720
+ if (out.ok) cache = { ...cache, at: 0 }
721
+ return out
722
+ }
723
+ : null,
724
+ // Domain packs: the shelf, and the two writes a human can make (author a
725
+ // pack, or change its status). Activation itself happens in the host half.
726
+ // Knowledge health. Same lazy-read rule as the other read routes: an existing
727
+ // store is read, a missing one is not created just to render a panel.
728
+ readTimeline: (options) => readTimeline(options),
729
+ readKnowledge: () => {
730
+ const store = core ?? (existsSync(coreDbPath) ? coreStore() : null)
731
+ if (store === null) {
732
+ return { unavailable: true, kinds: [], evidence: 0, promotions: 0, eligible: 0, retrievals: null, last: null }
733
+ }
734
+ return { ...knowledgeStats(store), last: lastKnowledge }
735
+ },
736
+ readDomains: () => {
737
+ const store = core ?? (existsSync(coreDbPath) ? coreStore() : null)
738
+ if (store === null) return { domains: [], active: [], shadow: [], unavailable: true }
739
+ return {
740
+ domains: listDomains(store, { status: 'all' }),
741
+ active: [...domainState.active],
742
+ shadow: domainState.shadow.map((entry) => entry.domainId),
743
+ }
744
+ },
745
+ writeDomain: panelWrites
746
+ ? (input) => {
747
+ const store = coreStore()
748
+ const action = String(input?.action ?? '').trim()
749
+ const out = action === 'status'
750
+ ? setDomainStatus(store, input.domain_id ?? input.domainId, input.status, { note: String(input.note ?? '') })
751
+ : upsertDomain(store, input, { proposer: 'panel' })
752
+ // The segment is cached; an authored pack must be visible on the next read.
753
+ if (out.ok) domainCache = { ...domainCache, at: 0 }
754
+ return out
755
+ }
756
+ : null,
509
757
  // The structure view: which scope dimensions hold what, which blocks are
510
758
  // actually injected, and the relation graph as it stands. `scopes` comes from
511
759
  // this plugin's own config, which is the only place that knows what is
@@ -670,6 +918,26 @@ let pendingStats = () => null
670
918
  path: STRUCTURE_PATH,
671
919
  handler: api.structure,
672
920
  }), 'dsh-memvault: panel structure route')
921
+ panelCtx.effect(() => panelCtx.webServer.register({
922
+ kind: 'exact',
923
+ path: PROPOSALS_PATH,
924
+ handler: api.proposals,
925
+ }), 'dsh-memvault: panel proposal route')
926
+ panelCtx.effect(() => panelCtx.webServer.register({
927
+ kind: 'exact',
928
+ path: DOMAIN_PATH,
929
+ handler: api.domain,
930
+ }), 'dsh-memvault: panel domain route')
931
+ panelCtx.effect(() => panelCtx.webServer.register({
932
+ kind: 'exact',
933
+ path: KNOWLEDGE_PATH,
934
+ handler: api.knowledge,
935
+ }), 'dsh-memvault: panel knowledge route')
936
+ panelCtx.effect(() => panelCtx.webServer.register({
937
+ kind: 'exact',
938
+ path: TIMELINE_PATH,
939
+ handler: api.timeline,
940
+ }), 'dsh-memvault: panel timeline route')
673
941
  })
674
942
 
675
943
  // ── half: memory tools on the in-plugin store (optional) ─────────────────
@@ -683,11 +951,65 @@ let pendingStats = () => null
683
951
  // store opens only when the host exposes the `tools` service (core/host.js).
684
952
  // A failure here leaves block injection and extraction exactly as they were.
685
953
  try {
686
- attachMemoryTools(ctx, { logger: ctx.logger, projectDir: extract.projectDir })
954
+ attachMemoryTools(ctx, {
955
+ logger: ctx.logger,
956
+ projectDir: extract.projectDir,
957
+ // The pipeline already resolved the embedder from the merged extraction
958
+ // environment (process env + config `env` + `.env`). Passing it in keeps
959
+ // `memory_add` writing the same `model` row extraction does; letting this
960
+ // resolve its own made the same text land under two model keys.
961
+ embedder: corePipeline.embedder,
962
+ // What the model can currently see, so a search can record whether the
963
+ // memory it returned was already in front of it (see `retrievals.injected`).
964
+ injectedText: () => cache.text,
965
+ })
687
966
  } catch (error) {
688
967
  warnOnce('memory-tools', 'memory tools unavailable', error)
689
968
  }
690
969
 
970
+ // Domain tools: same lazy-service treatment as the memory tools. They read packs
971
+ // from the same store, so an install without extraction still gets them — packs
972
+ // are authored and approved by a human, not derived from transcripts.
973
+ if (domainSettings.enabled !== false) {
974
+ try {
975
+ ctx.inject(['tools'], (toolCtx) => {
976
+ toolCtx.effect(() => {
977
+ try {
978
+ return registerDomainTools(toolCtx.tools, {
979
+ store: coreStore(),
980
+ state: domainState,
981
+ config: { ...domainGateSettings, maxPacks: domainSettings.maxPacks ?? 20 },
982
+ })
983
+ } catch (error) {
984
+ warnOnce('domain-tools', 'domain tools could not be registered', error)
985
+ return () => {}
986
+ }
987
+ })
988
+ // The guard is what makes a gate real. `tools.guard()` is synchronous and
989
+ // runs after policy and approval, before dispatch: its return value becomes
990
+ // an error result, so the model cannot proceed by ignoring the injected
991
+ // notice. Registered only when gates are enabled, because a deployment that
992
+ // wants advisory-only packs should not be silently refused calls.
993
+ if (domainGateSettings.enabled !== false) {
994
+ // `ctx.tools.guard()` is a 0.2.2 API. On 0.2.1 the plugin still has to
995
+ // start: gates then degrade to the injected notice, which is exactly the
996
+ // pre-0.11 behaviour, and the absence is reported once instead of throwing
997
+ // out of this effect.
998
+ if (typeof toolCtx.tools?.guard !== 'function') {
999
+ warnOnce('domain-gate', 'this DSH has no ctx.tools.guard(); gates are advisory only on this version')
1000
+ } else {
1001
+ toolCtx.effect(() => toolCtx.tools.guard((exec) => gateGuard(exec, {
1002
+ state: domainState,
1003
+ config: domainGateSettings,
1004
+ })))
1005
+ }
1006
+ }
1007
+ })
1008
+ } catch (error) {
1009
+ warnOnce('domain-tools', 'domain tool injection failed', error)
1010
+ }
1011
+ }
1012
+
691
1013
  if (!extract.enabled) return
692
1014
 
693
1015
  /**
@@ -747,8 +1069,71 @@ let pendingStats = () => null
747
1069
  * The one place that talks to MemVault for extraction — a window, a window
748
1070
  * recovered from the state file after a restart, or a replay a human asked for.
749
1071
  */
750
- async function extractTranscript(sessionId, { text, turns, seq, recovered = false, replayOf = null, env = {} }) {
751
- if (seq !== null && seq !== undefined) watermarks.set(sessionId, seq)
1072
+ /**
1073
+ * One knowledge-channel run: render its own transcript, extract, store, promote.
1074
+ *
1075
+ * Separated from `extractTranscript` so the fact path stays readable and so this
1076
+ * can be tested by calling it directly. Returns a summary that lands in the
1077
+ * diagnostics, because "the knowledge channel silently did nothing" is the state
1078
+ * a human most needs to be able to see.
1079
+ */
1080
+ async function runKnowledgeChannel({ sessionId, events, turns, seq, plan }) {
1081
+ // A replayed or restart-recovered window carries only the fact transcript, not
1082
+ // the events; the knowledge channel is skipped there and says why. Silence is
1083
+ // what hid this bug: the first version threw on a non-array and `warnOnce` ate
1084
+ // it, so the table stayed empty with no trace in the panel.
1085
+ const skip = (reason) => {
1086
+ lastKnowledge = { at: new Date().toISOString(), seq, sessionId, skipped: reason }
1087
+ diagnostics.push({ at: lastKnowledge.at, seq, turns, outcome: `knowledge skipped: ${reason}`, knowledge: { skipped: reason } })
1088
+ if (diagnostics.length > 5) diagnostics.shift()
1089
+ return { skipped: reason }
1090
+ }
1091
+ const usable = knowledgeEvents(events)
1092
+ if (usable.length === 0) return skip('no events')
1093
+ const rendered = renderTranscript(usable, knowledgeSettings.maxInputChars ?? 8000, {
1094
+ includeAssistant: knowledgeSettings.includeAssistant !== false,
1095
+ includeTools: knowledgeSettings.includeTools !== false,
1096
+ })
1097
+ if (rendered.replace(/\s/g, '').length < 40) return skip('transcript below 40 characters')
1098
+ const extractor = plan?.knowledgeExtractor ?? corePipeline.knowledgeExtractor
1099
+ if (!extractor) return skip('no knowledge extractor')
1100
+
1101
+ const items = await extractor.extract([{ role: 'user', content: rendered }])
1102
+ const written = rememberKnowledge(coreStore(), { items, scope: writeScope, sessionId, seq })
1103
+
1104
+ let promotion = null
1105
+ const promotionSettings = knowledgeSettings.promotion ?? {}
1106
+ if (promotionSettings.enabled !== false && writeScope.userId) {
1107
+ const limits = {}
1108
+ if (Number.isFinite(promotionSettings.minUsed)) limits.minUsed = promotionSettings.minUsed
1109
+ if (Number.isFinite(promotionSettings.minEvidence)) limits.minEvidence = promotionSettings.minEvidence
1110
+ const result = promoteKnowledge(coreStore(), {
1111
+ target: { scopeType: 'user', scopeId: writeScope.userId },
1112
+ limits,
1113
+ })
1114
+ promotion = {
1115
+ candidates: result.candidates,
1116
+ created: result.created.length,
1117
+ skipped: result.skipped.length,
1118
+ errors: result.errors.length,
1119
+ }
1120
+ }
1121
+
1122
+ const summary = {
1123
+ chars: rendered.length,
1124
+ items: items.length,
1125
+ added: written.added,
1126
+ duplicated: written.duplicated,
1127
+ skipped: written.skipped,
1128
+ promotion,
1129
+ }
1130
+ lastKnowledge = { at: new Date().toISOString(), seq, sessionId, ...summary }
1131
+ diagnostics.push({ at: new Date().toISOString(), seq, turns, outcome: `knowledge added=${written.added} dup=${written.duplicated}`, knowledge: summary })
1132
+ if (diagnostics.length > 5) diagnostics.shift()
1133
+ return summary
1134
+ }
1135
+
1136
+ async function extractTranscript(sessionId, { text, turns, events = null, seq, recovered = false, replayOf = null, env = {} }) { if (seq !== null && seq !== undefined) watermarks.set(sessionId, seq)
752
1137
 
753
1138
  // Retain the input BEFORE sending it: a run that fails is exactly the one a
754
1139
  // human may want to retry (or fix and retry).
@@ -816,6 +1201,17 @@ let pendingStats = () => null
816
1201
  at, seq, sessionId, inputKey: replayOf ?? inputKey, ...(replayOf === null ? {} : { replayOf }),
817
1202
  })
818
1203
  }
1204
+ // The six tacit-knowledge classes ride the same window through a different
1205
+ // prompt and a different budget. This runs after the fact pipeline on purpose: a
1206
+ // knowledge failure must never eat a fact run's success, and the two share no
1207
+ // rows (facts go to `memories` alone; knowledge adds the side row).
1208
+ if (knowledgeSettings.enabled !== false) {
1209
+ try {
1210
+ await runKnowledgeChannel({ sessionId, events, turns, seq, plan })
1211
+ } catch (error) {
1212
+ warnOnce('knowledge', 'knowledge extraction failed', error)
1213
+ }
1214
+ }
819
1215
  clearPending(sessionId)
820
1216
  persistState()
821
1217
 
@@ -832,6 +1228,10 @@ let pendingStats = () => null
832
1228
  async function extractWindow(sessionId, turns) {
833
1229
  await extractTranscript(sessionId, {
834
1230
  text: renderWindow(turns),
1231
+ // The knowledge channel needs the raw events (assistant prose and tool traffic
1232
+ // are where reasons and failure modes live), and `turns` arrives here as an
1233
+ // array of turns — passing the count instead made it throw and skip silently.
1234
+ events: turns.flatMap((turn) => turn.events ?? []),
835
1235
  turns: turns.length,
836
1236
  seq: turns.at(-1)?.seq ?? null,
837
1237
  })
@@ -886,6 +1286,11 @@ let pendingStats = () => null
886
1286
  // Buffer EVERY event: this observer is called for each appended event, and it
887
1287
  // is the only event source we can rely on.
888
1288
  eventLog.push(String(session?.id), event)
1289
+ // Domain activation scores on what has been said and touched lately. Feeding a
1290
+ // small ring here is cheaper than rescanning a session that keeps growing, and
1291
+ // it is the only signal available without a host hook that exposes messages.
1292
+ if (event?.type === 'user/message') domainSignals.pushUser(eventText(event))
1293
+ else if (event?.type === 'tool/call') domainSignals.pushTool(eventText(event))
889
1294
  if (event?.type !== 'turn/end') return
890
1295
  // Only turns that finished on purpose. `aborted` / `error` / `interrupted` /
891
1296
  // `blocked` are skipped by default; `max-tokens` is NOT, because a truncated