dsh-context-graph 0.4.0 → 0.6.2
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 +199 -93
- package/README.zh.md +37 -16
- package/cordis.patch.yml +4 -1
- package/graph.js +57 -7
- package/index.js +56 -32
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +3 -3
- package/store.js +2 -2
package/README.md
CHANGED
|
@@ -1,91 +1,188 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="icon.svg" width="72" height="72" alt="Context Graph icon">
|
|
3
|
+
</p>
|
|
2
4
|
|
|
3
|
-
|
|
4
|
-
want it. Other chats in the same workspace then get a short pointer to what was decided before, and
|
|
5
|
-
the model fetches the exact original text only when it needs it. Old messages are not re-sent;
|
|
6
|
-
decisions are not lost.
|
|
5
|
+
<h1 align="center">Context Graph for DeepSeek Harness</h1>
|
|
7
6
|
|
|
8
|
-
|
|
9
|
-
|
|
7
|
+
<p align="center">
|
|
8
|
+
Memory for your chats, on from the moment you install it.<br>
|
|
9
|
+
Later chats get a few lines that point at what was decided; the model fetches the exact text only when it needs it.
|
|
10
|
+
</p>
|
|
10
11
|
|
|
11
|
-
|
|
12
|
-
|
|
12
|
+
<p align="center">
|
|
13
|
+
<a href="https://www.npmjs.com/package/dsh-context-graph"><img alt="npm" src="https://img.shields.io/npm/v/dsh-context-graph?label=npm&color=4A65E8"></a>
|
|
14
|
+
<img alt="dsh" src="https://img.shields.io/badge/dsh-0.2.1-7AC2FF">
|
|
15
|
+
<img alt="license" src="https://img.shields.io/badge/license-MIT-lightgrey">
|
|
16
|
+
<a href="README.zh.md"><img alt="中文" src="https://img.shields.io/badge/文档-中文-4A65E8"></a>
|
|
17
|
+
</p>
|
|
13
18
|
|
|
14
|
-
|
|
15
|
-
[claude-context-graph](https://github.com/William20100221/claude-context-graph).
|
|
16
|
-
|
|
17
|
-
## How it works
|
|
19
|
+
---
|
|
18
20
|
|
|
19
|
-
|
|
21
|
+
**The problem.** Every message you send re-sends the whole conversation, and a new chat knows
|
|
22
|
+
nothing about the last one. You re-explain, the model re-reads, and you pay input tokens for both.
|
|
20
23
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
| First message after `on` | One block lists the shared chats of this workspace, newest first: chat id, date, title, topic count. | about 15 tokens per chat |
|
|
25
|
-
| Every human message | Your words are matched against the topics of the other shared chats by word overlap (no model call). Up to 5 hits are appended to the message. One clearly dominant short hit is included verbatim. | under about 150 tokens |
|
|
26
|
-
| Your message names a time | "yesterday", "last week", "11月1日", "2026-11-01" ... that slice is searched first: chats active then, then topics from then, then everything. If nothing matches, the chats from that time are listed instead. | same |
|
|
27
|
-
| Model calls `recall(id)` | `c3n12`: the topic's verbatim source and linked topics. `c3`: a chat's topics. `2026-11-01`: every chat and topic from that day. `t7`: turn 7 of this chat word for word. | one tool round trip |
|
|
28
|
-
| `/context-graph share` | Lets other chats in the workspace see this chat's graph. Nothing is copied or merged; it is a flag on the chat. | none |
|
|
29
|
-
|
|
30
|
-
Design rules, in order:
|
|
31
|
-
|
|
32
|
-
1. **Off until asked.** No surface map, no matches, no indexing in a chat that has not run `on`.
|
|
33
|
-
2. **Nothing is written without its source.** A topic is stored only together with the verbatim
|
|
34
|
-
messages it was drawn from. The gist is a pointer, never the record.
|
|
35
|
-
3. **Organise, never merge.** Each chat's graph stays in its own folder with its own dates. Sharing
|
|
36
|
-
is a flag. Ids carry the chat number (`c3n12`) so every topic traces back to its chat.
|
|
37
|
-
4. **Time is the first filter.** A named day or week narrows the search before anything else.
|
|
38
|
-
5. **Append at the end.** Injected blocks ride at the tail of the newest message so the provider's
|
|
39
|
-
prefix cache survives. Hiding or folding old turns is not this plugin's job.
|
|
40
|
-
|
|
41
|
-
## Commands
|
|
24
|
+
**What this does.** In every chat (memory is on by default), the plugin indexes what was
|
|
25
|
+
decided into a small graph of topics, each stored together with the original messages. Other
|
|
26
|
+
chats in the same workspace get, at most, a few lines like this appended to your message:
|
|
42
27
|
|
|
43
|
-
|
|
28
|
+
```
|
|
29
|
+
[context-graph] Related past context from yesterday (by chat). Call recall(id) for the verbatim source.
|
|
30
|
+
- c3n12 builder timeout: builderMaxTokens raised to 8192 after the 524s (2026-11-01)
|
|
31
|
+
- c3n4 publish flow: npm version patch, npm publish (2FA), git push --follow-tags (2026-11-01)
|
|
32
|
+
```
|
|
44
33
|
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
| `on` / `off` | Start or stop memory for this chat. `off` keeps the graph file. |
|
|
48
|
-
| `share` / `unshare` | Let other chats in the workspace use this chat's graph, or stop. |
|
|
49
|
-
| `stats` (default) | Memory state, topic counts, shared chats, pending turns, token counters. |
|
|
50
|
-
| `build` | Index this chat now. |
|
|
51
|
-
| `map` | Every chat in the workspace, newest first, with its top topics. |
|
|
52
|
-
| `find <words>` | Search the shared chats; time words narrow it. |
|
|
34
|
+
The model calls `recall("c3n12")` when a gist is not precise enough and gets the original turns,
|
|
35
|
+
word for word. Nothing is summarised away, and nothing is sent that you did not ask for.
|
|
53
36
|
|
|
54
|
-
|
|
37
|
+
> **First principle:** save input tokens without losing quality. A few lines per message; exact
|
|
38
|
+
> text on demand.
|
|
39
|
+
>
|
|
40
|
+
> **Turning it off.** Plugins page → Context Graph → switch it off: no chat is indexed or gets
|
|
41
|
+
> anything added. To stop only one chat, run `/context-graph off` in it.
|
|
55
42
|
|
|
56
|
-
##
|
|
43
|
+
## Quick start
|
|
57
44
|
|
|
58
|
-
|
|
59
|
-
|
|
45
|
+
1. **Plugins → Add plugin**, official npm registry, type `dsh-context-graph`, install, then fully
|
|
46
|
+
restart the app (new slash commands need a restart).
|
|
47
|
+
2. Chat as usual. Every chat indexes itself every 4 turns and is shared with the other chats of
|
|
48
|
+
its workspace. Type `/context-graph`, pick it from the menu, then `build` to index one right away.
|
|
49
|
+
3. Open a new chat in the same workspace and ask about something from the first.
|
|
50
|
+
4. To keep one chat out of the others, run `/context-graph unshare` in it.
|
|
60
51
|
|
|
61
|
-
Command line
|
|
52
|
+
Command line instead of the Plugins page (the desktop app uses the `desktop` profile):
|
|
62
53
|
|
|
63
54
|
```sh
|
|
64
55
|
dsh plugin --profile desktop add dsh-context-graph
|
|
65
56
|
```
|
|
66
57
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
Turn the check off with the environment variable `DSH_CONTEXT_GRAPH_NO_UPDATE_CHECK=1`.
|
|
58
|
+
## Commands
|
|
59
|
+
|
|
60
|
+
All commands are `/context-graph <word>`. Type `/context-graph`, pick it from the menu, then type
|
|
61
|
+
the word. Results show in dsh's own command card: a one-line summary that expands to the details.
|
|
62
|
+
No word means `stats`.
|
|
73
63
|
|
|
74
|
-
|
|
64
|
+
### `on` — resume memory for this chat
|
|
75
65
|
|
|
76
|
-
|
|
66
|
+
Memory is already on in every chat. `on` undoes an earlier `off` and indexes the chat right away.
|
|
77
67
|
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
68
|
+
Indexes the chat right away and then again every 4 human turns (one small auxiliary model call
|
|
69
|
+
each time, using the chat's own routed model unless you configure another). Creates
|
|
70
|
+
`.context-graph/chats/<chat>/` with the chat's graph, its verbatim sources and a `meta.json`
|
|
71
|
+
holding its title, dates and flags. From now on every message you send in this chat is matched
|
|
72
|
+
against the other shared chats of the workspace, and the first message of the chat also carries the
|
|
73
|
+
list of those chats, newest first.
|
|
74
|
+
|
|
75
|
+
Card: `Memory on · 7 topics in this chat · 2 shared chats to draw on`
|
|
76
|
+
|
|
77
|
+
### `off` — stop memory for this chat only
|
|
78
|
+
|
|
79
|
+
To stop it in every chat, switch the plugin off on the Plugins page instead.
|
|
80
|
+
|
|
81
|
+
Stops indexing and stops adding anything to your requests. The graph folder stays on disk, so
|
|
82
|
+
`on` later resumes where it left off. Other chats keep seeing this chat if it is shared.
|
|
83
|
+
|
|
84
|
+
### `share` / `unshare` — keep a chat private, or share it again
|
|
85
|
+
|
|
86
|
+
Every chat is shared by default: other chats with memory on can match and recall its topics.
|
|
87
|
+
`unshare` makes this chat private; `share` undoes that. Nothing is copied or merged: the graph stays in its own folder with its own dates, and its
|
|
88
|
+
ids carry the chat number (`c3n12`) so every hit traces back to where it came from. Both take
|
|
89
|
+
effect at once. A chat shared
|
|
90
|
+
before its first index has nothing to offer yet; it fills in every 4 turns or with `build`.
|
|
91
|
+
|
|
92
|
+
Card: `Shared with the workspace · 7 topics`
|
|
93
|
+
|
|
94
|
+
### `stats` — where things stand (default)
|
|
95
|
+
|
|
96
|
+
First line: memory on/off, topics in this chat, shared/private, how many shared chats are
|
|
97
|
+
visible, how many of this chat's turns are waiting to be indexed, and `update available` when a
|
|
98
|
+
newer version is on npm. The body shows the version, the memory folder, and counters since the app
|
|
99
|
+
started: builds and builder tokens, injected blocks and their size, recalls, and the main
|
|
100
|
+
conversation's input split into uncached, cache-read and cache-write with the cache-hit rate. A
|
|
101
|
+
high cache-hit rate is the sign that memory is saving money rather than spending it.
|
|
102
|
+
|
|
103
|
+
Card: `Memory on · 7 topics in this chat · shared · 2 shared chats · 3 turns waiting to be indexed`
|
|
104
|
+
|
|
105
|
+
### `build` — index this chat now
|
|
106
|
+
|
|
107
|
+
Runs the indexing call immediately instead of waiting for the next 4-turn mark. Useful right
|
|
108
|
+
before you switch chats. Needs memory on. If the model's answer cannot be read, the raw output is
|
|
109
|
+
saved to `last-builder-output.txt` in the chat's folder and the card tells you why.
|
|
110
|
+
|
|
111
|
+
Card: `3 topics indexed (2 new) · this chat has 7 topics`
|
|
112
|
+
|
|
113
|
+
### `map` — every chat in the workspace
|
|
114
|
+
|
|
115
|
+
Lists all indexed chats newest first: chat id, start date, title, topic count and flags (`this
|
|
116
|
+
chat`, `memory on`, `shared`/`private`), each followed by its most connected topics with their ids.
|
|
117
|
+
This is the text form of the graph; a visual page is planned.
|
|
118
|
+
|
|
119
|
+
```
|
|
120
|
+
2 chats in C:\Projects\site\.context-graph
|
|
121
|
+
c2 2026-11-02 Fix the login redirect loop · 4 topics · this chat, memory on, private
|
|
122
|
+
- c2n1 redirect loop cause: session cookie set with the wrong path (2026-11-02)
|
|
123
|
+
c1 2026-11-01 Set up CI for the site · 6 topics · memory on, shared
|
|
124
|
+
- c1n3 deploy step: GitHub Pages from the gh-pages branch (2026-11-01)
|
|
83
125
|
```
|
|
84
126
|
|
|
127
|
+
### `find <words>` — search the shared chats
|
|
128
|
+
|
|
129
|
+
The same matcher the plugin runs on your messages, so you can see what the model would be shown.
|
|
130
|
+
Time words narrow it: `find 524 timeout last week` looks in chats active last week first. Only
|
|
131
|
+
shared chats of other conversations are searched; the current chat's own topics are left out
|
|
132
|
+
because they are already in its context.
|
|
133
|
+
|
|
134
|
+
Card: `2 matching topics`, then `c3n12 builder timeout: ...` per line.
|
|
135
|
+
|
|
136
|
+
## How matching and recall work
|
|
137
|
+
|
|
138
|
+
**Matching is lexical and free.** Your message is split into words, identifiers (`clear_conversation`
|
|
139
|
+
also yields `clear` and `conversation`) and Chinese character pairs. Topic labels and aliases count
|
|
140
|
+
double, gists single, well-connected topics get a small boost, and a topic only counts when a label
|
|
141
|
+
or alias word matched. Up to 5 hits are shown; when one hit is clearly ahead and its source is
|
|
142
|
+
short, the source is included verbatim so no `recall` round trip is needed. A changed decision
|
|
143
|
+
links to its replacement with a `supersedes` edge, so a hit on the old one shows the new one.
|
|
144
|
+
|
|
145
|
+
**Time is the first filter.** If your message names a time, the search runs in that slice first and
|
|
146
|
+
widens only if it finds nothing:
|
|
147
|
+
|
|
148
|
+
| You write | Searched first |
|
|
149
|
+
|---|---|
|
|
150
|
+
| `yesterday`, `昨天` | chats active yesterday |
|
|
151
|
+
| `3 days ago`, `3天前` | that day |
|
|
152
|
+
| `last week`, `上周` / `this week`, `本周` | Monday to Monday |
|
|
153
|
+
| `last month`, `上个月` | that calendar month |
|
|
154
|
+
| `2026-11-01`, `11月1日` | that day |
|
|
155
|
+
|
|
156
|
+
If nothing matches in the slice and nothing matches anywhere, the chats from that time are listed
|
|
157
|
+
instead, so "what did we do yesterday?" still gets a useful answer.
|
|
158
|
+
|
|
159
|
+
**Recall ids.** The model (or you, in a message) can ask for:
|
|
160
|
+
|
|
161
|
+
| Id | Returns |
|
|
162
|
+
|---|---|
|
|
163
|
+
| `c3n12` | Topic 12 of chat 3: label, gist, the original messages word for word, and linked topics |
|
|
164
|
+
| `c3` | Chat 3: title, dates, and its topics most connected first |
|
|
165
|
+
| `2026-11-01` | Every shared chat active that day, each with its topics from that day first |
|
|
166
|
+
| `t7` | Turn 7 of the current chat word for word, including tool calls and results |
|
|
167
|
+
|
|
168
|
+
## What it costs
|
|
169
|
+
|
|
170
|
+
| Moment | Added to the request |
|
|
171
|
+
|---|---|
|
|
172
|
+
| Chats without `on` | nothing |
|
|
173
|
+
| First message of a chat | about 15 tokens per shared chat, 20 chats at most |
|
|
174
|
+
| Every later message | nothing when no topic matches; under about 150 tokens when some do |
|
|
175
|
+
| Indexing | one auxiliary call every 4 turns, off the critical path; roughly the new text in, under 1k tokens out |
|
|
176
|
+
| `recall` | one tool round trip with the exact text |
|
|
177
|
+
|
|
178
|
+
Injected blocks are appended to the end of your newest message, never inserted earlier, so the
|
|
179
|
+
provider's prefix cache keeps working. DeepSeek bills cached input at a small fraction of the
|
|
180
|
+
uncached price; protecting that cache matters more than shaving a few lines.
|
|
181
|
+
|
|
85
182
|
## Configuration
|
|
86
183
|
|
|
87
|
-
Defaults live in [cordis.patch.yml](cordis.patch.yml). A patch replaces the row's whole
|
|
88
|
-
|
|
184
|
+
Defaults live in [cordis.patch.yml](cordis.patch.yml). A patch replaces the row's whole `config`,
|
|
185
|
+
so restate every key you keep.
|
|
89
186
|
|
|
90
187
|
| Key | Default | Meaning |
|
|
91
188
|
|---|---|---|
|
|
@@ -94,55 +191,64 @@ Defaults live in [cordis.patch.yml](cordis.patch.yml). A patch replaces the row'
|
|
|
94
191
|
| `buildMinChars` | `400` | ...and at least this much new text |
|
|
95
192
|
| `maxHits` | `5` | Topics shown per human turn |
|
|
96
193
|
| `inlineMaxChars` | `1200` | A single dominant hit this short is shown verbatim |
|
|
97
|
-
| `surfaceMaxChats` | `20` |
|
|
194
|
+
| `surfaceMaxChats` | `20` | Shared chats listed on the first message of each chat |
|
|
98
195
|
| `builderMaxTokens` | `8192` | Output cap for the indexing call; thinking models spend part of it reasoning |
|
|
99
|
-
| `
|
|
196
|
+
| `builderMaxInputChars` | `60000` | Most text one indexing call reads; a long chat indexed for the first time keeps only its newest messages |
|
|
197
|
+
| `rangeMaxChats` | `3` | When a message names a time and no topic matches, at most this many chats from that time are listed |
|
|
198
|
+
| `rangeMaxTopics` | `3` | ...with this many topics each. The list names what it left out; `recall("2026-11-01")` shows the full day |
|
|
199
|
+
| `provider`, `model` | `''` | Empty: reuse the conversation's routed provider and model. Set both to index with a cheaper or faster model |
|
|
100
200
|
|
|
101
|
-
##
|
|
201
|
+
## Updating
|
|
102
202
|
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
graph
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
cordis.patch.yml mounts the plugin at the profile root with default config
|
|
112
|
-
test/ node --test; plugin.test.js needs DSH_NODE_MODULES (see below)
|
|
113
|
-
```
|
|
203
|
+
dsh 0.2.1 desktop builds have no update check for third-party plugins, so the plugin checks npm
|
|
204
|
+
itself once per app start. When a newer version exists, your next chat reply ends with one line
|
|
205
|
+
saying so, and `/context-graph stats` shows it on its first line. To update: Plugins, open
|
|
206
|
+
dsh-context-graph, **Uninstall**, then **Add plugin** `dsh-context-graph@<new version>` and restart.
|
|
207
|
+
Name the exact version: dsh's pnpm holds back very new releases otherwise. Turn the check off with
|
|
208
|
+
`DSH_CONTEXT_GRAPH_NO_UPDATE_CHECK=1`.
|
|
209
|
+
|
|
210
|
+
Remove with `dsh plugin --profile desktop remove dsh-context-graph`.
|
|
114
211
|
|
|
115
|
-
On disk
|
|
212
|
+
## On disk
|
|
116
213
|
|
|
117
214
|
```
|
|
118
|
-
.context-graph/chats/<sessionId>/meta.json cid, title, startedAt, lastActiveAt, turns,
|
|
215
|
+
.context-graph/chats/<sessionId>/meta.json cid, title, startedAt, lastActiveAt, turns, builtSeq (how far the chat is indexed); memoryOff / private only after off / unshare
|
|
119
216
|
.context-graph/chats/<sessionId>/graph.json topics and links; every topic has its time
|
|
120
217
|
.context-graph/chats/<sessionId>/src/<id>.md verbatim messages behind each topic
|
|
121
218
|
```
|
|
122
219
|
|
|
123
|
-
|
|
220
|
+
Delete a chat's folder to forget it. Delete `.context-graph/` to forget the workspace.
|
|
124
221
|
|
|
125
|
-
|
|
222
|
+
## Development
|
|
126
223
|
|
|
127
|
-
```sh
|
|
128
|
-
node --test test/graph.test.js
|
|
129
224
|
```
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
225
|
+
index.js dsh plugin: builder, matcher, recall tool, meter, /context-graph command
|
|
226
|
+
graph.js pure core: tokenize, match, time ranges, merge, render, builder prompt and parser
|
|
227
|
+
store.js chats/<chat>/{meta.json, graph.json, src/<id>.md}
|
|
228
|
+
update.js once-per-start check of npm for a newer version
|
|
229
|
+
lib/client.js dsh chat card for /context-graph (DisclosureRow, en/zh titles)
|
|
230
|
+
icon.svg Plugins page icon in dsh's built-in icon style
|
|
231
|
+
locale/ Plugins page title and description (en, zh); zh links README.zh.md
|
|
232
|
+
cordis.patch.yml mounts the plugin at the profile root with default config
|
|
233
|
+
test/ node --test
|
|
136
234
|
```
|
|
137
235
|
|
|
138
|
-
|
|
236
|
+
Unit tests need nothing: `node --test test/graph.test.js`. The wiring test imports the real dsh
|
|
237
|
+
packages from an existing install: `DSH_NODE_MODULES=/path/to/dsh/node_modules npm test`. Nothing
|
|
238
|
+
here calls a model.
|
|
239
|
+
|
|
240
|
+
Release: `npm test`, `npm version patch`, `npm publish`, `git push --follow-tags`.
|
|
139
241
|
|
|
140
242
|
## Known limits
|
|
141
243
|
|
|
142
|
-
-
|
|
244
|
+
- Not yet verified with a live model; tests run against the published dsh packages.
|
|
245
|
+
- Builds are tracked per process; after a restart the first build of a resumed chat re-reads its
|
|
143
246
|
whole surface. Existing ids are reused, so this costs one larger call, not duplicates.
|
|
144
247
|
- Two agents writing the same chat's graph at once: last writer wins.
|
|
145
248
|
- Subagent sessions are neither indexed nor given memory blocks.
|
|
146
249
|
- Tool outputs are not indexed as topics; `recall("tN")` returns them (each capped at 2000 characters).
|
|
147
250
|
- The chat title is the first message, shortened, until dsh exposes its own titles to plugins.
|
|
148
|
-
- The graph page
|
|
251
|
+
- The visual graph page is not built yet; `map` is the text version.
|
|
252
|
+
|
|
253
|
+
Using Claude Code? The Claude version is a separate plugin built for Claude's app:
|
|
254
|
+
[claude-context-graph](https://github.com/William20100221/claude-context-graph).
|
package/README.zh.md
CHANGED
|
@@ -1,25 +1,27 @@
|
|
|
1
1
|
# 上下文图谱(dsh-context-graph)
|
|
2
2
|
|
|
3
|
-
DeepSeek Harness
|
|
3
|
+
DeepSeek Harness 插件:给每个对话一张小型记忆图谱,安装后默认开启。同一工作区里的其他对话会收到几行指向过往结论的提示,模型需要细节时再取回原文。旧消息不再重复发送,结论也不会丢失。
|
|
4
4
|
|
|
5
|
-
第一原则:在不损失质量的前提下减少输入 token
|
|
5
|
+
第一原则:在不损失质量的前提下减少输入 token。
|
|
6
|
+
|
|
7
|
+
**如何关闭:** 插件页 → 上下文图谱 → 关闭开关,所有对话都不再索引,也不再往请求里加内容。只想停用某个对话,在该对话里运行 `/context-graph off`。
|
|
6
8
|
|
|
7
9
|
## 它做什么
|
|
8
10
|
|
|
9
|
-
|
|
11
|
+
每个对话默认开启记忆:
|
|
10
12
|
|
|
11
13
|
| 时机 | 发生了什么 |
|
|
12
14
|
|---|---|
|
|
13
|
-
|
|
|
14
|
-
|
|
|
15
|
+
| 每个对话 | 每 4 轮人类发言索引一次:一次小型模型调用把主题写进 `.context-graph/chats/<对话>/graph.json`,并原样保存被引用的消息。不会拖慢回复。 |
|
|
16
|
+
| 每个对话的第一条消息 | 附上本工作区已共享的对话列表(最新在前):对话编号、日期、标题、主题数。 |
|
|
15
17
|
| 每条人类消息 | 按词语重合匹配其他已共享对话的主题(不调用模型),把最多 5 个相关主题附在消息末尾。唯一且很短的命中会直接附原文。 |
|
|
16
18
|
| 消息里提到时间 | “昨天”“上周”“11月1日”“2026-11-01”……先搜那个时间段:先按对话,再按主题,最后才搜全部。没有命中时,列出那段时间的对话。 |
|
|
17
19
|
| 模型调用 `recall` | `c3n12`:该主题的原文和相邻主题。`c3`:某个对话的主题列表。`2026-11-01`:那天的全部对话和主题。`t7`:当前对话第 7 轮的原文。 |
|
|
18
|
-
|
|
|
20
|
+
| 共享 | 每个对话默认与同一工作区的其他对话共享。只是一个标记,不复制、不合并。`/context-graph unshare` 让某个对话保持私有。 |
|
|
19
21
|
|
|
20
22
|
设计规则:
|
|
21
23
|
|
|
22
|
-
1.
|
|
24
|
+
1. **默认开启,随时可关。** 插件页关闭本插件即全部停用;`/context-graph off` 只停用当前对话。
|
|
23
25
|
2. **没有原文不写入。** 主题只和它来源的原始消息一起保存。要点是指针,不是记录。
|
|
24
26
|
3. **只组织,不合并。** 每个对话的图谱留在自己的文件夹里,带自己的日期。编号带对话号(`c3n12`),每个主题都能追溯到来源对话。
|
|
25
27
|
4. **时间是第一过滤条件。**
|
|
@@ -29,16 +31,35 @@ DeepSeek Harness 插件:给每个对话一张小型记忆图谱,由你决定
|
|
|
29
31
|
|
|
30
32
|
输入 `/context-graph`,在菜单里选中后再输入后面的词:
|
|
31
33
|
|
|
32
|
-
|
|
34
|
+
结果显示在 dsh 自带的命令卡片里:第一行是摘要,展开看详情。不带词等于 `stats`。
|
|
35
|
+
|
|
36
|
+
**`on` — 恢复本对话的记忆。** 记忆默认已开启;`on` 用于撤销之前的 `off`,并立即索引一次;之后每 4 轮人类发言再索引一次(每次一个小型模型调用,默认用本对话的模型)。在 `.context-graph/chats/<对话>/` 下建立图谱、原文和 `meta.json`(标题、日期、标记)。此后你在本对话发的每条消息都会去匹配工作区里其他已共享的对话;开启后的第一条消息还会附上这些对话的列表。
|
|
37
|
+
卡片:`Memory on · 7 topics in this chat · 2 shared chats to draw on`
|
|
38
|
+
|
|
39
|
+
**`off` — 只关闭本对话的记忆。** 要在所有对话里关闭,请在插件页关闭本插件。 停止索引,不再往请求里加任何内容。图谱文件保留,之后 `on` 可以接着用。若本对话已共享,其他对话仍能看到它。
|
|
40
|
+
|
|
41
|
+
**`share` / `unshare` — 共享或设为私有。** 每个对话默认共享;`unshare` 让本对话私有,`share` 撤销私有。共享只是给本对话打一个标记,其他开了记忆的对话就能匹配和取回它的主题。不复制、不合并:图谱留在自己的文件夹,编号带对话号(`c3n12`),每个命中都能追溯来源。`unshare` 立刻恢复私有。尚未索引的对话可以共享,但在索引之前没有内容。
|
|
42
|
+
|
|
43
|
+
**`stats` — 当前状态(默认)。** 第一行:记忆开/关、本对话主题数、共享/私有、可见的共享对话数、待索引轮数,以及有新版本时的 `update available`。正文:版本、记忆文件夹,以及应用启动以来的计数:索引次数与 token、附加块数量与大小、recall 次数、主对话输入的未缓存/缓存读/缓存写与缓存命中率。命中率高,说明记忆在省钱而不是花钱。
|
|
44
|
+
|
|
45
|
+
**`build` — 立即索引。** 不等下一个 4 轮节点,适合在切换对话前运行。需要记忆已开启。模型输出无法解析时,原始输出保存到该对话文件夹的 `last-builder-output.txt`,卡片说明原因。
|
|
46
|
+
|
|
47
|
+
**`map` — 工作区的全部对话。** 最新在前:对话编号、开始日期、标题、主题数和标记(`this chat`、`memory on`、`shared`/`private`),下面列出各自连接最多的主题及编号。这是图谱的文字版;可视化页面在计划中。
|
|
48
|
+
|
|
49
|
+
**`find 关键词` — 在已共享对话里查找。** 用的就是插件匹配你消息时的同一套规则,可以看到模型会被展示什么。时间词会缩小范围:`find 524 超时 上周` 先搜上周活跃的对话。只搜其他对话,本对话自己的主题已在上下文里,不重复。
|
|
50
|
+
|
|
51
|
+
### 取回编号
|
|
52
|
+
|
|
53
|
+
| 编号 | 返回 |
|
|
33
54
|
|---|---|
|
|
34
|
-
| `
|
|
35
|
-
| `
|
|
36
|
-
| `
|
|
37
|
-
| `
|
|
38
|
-
|
|
39
|
-
|
|
55
|
+
| `c3n12` | 对话 3 的主题 12:名称、要点、原始消息原文、相邻主题 |
|
|
56
|
+
| `c3` | 对话 3:标题、日期、按连接数排序的主题 |
|
|
57
|
+
| `2026-11-01` | 当天活跃的全部共享对话,各自那天的主题在前 |
|
|
58
|
+
| `t7` | 当前对话第 7 轮的原文,含工具调用与结果 |
|
|
59
|
+
|
|
60
|
+
### 时间词
|
|
40
61
|
|
|
41
|
-
|
|
62
|
+
`昨天`/`yesterday`、`前天`、`3天前`、`上周`/`本周`、`上个月`/`本月`、`2026-11-01`、`11月1日`。先搜那段时间活跃的对话,再搜那段时间更新的主题,最后才搜全部;都没有时列出那段时间的对话。
|
|
42
63
|
|
|
43
64
|
## 安装与更新
|
|
44
65
|
|
|
@@ -49,7 +70,7 @@ DeepSeek Harness 插件:给每个对话一张小型记忆图谱,由你决定
|
|
|
49
70
|
## 文件
|
|
50
71
|
|
|
51
72
|
```
|
|
52
|
-
.context-graph/chats/<对话>/meta.json 编号、标题、开始/最近时间、轮数、
|
|
73
|
+
.context-graph/chats/<对话>/meta.json 编号、标题、开始/最近时间、轮数、builtSeq(已索引到哪里);执行 off / unshare 后才有 memoryOff / private
|
|
53
74
|
.context-graph/chats/<对话>/graph.json 主题与链接,每个主题带时间
|
|
54
75
|
.context-graph/chats/<对话>/src/<id>.md 每个主题背后的原始消息
|
|
55
76
|
```
|
package/cordis.patch.yml
CHANGED
|
@@ -9,7 +9,10 @@
|
|
|
9
9
|
buildMinChars: 400 # ...and at least this much new text
|
|
10
10
|
maxHits: 5 # topics shown per human turn
|
|
11
11
|
inlineMaxChars: 1200 # one dominant hit this short is shown verbatim, no recall needed
|
|
12
|
-
surfaceMaxChats: 20 # chats listed
|
|
12
|
+
surfaceMaxChats: 20 # shared chats listed on the first message of each chat
|
|
13
13
|
builderMaxTokens: 8192 # thinking models spend part of this on reasoning
|
|
14
|
+
builderMaxInputChars: 60000 # newest messages the indexing call reads; older ones are skipped
|
|
15
|
+
rangeMaxChats: 3 # a message naming a time with no topic match lists at most this many chats...
|
|
16
|
+
rangeMaxTopics: 3 # ...with this many topics each; recall("YYYY-MM-DD") shows the full day
|
|
14
17
|
provider: '' # empty: reuse the conversation's routed provider/model
|
|
15
18
|
model: ''
|
package/graph.js
CHANGED
|
@@ -180,11 +180,11 @@ export const globalId = (view, id) => `c${view.cid}${id}`
|
|
|
180
180
|
* try chats active in that range first, then topics updated in it, then everything.
|
|
181
181
|
* @returns { hits: [{ id, node, score, via, view }], slice }
|
|
182
182
|
*/
|
|
183
|
-
export function matchAcross(views, query, { max = 5, range } = {}) {
|
|
183
|
+
export function matchAcross(views, query, { max = 5, range, skip } = {}) {
|
|
184
184
|
const others = views.filter((v) => !v.own)
|
|
185
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)
|
|
186
|
+
.flatMap((view) => matchNodes(view.graph, query, { max: max + (skip?.size ?? 0) }).map((h) => ({ ...h, id: globalId(view, h.id), via: h.via && globalId(view, h.via), view })))
|
|
187
|
+
.filter((h) => keep(h) && !skip?.has(h.id))
|
|
188
188
|
.sort((a, b) => b.score - a.score)
|
|
189
189
|
.slice(0, max)
|
|
190
190
|
if (range) {
|
|
@@ -196,7 +196,12 @@ export function matchAcross(views, query, { max = 5, range } = {}) {
|
|
|
196
196
|
return { hits: run(others), slice: undefined }
|
|
197
197
|
}
|
|
198
198
|
|
|
199
|
-
|
|
199
|
+
/** Local calendar day (YYYY-MM-DD) of a timestamp, the same day recall("YYYY-MM-DD") and "today" search. */
|
|
200
|
+
export function day(iso) {
|
|
201
|
+
const d = new Date(iso ?? NaN)
|
|
202
|
+
if (Number.isNaN(+d)) return ''
|
|
203
|
+
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
|
|
204
|
+
}
|
|
200
205
|
const topicLine = (id, node) => `- ${id} ${node.label}: ${node.gist}${node.updated ? ` (${day(node.updated)})` : ''}`
|
|
201
206
|
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
207
|
const newestFirst = (views) => [...views].sort((a, b) => String(b.meta.lastActiveAt ?? '').localeCompare(String(a.meta.lastActiveAt ?? '')))
|
|
@@ -233,7 +238,10 @@ export function renderChatIndex(view, { max = 40 } = {}) {
|
|
|
233
238
|
return lines.join('\n')
|
|
234
239
|
}
|
|
235
240
|
|
|
236
|
-
/**
|
|
241
|
+
/**
|
|
242
|
+
* Everything that happened in a time range: each chat active then, with its topics from that range
|
|
243
|
+
* first. Whatever the caps cut is named, with the recall id that shows it, so nothing is hidden.
|
|
244
|
+
*/
|
|
237
245
|
export function renderRange(views, range, { maxChats = 10, maxTopics = 10 } = {}) {
|
|
238
246
|
const chats = newestFirst(views.filter((v) => chatInRange(v.meta, range)))
|
|
239
247
|
if (chats.length === 0) return `[${SOURCE_KIND}] No chats from ${range.label}.`
|
|
@@ -242,17 +250,28 @@ export function renderRange(views, range, { maxChats = 10, maxTopics = 10 } = {}
|
|
|
242
250
|
lines.push(chatLine(view))
|
|
243
251
|
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
252
|
for (const id of ids.slice(0, maxTopics)) lines.push(' ' + topicLine(globalId(view, id), view.graph.nodes[id]))
|
|
253
|
+
if (ids.length > maxTopics) lines.push(` - ... ${ids.length - maxTopics} more topics: recall("c${view.cid}")`)
|
|
254
|
+
}
|
|
255
|
+
if (chats.length > maxChats) {
|
|
256
|
+
const rest = chats.slice(maxChats).map((v) => `c${v.cid}`)
|
|
257
|
+
lines.push(`- ... ${rest.length} more chats (${rest.slice(0, 10).join(', ')}${rest.length > 10 ? ', ...' : ''}): recall a chat id or a day (YYYY-MM-DD)`)
|
|
245
258
|
}
|
|
246
259
|
return lines.join('\n')
|
|
247
260
|
}
|
|
248
261
|
|
|
262
|
+
/** Memory is on in every chat unless `/context-graph off` was run there; the Plugins page switch turns the whole plugin off. */
|
|
263
|
+
export const memoryOn = (meta) => meta?.memoryOff !== true
|
|
264
|
+
|
|
265
|
+
/** Chats are shared with the rest of the workspace unless `/context-graph unshare` was run there. */
|
|
266
|
+
export const sharedOn = (meta) => meta?.private !== true
|
|
267
|
+
|
|
249
268
|
/** The /context-graph map: workspace → chats (newest first) → topics. */
|
|
250
269
|
export function renderMap(views, { maxTopics = 8 } = {}) {
|
|
251
|
-
if (views.length === 0) return 'No chats indexed in this workspace yet.
|
|
270
|
+
if (views.length === 0) return 'No chats indexed in this workspace yet. Chats index themselves every few turns; /context-graph build indexes this one now.'
|
|
252
271
|
const lines = []
|
|
253
272
|
for (const view of newestFirst(views)) {
|
|
254
273
|
const meta = view.meta
|
|
255
|
-
const flags = [view.own ? 'this chat' : undefined, meta
|
|
274
|
+
const flags = [view.own ? 'this chat' : undefined, memoryOn(meta) ? 'memory on' : 'memory off', sharedOn(meta) ? 'shared' : 'private'].filter(Boolean).join(', ')
|
|
256
275
|
lines.push(`c${view.cid} ${day(meta.startedAt)} ${meta.title ?? '(untitled)'} · ${Object.keys(view.graph.nodes).length} topics · ${flags}`)
|
|
257
276
|
for (const id of surfaceNodes(view.graph, maxTopics)) lines.push(' ' + topicLine(globalId(view, id), view.graph.nodes[id]))
|
|
258
277
|
}
|
|
@@ -406,6 +425,37 @@ export function collectSpan(nodes, eventAt, afterSeq = -1) {
|
|
|
406
425
|
return { messages, lastSeq, userTurns }
|
|
407
426
|
}
|
|
408
427
|
|
|
428
|
+
/**
|
|
429
|
+
* What this chat has already been sent by the plugin and still holds in context: topic ids
|
|
430
|
+
* (c3n12) and whole block texts. Read from the surface, so after compaction drops a block its
|
|
431
|
+
* topics can be sent again.
|
|
432
|
+
*/
|
|
433
|
+
export function shownContext(nodes, eventAt) {
|
|
434
|
+
const ids = new Set()
|
|
435
|
+
const texts = new Set()
|
|
436
|
+
for (const seq of nodes) {
|
|
437
|
+
const event = eventAt(seq)
|
|
438
|
+
if (event?.type !== 'user/message' || event.data?.source?.kind !== SOURCE_KIND) continue
|
|
439
|
+
const text = textOf(event.data.content)
|
|
440
|
+
texts.add(text)
|
|
441
|
+
for (const m of text.matchAll(/\bc\d+n\d+\b/g)) ids.add(m[0])
|
|
442
|
+
}
|
|
443
|
+
return { ids, texts }
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/** The newest messages whose builder transcript fits in `maxChars` (each message counts at most `perMessage`). */
|
|
447
|
+
export function tailWithin(messages, maxChars, perMessage = 2000) {
|
|
448
|
+
let used = 0
|
|
449
|
+
let start = messages.length
|
|
450
|
+
while (start > 0) {
|
|
451
|
+
const cost = Math.min(messages[start - 1].text.length, perMessage) + 20
|
|
452
|
+
if (start < messages.length && used + cost > maxChars) break
|
|
453
|
+
used += cost
|
|
454
|
+
start--
|
|
455
|
+
}
|
|
456
|
+
return messages.slice(start)
|
|
457
|
+
}
|
|
458
|
+
|
|
409
459
|
/** First human prompt of the log, shortened: the chat's title until dsh gives us a better one. */
|
|
410
460
|
export function titleOf(eventAt, width = 60) {
|
|
411
461
|
for (let seq = 0; ; seq++) {
|
package/index.js
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* dsh-context-graph: memory of past chats as small per-chat graphs
|
|
2
|
+
* dsh-context-graph: memory of past chats as small per-chat graphs.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
4
|
+
* On in every chat by default. `/context-graph off` stops one chat; switching the plugin off on
|
|
5
|
+
* dsh's Plugins page stops all of them. While on:
|
|
5
6
|
* - `agent/turn-stopping`: every few human turns, one auxiliary model call indexes the new span
|
|
6
7
|
* into `<workspace>/.context-graph/chats/<session>/graph.json` and stores the cited text verbatim.
|
|
7
|
-
* - `agent/pre-step`: on a human turn, match the prompt against the other shared chats of this
|
|
8
|
+
* - `agent/pre-step`: on a human turn, match the prompt against the other shared chats (all chats unless unshared) of this
|
|
8
9
|
* workspace (a named day is searched first) and append one short `[context-graph]` block at the
|
|
9
|
-
* end of the request, so the provider's prefix cache survives.
|
|
10
|
+
* end of the request, so the provider's prefix cache survives. On a chat's first message, one block lists
|
|
10
11
|
* the shared chats, newest first.
|
|
11
12
|
* - Tool `recall`: a topic (c3n12), a chat (c3), a day (2026-11-01) or a turn of this chat (t7).
|
|
12
13
|
* - `llm/stream`: meters main vs builder tokens and cache reads for `/context-graph stats`.
|
|
@@ -21,8 +22,8 @@ import { BlockAssembler, createUserMessage } from '@deepseek-ai/dsh-llm'
|
|
|
21
22
|
import { defineTool } from '@deepseek-ai/dsh-tools'
|
|
22
23
|
|
|
23
24
|
import {
|
|
24
|
-
builderInstruction, collectSpan, estimateTokens, matchAcross, mergeDelta, neighbors, parseBuilderOutput, parseTimeRange,
|
|
25
|
-
renderChatIndex, renderChats, renderHits, renderMap, renderRange, SOURCE_KIND, titleOf, transcriptForBuilder, turnTranscript
|
|
25
|
+
builderInstruction, collectSpan, estimateTokens, matchAcross, memoryOn, mergeDelta, sharedOn, neighbors, parseBuilderOutput, parseTimeRange,
|
|
26
|
+
renderChatIndex, renderChats, renderHits, renderMap, renderRange, shownContext, SOURCE_KIND, tailWithin, titleOf, transcriptForBuilder, turnTranscript
|
|
26
27
|
} from './graph.js'
|
|
27
28
|
import { appendSource, chatDir, ensureMeta, listChats, loadGraph, loadMeta, readSource, saveGraph, saveMeta } from './store.js'
|
|
28
29
|
import { startUpdateCheck } from './update.js'
|
|
@@ -42,6 +43,9 @@ const DEFAULTS = {
|
|
|
42
43
|
inlineMaxChars: 1200,
|
|
43
44
|
surfaceMaxChats: 20,
|
|
44
45
|
builderMaxTokens: 8192,
|
|
46
|
+
builderMaxInputChars: 60000,
|
|
47
|
+
rangeMaxChats: 3,
|
|
48
|
+
rangeMaxTopics: 3,
|
|
45
49
|
provider: '',
|
|
46
50
|
model: ''
|
|
47
51
|
}
|
|
@@ -66,7 +70,8 @@ export function apply(ctx, config = {}) {
|
|
|
66
70
|
|
|
67
71
|
const state = (sid) => {
|
|
68
72
|
let st = sessions.get(sid)
|
|
69
|
-
|
|
73
|
+
// retryAt: after a failed build, wait for this many new human turns before trying again (#3).
|
|
74
|
+
if (!st) { st = { building: false, announce: true, retryAt: 0 }; sessions.set(sid, st) }
|
|
70
75
|
return st
|
|
71
76
|
}
|
|
72
77
|
|
|
@@ -97,7 +102,7 @@ export function apply(ctx, config = {}) {
|
|
|
97
102
|
const views = []
|
|
98
103
|
for (const { sid: other, meta } of await listChats(dir)) {
|
|
99
104
|
const own = other === sid
|
|
100
|
-
if (!own && !meta
|
|
105
|
+
if (!own && !sharedOn(meta)) continue
|
|
101
106
|
views.push({ sid: other, cid: meta.cid, meta, own, graph: await loadGraph(chatDir(dir, other)) })
|
|
102
107
|
}
|
|
103
108
|
return views
|
|
@@ -120,22 +125,33 @@ export function apply(ctx, config = {}) {
|
|
|
120
125
|
// ponytail: subagent chatter stays out of the graph; revisit if delegated work holds decisions worth keeping.
|
|
121
126
|
if (isSubagent(agent)) return { status: 'skipped', reason: 'subagent session' }
|
|
122
127
|
st.building = true
|
|
128
|
+
let span
|
|
129
|
+
const failed = (reason) => {
|
|
130
|
+
if (span) st.retryAt = span.userTurns + cfg.buildEveryTurns
|
|
131
|
+
return { status: 'failed', reason }
|
|
132
|
+
}
|
|
123
133
|
try {
|
|
124
|
-
|
|
125
|
-
if (!meta
|
|
126
|
-
|
|
134
|
+
let meta = await metaFor(agent)
|
|
135
|
+
if (!memoryOn(meta)) return { status: 'off', reason: 'memory is off for this chat; /context-graph on resumes it' }
|
|
136
|
+
// A chat that never ran a command has no folder yet; give it one so it gets a chat number (#1).
|
|
137
|
+
if (!meta) meta = await setFlags(agent, {})
|
|
138
|
+
// The index position is kept in meta.json so an app restart does not index the chat again (#2).
|
|
139
|
+
span = collectSpan(session.surface.nodes, (seq) => session.eventAt(seq), meta.builtSeq ?? -1)
|
|
127
140
|
const chars = span.messages.reduce((n, m) => n + m.text.length, 0)
|
|
128
141
|
if (span.messages.length === 0) return { status: 'nothing', reason: 'no new messages since the last build' }
|
|
129
|
-
|
|
130
|
-
|
|
142
|
+
const needTurns = Math.max(cfg.buildEveryTurns, st.retryAt)
|
|
143
|
+
if (!force && (span.userTurns < needTurns || chars < cfg.buildMinChars)) {
|
|
144
|
+
return { status: 'skipped', reason: `${span.userTurns}/${needTurns} human turns, ${chars}/${cfg.buildMinChars} chars` }
|
|
131
145
|
}
|
|
146
|
+
// A long chat indexed for the first time keeps the call small: only its newest messages are read (#4).
|
|
147
|
+
const messages = tailWithin(span.messages, cfg.builderMaxInputChars)
|
|
132
148
|
const llm = ctx.get('llm')
|
|
133
149
|
if (!llm) return { status: 'unavailable', reason: 'no llm service in this composition' }
|
|
134
150
|
const target = resolveTarget(agent)
|
|
135
151
|
if (!target) return { status: 'unavailable', reason: 'no provider/model routed yet' }
|
|
136
152
|
const chat = chatDir(dirFor(agent), sid)
|
|
137
153
|
const graph = await loadGraph(chat)
|
|
138
|
-
const prompt = `${transcriptForBuilder(
|
|
154
|
+
const prompt = `${transcriptForBuilder(messages)}\n\n${builderInstruction(graph)}`
|
|
139
155
|
const assembler = new BlockAssembler()
|
|
140
156
|
for await (const chunk of llm.stream({
|
|
141
157
|
provider: target.provider,
|
|
@@ -159,24 +175,26 @@ export function apply(ctx, config = {}) {
|
|
|
159
175
|
const why = finish?.kind === 'max-tokens'
|
|
160
176
|
? `the model ran out of output tokens (builderMaxTokens ${cfg.builderMaxTokens}) before finishing`
|
|
161
177
|
: 'builder output was not the expected JSON'
|
|
162
|
-
return
|
|
178
|
+
return failed(`${why}; raw output saved to ${saved}`)
|
|
163
179
|
}
|
|
164
180
|
// Reversibility rule: a node is written only when it cites text we can store verbatim.
|
|
165
|
-
delta.nodes = delta.nodes.filter((n) => n.msgs.some((i) =>
|
|
181
|
+
delta.nodes = delta.nodes.filter((n) => n.msgs.some((i) => messages[i]))
|
|
166
182
|
const now = new Date().toISOString()
|
|
167
183
|
const touched = mergeDelta(graph, delta, { session: sid, turn, now })
|
|
168
184
|
for (const { id, msgs } of touched) {
|
|
169
|
-
const cited = msgs.map((i) =>
|
|
185
|
+
const cited = msgs.map((i) => messages[i]).filter(Boolean)
|
|
170
186
|
if (cited.length > 0) await appendSource(chat, id, { session: sid, turn, at: now, messages: cited })
|
|
171
187
|
}
|
|
172
188
|
await saveGraph(chat, graph)
|
|
173
|
-
|
|
174
|
-
|
|
189
|
+
// Re-read: a share/off command may have changed the flags while the model was answering.
|
|
190
|
+
const latest = (await metaFor(agent)) ?? meta
|
|
191
|
+
await saveMeta(dirFor(agent), sid, { ...latest, title: latest.title ?? titleOf((seq) => session.eventAt(seq)), lastActiveAt: now, turns: (latest.turns ?? 0) + span.userTurns, builtSeq: span.lastSeq })
|
|
192
|
+
st.retryAt = 0
|
|
175
193
|
meter.builds++
|
|
176
194
|
return { status: 'built', nodes: touched.length, newNodes: touched.filter((t) => t.isNew).length, totalNodes: Object.keys(graph.nodes).length, edges: graph.edges.length, dir: chat }
|
|
177
195
|
} catch (error) {
|
|
178
196
|
console.error('context-graph: build failed (non-fatal)', error)
|
|
179
|
-
return
|
|
197
|
+
return failed(String(error?.message ?? error))
|
|
180
198
|
} finally {
|
|
181
199
|
st.building = false
|
|
182
200
|
}
|
|
@@ -212,7 +230,7 @@ export function apply(ctx, config = {}) {
|
|
|
212
230
|
async function addMemory(agent, prompt, decision) {
|
|
213
231
|
try {
|
|
214
232
|
if (isSubagent(agent) || !prompt) return decision
|
|
215
|
-
if (!(await metaFor(agent))
|
|
233
|
+
if (!memoryOn(await metaFor(agent))) return decision
|
|
216
234
|
const st = state(sidOf(agent))
|
|
217
235
|
const views = await loadViews(agent)
|
|
218
236
|
const parts = []
|
|
@@ -223,9 +241,15 @@ export function apply(ctx, config = {}) {
|
|
|
223
241
|
if (list) { parts.push(list); layer = 'surface' }
|
|
224
242
|
}
|
|
225
243
|
const range = parseTimeRange(prompt)
|
|
226
|
-
|
|
244
|
+
// Topics already sent in this chat are still in its context; do not send them again (#5).
|
|
245
|
+
const shown = shownContext(agent.session.surface.nodes, (seq) => agent.session.eventAt(seq))
|
|
246
|
+
const { hits, slice } = matchAcross(views, prompt, { max: cfg.maxHits, range, skip: shown.ids })
|
|
227
247
|
if (hits.length === 0 && range) {
|
|
228
|
-
|
|
248
|
+
// Sent with every message that names a time, so kept small; recall("YYYY-MM-DD") gives the full day.
|
|
249
|
+
const block = renderRange(views.filter((v) => !v.own), range, { maxChats: cfg.rangeMaxChats, maxTopics: cfg.rangeMaxTopics })
|
|
250
|
+
const ids = block.match(/\bc\d+n\d+\b/g) ?? []
|
|
251
|
+
const seen = shown.texts.has(block) || (ids.length > 0 && ids.every((id) => shown.ids.has(id)))
|
|
252
|
+
if (!seen) parts.push(block)
|
|
229
253
|
} else {
|
|
230
254
|
let inline
|
|
231
255
|
if (hits.length === 1 || (hits.length > 1 && hits[0].score >= 2 * hits[1].score)) {
|
|
@@ -308,7 +332,7 @@ export function apply(ctx, config = {}) {
|
|
|
308
332
|
const m = /^(?:c(\d+))?(n\d+)?$/.exec(id)
|
|
309
333
|
if (!m || (!m[1] && !m[2])) return { status: 'unknown', text: `"${id}" is not an id. Use c3n12, c3, 2026-11-01 or t7, and only ids you were shown.` }
|
|
310
334
|
const view = m[1] ? views.find((v) => String(v.cid) === m[1]) : views.find((v) => v.own)
|
|
311
|
-
if (!view) return { status: 'unknown', text: `No chat c${m[1]} shared in this workspace.` }
|
|
335
|
+
if (!view) return { status: 'unknown', text: m[1] ? `No chat c${m[1]} shared in this workspace.` : 'This chat has no indexed topics yet. Use a full id such as c3n12 from a [context-graph] block.' }
|
|
312
336
|
if (!m[2]) return ok(renderChatIndex(view))
|
|
313
337
|
const node = view.graph.nodes[m[2]]
|
|
314
338
|
if (!node) return { status: 'unknown', text: `No topic ${id}. Only use ids shown in a [context-graph] block.` }
|
|
@@ -348,21 +372,21 @@ export function apply(ctx, config = {}) {
|
|
|
348
372
|
const agent = invocation.agent
|
|
349
373
|
const sid = sidOf(agent)
|
|
350
374
|
if (sub === 'on') {
|
|
351
|
-
await setFlags(agent, {
|
|
375
|
+
await setFlags(agent, { memoryOff: false })
|
|
352
376
|
state(sid).announce = true
|
|
353
377
|
const result = await agent.runMaintenance(() => build(agent, { force: true }))
|
|
354
378
|
const shared = (await loadViews(agent)).filter((v) => !v.own).length
|
|
355
379
|
const indexed = result.status === 'built' ? `${result.totalNodes} topics in this chat` : `nothing indexed yet (${result.reason ?? result.status})`
|
|
356
|
-
return { kind: 'success', text: `Memory on · ${indexed} · ${shared} shared ${shared === 1 ? 'chat' : 'chats'} to draw on\nThis chat indexes itself every ${cfg.buildEveryTurns} turns. /context-graph
|
|
380
|
+
return { kind: 'success', text: `Memory on · ${indexed} · ${shared} shared ${shared === 1 ? 'chat' : 'chats'} to draw on\nThis chat indexes itself every ${cfg.buildEveryTurns} turns and other chats in this workspace can use it. /context-graph unshare keeps it private; /context-graph off stops it.` }
|
|
357
381
|
}
|
|
358
382
|
if (sub === 'off') {
|
|
359
|
-
await setFlags(agent, {
|
|
360
|
-
return { kind: 'success', text: 'Memory off · nothing is added to requests\nThe graph
|
|
383
|
+
await setFlags(agent, { memoryOff: true })
|
|
384
|
+
return { kind: 'success', text: 'Memory off for this chat · nothing is added to its requests\nThe graph stays; /context-graph on resumes. To turn memory off in every chat, switch dsh-context-graph off on the Plugins page.' }
|
|
361
385
|
}
|
|
362
386
|
if (sub === 'share' || sub === 'unshare') {
|
|
363
|
-
const meta = await setFlags(agent, {
|
|
387
|
+
const meta = await setFlags(agent, { private: sub === 'unshare' })
|
|
364
388
|
const topics = Object.keys((await loadGraph(chatDir(dirFor(agent), sid))).nodes).length
|
|
365
|
-
const hint = meta
|
|
389
|
+
const hint = memoryOn(meta) ? '' : '\nMemory is off for this chat, so it has nothing new to share until /context-graph on.'
|
|
366
390
|
return { kind: 'success', text: sub === 'share' ? `Shared with the workspace · ${topics} topics\nOther chats with memory on can now match and recall this chat.${hint}` : `No longer shared · ${topics} topics stay private to this chat` }
|
|
367
391
|
}
|
|
368
392
|
if (sub === 'build') {
|
|
@@ -388,12 +412,12 @@ export function apply(ctx, config = {}) {
|
|
|
388
412
|
const cached = m.cacheRead + m.cacheWrite
|
|
389
413
|
const hitRate = m.input + cached > 0 ? Math.round((m.cacheRead / (m.input + cached)) * 100) : 0
|
|
390
414
|
const session = agent.session
|
|
391
|
-
const pending = collectSpan(session.surface.nodes, (seq) => session.eventAt(seq),
|
|
415
|
+
const pending = collectSpan(session.surface.nodes, (seq) => session.eventAt(seq), own?.meta.builtSeq ?? -1).userTurns
|
|
392
416
|
const shared = views.filter((v) => !v.own).length
|
|
393
417
|
return {
|
|
394
418
|
kind: 'success',
|
|
395
419
|
text: [
|
|
396
|
-
`Memory ${own?.meta
|
|
420
|
+
`Memory ${memoryOn(own?.meta) ? 'on' : 'off'} · ${Object.keys(own?.graph.nodes ?? {}).length} topics in this chat · ${sharedOn(own?.meta) ? 'shared' : 'private'} · ${shared} shared ${shared === 1 ? 'chat' : 'chats'} · ${pending} turns waiting to be indexed${updates.current() ? ' · update available' : ''}`,
|
|
397
421
|
`Version ${version}: ${updates.current() ?? 'no newer version found'}`,
|
|
398
422
|
`Graph folder: ${dirFor(agent)}`,
|
|
399
423
|
'Counters below are since the app started:',
|
package/locale/en.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"meta": {
|
|
3
3
|
"title": "Context Graph",
|
|
4
|
-
"description": "
|
|
4
|
+
"description": "Memory for every chat, on by default; switch this plugin off here to stop it everywhere, or run /context-graph off in one chat. Other chats in the workspace recall exact past text by topic, chat or day instead of re-sending it, so fewer input tokens go out."
|
|
5
5
|
}
|
|
6
6
|
}
|
package/locale/zh.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"meta": {
|
|
3
3
|
"title": "上下文图谱",
|
|
4
|
-
"description": "
|
|
4
|
+
"description": "每个对话默认开启记忆;在这里关闭本插件即可全部停用,或在某个对话里运行 /context-graph off 只停用该对话。工作区里的其他对话可按主题、对话或日期取回过往原文,而不是把旧消息重复发送,从而减少输入 token。",
|
|
5
5
|
"detail": "README.zh.md"
|
|
6
6
|
}
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-context-graph",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "DeepSeek Harness plugin:
|
|
3
|
+
"version": "0.6.2",
|
|
4
|
+
"description": "DeepSeek Harness plugin: memory graphs for every chat, on by default (switch the plugin off on the Plugins page to stop); other chats in the workspace recall exact past text by topic, chat or day, so fewer input tokens are re-sent",
|
|
5
5
|
"icon": "./icon.svg",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"main": "index.js",
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
"LICENSE"
|
|
27
27
|
],
|
|
28
28
|
"scripts": {
|
|
29
|
-
"test": "node --import ./test/resolve-dsh.mjs --test test/graph.test.js test/update.test.js test/client.test.js test/plugin.test.js"
|
|
29
|
+
"test": "node --import ./test/resolve-dsh.mjs --test test/graph.test.js test/update.test.js test/client.test.js test/plugin.test.js test/review.test.js"
|
|
30
30
|
},
|
|
31
31
|
"keywords": [
|
|
32
32
|
"dsh-plugin",
|
package/store.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* On-disk layout under `<dir>` (default `<workspace>/.context-graph`), one folder per chat:
|
|
3
|
-
* chats/<sessionId>/meta.json { cid, title, workspace, startedAt, lastActiveAt, turns,
|
|
3
|
+
* chats/<sessionId>/meta.json { cid, title, workspace, startedAt, lastActiveAt, turns, memoryOff?, private? }
|
|
4
4
|
* chats/<sessionId>/graph.json the chat's graph (see graph.js)
|
|
5
5
|
* chats/<sessionId>/src/<id>.md verbatim source text of one node, one section appended per build
|
|
6
6
|
* Nothing is merged or copied between chats; the list of chats is the list of folders.
|
|
@@ -59,7 +59,7 @@ export async function ensureMeta(dir, sid, { title, workspace, now }) {
|
|
|
59
59
|
const existing = await loadMeta(dir, sid)
|
|
60
60
|
if (existing) return existing
|
|
61
61
|
const cid = (await listChats(dir)).reduce((max, c) => Math.max(max, c.meta.cid ?? 0), 0) + 1
|
|
62
|
-
const meta = { cid, title, workspace, startedAt: now, lastActiveAt: now, turns: 0
|
|
62
|
+
const meta = { cid, title, workspace, startedAt: now, lastActiveAt: now, turns: 0 }
|
|
63
63
|
await saveMeta(dir, sid, meta)
|
|
64
64
|
return meta
|
|
65
65
|
}
|