dsh-context-graph 0.3.0 → 0.4.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/graph.js CHANGED
@@ -1,8 +1,9 @@
1
1
  /**
2
2
  * context-graph core. Pure: no I/O, no dsh imports, so `node --test` covers it without a harness.
3
3
  *
4
- * A graph is `{ version, nextId, nodes: { [id]: Node }, edges: [[from, to, relation], ...] }`.
4
+ * One graph per chat: `{ version, nextId, nodes: { [id]: Node }, edges: [[from, to, relation], ...] }`.
5
5
  * A Node is `{ label, gist, aliases, kind, src: [{ session, turn, at }], updated, hits }`.
6
+ * Ids inside a graph are `n12`; across chats they are prefixed by the chat's number: `c3n12`.
6
7
  * The verbatim source text of a node lives outside the graph (see store.js); `src` is provenance.
7
8
  */
8
9
 
@@ -61,11 +62,6 @@ function nodeTokens(node) {
61
62
  }
62
63
  }
63
64
 
64
- /** True when every provenance entry of `node` comes from `session` (its text is still in that session's context). */
65
- export function onlyFromSession(node, session) {
66
- return Boolean(session) && (node.src ?? []).length > 0 && node.src.every((s) => s.session === session)
67
- }
68
-
69
65
  export function degree(graph, id) {
70
66
  let n = 0
71
67
  for (const [a, b] of graph.edges) if (a === id || b === id) n++
@@ -96,17 +92,15 @@ export function resolveSuperseded(graph, id) {
96
92
  }
97
93
 
98
94
  /**
99
- * Lexical match of a user message against node labels/aliases (weight 2) and gists (weight 1),
100
- * with a small boost for well-connected nodes. Nodes whose every source is the current session are
101
- * skipped while that session has not compacted: their text is still on the surface.
102
- * @returns [{ id, node, score }] best first, at most `max`, only nodes with a strong (label/alias) hit.
95
+ * Lexical match of a user message against one graph: labels/aliases weigh 2, gists 1, plus a small
96
+ * boost for well-connected nodes. Only nodes with a strong (label/alias) hit count.
97
+ * @returns [{ id, node, score, via }] best first, at most `max`.
103
98
  */
104
- export function matchNodes(graph, query, { max = 5, session, sessionCompacted = false } = {}) {
99
+ export function matchNodes(graph, query, { max = 5 } = {}) {
105
100
  const q = tokenize(query)
106
101
  if (q.length === 0) return []
107
102
  const scored = []
108
103
  for (const [rawId, node] of Object.entries(graph.nodes)) {
109
- if (!sessionCompacted && onlyFromSession(node, session)) continue
110
104
  const { strong, weak } = nodeTokens(node)
111
105
  let strongHits = 0
112
106
  let weakHits = 0
@@ -133,32 +127,140 @@ export function surfaceNodes(graph, max = 40) {
133
127
  .map(({ id }) => id)
134
128
  }
135
129
 
136
- function line(id, node) {
137
- const date = (node.updated ?? '').slice(0, 10)
138
- return `- ${id} ${node.label}: ${node.gist}${date ? ` (${date})` : ''}`
130
+ // ---------- time: the first filter when a message names a day ----------
131
+
132
+ const DAY = 86400000
133
+ const dayStart = (d) => { const x = new Date(d); x.setHours(0, 0, 0, 0); return x }
134
+
135
+ /**
136
+ * A from/to range (to exclusive) when the text names a time: yesterday, today, N days ago, last/this
137
+ * week or month, 2026-11-01, 11月1日, 昨天, 上周 ... `undefined` otherwise. No model call.
138
+ */
139
+ export function parseTimeRange(text, now = new Date()) {
140
+ const s = String(text ?? '').toLowerCase()
141
+ const today = dayStart(now)
142
+ const days = (offset, label, span = 1) => ({ from: new Date(+today + offset * DAY), to: new Date(+today + (offset + span) * DAY), label })
143
+ let m
144
+ if ((m = /\b(\d{4})-(\d{2})-(\d{2})\b/.exec(s))) {
145
+ const d = new Date(+m[1], +m[2] - 1, +m[3])
146
+ return { from: d, to: new Date(+d + DAY), label: m[0] }
147
+ }
148
+ if ((m = /(\d{1,2})月(\d{1,2})[日号]/.exec(s))) {
149
+ const d = new Date(now.getFullYear(), +m[1] - 1, +m[2])
150
+ if (d > now) d.setFullYear(d.getFullYear() - 1)
151
+ return { from: d, to: new Date(+d + DAY), label: m[0] }
152
+ }
153
+ if (/day before yesterday|前天/.test(s)) return days(-2, 'the day before yesterday')
154
+ if (/\byesterday\b|昨天|昨日/.test(s)) return days(-1, 'yesterday')
155
+ if (/\btoday\b|this morning|今天|今早|今日/.test(s)) return days(0, 'today')
156
+ if ((m = /\b(\d+) days? ago\b/.exec(s)) || (m = /(\d+)天前/.exec(s))) return days(-Number(m[1]), m[0])
157
+ const monday = new Date(+today - ((today.getDay() + 6) % 7) * DAY)
158
+ if (/\blast week\b|上周|上星期|上个星期/.test(s)) return { from: new Date(+monday - 7 * DAY), to: monday, label: 'last week' }
159
+ if (/\bthis week\b|本周|这周|这星期|这个星期/.test(s)) return { from: monday, to: new Date(+monday + 7 * DAY), label: 'this week' }
160
+ if (/\blast month\b|上个月|上月/.test(s)) {
161
+ return { from: new Date(now.getFullYear(), now.getMonth() - 1, 1), to: new Date(now.getFullYear(), now.getMonth(), 1), label: 'last month' }
162
+ }
163
+ if (/\bthis month\b|本月|这个月/.test(s)) {
164
+ return { from: new Date(now.getFullYear(), now.getMonth(), 1), to: new Date(now.getFullYear(), now.getMonth() + 1, 1), label: 'this month' }
165
+ }
166
+ return undefined
167
+ }
168
+
169
+ const inRange = (iso, range) => Boolean(iso) && new Date(iso) >= range.from && new Date(iso) < range.to
170
+ /** A chat overlaps the range when it was active at any point inside it. */
171
+ export const chatInRange = (meta, range) => Boolean(meta?.startedAt) && new Date(meta.startedAt) < range.to && new Date(meta.lastActiveAt ?? meta.startedAt) >= range.from
172
+
173
+ // ---------- views: one chat's graph seen from another chat ----------
174
+
175
+ /** A view is `{ sid, cid, meta, graph, own }`; `own` is the chat the request belongs to. */
176
+ export const globalId = (view, id) => `c${view.cid}${id}`
177
+
178
+ /**
179
+ * Match across every view except the own chat (its text is still in context). With a time range,
180
+ * try chats active in that range first, then topics updated in it, then everything.
181
+ * @returns { hits: [{ id, node, score, via, view }], slice }
182
+ */
183
+ export function matchAcross(views, query, { max = 5, range } = {}) {
184
+ const others = views.filter((v) => !v.own)
185
+ const run = (vs, keep = () => true) => vs
186
+ .flatMap((view) => matchNodes(view.graph, query, { max }).map((h) => ({ ...h, id: globalId(view, h.id), via: h.via && globalId(view, h.via), view })))
187
+ .filter(keep)
188
+ .sort((a, b) => b.score - a.score)
189
+ .slice(0, max)
190
+ if (range) {
191
+ const byChat = run(others.filter((v) => chatInRange(v.meta, range)))
192
+ if (byChat.length > 0) return { hits: byChat, slice: `${range.label} (by chat)` }
193
+ const byTopic = run(others, (h) => inRange(h.node.updated, range))
194
+ if (byTopic.length > 0) return { hits: byTopic, slice: `${range.label} (by topic)` }
195
+ }
196
+ return { hits: run(others), slice: undefined }
139
197
  }
140
198
 
199
+ const day = (iso) => String(iso ?? '').slice(0, 10)
200
+ const topicLine = (id, node) => `- ${id} ${node.label}: ${node.gist}${node.updated ? ` (${day(node.updated)})` : ''}`
201
+ const chatLine = (view) => `- c${view.cid} ${day(view.meta.lastActiveAt ?? view.meta.startedAt)} ${view.meta.title ?? '(untitled)'} (${Object.keys(view.graph.nodes).length} topics${view.own ? ', this chat' : ''})`
202
+ const newestFirst = (views) => [...views].sort((a, b) => String(b.meta.lastActiveAt ?? '').localeCompare(String(a.meta.lastActiveAt ?? '')))
203
+
141
204
  /** The per-turn block appended to the user's message. `inline` carries one node's verbatim text when it is short. */
142
- export function renderHits(graph, hits, { inline } = {}) {
205
+ export function renderHits(hits, { inline, slice } = {}) {
143
206
  if (hits.length === 0) return ''
144
- const lines = [`[${SOURCE_KIND}] Related past context. Call recall(id) for the verbatim source.`]
145
- for (const { id, node, via } of hits) lines.push(line(id, node) + (via ? ` [replaces ${via}]` : ''))
207
+ const lines = [`[${SOURCE_KIND}] Related past context${slice ? ` from ${slice}` : ''}. Call recall(id) for the verbatim source.`]
208
+ for (const { id, node, via } of hits) lines.push(topicLine(id, node) + (via ? ` [replaces ${via}]` : ''))
146
209
  if (inline) lines.push('', `Verbatim source of ${inline.id}:`, inline.text.trim())
147
210
  return lines.join('\n')
148
211
  }
149
212
 
150
- /** The cross-session surface layer sent once at the start of a session. */
151
- export function renderSurface(graph, ids) {
152
- if (ids.length === 0) return ''
213
+ /** Sent once after memory is switched on: the chats this chat can draw on, newest first. */
214
+ export function renderChats(views, { max = 20 } = {}) {
215
+ const shared = newestFirst(views.filter((v) => !v.own))
216
+ if (shared.length === 0) return ''
153
217
  const lines = [
154
- `[${SOURCE_KIND}] Memory of earlier sessions in this project (${Object.keys(graph.nodes).length} nodes). ` +
155
- 'Each line is one node: id, label, gist. Call recall(id) for the verbatim source and its neighbours. ' +
218
+ `[${SOURCE_KIND}] Memory is on. Earlier chats in this workspace, newest first. ` +
219
+ 'Call recall("c3") for a chat\'s topics, recall("2026-11-01") for everything from a day, recall("c3n12") for one topic\'s exact text. ' +
156
220
  'Treat this as background; do not restate it.'
157
221
  ]
158
- for (const id of ids) lines.push(line(id, graph.nodes[id]))
222
+ for (const view of shared.slice(0, max)) lines.push(chatLine(view))
223
+ if (shared.length > max) lines.push(`- ... ${shared.length - max} older chats; name a day to see them`)
224
+ return lines.join('\n')
225
+ }
226
+
227
+ /** One chat's topics, most connected first. */
228
+ export function renderChatIndex(view, { max = 40 } = {}) {
229
+ const lines = [`# c${view.cid} ${view.meta.title ?? '(untitled)'} (${day(view.meta.startedAt)} → ${day(view.meta.lastActiveAt)})`]
230
+ const ids = surfaceNodes(view.graph, max)
231
+ if (ids.length === 0) lines.push('(no topics indexed yet)')
232
+ for (const id of ids) lines.push(topicLine(globalId(view, id), view.graph.nodes[id]))
233
+ return lines.join('\n')
234
+ }
235
+
236
+ /** Everything that happened in a time range: each chat active then, with its topics from that range first. */
237
+ export function renderRange(views, range, { maxChats = 10, maxTopics = 10 } = {}) {
238
+ const chats = newestFirst(views.filter((v) => chatInRange(v.meta, range)))
239
+ if (chats.length === 0) return `[${SOURCE_KIND}] No chats from ${range.label}.`
240
+ const lines = [`[${SOURCE_KIND}] Chats from ${range.label}:`]
241
+ for (const view of chats.slice(0, maxChats)) {
242
+ lines.push(chatLine(view))
243
+ const ids = Object.keys(view.graph.nodes).sort((a, b) => Number(inRange(view.graph.nodes[b].updated, range)) - Number(inRange(view.graph.nodes[a].updated, range)))
244
+ for (const id of ids.slice(0, maxTopics)) lines.push(' ' + topicLine(globalId(view, id), view.graph.nodes[id]))
245
+ }
246
+ return lines.join('\n')
247
+ }
248
+
249
+ /** The /context-graph map: workspace → chats (newest first) → topics. */
250
+ export function renderMap(views, { maxTopics = 8 } = {}) {
251
+ if (views.length === 0) return 'No chats indexed in this workspace yet. Run /context-graph on in a chat to start.'
252
+ const lines = []
253
+ for (const view of newestFirst(views)) {
254
+ const meta = view.meta
255
+ const flags = [view.own ? 'this chat' : undefined, meta.memory ? 'memory on' : undefined, meta.shared ? 'shared' : 'private'].filter(Boolean).join(', ')
256
+ lines.push(`c${view.cid} ${day(meta.startedAt)} ${meta.title ?? '(untitled)'} · ${Object.keys(view.graph.nodes).length} topics · ${flags}`)
257
+ for (const id of surfaceNodes(view.graph, maxTopics)) lines.push(' ' + topicLine(globalId(view, id), view.graph.nodes[id]))
258
+ }
159
259
  return lines.join('\n')
160
260
  }
161
261
 
262
+ // ---------- builder ----------
263
+
162
264
  /** `[m0 user] ...` transcript the builder reads; each message capped so one huge paste cannot eat the call. */
163
265
  export function transcriptForBuilder(messages, maxChars = 2000) {
164
266
  return messages.map((m, i) => {
@@ -270,6 +372,15 @@ export function mergeDelta(graph, delta, { session, turn, now }) {
270
372
  return touched
271
373
  }
272
374
 
375
+ // ---------- session events ----------
376
+
377
+ const isHuman = (event) => event?.type === 'user/message' && event.data?.source?.kind === 'user'
378
+
379
+ function textOf(content) {
380
+ if (!Array.isArray(content)) return ''
381
+ return content.filter((b) => b?.type === 'text' && typeof b.text === 'string').map((b) => b.text).join('\n').trim()
382
+ }
383
+
273
384
  /**
274
385
  * Pull the human/assistant exchange out of dsh session events in surface order.
275
386
  * @param nodes surface seqs; @param eventAt session lookup; @param afterSeq only events past this seq.
@@ -284,7 +395,7 @@ export function collectSpan(nodes, eventAt, afterSeq = -1) {
284
395
  const event = eventAt(seq)
285
396
  if (!event) continue
286
397
  lastSeq = Math.max(lastSeq, seq)
287
- if (event.type === 'user/message' && event.data?.source?.kind === 'user') {
398
+ if (isHuman(event)) {
288
399
  const text = textOf(event.data.content)
289
400
  if (text) { messages.push({ seq, role: 'user', text }); userTurns++ }
290
401
  } else if (event.type === 'assistant/message') {
@@ -295,56 +406,16 @@ export function collectSpan(nodes, eventAt, afterSeq = -1) {
295
406
  return { messages, lastSeq, userTurns }
296
407
  }
297
408
 
298
- function textOf(content) {
299
- if (!Array.isArray(content)) return ''
300
- return content.filter((b) => b?.type === 'text' && typeof b.text === 'string').map((b) => b.text).join('\n').trim()
301
- }
302
-
303
- // ---------- folding: replace old turns of the current chat with a table of contents ----------
304
-
305
- /** Injected context kinds that must survive a fold (carried into the fold message verbatim). */
306
- export const KEEP_KINDS = ['skill-catalog', 'runtime-context']
307
-
308
- const isHuman = (event) => event?.type === 'user/message' && event.data?.source?.kind === 'user'
309
- export const isFold = (event) => event?.type === 'user/message' && event.data?.source?.kind === SOURCE_KIND && event.data.source.fold === true
310
-
311
- function toolDelta(event) {
312
- if (event?.type === 'assistant/message') return (event.data?.message?.content ?? []).filter((b) => b.type === 'tool-call').length
313
- return event?.type === 'tool/result' ? -1 : 0
314
- }
315
-
316
- /**
317
- * Choose the surface range to fold: everything after the system prompt up to (not including) the
318
- * human prompt that starts the last `keepTurns` turns. Only content already indexed (seq <= maxSeq)
319
- * is folded, and the cut never splits a tool call from its result.
320
- * @returns {{ startSeq, endSeq, shadowedSeqs } | undefined}
321
- */
322
- export function planFold(nodes, eventAt, { keepTurns = 2, maxSeq = Infinity } = {}) {
323
- const first = eventAt(nodes[0])?.type === 'system/message' ? 1 : 0
324
- const humans = []
325
- for (let i = first; i < nodes.length; i++) if (isHuman(eventAt(nodes[i]))) humans.push(i)
326
- for (let h = humans.length - keepTurns; h >= 1; h--) {
327
- const cut = humans[h]
328
- const range = nodes.slice(first, cut)
329
- if (!range.some((seq) => isHuman(eventAt(seq)))) return undefined
330
- if (range.some((seq) => seq > maxSeq && !isFold(eventAt(seq)))) continue
331
- let open = 0
332
- for (const seq of nodes.slice(0, cut)) open += toolDelta(eventAt(seq))
333
- if (open !== 0) continue
334
- return { startSeq: range[0], endSeq: range.at(-1), shadowedSeqs: range }
335
- }
336
- return undefined
337
- }
338
-
339
- /** Every human prompt in the session log up to `endSeq`, numbered t1, t2, ... in log order. */
340
- export function turnIndex(eventAt, endSeq = Infinity) {
341
- const turns = []
342
- for (let seq = 0; seq <= endSeq; seq++) {
409
+ /** First human prompt of the log, shortened: the chat's title until dsh gives us a better one. */
410
+ export function titleOf(eventAt, width = 60) {
411
+ for (let seq = 0; ; seq++) {
343
412
  const event = eventAt(seq)
344
- if (!event) break
345
- if (isHuman(event)) turns.push({ turn: turns.length + 1, seq, text: textOf(event.data.content) })
413
+ if (!event) return undefined
414
+ if (isHuman(event)) {
415
+ const text = textOf(event.data.content).replace(/\s+/g, ' ')
416
+ return text.length > width ? `${text.slice(0, width - 1)}…` : text
417
+ }
346
418
  }
347
- return turns
348
419
  }
349
420
 
350
421
  /** Verbatim text of turn `n` (its prompt through the step before the next human prompt). */
@@ -373,39 +444,3 @@ export function turnTranscript(eventAt, n, { maxToolChars = 2000 } = {}) {
373
444
  }
374
445
  return out.join('\n\n')
375
446
  }
376
-
377
- /** Content blocks the fold message must carry: latest standing context of each KEEP_KINDS kind. */
378
- export function foldKept(shadowedSeqs, eventAt) {
379
- const kept = new Map()
380
- for (const seq of shadowedSeqs) {
381
- const event = eventAt(seq)
382
- if (isFold(event)) {
383
- const kinds = event.data.source.keptKinds ?? []
384
- kinds.forEach((kind, i) => kept.set(kind, event.data.content[i + 1]))
385
- } else if (event?.type === 'user/message' && KEEP_KINDS.includes(event.data?.source?.kind)) {
386
- kept.set(event.data.source.kind, { type: 'text', text: textOf(event.data.content) })
387
- }
388
- }
389
- return { kinds: [...kept.keys()], blocks: [...kept.values()].filter(Boolean) }
390
- }
391
-
392
- /** The table of contents that replaces the folded turns. */
393
- export function renderFoldIndex(graph, session, turns, { maxNodes = 40, maxTurns = 60, width = 90 } = {}) {
394
- const lines = [
395
- `[${SOURCE_KIND}] Turns t1-t${turns.length} of this conversation are folded to save tokens. They are not lost.`,
396
- 'Below is their table of contents. Before answering anything that depends on their details, call recall with a topic id (n12) for the facts, or a turn id (t7) for the exact messages of that turn. Do not guess folded details.'
397
- ]
398
- const ids = surfaceNodes(graph, Infinity).filter((id) => (graph.nodes[id].src ?? []).some((s) => s.session === session)).slice(0, maxNodes)
399
- if (ids.length > 0) {
400
- lines.push('', 'Topics:')
401
- for (const id of ids) lines.push(`- ${id} ${graph.nodes[id].label}: ${graph.nodes[id].gist}`)
402
- }
403
- lines.push('', 'Turns (what the user asked):')
404
- const shown = turns.slice(-maxTurns)
405
- if (shown.length < turns.length) lines.push(`- t1-t${turns.length - shown.length}: earlier turns, recall by id`)
406
- for (const t of shown) {
407
- const first = t.text.replace(/\s+/g, ' ').trim()
408
- lines.push(`- t${t.turn}: ${first.length > width ? `${first.slice(0, width - 1)}…` : first}`)
409
- }
410
- return lines.join('\n')
411
- }