dsh-context-graph 0.2.1 → 0.2.3

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/README.md CHANGED
@@ -53,10 +53,12 @@ Command line (use the profile your app runs; the desktop app uses `desktop`):
53
53
  dsh plugin --profile desktop add dsh-context-graph
54
54
  ```
55
55
 
56
- **Updates.** Installed from npm, the plugin gets dsh's built-in updater: on the Plugins page
57
- press **Refresh**, and when a newer version is published an **Update** button appears on the
58
- plugin. Restart the app after updating. A `github:` install is not eligible for this; remove
59
- it and add `dsh-context-graph` from npm once.
56
+ **Updates.** dsh 0.2.1 desktop builds have no update check for third-party plugins, so the
57
+ plugin checks npm itself once per app start. When a newer version exists, your next chat reply
58
+ ends with one line saying so, and `/context-graph stats` shows it on its first line. To update:
59
+ Plugins, open dsh-context-graph, **Uninstall**, then **Add plugin** `dsh-context-graph@<new version>`
60
+ and restart the app. Name the exact version: dsh's pnpm holds back very new releases otherwise.
61
+ Turn the check off with the environment variable `DSH_CONTEXT_GRAPH_NO_UPDATE_CHECK=1`.
60
62
 
61
63
  Remove with `dsh plugin --profile desktop remove dsh-context-graph`.
62
64
 
@@ -85,7 +87,7 @@ Defaults live in [cordis.patch.yml](cordis.patch.yml). A patch replaces the row'
85
87
  | `maxHits` | `5` | Nodes shown per human turn |
86
88
  | `inlineMaxChars` | `1200` | A single dominant hit this short is shown verbatim |
87
89
  | `surfaceMaxNodes` | `40` | Nodes listed at the start of a session |
88
- | `builderMaxTokens` | `2048` | Output cap for the indexing call |
90
+ | `builderMaxTokens` | `8192` | Output cap for the indexing call; thinking models spend part of it reasoning |
89
91
  | `provider`, `model` | `''` | Empty: reuse the conversation's routed provider and model |
90
92
  | `fold` | `true` | Fold old turns of the current chat into a table of contents |
91
93
  | `foldAtTokens` | `24000` | Fold once the foldable part costs this much per request |
package/cordis.patch.yml CHANGED
@@ -10,7 +10,7 @@
10
10
  maxHits: 5 # nodes shown per human turn
11
11
  inlineMaxChars: 1200 # one dominant hit this short is shown verbatim, no recall needed
12
12
  surfaceMaxNodes: 40 # god nodes listed at the start of a session
13
- builderMaxTokens: 2048
13
+ builderMaxTokens: 8192 # thinking models spend part of this on reasoning
14
14
  provider: '' # empty: reuse the conversation's routed provider/model
15
15
  model: ''
16
16
  fold: true # replace old turns of the current chat with a table of contents
package/graph.js CHANGED
@@ -187,18 +187,48 @@ export function builderInstruction(graph) {
187
187
  ].join('\n')
188
188
  }
189
189
 
190
- /** Tolerant JSON extraction: fences, leading prose, trailing commas. `undefined` when nothing usable. */
190
+ /** Complete top-level `{...}` objects inside the array that opens at `open`; an unfinished last one is dropped. */
191
+ function objectsInArray(text, open) {
192
+ const out = []
193
+ let depth = 0
194
+ let start = -1
195
+ let inString = false
196
+ for (let i = open + 1; i < text.length; i++) {
197
+ const ch = text[i]
198
+ if (inString) {
199
+ if (ch === '\\') i++
200
+ else if (ch === '"') inString = false
201
+ continue
202
+ }
203
+ if (ch === '"') inString = true
204
+ else if (ch === '{' || ch === '[') { if (depth++ === 0 && ch === '{') start = i }
205
+ else if (ch === '}' || ch === ']') {
206
+ if (depth === 0) break
207
+ if (--depth === 0 && ch === '}' && start >= 0) { out.push(text.slice(start, i + 1)); start = -1 }
208
+ }
209
+ }
210
+ return out
211
+ }
212
+
213
+ /**
214
+ * Tolerant extraction of the builder's JSON. Handles code fences, prose around it, `<think>` blocks,
215
+ * trailing commas, and output cut off mid-way (every complete node object is kept).
216
+ * `undefined` when there is no `"nodes"` array at all.
217
+ */
191
218
  export function parseBuilderOutput(text) {
192
- const start = text.indexOf('{')
193
- const end = text.lastIndexOf('}')
194
- if (start < 0 || end <= start) return undefined
195
- const body = text.slice(start, end + 1).replace(/,\s*([}\]])/g, '$1')
196
- let parsed
197
- try { parsed = JSON.parse(body) } catch { return undefined }
198
- if (!parsed || !Array.isArray(parsed.nodes)) return undefined
199
- const nodes = parsed.nodes.filter((n) => n && typeof n.label === 'string' && n.label.trim() && Array.isArray(n.msgs) && n.msgs.length > 0)
200
- const edges = Array.isArray(parsed.edges) ? parsed.edges.filter((e) => Array.isArray(e) && e.length === 3 && e.every((x) => typeof x === 'string')) : []
201
- return { nodes, edges }
219
+ const clean = String(text ?? '').replace(/<think>[\s\S]*?(?:<\/think>|$)/g, '')
220
+ const at = clean.search(/"nodes"\s*:\s*\[/)
221
+ if (at < 0) return undefined
222
+ const nodes = []
223
+ for (const raw of objectsInArray(clean, clean.indexOf('[', at))) {
224
+ try { nodes.push(JSON.parse(raw.replace(/,\s*([}\]])/g, '$1'))) } catch { /* skip a malformed node */ }
225
+ }
226
+ const edgesAt = clean.search(/"edges"\s*:/)
227
+ const edges = edgesAt < 0 ? [] : [...clean.slice(edgesAt).matchAll(/\[\s*"([^"]+)"\s*,\s*"([^"]+)"\s*,\s*"([^"]+)"\s*\]/g)].map((m) => [m[1], m[2], m[3]])
228
+ return {
229
+ nodes: nodes.filter((n) => n && typeof n.label === 'string' && n.label.trim() && Array.isArray(n.msgs) && n.msgs.length > 0),
230
+ edges
231
+ }
202
232
  }
203
233
 
204
234
  /**
package/index.js CHANGED
@@ -1,384 +1,421 @@
1
- /**
2
- * dsh-context-graph: memory of past conversations as a small graph, so the model reads node
3
- * gists instead of old messages and fetches verbatim text only when it needs it.
4
- *
5
- * - `agent/turn-stopping`: every few human turns, one cheap auxiliary model call indexes the new
6
- * span into `<workspace>/.context-graph/graph.json` and stores the cited messages verbatim.
7
- * - `agent/pre-step`: on a human turn, lexically match the prompt against the graph and append one
8
- * short `[context-graph]` block to the admitted messages (end of the request, so the provider's
9
- * prefix cache survives). The first human turn of a session also gets the cross-session surface layer.
10
- * - Tool `recall`: verbatim source and neighbours of one node.
11
- * - `llm/stream`: meters main vs builder tokens and cache reads for `/context-graph stats`.
12
- * Stock compaction is untouched.
13
- */
14
-
15
- import { isAbsolute, join } from 'node:path'
16
- import { stat } from 'node:fs/promises'
17
-
18
- import { BlockAssembler, createUserMessage } from '@deepseek-ai/dsh-llm'
19
- import { defineTool } from '@deepseek-ai/dsh-tools'
20
-
21
- import {
22
- builderInstruction, collectSpan, emptyGraph, estimateTokens, foldKept, matchNodes, mergeDelta, neighbors, onlyFromSession,
23
- parseBuilderOutput, planFold, renderFoldIndex, renderHits, renderSurface, SOURCE_KIND, surfaceNodes, transcriptForBuilder,
24
- turnIndex, turnTranscript
25
- } from './graph.js'
26
- import { appendSource, loadGraph, readSource, saveGraph } from './store.js'
27
-
28
- export const name = 'context-graph'
29
- export const inject = ['tools']
30
-
31
- const PURPOSE = 'context-graph'
32
-
33
- const DEFAULTS = {
34
- dir: '.context-graph',
35
- buildEveryTurns: 4,
36
- buildMinChars: 400,
37
- maxHits: 5,
38
- inlineMaxChars: 1200,
39
- surfaceMaxNodes: 40,
40
- builderMaxTokens: 2048,
41
- provider: '',
42
- model: '',
43
- fold: true,
44
- foldAtTokens: 24000,
45
- keepTurns: 2
46
- }
47
-
48
- const textOf = (content) => (Array.isArray(content) ? content : []).filter((b) => b?.type === 'text').map((b) => b.text).join('\n').trim()
49
-
50
- export function apply(ctx, config = {}) {
51
- const cfg = { ...DEFAULTS, ...config }
52
- const sessions = new Map()
53
- const graphCache = new Map()
54
- const meter = {
55
- main: { requests: 0, input: 0, cacheRead: 0, cacheWrite: 0, output: 0 },
56
- builder: { requests: 0, input: 0, cacheRead: 0, cacheWrite: 0, output: 0 },
57
- builds: 0,
58
- folds: 0,
59
- foldSaved: 0,
60
- injected: 0,
61
- injectedTokens: 0,
62
- recalls: 0
63
- }
64
-
65
- const state = (sid) => {
66
- let st = sessions.get(sid)
67
- if (!st) { st = { lastBuiltSeq: -1, building: false, surfaceSent: false }; sessions.set(sid, st) }
68
- return st
69
- }
70
-
71
- function dirFor(agent) {
72
- const base = agent.options?.cwd ?? agent.session.header?.cwd ?? process.cwd()
73
- return isAbsolute(cfg.dir) ? cfg.dir : join(base, cfg.dir)
74
- }
75
-
76
- /** Graph read with an mtime check so other sessions' builds show up without a restart. */
77
- async function getGraph(dir) {
78
- let mtimeMs = 0
79
- try { mtimeMs = (await stat(join(dir, 'graph.json'))).mtimeMs } catch { return emptyGraph() }
80
- const cached = graphCache.get(dir)
81
- if (cached && cached.mtimeMs === mtimeMs) return cached.graph
82
- const graph = await loadGraph(dir)
83
- graphCache.set(dir, { mtimeMs, graph })
84
- return graph
85
- }
86
-
87
- function resolveTarget(agent) {
88
- if (cfg.provider && cfg.model) return { provider: cfg.provider, model: cfg.model }
89
- const routed = agent.session.requestHeader()?.config
90
- if (routed?.provider && routed?.model) return { provider: routed.provider, model: routed.model }
91
- const { provider, model } = agent.options ?? {}
92
- return provider && model ? { provider, model } : undefined
93
- }
94
-
95
- function surfaceAlreadyOnLog(session) {
96
- return session.surface.nodes.some((seq) => {
97
- const event = session.eventAt(seq)
98
- return event?.type === 'user/message' && event.data?.source?.kind === SOURCE_KIND && event.data.source.layer === 'surface'
99
- })
100
- }
101
-
102
- // ---------- builder ----------
103
- const isSubagent = (agent) => agent.options?.origin === 'subagent' || agent.session.header?.origin === 'subagent'
104
-
105
- async function build(agent, { force = false, turn = null } = {}) {
106
- const session = agent.session
107
- const sid = String(session.id)
108
- const st = state(sid)
109
- if (st.building) return { status: 'busy' }
110
- // ponytail: subagent chatter stays out of the project graph; revisit if delegated work holds decisions worth keeping.
111
- if (isSubagent(agent)) return { status: 'skipped', reason: 'subagent session' }
112
- st.building = true
113
- try {
114
- const span = collectSpan(session.surface.nodes, (seq) => session.eventAt(seq), st.lastBuiltSeq)
115
- const chars = span.messages.reduce((n, m) => n + m.text.length, 0)
116
- if (span.messages.length === 0) return { status: 'nothing', reason: 'no new messages since the last build' }
117
- if (!force && (span.userTurns < cfg.buildEveryTurns || chars < cfg.buildMinChars)) {
118
- return { status: 'skipped', reason: `${span.userTurns}/${cfg.buildEveryTurns} human turns, ${chars}/${cfg.buildMinChars} chars` }
119
- }
120
- const llm = ctx.get('llm')
121
- if (!llm) return { status: 'unavailable', reason: 'no llm service in this composition' }
122
- const target = resolveTarget(agent)
123
- if (!target) return { status: 'unavailable', reason: 'no provider/model routed yet' }
124
- const dir = dirFor(agent)
125
- const graph = await loadGraph(dir)
126
- const prompt = `${transcriptForBuilder(span.messages)}\n\n${builderInstruction(graph)}`
127
- const assembler = new BlockAssembler()
128
- for await (const chunk of llm.stream({
129
- provider: target.provider,
130
- model: target.model,
131
- messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }],
132
- maxTokens: cfg.builderMaxTokens,
133
- sessionId: session.id,
134
- purpose: PURPOSE
135
- })) assembler.push(chunk)
136
- const finish = assembler.finish
137
- if (finish?.kind === 'error' || finish?.kind === 'aborted') throw new Error(finish.failure?.message ?? finish.kind)
138
- const delta = parseBuilderOutput(textOf(assembler.blocks()))
139
- if (!delta) return { status: 'failed', reason: 'builder output was not the expected JSON' }
140
- // Reversibility rule: a node is written only when it cites text we can store verbatim.
141
- delta.nodes = delta.nodes.filter((n) => n.msgs.some((i) => span.messages[i]))
142
- const now = new Date().toISOString()
143
- const touched = mergeDelta(graph, delta, { session: sid, turn, now })
144
- for (const { id, msgs } of touched) {
145
- const cited = msgs.map((i) => span.messages[i]).filter(Boolean)
146
- if (cited.length > 0) await appendSource(dir, id, { session: sid, turn, at: now, messages: cited })
147
- }
148
- await saveGraph(dir, graph)
149
- st.lastBuiltSeq = span.lastSeq
150
- meter.builds++
151
- return { status: 'built', nodes: touched.length, newNodes: touched.filter((t) => t.isNew).length, totalNodes: Object.keys(graph.nodes).length, edges: graph.edges.length, dir }
152
- } catch (error) {
153
- console.error('context-graph: build failed (non-fatal)', error)
154
- return { status: 'failed', reason: String(error?.message ?? error) }
155
- } finally {
156
- st.building = false
157
- }
158
- }
159
-
160
- ctx.on('agent/turn-stopping', (payload) => {
161
- // Fire and forget: the build must never delay the turn's close.
162
- void build(payload.agent, { turn: payload.turn })
163
- })
164
-
165
- // ---------- fold: replace old turns of this chat with a table of contents ----------
166
- function rangeTokens(session, seqs) {
167
- const wanted = new Set(seqs)
168
- try {
169
- const nodes = ctx.get('tokenMeter')?.measure(session)?.nodes
170
- if (Array.isArray(nodes)) return nodes.filter((n) => wanted.has(n.seq)).reduce((sum, n) => sum + (n.tokens ?? n.heuristicTokens ?? 0), 0)
171
- } catch { /* fall back to the estimate */ }
172
- return seqs.reduce((sum, seq) => sum + estimateTokens(JSON.stringify(session.eventAt(seq)?.data ?? '')), 0)
173
- }
174
-
175
- async function fold(agent, { force = false } = {}) {
176
- const session = agent.session
177
- const sid = String(session.id)
178
- const eventAt = (seq) => session.eventAt(seq)
179
- const plan = planFold(session.surface.nodes, eventAt, { keepTurns: cfg.keepTurns, maxSeq: state(sid).lastBuiltSeq })
180
- if (!plan) return { status: 'skipped', reason: `nothing indexed outside the last ${cfg.keepTurns} turns yet` }
181
- const before = rangeTokens(session, plan.shadowedSeqs)
182
- if (!force && before < cfg.foldAtTokens) return { status: 'skipped', reason: `foldable part is ~${before} tokens, folds at ${cfg.foldAtTokens}` }
183
- const turns = turnIndex(eventAt, plan.endSeq)
184
- const index = renderFoldIndex(await getGraph(dirFor(agent)), sid, turns, { maxNodes: cfg.surfaceMaxNodes })
185
- const kept = foldKept(plan.shadowedSeqs, eventAt)
186
- const after = estimateTokens([index, ...kept.blocks.map((b) => b.text ?? '')].join('\n'))
187
- // Never-worse gate: a fold must at least halve what it replaces, or it is not worth breaking the cache.
188
- if (after * 2 > before) return { status: 'skipped', reason: `table of contents (~${after}) is not under half of the ~${before} tokens it would replace` }
189
- const message = createUserMessage({
190
- content: [{ type: 'text', text: index }, ...kept.blocks],
191
- source: { kind: SOURCE_KIND, fold: true, keptKinds: kept.kinds, foldedTurns: turns.length, foldedTokens: before }
192
- })
193
- session.append('user/message', message, {
194
- surfaceOp: { op: 'replace', startSeq: plan.startSeq, endSeq: plan.endSeq },
195
- sourceEventSeqs: [...plan.shadowedSeqs]
196
- })
197
- meter.folds++
198
- meter.foldSaved += before - after
199
- return { status: 'folded', turns: turns.length, before, after }
200
- }
201
-
202
- // ---------- matcher ----------
203
- ctx.on('agent/pre-step', async (payload, next) => {
204
- const agent = payload.agent
205
- const prompt = payload.messages.filter((m) => m.source?.kind === 'user').map((m) => textOf(m.content)).join('\n')
206
- // Fold only at the start of a human turn: the previous turn is closed, so no tool call is open.
207
- if (cfg.fold && prompt && !isSubagent(agent)) {
208
- try { await fold(agent) } catch (error) { console.error('context-graph: fold failed (non-fatal)', error) }
209
- }
210
- const decision = await next()
211
- if (decision.kind !== 'enter') return decision
212
- try {
213
- if (isSubagent(agent) || !prompt) return decision
214
- const dir = dirFor(agent)
215
- const graph = await getGraph(dir)
216
- if (Object.keys(graph.nodes).length === 0) return decision
217
- const sid = String(agent.session.id)
218
- const st = state(sid)
219
- const sessionCompacted = agent.session.surface.replaceGeneration > 0
220
- const parts = []
221
- let layer
222
- if (!st.surfaceSent) {
223
- st.surfaceSent = true
224
- // Nodes that only come from this very session are still in its context: no need to repeat them.
225
- const ids = surfaceNodes(graph, cfg.surfaceMaxNodes).filter((id) => sessionCompacted || !onlyFromSession(graph.nodes[id], sid))
226
- if (ids.length > 0 && !surfaceAlreadyOnLog(agent.session)) {
227
- parts.push(renderSurface(graph, ids))
228
- layer = 'surface'
229
- }
230
- }
231
- const hits = matchNodes(graph, prompt, { max: cfg.maxHits, session: sid, sessionCompacted })
232
- let inline
233
- if (hits.length === 1 || (hits.length > 1 && hits[0].score >= 2 * hits[1].score)) {
234
- const text = await readSource(dir, hits[0].id)
235
- if (text && text.length <= cfg.inlineMaxChars) inline = { id: hits[0].id, text }
236
- }
237
- const block = renderHits(graph, hits, { inline })
238
- if (block) parts.push(block)
239
- if (parts.length === 0) return decision
240
- const text = parts.join('\n\n')
241
- meter.injected++
242
- meter.injectedTokens += estimateTokens(text)
243
- const message = createUserMessage({ content: [{ type: 'text', text }], source: layer ? { kind: SOURCE_KIND, layer } : { kind: SOURCE_KIND } })
244
- return { ...decision, messages: [...decision.messages, message] }
245
- } catch (error) {
246
- console.error('context-graph: matcher failed (non-fatal)', error)
247
- return decision
248
- }
249
- })
250
-
251
- // ---------- meter ----------
252
- ctx.on('llm/stream', (options, next) => {
253
- const inner = next()
254
- const bucket = options.purpose === PURPOSE ? meter.builder : meter.main
255
- async function* tracked() {
256
- try {
257
- for await (const chunk of inner) {
258
- if (chunk?.type === 'usage' && chunk.usage) {
259
- bucket.input += chunk.usage.inputTokens ?? 0
260
- bucket.cacheRead += chunk.usage.cacheReadTokens ?? 0
261
- bucket.cacheWrite += chunk.usage.cacheWriteTokens ?? 0
262
- bucket.output += chunk.usage.outputTokens ?? 0
263
- }
264
- yield chunk
265
- }
266
- } finally {
267
- bucket.requests++
268
- }
269
- }
270
- return tracked()
271
- })
272
-
273
- // ---------- recall tool ----------
274
- ctx.tools.register(defineTool({
275
- name: 'recall',
276
- description: [
277
- 'Fetch verbatim text behind an id shown in a [context-graph] block: a topic id (n17) returns its source messages and neighbouring topics; a turn id (t7) returns that folded turn of this conversation exactly.',
278
- 'Call it when a gist is relevant but not precise enough to answer. Never invent an id; only use ids you were shown.'
279
- ].join(' '),
280
- parameters: {
281
- id: { type: 'string', required: true, description: 'Topic id such as n17, or turn id such as t7.' },
282
- depth: { type: 'integer', description: '0 (default): this node only. 1: also include each neighbour\'s gist.' }
283
- },
284
- output: {
285
- schema: {
286
- type: 'object',
287
- additionalProperties: false,
288
- properties: {
289
- status: { type: 'string', enum: ['ok', 'unknown'], required: true },
290
- text: { type: 'string', required: true }
291
- }
292
- },
293
- render: (_args, value) => [{ type: 'text', text: value.text }]
294
- },
295
- async execute(args, exec) {
296
- const agent = exec.agent
297
- if (!agent?.session) return { status: 'unknown', text: 'recall is unavailable: no session attached to this call.' }
298
- const id = String(args.id ?? '').trim()
299
- const turn = /^t(\d+)$/.exec(id)
300
- if (turn) {
301
- const text = turnTranscript((seq) => agent.session.eventAt(seq), Number(turn[1]))
302
- if (text === undefined) return { status: 'unknown', text: `No turn ${id} in this conversation.` }
303
- meter.recalls++
304
- return { status: 'ok', text: `# ${id} (verbatim)\n\n${text}` }
305
- }
306
- const dir = dirFor(agent)
307
- const graph = await getGraph(dir)
308
- const node = graph.nodes[id]
309
- if (!node) return { status: 'unknown', text: `No node "${id}" in this project's context graph. Only use ids shown in a [context-graph] block.` }
310
- meter.recalls++
311
- node.hits = (node.hits ?? 0) + 1
312
- saveGraph(dir, graph).catch((error) => console.error('context-graph: hit count save failed', error))
313
- const lines = [`# ${id} ${node.label}`, `${node.kind}. ${node.gist}`, '']
314
- const source = await readSource(dir, id)
315
- lines.push(source ? source.trim() : '(no verbatim source stored for this node)')
316
- const links = neighbors(graph, id)
317
- if (links.length > 0) {
318
- lines.push('', 'Neighbours:')
319
- for (const link of links) {
320
- const other = graph.nodes[link.id]
321
- const arrow = link.direction === 'out' ? `${id} ${link.relation} ${link.id}` : `${link.id} ${link.relation} ${id}`
322
- lines.push(`- ${arrow}: ${other.label}${args.depth >= 1 ? ` — ${other.gist}` : ''}`)
323
- }
324
- }
325
- return { status: 'ok', text: lines.join('\n') }
326
- }
327
- }))
328
-
329
- // ---------- /context-graph command (nested: only where a human-command surface exists) ----------
330
- ctx.plugin({
331
- name: 'context-graph-command',
332
- inject: ['commands'],
333
- apply(cmdCtx) {
334
- cmdCtx.effect(function* () {
335
- yield cmdCtx.commands.register({
336
- name: 'context-graph',
337
- description: 'Project memory graph: /context-graph [stats|build|fold|find <words>]',
338
- // Without `input`, dsh clients run the bare name and send any typed arguments to the model as chat.
339
- input: { hint: '[stats|build|fold|find <words>]' },
340
- async handler(invocation) {
341
- const [sub = 'stats', ...rest] = invocation.rawInput.trim().split(/\s+/).filter(Boolean)
342
- const agent = invocation.agent
343
- if (sub === 'fold') {
344
- const result = await agent.runMaintenance(async () => {
345
- await build(agent, { force: true })
346
- return fold(agent, { force: true })
347
- })
348
- if (result.status !== 'folded') return { kind: 'error', text: `Not folded: ${result.reason}` }
349
- return { kind: 'success', text: `Folded turns t1-t${result.turns}: ~${result.before} tokens replaced by a ~${result.after}-token table of contents.` }
350
- }
351
- if (sub === 'build') {
352
- const result = await agent.runMaintenance(() => build(agent, { force: true }))
353
- if (result.status !== 'built') return { kind: 'error', text: `Build ${result.status}: ${result.reason ?? ''}`.trim() }
354
- return { kind: 'success', text: `Indexed ${result.nodes} nodes (${result.newNodes} new); graph now ${result.totalNodes} nodes, ${result.edges} edges at ${result.dir}` }
355
- }
356
- const graph = await getGraph(dirFor(agent))
357
- if (sub === 'find') {
358
- const hits = matchNodes(graph, rest.join(' '), { max: cfg.maxHits })
359
- return { kind: 'success', text: hits.length ? renderHits(graph, hits) : 'No matching nodes.' }
360
- }
361
- if (sub !== 'stats') return { kind: 'error', text: 'Usage: /context-graph [stats|build|fold|find <words>]' }
362
- const m = meter.main
363
- const cached = m.cacheRead + m.cacheWrite
364
- const hitRate = m.input + cached > 0 ? Math.round((m.cacheRead / (m.input + cached)) * 100) : 0
365
- const session = agent.session
366
- const pending = collectSpan(session.surface.nodes, (seq) => session.eventAt(seq), state(String(session.id)).lastBuiltSeq).userTurns
367
- return {
368
- kind: 'success',
369
- text: [
370
- `Graph: ${Object.keys(graph.nodes).length} nodes, ${graph.edges.length} edges (${dirFor(agent)})`,
371
- `This chat: ${pending} human turns not indexed yet; auto-index at ${cfg.buildEveryTurns}, or run /context-graph build now.`,
372
- 'Counters below are since the app started:',
373
- `Builds: ${meter.builds}; builder tokens in/out: ${meter.builder.input + meter.builder.cacheRead + meter.builder.cacheWrite}/${meter.builder.output}`,
374
- `Folds: ${meter.folds}; ~${meter.foldSaved} input tokens removed from every later request`,
375
- `Injected blocks: ${meter.injected} (~${meter.injectedTokens} tokens); recalls: ${meter.recalls}`,
376
- `Main requests: ${m.requests}; input ${m.input} uncached + ${m.cacheRead} cache-read + ${m.cacheWrite} cache-write; cache-hit ${hitRate}%`
377
- ].join('\n')
378
- }
379
- }
380
- })
381
- }, 'context-graph command')
382
- }
383
- })
384
- }
1
+ /**
2
+ * dsh-context-graph: memory of past conversations as a small graph, so the model reads node
3
+ * gists instead of old messages and fetches verbatim text only when it needs it.
4
+ *
5
+ * - `agent/turn-stopping`: every few human turns, one cheap auxiliary model call indexes the new
6
+ * span into `<workspace>/.context-graph/graph.json` and stores the cited messages verbatim.
7
+ * - `agent/pre-step`: on a human turn, lexically match the prompt against the graph and append one
8
+ * short `[context-graph]` block to the admitted messages (end of the request, so the provider's
9
+ * prefix cache survives). The first human turn of a session also gets the cross-session surface layer.
10
+ * - Tool `recall`: verbatim source and neighbours of one node.
11
+ * - `llm/stream`: meters main vs builder tokens and cache reads for `/context-graph stats`.
12
+ * Stock compaction is untouched.
13
+ */
14
+
15
+ import { isAbsolute, join } from 'node:path'
16
+ import { readFileSync } from 'node:fs'
17
+ import { mkdir, stat, writeFile } from 'node:fs/promises'
18
+
19
+ import { BlockAssembler, createUserMessage } from '@deepseek-ai/dsh-llm'
20
+ import { defineTool } from '@deepseek-ai/dsh-tools'
21
+
22
+ import {
23
+ builderInstruction, collectSpan, emptyGraph, estimateTokens, foldKept, matchNodes, mergeDelta, neighbors, onlyFromSession,
24
+ parseBuilderOutput, planFold, renderFoldIndex, renderHits, renderSurface, SOURCE_KIND, surfaceNodes, transcriptForBuilder,
25
+ turnIndex, turnTranscript
26
+ } from './graph.js'
27
+ import { appendSource, loadGraph, readSource, saveGraph } from './store.js'
28
+ import { startUpdateCheck } from './update.js'
29
+
30
+ export const name = 'context-graph'
31
+ export const inject = ['tools']
32
+
33
+ const PURPOSE = 'context-graph'
34
+ const { version } = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8'))
35
+
36
+ const DEFAULTS = {
37
+ dir: '.context-graph',
38
+ buildEveryTurns: 4,
39
+ buildMinChars: 400,
40
+ maxHits: 5,
41
+ inlineMaxChars: 1200,
42
+ surfaceMaxNodes: 40,
43
+ builderMaxTokens: 8192,
44
+ provider: '',
45
+ model: '',
46
+ fold: true,
47
+ foldAtTokens: 24000,
48
+ keepTurns: 2
49
+ }
50
+
51
+ const textOf = (content) => (Array.isArray(content) ? content : []).filter((b) => b?.type === 'text').map((b) => b.text).join('\n').trim()
52
+
53
+ export function apply(ctx, config = {}) {
54
+ const { _updates, ...rest } = config
55
+ const cfg = { ...DEFAULTS, ...rest }
56
+ // `_updates` lets tests stand in for the network check.
57
+ const updates = _updates ?? startUpdateCheck(version)
58
+ let noticeShown = false
59
+ const sessions = new Map()
60
+ const graphCache = new Map()
61
+ const meter = {
62
+ main: { requests: 0, input: 0, cacheRead: 0, cacheWrite: 0, output: 0 },
63
+ builder: { requests: 0, input: 0, cacheRead: 0, cacheWrite: 0, output: 0 },
64
+ builds: 0,
65
+ folds: 0,
66
+ foldSaved: 0,
67
+ injected: 0,
68
+ injectedTokens: 0,
69
+ recalls: 0
70
+ }
71
+
72
+ const state = (sid) => {
73
+ let st = sessions.get(sid)
74
+ if (!st) { st = { lastBuiltSeq: -1, building: false, surfaceSent: false }; sessions.set(sid, st) }
75
+ return st
76
+ }
77
+
78
+ function dirFor(agent) {
79
+ const base = agent.options?.cwd ?? agent.session.header?.cwd ?? process.cwd()
80
+ return isAbsolute(cfg.dir) ? cfg.dir : join(base, cfg.dir)
81
+ }
82
+
83
+ /** Graph read with an mtime check so other sessions' builds show up without a restart. */
84
+ async function getGraph(dir) {
85
+ let mtimeMs = 0
86
+ try { mtimeMs = (await stat(join(dir, 'graph.json'))).mtimeMs } catch { return emptyGraph() }
87
+ const cached = graphCache.get(dir)
88
+ if (cached && cached.mtimeMs === mtimeMs) return cached.graph
89
+ const graph = await loadGraph(dir)
90
+ graphCache.set(dir, { mtimeMs, graph })
91
+ return graph
92
+ }
93
+
94
+ function resolveTarget(agent) {
95
+ if (cfg.provider && cfg.model) return { provider: cfg.provider, model: cfg.model }
96
+ const routed = agent.session.requestHeader()?.config
97
+ if (routed?.provider && routed?.model) return { provider: routed.provider, model: routed.model }
98
+ const { provider, model } = agent.options ?? {}
99
+ return provider && model ? { provider, model } : undefined
100
+ }
101
+
102
+ function surfaceAlreadyOnLog(session) {
103
+ return session.surface.nodes.some((seq) => {
104
+ const event = session.eventAt(seq)
105
+ return event?.type === 'user/message' && event.data?.source?.kind === SOURCE_KIND && event.data.source.layer === 'surface'
106
+ })
107
+ }
108
+
109
+ // ---------- builder ----------
110
+ const isSubagent = (agent) => agent.options?.origin === 'subagent' || agent.session.header?.origin === 'subagent'
111
+
112
+ async function build(agent, { force = false, turn = null } = {}) {
113
+ const session = agent.session
114
+ const sid = String(session.id)
115
+ const st = state(sid)
116
+ if (st.building) return { status: 'busy' }
117
+ // ponytail: subagent chatter stays out of the project graph; revisit if delegated work holds decisions worth keeping.
118
+ if (isSubagent(agent)) return { status: 'skipped', reason: 'subagent session' }
119
+ st.building = true
120
+ try {
121
+ const span = collectSpan(session.surface.nodes, (seq) => session.eventAt(seq), st.lastBuiltSeq)
122
+ const chars = span.messages.reduce((n, m) => n + m.text.length, 0)
123
+ if (span.messages.length === 0) return { status: 'nothing', reason: 'no new messages since the last build' }
124
+ if (!force && (span.userTurns < cfg.buildEveryTurns || chars < cfg.buildMinChars)) {
125
+ return { status: 'skipped', reason: `${span.userTurns}/${cfg.buildEveryTurns} human turns, ${chars}/${cfg.buildMinChars} chars` }
126
+ }
127
+ const llm = ctx.get('llm')
128
+ if (!llm) return { status: 'unavailable', reason: 'no llm service in this composition' }
129
+ const target = resolveTarget(agent)
130
+ if (!target) return { status: 'unavailable', reason: 'no provider/model routed yet' }
131
+ const dir = dirFor(agent)
132
+ const graph = await loadGraph(dir)
133
+ const prompt = `${transcriptForBuilder(span.messages)}\n\n${builderInstruction(graph)}`
134
+ const assembler = new BlockAssembler()
135
+ for await (const chunk of llm.stream({
136
+ provider: target.provider,
137
+ model: target.model,
138
+ messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }],
139
+ maxTokens: cfg.builderMaxTokens,
140
+ sessionId: session.id,
141
+ purpose: PURPOSE
142
+ })) assembler.push(chunk)
143
+ const finish = assembler.finish
144
+ if (finish?.kind === 'error' || finish?.kind === 'aborted') throw new Error(finish.failure?.message ?? finish.kind)
145
+ const blocks = assembler.blocks()
146
+ const answer = textOf(blocks)
147
+ // Some thinking models put everything, JSON included, into reasoning blocks.
148
+ const reasoning = blocks.filter((b) => b?.type === 'reasoning').map((b) => b.text).join('\n')
149
+ const delta = parseBuilderOutput(answer) ?? parseBuilderOutput(reasoning)
150
+ if (!delta || (delta.nodes.length === 0 && finish?.kind === 'max-tokens')) {
151
+ const saved = join(dir, 'last-builder-output.txt')
152
+ await mkdir(dir, { recursive: true })
153
+ await writeFile(saved, `finish: ${finish?.kind}\n\n--- answer ---\n${answer}\n\n--- reasoning ---\n${reasoning}\n`, 'utf8')
154
+ const why = finish?.kind === 'max-tokens'
155
+ ? `the model ran out of output tokens (builderMaxTokens ${cfg.builderMaxTokens}) before finishing`
156
+ : 'builder output was not the expected JSON'
157
+ return { status: 'failed', reason: `${why}; raw output saved to ${saved}` }
158
+ }
159
+ // Reversibility rule: a node is written only when it cites text we can store verbatim.
160
+ delta.nodes = delta.nodes.filter((n) => n.msgs.some((i) => span.messages[i]))
161
+ const now = new Date().toISOString()
162
+ const touched = mergeDelta(graph, delta, { session: sid, turn, now })
163
+ for (const { id, msgs } of touched) {
164
+ const cited = msgs.map((i) => span.messages[i]).filter(Boolean)
165
+ if (cited.length > 0) await appendSource(dir, id, { session: sid, turn, at: now, messages: cited })
166
+ }
167
+ await saveGraph(dir, graph)
168
+ st.lastBuiltSeq = span.lastSeq
169
+ meter.builds++
170
+ return { status: 'built', nodes: touched.length, newNodes: touched.filter((t) => t.isNew).length, totalNodes: Object.keys(graph.nodes).length, edges: graph.edges.length, dir }
171
+ } catch (error) {
172
+ console.error('context-graph: build failed (non-fatal)', error)
173
+ return { status: 'failed', reason: String(error?.message ?? error) }
174
+ } finally {
175
+ st.building = false
176
+ }
177
+ }
178
+
179
+ ctx.on('agent/turn-stopping', (payload) => {
180
+ // Fire and forget: the build must never delay the turn's close.
181
+ void build(payload.agent, { turn: payload.turn })
182
+ })
183
+
184
+ // ---------- fold: replace old turns of this chat with a table of contents ----------
185
+ function rangeTokens(session, seqs) {
186
+ const wanted = new Set(seqs)
187
+ try {
188
+ const nodes = ctx.get('tokenMeter')?.measure(session)?.nodes
189
+ if (Array.isArray(nodes)) return nodes.filter((n) => wanted.has(n.seq)).reduce((sum, n) => sum + (n.tokens ?? n.heuristicTokens ?? 0), 0)
190
+ } catch { /* fall back to the estimate */ }
191
+ return seqs.reduce((sum, seq) => sum + estimateTokens(JSON.stringify(session.eventAt(seq)?.data ?? '')), 0)
192
+ }
193
+
194
+ async function fold(agent, { force = false } = {}) {
195
+ const session = agent.session
196
+ const sid = String(session.id)
197
+ const eventAt = (seq) => session.eventAt(seq)
198
+ const plan = planFold(session.surface.nodes, eventAt, { keepTurns: cfg.keepTurns, maxSeq: state(sid).lastBuiltSeq })
199
+ if (!plan) return { status: 'skipped', reason: `nothing indexed outside the last ${cfg.keepTurns} turns yet` }
200
+ const before = rangeTokens(session, plan.shadowedSeqs)
201
+ if (!force && before < cfg.foldAtTokens) return { status: 'skipped', reason: `foldable part is ~${before} tokens, folds at ${cfg.foldAtTokens}` }
202
+ const turns = turnIndex(eventAt, plan.endSeq)
203
+ const index = renderFoldIndex(await getGraph(dirFor(agent)), sid, turns, { maxNodes: cfg.surfaceMaxNodes })
204
+ const kept = foldKept(plan.shadowedSeqs, eventAt)
205
+ const after = estimateTokens([index, ...kept.blocks.map((b) => b.text ?? '')].join('\n'))
206
+ // Never-worse gate: a fold must at least halve what it replaces, or it is not worth breaking the cache.
207
+ if (after * 2 > before) return { status: 'skipped', reason: `table of contents (~${after}) is not under half of the ~${before} tokens it would replace` }
208
+ const message = createUserMessage({
209
+ content: [{ type: 'text', text: index }, ...kept.blocks],
210
+ source: { kind: SOURCE_KIND, fold: true, keptKinds: kept.kinds, foldedTurns: turns.length, foldedTokens: before }
211
+ })
212
+ session.append('user/message', message, {
213
+ surfaceOp: { op: 'replace', startSeq: plan.startSeq, endSeq: plan.endSeq },
214
+ sourceEventSeqs: [...plan.shadowedSeqs]
215
+ })
216
+ meter.folds++
217
+ meter.foldSaved += before - after
218
+ return { status: 'folded', turns: turns.length, before, after }
219
+ }
220
+
221
+ // ---------- matcher ----------
222
+ ctx.on('agent/pre-step', async (payload, next) => {
223
+ const agent = payload.agent
224
+ const prompt = payload.messages.filter((m) => m.source?.kind === 'user').map((m) => textOf(m.content)).join('\n')
225
+ // Fold only at the start of a human turn: the previous turn is closed, so no tool call is open.
226
+ if (cfg.fold && prompt && !isSubagent(agent)) {
227
+ try { await fold(agent) } catch (error) { console.error('context-graph: fold failed (non-fatal)', error) }
228
+ }
229
+ const decision = await next()
230
+ if (decision.kind !== 'enter') return decision
231
+ const result = await addMemory(agent, prompt, decision)
232
+ return prompt && !isSubagent(agent) ? addUpdateNotice(result) : result
233
+ })
234
+
235
+ /** Once per app start, ask the model to pass an available update on to the user. */
236
+ function addUpdateNotice(decision) {
237
+ const notice = updates.current()
238
+ if (!notice || noticeShown) return decision
239
+ noticeShown = true
240
+ const message = createUserMessage({
241
+ content: [{ type: 'text', text: `[${SOURCE_KIND}] ${notice} At the end of your reply, tell the user this in one short line.` }],
242
+ source: { kind: SOURCE_KIND, notice: true }
243
+ })
244
+ return { ...decision, messages: [...decision.messages, message] }
245
+ }
246
+
247
+ async function addMemory(agent, prompt, decision) {
248
+ try {
249
+ if (isSubagent(agent) || !prompt) return decision
250
+ const dir = dirFor(agent)
251
+ const graph = await getGraph(dir)
252
+ if (Object.keys(graph.nodes).length === 0) return decision
253
+ const sid = String(agent.session.id)
254
+ const st = state(sid)
255
+ const sessionCompacted = agent.session.surface.replaceGeneration > 0
256
+ const parts = []
257
+ let layer
258
+ if (!st.surfaceSent) {
259
+ st.surfaceSent = true
260
+ // Nodes that only come from this very session are still in its context: no need to repeat them.
261
+ const ids = surfaceNodes(graph, cfg.surfaceMaxNodes).filter((id) => sessionCompacted || !onlyFromSession(graph.nodes[id], sid))
262
+ if (ids.length > 0 && !surfaceAlreadyOnLog(agent.session)) {
263
+ parts.push(renderSurface(graph, ids))
264
+ layer = 'surface'
265
+ }
266
+ }
267
+ const hits = matchNodes(graph, prompt, { max: cfg.maxHits, session: sid, sessionCompacted })
268
+ let inline
269
+ if (hits.length === 1 || (hits.length > 1 && hits[0].score >= 2 * hits[1].score)) {
270
+ const text = await readSource(dir, hits[0].id)
271
+ if (text && text.length <= cfg.inlineMaxChars) inline = { id: hits[0].id, text }
272
+ }
273
+ const block = renderHits(graph, hits, { inline })
274
+ if (block) parts.push(block)
275
+ if (parts.length === 0) return decision
276
+ const text = parts.join('\n\n')
277
+ meter.injected++
278
+ meter.injectedTokens += estimateTokens(text)
279
+ const message = createUserMessage({ content: [{ type: 'text', text }], source: layer ? { kind: SOURCE_KIND, layer } : { kind: SOURCE_KIND } })
280
+ return { ...decision, messages: [...decision.messages, message] }
281
+ } catch (error) {
282
+ console.error('context-graph: matcher failed (non-fatal)', error)
283
+ return decision
284
+ }
285
+ }
286
+
287
+ // ---------- meter ----------
288
+ ctx.on('llm/stream', (options, next) => {
289
+ const inner = next()
290
+ const bucket = options.purpose === PURPOSE ? meter.builder : meter.main
291
+ async function* tracked() {
292
+ try {
293
+ for await (const chunk of inner) {
294
+ if (chunk?.type === 'usage' && chunk.usage) {
295
+ bucket.input += chunk.usage.inputTokens ?? 0
296
+ bucket.cacheRead += chunk.usage.cacheReadTokens ?? 0
297
+ bucket.cacheWrite += chunk.usage.cacheWriteTokens ?? 0
298
+ bucket.output += chunk.usage.outputTokens ?? 0
299
+ }
300
+ yield chunk
301
+ }
302
+ } finally {
303
+ bucket.requests++
304
+ }
305
+ }
306
+ return tracked()
307
+ })
308
+
309
+ // ---------- recall tool ----------
310
+ ctx.tools.register(defineTool({
311
+ name: 'recall',
312
+ description: [
313
+ 'Fetch verbatim text behind an id shown in a [context-graph] block: a topic id (n17) returns its source messages and neighbouring topics; a turn id (t7) returns that folded turn of this conversation exactly.',
314
+ 'Call it when a gist is relevant but not precise enough to answer. Never invent an id; only use ids you were shown.'
315
+ ].join(' '),
316
+ parameters: {
317
+ id: { type: 'string', required: true, description: 'Topic id such as n17, or turn id such as t7.' },
318
+ depth: { type: 'integer', description: '0 (default): this node only. 1: also include each neighbour\'s gist.' }
319
+ },
320
+ output: {
321
+ schema: {
322
+ type: 'object',
323
+ additionalProperties: false,
324
+ properties: {
325
+ status: { type: 'string', enum: ['ok', 'unknown'], required: true },
326
+ text: { type: 'string', required: true }
327
+ }
328
+ },
329
+ render: (_args, value) => [{ type: 'text', text: value.text }]
330
+ },
331
+ async execute(args, exec) {
332
+ const agent = exec.agent
333
+ if (!agent?.session) return { status: 'unknown', text: 'recall is unavailable: no session attached to this call.' }
334
+ const id = String(args.id ?? '').trim()
335
+ const turn = /^t(\d+)$/.exec(id)
336
+ if (turn) {
337
+ const text = turnTranscript((seq) => agent.session.eventAt(seq), Number(turn[1]))
338
+ if (text === undefined) return { status: 'unknown', text: `No turn ${id} in this conversation.` }
339
+ meter.recalls++
340
+ return { status: 'ok', text: `# ${id} (verbatim)\n\n${text}` }
341
+ }
342
+ const dir = dirFor(agent)
343
+ const graph = await getGraph(dir)
344
+ const node = graph.nodes[id]
345
+ if (!node) return { status: 'unknown', text: `No node "${id}" in this project's context graph. Only use ids shown in a [context-graph] block.` }
346
+ meter.recalls++
347
+ node.hits = (node.hits ?? 0) + 1
348
+ saveGraph(dir, graph).catch((error) => console.error('context-graph: hit count save failed', error))
349
+ const lines = [`# ${id} ${node.label}`, `${node.kind}. ${node.gist}`, '']
350
+ const source = await readSource(dir, id)
351
+ lines.push(source ? source.trim() : '(no verbatim source stored for this node)')
352
+ const links = neighbors(graph, id)
353
+ if (links.length > 0) {
354
+ lines.push('', 'Neighbours:')
355
+ for (const link of links) {
356
+ const other = graph.nodes[link.id]
357
+ const arrow = link.direction === 'out' ? `${id} ${link.relation} ${link.id}` : `${link.id} ${link.relation} ${id}`
358
+ lines.push(`- ${arrow}: ${other.label}${args.depth >= 1 ? ` — ${other.gist}` : ''}`)
359
+ }
360
+ }
361
+ return { status: 'ok', text: lines.join('\n') }
362
+ }
363
+ }))
364
+
365
+ // ---------- /context-graph command (nested: only where a human-command surface exists) ----------
366
+ ctx.plugin({
367
+ name: 'context-graph-command',
368
+ inject: ['commands'],
369
+ apply(cmdCtx) {
370
+ cmdCtx.effect(function* () {
371
+ yield cmdCtx.commands.register({
372
+ name: 'context-graph',
373
+ description: 'Project memory graph: /context-graph [stats|build|fold|find <words>]',
374
+ // Without `input`, dsh clients run the bare name and send any typed arguments to the model as chat.
375
+ input: { hint: '[stats|build|fold|find <words>]' },
376
+ async handler(invocation) {
377
+ const [sub = 'stats', ...rest] = invocation.rawInput.trim().split(/\s+/).filter(Boolean)
378
+ const agent = invocation.agent
379
+ if (sub === 'fold') {
380
+ const result = await agent.runMaintenance(async () => {
381
+ await build(agent, { force: true })
382
+ return fold(agent, { force: true })
383
+ })
384
+ if (result.status !== 'folded') return { kind: 'error', text: `Not folded: ${result.reason}` }
385
+ return { kind: 'success', text: `Folded turns t1-t${result.turns}: ~${result.before} tokens replaced by a ~${result.after}-token table of contents.` }
386
+ }
387
+ if (sub === 'build') {
388
+ const result = await agent.runMaintenance(() => build(agent, { force: true }))
389
+ if (result.status !== 'built') return { kind: 'error', text: `Build ${result.status}: ${result.reason ?? ''}`.trim() }
390
+ return { kind: 'success', text: `Indexed ${result.nodes} nodes (${result.newNodes} new); graph now ${result.totalNodes} nodes, ${result.edges} edges at ${result.dir}` }
391
+ }
392
+ const graph = await getGraph(dirFor(agent))
393
+ if (sub === 'find') {
394
+ const hits = matchNodes(graph, rest.join(' '), { max: cfg.maxHits })
395
+ return { kind: 'success', text: hits.length ? renderHits(graph, hits) : 'No matching nodes.' }
396
+ }
397
+ if (sub !== 'stats') return { kind: 'error', text: 'Usage: /context-graph [stats|build|fold|find <words>]' }
398
+ const m = meter.main
399
+ const cached = m.cacheRead + m.cacheWrite
400
+ const hitRate = m.input + cached > 0 ? Math.round((m.cacheRead / (m.input + cached)) * 100) : 0
401
+ const session = agent.session
402
+ const pending = collectSpan(session.surface.nodes, (seq) => session.eventAt(seq), state(String(session.id)).lastBuiltSeq).userTurns
403
+ return {
404
+ kind: 'success',
405
+ text: [
406
+ `Version ${version}: ${updates.current() ?? 'no newer version found'}`,
407
+ `Graph: ${Object.keys(graph.nodes).length} nodes, ${graph.edges.length} edges (${dirFor(agent)})`,
408
+ `This chat: ${pending} human turns not indexed yet; auto-index at ${cfg.buildEveryTurns}, or run /context-graph build now.`,
409
+ 'Counters below are since the app started:',
410
+ `Builds: ${meter.builds}; builder tokens in/out: ${meter.builder.input + meter.builder.cacheRead + meter.builder.cacheWrite}/${meter.builder.output}`,
411
+ `Folds: ${meter.folds}; ~${meter.foldSaved} input tokens removed from every later request`,
412
+ `Injected blocks: ${meter.injected} (~${meter.injectedTokens} tokens); recalls: ${meter.recalls}`,
413
+ `Main requests: ${m.requests}; input ${m.input} uncached + ${m.cacheRead} cache-read + ${m.cacheWrite} cache-write; cache-hit ${hitRate}%`
414
+ ].join('\n')
415
+ }
416
+ }
417
+ })
418
+ }, 'context-graph command')
419
+ }
420
+ })
421
+ }
package/package.json CHANGED
@@ -1,53 +1,54 @@
1
- {
2
- "name": "dsh-context-graph",
3
- "version": "0.2.1",
4
- "description": "DeepSeek Harness plugin: remembers past conversations as a small graph and folds old turns of a long chat into a table of contents, so fewer input tokens are sent; exact text is recalled on demand",
5
- "type": "module",
6
- "main": "index.js",
7
- "exports": {
8
- ".": "./index.js",
9
- "./graph": "./graph.js",
10
- "./package.json": "./package.json"
11
- },
12
- "files": [
13
- "index.js",
14
- "graph.js",
15
- "store.js",
16
- "cordis.patch.yml",
17
- "README.md",
18
- "LICENSE"
19
- ],
20
- "scripts": {
21
- "test": "node --import ./test/resolve-dsh.mjs --test test/graph.test.js test/fold.test.js test/plugin.test.js"
22
- },
23
- "keywords": [
24
- "dsh-plugin",
25
- "deepseek-harness",
26
- "deepseek",
27
- "memory",
28
- "context",
29
- "knowledge-graph"
30
- ],
31
- "license": "MIT",
32
- "repository": {
33
- "type": "git",
34
- "url": "git+https://github.com/William20100221/dsh-context-graph.git"
35
- },
36
- "homepage": "https://github.com/William20100221/dsh-context-graph#readme",
37
- "bugs": {
38
- "url": "https://github.com/William20100221/dsh-context-graph/issues"
39
- },
40
- "engines": {
41
- "dsh": ">=0.2.1-rc.5 <0.3.0",
42
- "node": ">=20"
43
- },
44
- "peerDependencies": {
45
- "@deepseek-ai/dsh-llm": ">=0.2.1-rc.5 <0.3.0",
46
- "@deepseek-ai/dsh-tools": ">=0.2.1-rc.5 <0.3.0"
47
- },
48
- "dsh": {
49
- "bundle": {
50
- "patch": "./cordis.patch.yml"
51
- }
52
- }
53
- }
1
+ {
2
+ "name": "dsh-context-graph",
3
+ "version": "0.2.3",
4
+ "description": "DeepSeek Harness plugin: remembers past conversations as a small graph and folds old turns of a long chat into a table of contents, so fewer input tokens are sent; exact text is recalled on demand",
5
+ "type": "module",
6
+ "main": "index.js",
7
+ "exports": {
8
+ ".": "./index.js",
9
+ "./graph": "./graph.js",
10
+ "./package.json": "./package.json"
11
+ },
12
+ "files": [
13
+ "index.js",
14
+ "graph.js",
15
+ "store.js",
16
+ "update.js",
17
+ "cordis.patch.yml",
18
+ "README.md",
19
+ "LICENSE"
20
+ ],
21
+ "scripts": {
22
+ "test": "node --import ./test/resolve-dsh.mjs --test test/graph.test.js test/fold.test.js test/update.test.js test/plugin.test.js"
23
+ },
24
+ "keywords": [
25
+ "dsh-plugin",
26
+ "deepseek-harness",
27
+ "deepseek",
28
+ "memory",
29
+ "context",
30
+ "knowledge-graph"
31
+ ],
32
+ "license": "MIT",
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "git+https://github.com/William20100221/dsh-context-graph.git"
36
+ },
37
+ "homepage": "https://github.com/William20100221/dsh-context-graph#readme",
38
+ "bugs": {
39
+ "url": "https://github.com/William20100221/dsh-context-graph/issues"
40
+ },
41
+ "engines": {
42
+ "dsh": ">=0.2.1-rc.5 <0.3.0",
43
+ "node": ">=20"
44
+ },
45
+ "peerDependencies": {
46
+ "@deepseek-ai/dsh-llm": ">=0.2.1-rc.5 <0.3.0",
47
+ "@deepseek-ai/dsh-tools": ">=0.2.1-rc.5 <0.3.0"
48
+ },
49
+ "dsh": {
50
+ "bundle": {
51
+ "patch": "./cordis.patch.yml"
52
+ }
53
+ }
54
+ }
package/update.js ADDED
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Update check (same pattern as dsh-clear-conversation/update.js): asks the npm registry once per app
3
+ * start for the latest published version. Never throws and never delays a turn; offline means no notice.
4
+ * Needed because dsh 0.2.1 builds have no update check for third-party plugins on the Plugins page.
5
+ * Opt out with the environment variable DSH_CONTEXT_GRAPH_NO_UPDATE_CHECK=1.
6
+ */
7
+
8
+ export const PACKAGE = 'dsh-context-graph'
9
+ const LATEST_URL = `https://registry.npmjs.org/${PACKAGE}/latest`
10
+
11
+ const parts = (version) => String(version).replace(/^v/, '').split(/[-+]/)[0].split('.').map(Number)
12
+
13
+ /** True when `latest` has a higher major.minor.patch than `current`; prerelease tags are ignored. */
14
+ export function isNewer(latest, current) {
15
+ const a = parts(latest)
16
+ const b = parts(current)
17
+ if (a.some(Number.isNaN) || b.some(Number.isNaN)) return false
18
+ for (let i = 0; i < 3; i++) {
19
+ if ((a[i] ?? 0) !== (b[i] ?? 0)) return (a[i] ?? 0) > (b[i] ?? 0)
20
+ }
21
+ return false
22
+ }
23
+
24
+ /** The latest published version, or undefined when it cannot be read in time. */
25
+ export async function fetchLatestVersion({ fetchImpl = globalThis.fetch, timeoutMs = 5000 } = {}) {
26
+ try {
27
+ const response = await fetchImpl(LATEST_URL, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(timeoutMs) })
28
+ if (!response.ok) return undefined
29
+ const version = (await response.json())?.version
30
+ return typeof version === 'string' ? version : undefined
31
+ } catch {
32
+ return undefined
33
+ }
34
+ }
35
+
36
+ /**
37
+ * One line telling the user how to update, or undefined when this copy is current. The exact
38
+ * `name@version` matters: dsh's pnpm holds back very new releases unless the version is named.
39
+ */
40
+ export function updateNotice(latest, current) {
41
+ if (!latest || !isNewer(latest, current)) return undefined
42
+ return `${PACKAGE} ${latest} is available (you have ${current}). To update: Plugins, open ${PACKAGE}, Uninstall, then Add plugin ${PACKAGE}@${latest} and restart the app.`
43
+ }
44
+
45
+ /** Start the check now; `current()` returns the notice once the answer has arrived. */
46
+ export function startUpdateCheck(version, { env = process.env, ...options } = {}) {
47
+ let notice
48
+ if (!env.DSH_CONTEXT_GRAPH_NO_UPDATE_CHECK) {
49
+ void fetchLatestVersion(options).then((latest) => {
50
+ notice = updateNotice(latest, version)
51
+ })
52
+ }
53
+ return { current: () => notice }
54
+ }