dsh-solution-ledger 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/search.js ADDED
@@ -0,0 +1,206 @@
1
+ /**
2
+ * Relevance scoring over the ledger. There is no index and no embedding model:
3
+ * a few hundred entries are scanned in memory, so the scorer is the whole
4
+ * retrieval strategy and its weights are the design.
5
+ *
6
+ * The ordering of weights matters more than their exact values: a machine-
7
+ * matchable `signal` (an error code, a command name) beats a tag, a tag beats
8
+ * the title, and the title beats free body text. Semantic guesses are the
9
+ * weakest signal we have, so they score last.
10
+ */
11
+
12
+ /** Bound on how many surface tokens one query may contribute. */
13
+ const MAX_QUERY_TOKENS = 64
14
+
15
+ /**
16
+ * Split text into comparable tokens: Latin/digit runs stay whole, and CJK
17
+ * runs become character bigrams because there are no spaces to split on.
18
+ * @param text - any text.
19
+ * @returns the token set, possibly empty.
20
+ */
21
+ export function tokenize(text) {
22
+ const tokens = new Set()
23
+ const source = String(text ?? '').toLowerCase()
24
+ if (source.length === 0) return tokens
25
+ for (const match of source.matchAll(/[a-z0-9][a-z0-9_.\-\\/]{1,}/g)) {
26
+ const word = match[0]
27
+ tokens.add(word)
28
+ // A compound such as `sandbox-local` must also match a plain `sandbox`:
29
+ // keeping only the joined form misses the prefix a user actually types, and
30
+ // that showed up as a valid query returning nothing.
31
+ if (/[_.\-\\/]/.test(word)) {
32
+ for (const part of word.split(/[_.\-\\/]+/)) {
33
+ if (part.length >= 2) tokens.add(part)
34
+ }
35
+ }
36
+ if (tokens.size >= MAX_QUERY_TOKENS) return tokens
37
+ }
38
+ const cjk = source.replace(/[^\u4e00-\u9fff]+/g, ' ')
39
+ for (const segment of cjk.split(/\s+/)) {
40
+ for (let i = 0; i + 2 <= segment.length; i += 1) {
41
+ tokens.add(segment.slice(i, i + 2))
42
+ if (tokens.size >= MAX_QUERY_TOKENS) return tokens
43
+ }
44
+ }
45
+ return tokens
46
+ }
47
+
48
+ /**
49
+ * Score one entry against one query. Weights are documented inline because
50
+ * tuning them is the expected maintenance task here.
51
+ *
52
+ * The return separates two things a single number conflates: `matched` records
53
+ * whether the entry matched anything the query actually asked for, while
54
+ * `score` also folds in ranking adjustments (status, platform, scope). Without
55
+ * that split, a confirmed entry on the same platform scores +4 against any
56
+ * query whatsoever and would be returned as a "result".
57
+ * @param entry - a normalized ledger entry.
58
+ * @param query - the normalized query (see `searchEntries`).
59
+ * @returns `{ score, matched }`; `score` can be negative for penalized entries.
60
+ */
61
+ export function scoreEntry(entry, query) {
62
+ let score = 0
63
+ let matched = false
64
+ const haystack = String(query.text ?? '').toLowerCase()
65
+
66
+ // Machine-matchable fingerprints dominate: an error string that appears
67
+ // verbatim in the failure text is the strongest evidence we can get.
68
+ if (haystack.length > 0) {
69
+ let signalScore = 0
70
+ for (const signal of entry.signals) {
71
+ const needle = String(signal ?? '').toLowerCase()
72
+ if (needle.length >= 2 && haystack.includes(needle)) {
73
+ signalScore += 5
74
+ matched = true
75
+ }
76
+ }
77
+ score += Math.min(signalScore, 15)
78
+ }
79
+
80
+ if (query.tags !== undefined && query.tags.length > 0) {
81
+ const owned = new Set(entry.tags.map((tag) => tag.toLowerCase()))
82
+ let tagScore = 0
83
+ for (const tag of query.tags) {
84
+ if (owned.has(String(tag).toLowerCase())) {
85
+ tagScore += 3
86
+ matched = true
87
+ }
88
+ }
89
+ score += Math.min(tagScore, 9)
90
+ }
91
+
92
+ if (query.domain !== undefined && entry.domain === query.domain) {
93
+ score += 3
94
+ matched = true
95
+ }
96
+ if (query.kind !== undefined && entry.kind === query.kind) {
97
+ score += 2
98
+ matched = true
99
+ }
100
+
101
+ const queryTokens = query.tokens ?? tokenize(query.text)
102
+ if (queryTokens.size > 0) {
103
+ const titleTokens = tokenize(entry.title)
104
+ let titleScore = 0
105
+ for (const token of queryTokens) {
106
+ if (titleTokens.has(token)) {
107
+ titleScore += 2
108
+ matched = true
109
+ }
110
+ }
111
+ score += Math.min(titleScore, 8)
112
+
113
+ const bodyTokens = tokenize(`${entry.problem} ${entry.resolution} ${entry.rejected}`)
114
+ let bodyScore = 0
115
+ for (const token of queryTokens) {
116
+ if (bodyTokens.has(token)) {
117
+ bodyScore += 1
118
+ matched = true
119
+ }
120
+ }
121
+ score += Math.min(bodyScore, 4)
122
+ }
123
+
124
+ // Below here: ranking adjustments only. They never make an entry a result.
125
+
126
+ // A platform-specific entry is a guess that can be actively wrong elsewhere.
127
+ if (entry.platform !== undefined && query.platform !== undefined) {
128
+ score += entry.platform === query.platform ? 2 : -3
129
+ }
130
+
131
+ // Machine-scoped knowledge (this box's paths, this box's ACLs) travels poorly.
132
+ const entryCwd = entry.source?.cwd
133
+ if (entry.scope === 'machine' && typeof query.cwd === 'string' && query.cwd.length > 0) {
134
+ if (typeof entryCwd === 'string' && entryCwd.length > 0 && entryCwd !== query.cwd) score -= 2
135
+ }
136
+
137
+ if (entry.status === 'confirmed') score += 2
138
+ else if (entry.status === 'draft') score -= 1
139
+ else if (entry.status === 'deprecated') score -= 5
140
+
141
+ return { score, matched }
142
+ }
143
+
144
+ /**
145
+ * Filter and rank entries for one query.
146
+ * @param entries - every live entry.
147
+ * @param query - `{ text, tags, kind, domain, scope, status, platform, cwd, includeArchived }`.
148
+ * @param limit - maximum results.
149
+ * @returns ranked `{ entry, score }` pairs.
150
+ */
151
+ export function searchEntries(entries, query, limit) {
152
+ const normalized = {
153
+ text: String(query.text ?? ''),
154
+ tags: Array.isArray(query.tags) ? query.tags : [],
155
+ kind: query.kind,
156
+ domain: query.domain,
157
+ scope: query.scope,
158
+ status: query.status,
159
+ platform: query.platform,
160
+ cwd: query.cwd,
161
+ includeArchived: query.includeArchived === true,
162
+ }
163
+ normalized.tokens = tokenize(normalized.text)
164
+
165
+ const filtered = []
166
+ for (const entry of entries) {
167
+ if (normalized.includeArchived !== true && entry.archived === true) continue
168
+ if (normalized.status !== undefined && entry.status !== normalized.status) continue
169
+ if (normalized.kind !== undefined && entry.kind !== normalized.kind) continue
170
+ if (normalized.domain !== undefined && entry.domain !== normalized.domain) continue
171
+ if (normalized.scope !== undefined && entry.scope !== normalized.scope) continue
172
+ filtered.push(entry)
173
+ }
174
+
175
+ // Without search text or tags there is nothing to score against, so this is
176
+ // a filtered browse (respecting kind/domain/scope/status) ordered by recency.
177
+ // Scoring it instead would rank every survivor on status alone and then drop
178
+ // the drafts below MIN_RELEVANCE, which is not what a filter means.
179
+ const browsing = normalized.text.trim().length === 0 && normalized.tags.length === 0
180
+ if (browsing) {
181
+ return filtered
182
+ .slice()
183
+ .sort((a, b) => b.updatedAt - a.updatedAt)
184
+ .slice(0, limit)
185
+ .map((entry) => ({ entry, score: 0 }))
186
+ }
187
+
188
+ const ranked = []
189
+ for (const entry of filtered) {
190
+ const { score, matched } = scoreEntry(entry, normalized)
191
+ // `matched` is the real gate: an entry that shares nothing with the query
192
+ // must not be returned just because its status and platform score well.
193
+ if (matched && score > 0) ranked.push({ entry, score })
194
+ }
195
+ ranked.sort((a, b) => b.score - a.score || recency(b.entry) - recency(a.entry))
196
+ return ranked.slice(0, limit)
197
+ }
198
+
199
+ /**
200
+ * Last-use timestamp, falling back to creation for entries never surfaced.
201
+ * @param entry - a normalized ledger entry.
202
+ * @returns a comparable millisecond timestamp.
203
+ */
204
+ function recency(entry) {
205
+ return entry.lastHitAt > 0 ? entry.lastHitAt : entry.createdAt
206
+ }
package/lib/store.js ADDED
@@ -0,0 +1,222 @@
1
+ /**
2
+ * Durable storage for the ledger: one JSON document under $DSH_HOME, loaded
3
+ * once into memory and saved atomically (temp file + rename) so a crash mid-write
4
+ * cannot truncate the store.
5
+ *
6
+ * Two write paths exist on purpose:
7
+ * - `mutate()` is serialized and awaits durability; use it for anything the
8
+ * caller must be able to rely on immediately.
9
+ * - `bumpHits()` only touches memory and sets a dirty flag, because a search
10
+ * would otherwise force a disk write on every lookup. The debounce timer
11
+ * flushes those counters later.
12
+ */
13
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
14
+ import { dirname, join } from 'node:path'
15
+
16
+ /** On-disk document version. Bump only when the shape changes incompatibly. */
17
+ export const STATE_VERSION = 1
18
+
19
+ /** How long hit counters may stay in memory before a flush is attempted. */
20
+ const FLUSH_MS = 30_000
21
+
22
+ /**
23
+ * Resolve the store path. The plugin never picks a path inside a project
24
+ * checkout: entries are global, so they belong beside the other Harness state.
25
+ * @param config - the Loader row config.
26
+ * @returns absolute path of the JSON store.
27
+ */
28
+ export function resolveStatePath(config) {
29
+ if (typeof config?.statePath === 'string' && config.statePath.length > 0) return config.statePath
30
+ const home = process.env.DSH_HOME
31
+ if (typeof home === 'string' && home.length > 0) return join(home, 'solution-ledger.json')
32
+ return join(process.cwd(), '.solution-ledger.json')
33
+ }
34
+
35
+ /**
36
+ * Keep a stored record usable: drop unknown keys, coerce every field the
37
+ * search and render paths read, and never let one hand-edited record throw.
38
+ * @param raw - untrusted value from disk.
39
+ * @returns a normalized entry, or null when it has no usable identity.
40
+ */
41
+ export function normalizeEntry(raw) {
42
+ if (raw === null || typeof raw !== 'object') return null
43
+ const id = typeof raw.id === 'string' && raw.id.length > 0 ? raw.id : null
44
+ if (id === null) return null
45
+ const str = (value, fallback = '') => (typeof value === 'string' ? value : fallback)
46
+ const strList = (value) =>
47
+ Array.isArray(value) ? value.filter((v) => typeof v === 'string' && v.length > 0) : []
48
+ const num = (value, fallback) => (typeof value === 'number' && Number.isFinite(value) ? value : fallback)
49
+ const createdAt = num(raw.createdAt, Date.now())
50
+ return {
51
+ id,
52
+ kind: raw.kind === 'decision' ? 'decision' : 'troubleshoot',
53
+ domain: ['environment', 'tooling', 'code', 'config', 'process', 'other'].includes(raw.domain)
54
+ ? raw.domain
55
+ : 'other',
56
+ title: str(raw.title, '(untitled)'),
57
+ problem: str(raw.problem),
58
+ resolution: str(raw.resolution),
59
+ rejected: str(raw.rejected),
60
+ verify: str(raw.verify),
61
+ signals: strList(raw.signals),
62
+ tags: strList(raw.tags),
63
+ scope: ['machine', 'project', 'general'].includes(raw.scope) ? raw.scope : 'general',
64
+ platform: ['win32', 'darwin', 'linux'].includes(raw.platform) ? raw.platform : undefined,
65
+ status: ['draft', 'confirmed', 'deprecated'].includes(raw.status) ? raw.status : 'draft',
66
+ supersedes: typeof raw.supersedes === 'string' ? raw.supersedes : undefined,
67
+ archived: raw.archived === true,
68
+ source: raw.source !== null && typeof raw.source === 'object' ? raw.source : {},
69
+ createdAt,
70
+ updatedAt: num(raw.updatedAt, createdAt),
71
+ lastHitAt: num(raw.lastHitAt, 0),
72
+ hits: num(raw.hits, 0),
73
+ }
74
+ }
75
+
76
+ /** In-memory ledger with atomic, serialized persistence. */
77
+ export class Ledger {
78
+ #path
79
+ #data = { version: STATE_VERSION, entries: {} }
80
+ #loaded = false
81
+ #chain = Promise.resolve()
82
+ #dirty = false
83
+ #timer = null
84
+
85
+ /** @param path - absolute path of the JSON store. */
86
+ constructor(path) {
87
+ this.#path = path
88
+ }
89
+
90
+ get path() {
91
+ return this.#path
92
+ }
93
+
94
+ /** Begin the lazy flush timer; the caller disposes it with the plugin. */
95
+ start() {
96
+ if (this.#timer !== null) return
97
+ this.#timer = setInterval(() => {
98
+ if (this.#dirty) void this.#flushQuietly()
99
+ }, FLUSH_MS)
100
+ this.#timer.unref?.()
101
+ }
102
+
103
+ /** Stop flushing and persist any outstanding hit counters. */
104
+ async dispose() {
105
+ if (this.#timer !== null) {
106
+ clearInterval(this.#timer)
107
+ this.#timer = null
108
+ }
109
+ if (this.#dirty) await this.#flushQuietly()
110
+ }
111
+
112
+ /** Load the store once; a missing or corrupt file starts an empty ledger. */
113
+ async ready() {
114
+ if (this.#loaded) return
115
+ this.#loaded = true
116
+ let raw
117
+ try {
118
+ raw = await readFile(this.#path, 'utf8')
119
+ } catch (error) {
120
+ if (error?.code !== 'ENOENT') {
121
+ console.log('solution-ledger: store unreadable, starting empty:', String(error))
122
+ }
123
+ return
124
+ }
125
+ try {
126
+ const parsed = JSON.parse(raw)
127
+ const source = parsed?.entries
128
+ if (source !== null && typeof source === 'object') {
129
+ const entries = {}
130
+ for (const [key, value] of Object.entries(source)) {
131
+ const entry = normalizeEntry(value)
132
+ if (entry !== null) entries[entry.id ?? key] = entry
133
+ }
134
+ this.#data = { version: STATE_VERSION, entries }
135
+ }
136
+ } catch (error) {
137
+ console.log('solution-ledger: store malformed, starting empty:', String(error))
138
+ }
139
+ }
140
+
141
+ /** Every live entry, newest first. Call after `ready()`. */
142
+ all() {
143
+ return Object.values(this.#data.entries).sort((a, b) => b.updatedAt - a.updatedAt)
144
+ }
145
+
146
+ /** One entry by id, or undefined. */
147
+ get(id) {
148
+ return this.#data.entries[id]
149
+ }
150
+
151
+ /** Number of stored entries, archived included. */
152
+ get size() {
153
+ return Object.keys(this.#data.entries).length
154
+ }
155
+
156
+ /** Insert or overwrite one entry in memory. Call inside `mutate()`. */
157
+ set(id, entry) {
158
+ this.#data.entries[id] = entry
159
+ }
160
+
161
+ /** Remove one entry outright. Only pruning calls this; deposits never do. */
162
+ drop(id) {
163
+ if (!(id in this.#data.entries)) return false
164
+ delete this.#data.entries[id]
165
+ return true
166
+ }
167
+
168
+ /**
169
+ * Apply a mutation and await durability.
170
+ * @param fn - pure mutation against the in-memory table.
171
+ * @returns whatever `fn` returned.
172
+ */
173
+ mutate(fn) {
174
+ const run = this.#chain.then(async () => {
175
+ await this.ready()
176
+ const result = fn()
177
+ await this.#persist()
178
+ return result
179
+ })
180
+ // Keep the chain healthy: one rejected write must not block later writes.
181
+ this.#chain = run.then(
182
+ () => undefined,
183
+ () => undefined,
184
+ )
185
+ return run
186
+ }
187
+
188
+ /**
189
+ * Record that entries were surfaced by a search. Memory only; the debounce
190
+ * timer persists the counters so a lookup never pays for a disk write.
191
+ * @param ids - ids that appeared in a result.
192
+ */
193
+ bumpHits(ids) {
194
+ const now = Date.now()
195
+ let changed = false
196
+ for (const id of ids) {
197
+ const entry = this.#data.entries[id]
198
+ if (entry === undefined) continue
199
+ entry.hits += 1
200
+ entry.lastHitAt = now
201
+ changed = true
202
+ }
203
+ if (changed) this.#dirty = true
204
+ }
205
+
206
+ async #flushQuietly() {
207
+ this.#dirty = false
208
+ try {
209
+ await this.#persist()
210
+ } catch (error) {
211
+ console.log('solution-ledger: deferred flush failed:', String(error))
212
+ }
213
+ }
214
+
215
+ async #persist() {
216
+ await mkdir(dirname(this.#path), { recursive: true })
217
+ const tmp = `${this.#path}.tmp`
218
+ await writeFile(tmp, JSON.stringify(this.#data, null, 2), 'utf8')
219
+ await rename(tmp, this.#path)
220
+ this.#dirty = false
221
+ }
222
+ }
package/locale/en.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "Solution ledger",
4
+ "description": "Records troubleshooting fixes and design decisions in one global ledger, searches it before debugging starts, and surfaces a matching confirmed entry when a tool call fails.",
5
+ "detail": "README.md"
6
+ }
7
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "问题解决账本",
4
+ "description": "把踩过的坑和做过的取舍记进一个全局账本;调试前先检索,工具调用失败时自动带出已确认的相关条目。",
5
+ "detail": "README.md"
6
+ }
7
+ }
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "dsh-solution-ledger",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "license": "MIT",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "https://github.com/Catwb/dsh-solution-ledger.git"
8
+ },
9
+ "type": "module",
10
+ "description": "Global problem-solving ledger: records troubleshooting and design decisions, searches them before debugging, and surfaces a matching entry when a tool fails. Managed from a sidebar drawer.",
11
+ "main": "./lib/index.js",
12
+ "exports": {
13
+ ".": "./lib/index.js",
14
+ "./client": "./lib/client.js",
15
+ "./locale/*.json": "./locale/*.json",
16
+ "./icon": "./icon.svg",
17
+ "./package.json": "./package.json"
18
+ },
19
+ "files": [
20
+ "lib/index.js",
21
+ "lib/store.js",
22
+ "lib/search.js",
23
+ "lib/client.js",
24
+ "cordis.patch.yml",
25
+ "locale/*.json",
26
+ "icon.svg",
27
+ "README.md"
28
+ ],
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "dsh": {
33
+ "bundle": {
34
+ "patch": "./cordis.patch.yml"
35
+ },
36
+ "client": {
37
+ "platform": "web",
38
+ "inject": [
39
+ "@deepseek-ai/dsh-client-ui-sidebar"
40
+ ]
41
+ }
42
+ }
43
+ }