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/LICENSE +21 -0
- package/README.md +156 -2
- package/cordis.patch.yml +19 -0
- package/icon.svg +11 -0
- package/lib/client.js +617 -0
- package/lib/index.js +716 -0
- package/lib/search.js +206 -0
- package/lib/store.js +222 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +41 -4
package/lib/index.js
ADDED
|
@@ -0,0 +1,716 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Global problem-solving ledger.
|
|
3
|
+
*
|
|
4
|
+
* Two tools and one hook:
|
|
5
|
+
* - `solution_log` writes an entry (troubleshooting or decision).
|
|
6
|
+
* - `solution_search` reads the ledger back.
|
|
7
|
+
* - `tools/post-execute` pushes a matching confirmed entry onto a failed tool
|
|
8
|
+
* result, so a known problem is surfaced in the same step it is hit instead
|
|
9
|
+
* of waiting for the model to remember that a ledger exists.
|
|
10
|
+
*
|
|
11
|
+
* The plugin imports nothing from the Harness: a locally linked package cannot
|
|
12
|
+
* resolve `@deepseek-ai/*` from its own directory, so every integration point
|
|
13
|
+
* goes through `ctx` and the standard tool/hook contracts.
|
|
14
|
+
*/
|
|
15
|
+
import { Ledger, resolveStatePath } from './store.js'
|
|
16
|
+
import { searchEntries } from './search.js'
|
|
17
|
+
|
|
18
|
+
export const name = 'solution-ledger'
|
|
19
|
+
|
|
20
|
+
/** Activation gate: the ledger is pointless without the tool registry. */
|
|
21
|
+
export const inject = ['tools']
|
|
22
|
+
|
|
23
|
+
const KINDS = ['troubleshoot', 'decision']
|
|
24
|
+
const DOMAINS = ['environment', 'tooling', 'code', 'config', 'process', 'other']
|
|
25
|
+
const SCOPES = ['machine', 'project', 'general']
|
|
26
|
+
const STATUSES = ['draft', 'confirmed', 'deprecated']
|
|
27
|
+
const PLATFORMS = ['win32', 'darwin', 'linux']
|
|
28
|
+
|
|
29
|
+
const DAY_MS = 86_400_000
|
|
30
|
+
|
|
31
|
+
/** Defaults mirror cordis.patch.yml; the config there is what users edit. */
|
|
32
|
+
const DEFAULTS = {
|
|
33
|
+
pushOnToolError: true,
|
|
34
|
+
pushMinScore: 12,
|
|
35
|
+
maxEntries: 2000,
|
|
36
|
+
archiveAfterDays: 90,
|
|
37
|
+
draftArchiveAfterDays: 30,
|
|
38
|
+
statePath: '',
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Coerce the Loader row config onto the known shape. A hand-edited patch with a
|
|
43
|
+
* typo falls back per field instead of disabling the plugin.
|
|
44
|
+
* @param raw - the Loader row config.
|
|
45
|
+
* @returns a complete, range-checked config.
|
|
46
|
+
*/
|
|
47
|
+
function normalizeConfig(raw) {
|
|
48
|
+
const source = raw !== null && typeof raw === 'object' ? raw : {}
|
|
49
|
+
const bool = (value, fallback) => (typeof value === 'boolean' ? value : fallback)
|
|
50
|
+
const int = (value, fallback, min, max) => {
|
|
51
|
+
const parsed = typeof value === 'number' ? value : Number(value)
|
|
52
|
+
if (!Number.isFinite(parsed)) return fallback
|
|
53
|
+
return Math.min(max, Math.max(min, Math.round(parsed)))
|
|
54
|
+
}
|
|
55
|
+
return {
|
|
56
|
+
pushOnToolError: bool(source.pushOnToolError, DEFAULTS.pushOnToolError),
|
|
57
|
+
pushMinScore: int(source.pushMinScore, DEFAULTS.pushMinScore, 1, 100),
|
|
58
|
+
maxEntries: int(source.maxEntries, DEFAULTS.maxEntries, 10, 100_000),
|
|
59
|
+
archiveAfterDays: int(source.archiveAfterDays, DEFAULTS.archiveAfterDays, 1, 3650),
|
|
60
|
+
draftArchiveAfterDays: int(source.draftArchiveAfterDays, DEFAULTS.draftArchiveAfterDays, 1, 3650),
|
|
61
|
+
statePath: typeof source.statePath === 'string' ? source.statePath : DEFAULTS.statePath,
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Collision-resistant sortable id: millisecond timestamp plus random tail.
|
|
67
|
+
* @returns a new entry id.
|
|
68
|
+
*/
|
|
69
|
+
function newId() {
|
|
70
|
+
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Age out entries and enforce the ceiling, in place, inside a write.
|
|
75
|
+
* Deprecated entries leave search immediately; so does anything the user has
|
|
76
|
+
* not touched in `archiveAfterDays`. A draft that nobody ever searched for
|
|
77
|
+
* leaves on the shorter `draftArchiveAfterDays` clock: models do write the
|
|
78
|
+
* occasional note that is an implementation remark rather than a problem, and
|
|
79
|
+
* without this those accumulate forever as unreviewed drafts. Nothing is
|
|
80
|
+
* deleted until the ceiling is actually exceeded, so every archived entry stays
|
|
81
|
+
* recoverable.
|
|
82
|
+
* @param ledger - the ledger being written.
|
|
83
|
+
* @param config - resolved plugin config.
|
|
84
|
+
*/
|
|
85
|
+
function maintainInPlace(ledger, config) {
|
|
86
|
+
const now = Date.now()
|
|
87
|
+
const cutoff = now - config.archiveAfterDays * DAY_MS
|
|
88
|
+
const draftCutoff = now - config.draftArchiveAfterDays * DAY_MS
|
|
89
|
+
for (const snapshot of ledger.all()) {
|
|
90
|
+
const entry = ledger.get(snapshot.id)
|
|
91
|
+
if (entry === undefined || entry.archived === true) continue
|
|
92
|
+
const lastUse = entry.lastHitAt > 0 ? entry.lastHitAt : entry.createdAt
|
|
93
|
+
if (entry.status === 'deprecated' || lastUse < cutoff) {
|
|
94
|
+
entry.archived = true
|
|
95
|
+
continue
|
|
96
|
+
}
|
|
97
|
+
// Never surfaced, never confirmed, and older than the draft clock: this is
|
|
98
|
+
// the shape of a remark that was never useful to anyone.
|
|
99
|
+
if (entry.status === 'draft' && entry.hits === 0 && entry.createdAt < draftCutoff) {
|
|
100
|
+
entry.archived = true
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
if (ledger.size <= config.maxEntries) return
|
|
104
|
+
const oldestArchived = ledger
|
|
105
|
+
.all()
|
|
106
|
+
.filter((entry) => entry.archived === true)
|
|
107
|
+
.sort((a, b) => a.updatedAt - b.updatedAt)
|
|
108
|
+
for (const entry of oldestArchived) {
|
|
109
|
+
if (ledger.size <= config.maxEntries) break
|
|
110
|
+
ledger.drop(entry.id)
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Decide whether a dispatch outcome counts as a failure worth matching.
|
|
116
|
+
*
|
|
117
|
+
* `isError` alone is far too narrow: a shell command that exits non-zero is a
|
|
118
|
+
* normal successful tool result carrying `value.exitCode`, and that is the
|
|
119
|
+
* single most common way a user hits a problem. `value` is the tool's declared
|
|
120
|
+
* output schema, so these fields are part of the tool contract rather than a
|
|
121
|
+
* guess about its render text.
|
|
122
|
+
* @param result - the dispatch outcome.
|
|
123
|
+
* @returns true when the model just hit something that went wrong.
|
|
124
|
+
*/
|
|
125
|
+
function looksFailed(result) {
|
|
126
|
+
if (result?.isError === true) return true
|
|
127
|
+
const value = result?.value
|
|
128
|
+
if (value !== null && typeof value === 'object') {
|
|
129
|
+
if (typeof value.exitCode === 'number' && value.exitCode !== 0) return true
|
|
130
|
+
if (value.timedOut === true) return true
|
|
131
|
+
if (value.sandbox?.denied === true) return true
|
|
132
|
+
// An explicit zero proves the command ran; do not fall through to text.
|
|
133
|
+
if (value.exitCode === 0 && value.timedOut !== true) return false
|
|
134
|
+
}
|
|
135
|
+
for (const block of result?.content ?? []) {
|
|
136
|
+
if (block !== null && typeof block === 'object' && block.type === 'text' && typeof block.text === 'string') {
|
|
137
|
+
if (/\[exit code: [1-9]\d*\]/.test(block.text)) return true
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return false
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Flatten a failed dispatch into the text the scorer matches against, so an
|
|
145
|
+
* error code that the tool reported structurally is still searchable.
|
|
146
|
+
* @param result - the failed ToolExecutionResult.
|
|
147
|
+
* @returns normalized failure text, capped so one huge stderr cannot bloat the store.
|
|
148
|
+
*/
|
|
149
|
+
function failureText(result) {
|
|
150
|
+
const parts = []
|
|
151
|
+
const error = result?.error
|
|
152
|
+
if (error !== null && typeof error === 'object') {
|
|
153
|
+
if (typeof error.message === 'string') parts.push(error.message)
|
|
154
|
+
const info = error.info
|
|
155
|
+
if (info !== null && typeof info === 'object') {
|
|
156
|
+
if (typeof info.name === 'string') parts.push(info.name)
|
|
157
|
+
if (typeof info.code === 'string') parts.push(info.code)
|
|
158
|
+
if (typeof info.reason === 'string') parts.push(info.reason)
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
// Structured streams first: `content` may be truncated or re-rendered, while
|
|
162
|
+
// the tool's own value carries the real stderr.
|
|
163
|
+
const value = result?.value
|
|
164
|
+
if (value !== null && typeof value === 'object') {
|
|
165
|
+
if (typeof value.stderr?.text === 'string') parts.push(value.stderr.text)
|
|
166
|
+
if (typeof value.stdout?.text === 'string') parts.push(value.stdout.text)
|
|
167
|
+
}
|
|
168
|
+
for (const block of result?.content ?? []) {
|
|
169
|
+
if (block !== null && typeof block === 'object' && block.type === 'text' && typeof block.text === 'string') {
|
|
170
|
+
parts.push(block.text)
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
return parts.join('\n').slice(0, 4000)
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Compose the note attached to a failed tool result.
|
|
178
|
+
* @param hit - the ranked match.
|
|
179
|
+
* @returns the note text.
|
|
180
|
+
*/
|
|
181
|
+
function buildNote(hit) {
|
|
182
|
+
const { entry } = hit
|
|
183
|
+
const excerpt = entry.resolution.length > 200 ? `${entry.resolution.slice(0, 200)}…` : entry.resolution
|
|
184
|
+
const lines = [
|
|
185
|
+
`[solution-ledger] Known problem match (score ${hit.score}): ${entry.title}`,
|
|
186
|
+
`Resolution: ${excerpt}`,
|
|
187
|
+
]
|
|
188
|
+
if (entry.verify.length > 0) lines.push(`Verify: ${entry.verify.slice(0, 160)}`)
|
|
189
|
+
lines.push(`(id ${entry.id}; call solution_search for the full entry, or solution_log with replaces to correct it)`)
|
|
190
|
+
return lines.join('\n')
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Register the two tools and the failure hook.
|
|
195
|
+
* @param ctx - plugin context carrying `tools`.
|
|
196
|
+
* @param config - the Loader row config.
|
|
197
|
+
*/
|
|
198
|
+
export async function apply(ctx, config) {
|
|
199
|
+
const resolved = normalizeConfig(config)
|
|
200
|
+
const ledger = new Ledger(resolveStatePath(resolved))
|
|
201
|
+
ledger.start()
|
|
202
|
+
ctx.effect(() => () => ledger.dispose(), 'solution-ledger: store flush timer')
|
|
203
|
+
await ledger.ready()
|
|
204
|
+
|
|
205
|
+
// One note per distinct failure shape: a retry loop must not stack notes.
|
|
206
|
+
const recentPushes = new Set()
|
|
207
|
+
|
|
208
|
+
ctx.tools.register({
|
|
209
|
+
name: 'solution_log',
|
|
210
|
+
description:
|
|
211
|
+
'Record a problem whose root cause was not obvious, or a route you chose after genuinely rejecting a '
|
|
212
|
+
+ 'workable alternative, so a later session can skip the same search.\n\n'
|
|
213
|
+
+ 'Do NOT record how something was implemented, what a file contains, or a decision where no alternative '
|
|
214
|
+
+ 'was seriously considered. If a note would never appear in a failure message and would not change '
|
|
215
|
+
+ "anyone's next decision, it is a log line, not a ledger entry.\n\n"
|
|
216
|
+
+ 'Before calling, all three must be true: (1) a future session is likely to hit the same situation; '
|
|
217
|
+
+ '(2) the answer is not obvious from one glance at the code or docs; (3) skipping this entry would '
|
|
218
|
+
+ 'cost that session real time.\n\n'
|
|
219
|
+
+ 'New entries start as drafts and are not surfaced automatically until the user confirms them.',
|
|
220
|
+
parameters: {
|
|
221
|
+
kind: {
|
|
222
|
+
type: 'string',
|
|
223
|
+
required: true,
|
|
224
|
+
enum: KINDS,
|
|
225
|
+
description: 'troubleshoot for a failure you actually hit and fixed; decision only when you seriously considered a workable alternative and rejected it.',
|
|
226
|
+
},
|
|
227
|
+
domain: {
|
|
228
|
+
type: 'string',
|
|
229
|
+
required: true,
|
|
230
|
+
enum: DOMAINS,
|
|
231
|
+
description: 'Which knowledge area this belongs to; searches filter on it first.',
|
|
232
|
+
},
|
|
233
|
+
title: {
|
|
234
|
+
type: 'string',
|
|
235
|
+
required: true,
|
|
236
|
+
description: 'One-line conclusion that reads as a finding. A statement like "we use X to do Y" is an implementation note, not a finding.',
|
|
237
|
+
},
|
|
238
|
+
problem: {
|
|
239
|
+
type: 'string',
|
|
240
|
+
required: true,
|
|
241
|
+
description: 'The symptom as it appeared in an error or a failed attempt. For a decision, the two options that looked equally viable and what made the choice hard.',
|
|
242
|
+
},
|
|
243
|
+
resolution: {
|
|
244
|
+
type: 'string',
|
|
245
|
+
required: true,
|
|
246
|
+
description: 'The fix that worked, or the route you took.',
|
|
247
|
+
},
|
|
248
|
+
rejected: {
|
|
249
|
+
type: 'string',
|
|
250
|
+
description: 'An alternative you seriously considered and could have used, plus the concrete cost that ruled it out. Required when kind is decision.',
|
|
251
|
+
},
|
|
252
|
+
verify: {
|
|
253
|
+
type: 'string',
|
|
254
|
+
description: 'How to confirm the fix worked: the command to run and what it should print.',
|
|
255
|
+
},
|
|
256
|
+
signals: {
|
|
257
|
+
type: 'array',
|
|
258
|
+
items: { type: 'string' },
|
|
259
|
+
description:
|
|
260
|
+
'Short strings a future failure message would contain verbatim: error codes, command names, file names. '
|
|
261
|
+
+ 'Automatic matching keys on these, so copy them from the real output.',
|
|
262
|
+
},
|
|
263
|
+
tags: {
|
|
264
|
+
type: 'array',
|
|
265
|
+
items: { type: 'string' },
|
|
266
|
+
description: 'Two to six lowercase reuse words, such as windows, sandbox, pwsh, acl.',
|
|
267
|
+
},
|
|
268
|
+
scope: {
|
|
269
|
+
type: 'string',
|
|
270
|
+
enum: SCOPES,
|
|
271
|
+
description:
|
|
272
|
+
"machine for this computer's paths, permissions, or installed tools; "
|
|
273
|
+
+ "project for one repository's conventions; general for anything reusable anywhere.",
|
|
274
|
+
},
|
|
275
|
+
platform: {
|
|
276
|
+
type: 'string',
|
|
277
|
+
enum: PLATFORMS,
|
|
278
|
+
description: 'Set only when the entry is platform-specific, such as a Windows path or a filesystem quirk.',
|
|
279
|
+
},
|
|
280
|
+
status: {
|
|
281
|
+
type: 'string',
|
|
282
|
+
enum: STATUSES,
|
|
283
|
+
description:
|
|
284
|
+
'draft (default) until the user confirms the entry; confirmed entries are the only ones surfaced '
|
|
285
|
+
+ 'automatically; deprecated keeps the entry out of search without deleting it.',
|
|
286
|
+
},
|
|
287
|
+
replaces: {
|
|
288
|
+
type: 'string',
|
|
289
|
+
description: 'Id of an existing entry to update in place. Prefer this over adding a near-duplicate.',
|
|
290
|
+
},
|
|
291
|
+
},
|
|
292
|
+
output: {
|
|
293
|
+
schema: {
|
|
294
|
+
type: 'object',
|
|
295
|
+
additionalProperties: false,
|
|
296
|
+
required: ['id', 'action', 'status', 'total', 'similar'],
|
|
297
|
+
properties: {
|
|
298
|
+
id: { type: 'string' },
|
|
299
|
+
action: { type: 'string', enum: ['created', 'updated'] },
|
|
300
|
+
status: { type: 'string', enum: STATUSES },
|
|
301
|
+
total: { type: 'integer' },
|
|
302
|
+
similar: {
|
|
303
|
+
type: 'array',
|
|
304
|
+
items: {
|
|
305
|
+
type: 'object',
|
|
306
|
+
additionalProperties: false,
|
|
307
|
+
required: ['id', 'title', 'score'],
|
|
308
|
+
properties: {
|
|
309
|
+
id: { type: 'string' },
|
|
310
|
+
title: { type: 'string' },
|
|
311
|
+
score: { type: 'number' },
|
|
312
|
+
},
|
|
313
|
+
},
|
|
314
|
+
},
|
|
315
|
+
},
|
|
316
|
+
},
|
|
317
|
+
render: (_args, value) => {
|
|
318
|
+
const lines = [
|
|
319
|
+
`${value.action === 'updated' ? 'Updated' : 'Recorded'} entry ${value.id} as ${value.status}. `
|
|
320
|
+
+ `Ledger holds ${value.total} entries.`,
|
|
321
|
+
]
|
|
322
|
+
if (value.similar.length > 0) {
|
|
323
|
+
lines.push('Similar entries already present — consider folding this into one of them with `replaces`:')
|
|
324
|
+
for (const item of value.similar) lines.push(`- ${item.id} (score ${item.score}): ${item.title}`)
|
|
325
|
+
}
|
|
326
|
+
if (value.status === 'draft') {
|
|
327
|
+
lines.push('This entry stays a draft until the user confirms it; drafts are not surfaced automatically.')
|
|
328
|
+
}
|
|
329
|
+
return [{ type: 'text', text: lines.join('\n') }]
|
|
330
|
+
},
|
|
331
|
+
},
|
|
332
|
+
async execute(args, exec) {
|
|
333
|
+
const input = args !== null && typeof args === 'object' ? args : {}
|
|
334
|
+
const now = Date.now()
|
|
335
|
+
const cwd = exec?.agent?.session?.header?.cwd
|
|
336
|
+
const sessionId = exec?.agent?.id
|
|
337
|
+
|
|
338
|
+
if (typeof input.kind === 'string' && !KINDS.includes(input.kind)) {
|
|
339
|
+
throw new Error(`invalid kind ${JSON.stringify(input.kind)}; expected one of ${KINDS.join(', ')}`)
|
|
340
|
+
}
|
|
341
|
+
if (input.kind === 'decision' && (typeof input.rejected !== 'string' || input.rejected.trim().length === 0)) {
|
|
342
|
+
throw new Error('kind=decision requires `rejected`: state the route you turned down and why')
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
await ledger.ready()
|
|
346
|
+
|
|
347
|
+
const replacing = typeof input.replaces === 'string' && input.replaces.length > 0
|
|
348
|
+
if (replacing && ledger.get(input.replaces) === undefined) {
|
|
349
|
+
throw new Error(`no entry with id ${input.replaces}; omit replaces to create a new one`)
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
// Probe for near-duplicates before writing, but never block the write:
|
|
353
|
+
// a false positive must not cost the user the entry they asked for. The
|
|
354
|
+
// bar sits well above the search floor because a wrong "you already have
|
|
355
|
+
// this" is more annoying than a missed merge.
|
|
356
|
+
const probeText = `${input.title ?? ''} ${input.problem ?? ''}`
|
|
357
|
+
const similar = searchEntries(ledger.all(), { text: probeText, includeArchived: false }, 4)
|
|
358
|
+
.filter((hit) => hit.score >= 12 && hit.entry.id !== input.replaces)
|
|
359
|
+
.map((hit) => ({ id: hit.entry.id, title: hit.entry.title, score: hit.score }))
|
|
360
|
+
|
|
361
|
+
return ledger.mutate(() => {
|
|
362
|
+
maintainInPlace(ledger, resolved)
|
|
363
|
+
const existing = replacing ? ledger.get(input.replaces) : undefined
|
|
364
|
+
const base = existing ?? {}
|
|
365
|
+
const pick = (key, fallback) => (typeof input[key] === 'string' && input[key].length > 0 ? input[key] : fallback)
|
|
366
|
+
const pickList = (key, fallback) =>
|
|
367
|
+
Array.isArray(input[key]) && input[key].every((item) => typeof item === 'string')
|
|
368
|
+
? input[key].map((item) => item.trim()).filter((item) => item.length > 0)
|
|
369
|
+
: fallback
|
|
370
|
+
|
|
371
|
+
const entry = {
|
|
372
|
+
id: existing?.id ?? newId(),
|
|
373
|
+
kind: pick('kind', base.kind ?? 'troubleshoot'),
|
|
374
|
+
domain: pick('domain', base.domain ?? 'other'),
|
|
375
|
+
title: pick('title', base.title ?? ''),
|
|
376
|
+
problem: pick('problem', base.problem ?? ''),
|
|
377
|
+
resolution: pick('resolution', base.resolution ?? ''),
|
|
378
|
+
rejected: pick('rejected', base.rejected ?? ''),
|
|
379
|
+
verify: pick('verify', base.verify ?? ''),
|
|
380
|
+
signals: pickList('signals', base.signals ?? []),
|
|
381
|
+
tags: pickList('tags', base.tags ?? []),
|
|
382
|
+
scope: pick('scope', base.scope ?? 'general'),
|
|
383
|
+
platform: pick('platform', base.platform),
|
|
384
|
+
status: pick('status', base.status ?? 'draft'),
|
|
385
|
+
supersedes: typeof input.supersedes === 'string' ? input.supersedes : base.supersedes,
|
|
386
|
+
archived: existing?.archived === true,
|
|
387
|
+
source: existing?.source ?? {},
|
|
388
|
+
createdAt: existing?.createdAt ?? now,
|
|
389
|
+
updatedAt: now,
|
|
390
|
+
lastHitAt: existing?.lastHitAt ?? 0,
|
|
391
|
+
hits: existing?.hits ?? 0,
|
|
392
|
+
}
|
|
393
|
+
if (typeof cwd === 'string' && cwd.length > 0) entry.source.cwd = cwd
|
|
394
|
+
if (typeof sessionId === 'string' && sessionId.length > 0) entry.source.sessionId = sessionId
|
|
395
|
+
if (entry.title.trim().length < 6) {
|
|
396
|
+
throw new Error('`title` must be a real one-line finding, at least 6 characters')
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
ledger.set(entry.id, entry)
|
|
400
|
+
return {
|
|
401
|
+
id: entry.id,
|
|
402
|
+
action: existing === undefined ? 'created' : 'updated',
|
|
403
|
+
status: entry.status,
|
|
404
|
+
total: ledger.size,
|
|
405
|
+
similar,
|
|
406
|
+
}
|
|
407
|
+
})
|
|
408
|
+
},
|
|
409
|
+
presentCall: (args) => ({
|
|
410
|
+
card: 'generic',
|
|
411
|
+
title: args?.kind === 'decision' ? 'Record decision' : 'Record solution',
|
|
412
|
+
kind: 'other',
|
|
413
|
+
rawInput: args,
|
|
414
|
+
}),
|
|
415
|
+
})
|
|
416
|
+
|
|
417
|
+
ctx.tools.register({
|
|
418
|
+
name: 'solution_search',
|
|
419
|
+
description:
|
|
420
|
+
'Search the global problem ledger before you start debugging an environment or tooling failure, and before '
|
|
421
|
+
+ 'you commit to a technical route on a new task: a past session may have already hit it. Results are a short '
|
|
422
|
+
+ 'title plus a resolution excerpt. Update a match in place with solution_log `replaces` instead of adding a '
|
|
423
|
+
+ 'near-duplicate.',
|
|
424
|
+
parameters: {
|
|
425
|
+
query: {
|
|
426
|
+
type: 'string',
|
|
427
|
+
description: 'Failure text, error codes, or the decision you are weighing. Paste the real error when you have one.',
|
|
428
|
+
},
|
|
429
|
+
tags: {
|
|
430
|
+
type: 'array',
|
|
431
|
+
items: { type: 'string' },
|
|
432
|
+
description: 'Restrict to entries carrying these tags.',
|
|
433
|
+
},
|
|
434
|
+
kind: { type: 'string', enum: KINDS, description: 'Restrict to troubleshooting or decision entries.' },
|
|
435
|
+
domain: { type: 'string', enum: DOMAINS, description: 'Restrict to one knowledge area.' },
|
|
436
|
+
scope: { type: 'string', enum: SCOPES, description: 'Restrict to machine, project, or general knowledge.' },
|
|
437
|
+
status: {
|
|
438
|
+
type: 'string',
|
|
439
|
+
enum: STATUSES,
|
|
440
|
+
description: 'Restrict by lifecycle state, e.g. draft to review what still needs confirming.',
|
|
441
|
+
},
|
|
442
|
+
limit: { type: 'integer', description: 'Maximum matches, default 8, capped at 20.' },
|
|
443
|
+
},
|
|
444
|
+
output: {
|
|
445
|
+
schema: {
|
|
446
|
+
type: 'object',
|
|
447
|
+
additionalProperties: false,
|
|
448
|
+
required: ['count', 'entries'],
|
|
449
|
+
properties: {
|
|
450
|
+
count: { type: 'integer' },
|
|
451
|
+
entries: {
|
|
452
|
+
type: 'array',
|
|
453
|
+
items: {
|
|
454
|
+
type: 'object',
|
|
455
|
+
additionalProperties: false,
|
|
456
|
+
required: ['id', 'kind', 'domain', 'status', 'title', 'excerpt', 'tags', 'score'],
|
|
457
|
+
properties: {
|
|
458
|
+
id: { type: 'string' },
|
|
459
|
+
kind: { type: 'string' },
|
|
460
|
+
domain: { type: 'string' },
|
|
461
|
+
status: { type: 'string' },
|
|
462
|
+
title: { type: 'string' },
|
|
463
|
+
excerpt: { type: 'string' },
|
|
464
|
+
tags: { type: 'array', items: { type: 'string' } },
|
|
465
|
+
score: { type: 'number' },
|
|
466
|
+
},
|
|
467
|
+
},
|
|
468
|
+
},
|
|
469
|
+
},
|
|
470
|
+
},
|
|
471
|
+
render: (_args, value) => {
|
|
472
|
+
if (value.count === 0) {
|
|
473
|
+
return [{ type: 'text', text: 'No matching entries in the problem ledger. Solve it, then record it with solution_log.' }]
|
|
474
|
+
}
|
|
475
|
+
const lines = [`${value.count} matching entr${value.count === 1 ? 'y' : 'ies'}:`]
|
|
476
|
+
for (const item of value.entries) {
|
|
477
|
+
const tags = item.tags.length > 0 ? ` [${item.tags.join(', ')}]` : ''
|
|
478
|
+
lines.push(
|
|
479
|
+
`- ${item.id} (${item.kind}/${item.domain}/${item.status}, score ${item.score})${tags}`,
|
|
480
|
+
` ${item.title}`,
|
|
481
|
+
` ${item.excerpt}`,
|
|
482
|
+
)
|
|
483
|
+
}
|
|
484
|
+
return [{ type: 'text', text: lines.join('\n') }]
|
|
485
|
+
},
|
|
486
|
+
},
|
|
487
|
+
async execute(args, exec) {
|
|
488
|
+
const input = args !== null && typeof args === 'object' ? args : {}
|
|
489
|
+
await ledger.ready()
|
|
490
|
+
const limit = Math.min(20, Math.max(1, Number.isFinite(input.limit) ? Math.round(input.limit) : 8))
|
|
491
|
+
const ranked = searchEntries(
|
|
492
|
+
ledger.all(),
|
|
493
|
+
{
|
|
494
|
+
text: typeof input.query === 'string' ? input.query : '',
|
|
495
|
+
tags: Array.isArray(input.tags) ? input.tags : [],
|
|
496
|
+
kind: typeof input.kind === 'string' ? input.kind : undefined,
|
|
497
|
+
domain: typeof input.domain === 'string' ? input.domain : undefined,
|
|
498
|
+
scope: typeof input.scope === 'string' ? input.scope : undefined,
|
|
499
|
+
status: typeof input.status === 'string' ? input.status : undefined,
|
|
500
|
+
platform: process.platform,
|
|
501
|
+
cwd: exec?.agent?.session?.header?.cwd,
|
|
502
|
+
},
|
|
503
|
+
limit,
|
|
504
|
+
)
|
|
505
|
+
ledger.bumpHits(ranked.map((hit) => hit.entry.id))
|
|
506
|
+
return {
|
|
507
|
+
count: ranked.length,
|
|
508
|
+
entries: ranked.map((hit) => ({
|
|
509
|
+
id: hit.entry.id,
|
|
510
|
+
kind: hit.entry.kind,
|
|
511
|
+
domain: hit.entry.domain,
|
|
512
|
+
status: hit.entry.status,
|
|
513
|
+
title: hit.entry.title,
|
|
514
|
+
excerpt: hit.entry.resolution.length > 240 ? `${hit.entry.resolution.slice(0, 240)}…` : hit.entry.resolution,
|
|
515
|
+
tags: hit.entry.tags,
|
|
516
|
+
score: hit.score,
|
|
517
|
+
})),
|
|
518
|
+
}
|
|
519
|
+
},
|
|
520
|
+
presentCall: (args) => ({
|
|
521
|
+
card: 'generic',
|
|
522
|
+
title: 'Search problem ledger',
|
|
523
|
+
kind: 'other',
|
|
524
|
+
rawInput: args,
|
|
525
|
+
}),
|
|
526
|
+
})
|
|
527
|
+
|
|
528
|
+
// ---- Browser surface -------------------------------------------------
|
|
529
|
+
// The store is a Host-side JSON file, so the settings page reads and writes
|
|
530
|
+
// through these routes. Registered on whichever web server is mounted; a
|
|
531
|
+
// headless composition simply skips them and keeps the tools working.
|
|
532
|
+
const webServer = ctx.get('webServer')
|
|
533
|
+
if (webServer !== undefined) {
|
|
534
|
+
/**
|
|
535
|
+
* Read a request body as JSON.
|
|
536
|
+
* @param req - the HTTP request.
|
|
537
|
+
* @returns the parsed body, or an empty object for an empty body.
|
|
538
|
+
*/
|
|
539
|
+
const readJsonBody = async (req) => {
|
|
540
|
+
const chunks = []
|
|
541
|
+
let size = 0
|
|
542
|
+
for await (const chunk of req) {
|
|
543
|
+
size += chunk.length
|
|
544
|
+
if (size > 256 * 1024) throw new Error('request body too large')
|
|
545
|
+
chunks.push(chunk)
|
|
546
|
+
}
|
|
547
|
+
if (size === 0) return {}
|
|
548
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8'))
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/** Send one JSON answer. */
|
|
552
|
+
const reply = (res, status, payload) => {
|
|
553
|
+
res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' })
|
|
554
|
+
res.end(JSON.stringify(payload))
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/**
|
|
558
|
+
* Serialize one entry for the page, trimming the long prose so a large
|
|
559
|
+
* ledger still fits in one response.
|
|
560
|
+
* @param entry - a normalized ledger entry.
|
|
561
|
+
* @returns the wire shape.
|
|
562
|
+
*/
|
|
563
|
+
const wireEntry = (entry) => {
|
|
564
|
+
const clip = (text) => (text.length > 4000 ? `${text.slice(0, 4000)}…` : text)
|
|
565
|
+
return {
|
|
566
|
+
id: entry.id,
|
|
567
|
+
kind: entry.kind,
|
|
568
|
+
domain: entry.domain,
|
|
569
|
+
title: entry.title,
|
|
570
|
+
problem: clip(entry.problem),
|
|
571
|
+
resolution: clip(entry.resolution),
|
|
572
|
+
rejected: clip(entry.rejected),
|
|
573
|
+
verify: clip(entry.verify),
|
|
574
|
+
tags: entry.tags,
|
|
575
|
+
signals: entry.signals,
|
|
576
|
+
scope: entry.scope,
|
|
577
|
+
platform: entry.platform ?? null,
|
|
578
|
+
status: entry.status,
|
|
579
|
+
archived: entry.archived === true,
|
|
580
|
+
createdAt: entry.createdAt,
|
|
581
|
+
updatedAt: entry.updatedAt,
|
|
582
|
+
hits: entry.hits,
|
|
583
|
+
lastHitAt: entry.lastHitAt,
|
|
584
|
+
cwd: typeof entry.source?.cwd === 'string' ? entry.source.cwd : null,
|
|
585
|
+
sessionId: typeof entry.source?.sessionId === 'string' ? entry.source.sessionId : null,
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
/**
|
|
590
|
+
* Register one exact route and tie its disposer to the plugin lifetime.
|
|
591
|
+
* @param path - absolute request path.
|
|
592
|
+
* @param handler - async (req, res) => void.
|
|
593
|
+
*/
|
|
594
|
+
const route = (path, handler) => {
|
|
595
|
+
const dispose = webServer.register({
|
|
596
|
+
kind: 'exact',
|
|
597
|
+
path,
|
|
598
|
+
handler: async (req, res) => {
|
|
599
|
+
try {
|
|
600
|
+
await handler(req, res)
|
|
601
|
+
} catch (error) {
|
|
602
|
+
console.log(`solution-ledger: ${path} failed:`, String(error))
|
|
603
|
+
if (!res.headersSent) reply(res, 500, { ok: false, error: String(error) })
|
|
604
|
+
else res.end()
|
|
605
|
+
}
|
|
606
|
+
},
|
|
607
|
+
})
|
|
608
|
+
ctx.effect(() => dispose, `solution-ledger: route ${path}`)
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
route('/solution-ledger/list', async (req, res) => {
|
|
612
|
+
if (req.method !== 'GET') return reply(res, 405, { ok: false, error: 'method not allowed' })
|
|
613
|
+
await ledger.ready()
|
|
614
|
+
const all = ledger.all()
|
|
615
|
+
reply(res, 200, {
|
|
616
|
+
ok: true,
|
|
617
|
+
storePath: ledger.path,
|
|
618
|
+
entries: all.map(wireEntry),
|
|
619
|
+
stats: {
|
|
620
|
+
total: all.length,
|
|
621
|
+
draft: all.filter((entry) => entry.status === 'draft' && entry.archived !== true).length,
|
|
622
|
+
confirmed: all.filter((entry) => entry.status === 'confirmed' && entry.archived !== true).length,
|
|
623
|
+
deprecated: all.filter((entry) => entry.status === 'deprecated').length,
|
|
624
|
+
archived: all.filter((entry) => entry.archived === true).length,
|
|
625
|
+
},
|
|
626
|
+
})
|
|
627
|
+
})
|
|
628
|
+
|
|
629
|
+
route('/solution-ledger/update', async (req, res) => {
|
|
630
|
+
if (req.method !== 'POST') return reply(res, 405, { ok: false, error: 'method not allowed' })
|
|
631
|
+
const body = await readJsonBody(req)
|
|
632
|
+
const id = typeof body.id === 'string' ? body.id : ''
|
|
633
|
+
const patch = body.patch !== null && typeof body.patch === 'object' ? body.patch : {}
|
|
634
|
+
await ledger.ready()
|
|
635
|
+
if (ledger.get(id) === undefined) return reply(res, 404, { ok: false, error: `no entry with id ${id}` })
|
|
636
|
+
|
|
637
|
+
const TEXT_FIELDS = ['title', 'problem', 'resolution', 'rejected', 'verify']
|
|
638
|
+
const updated = await ledger.mutate(() => {
|
|
639
|
+
const existing = ledger.get(id)
|
|
640
|
+
const next = { ...existing }
|
|
641
|
+
for (const field of TEXT_FIELDS) {
|
|
642
|
+
if (typeof patch[field] === 'string') next[field] = patch[field]
|
|
643
|
+
}
|
|
644
|
+
if (typeof patch.status === 'string' && STATUSES.includes(patch.status)) next.status = patch.status
|
|
645
|
+
if (typeof patch.kind === 'string' && KINDS.includes(patch.kind)) next.kind = patch.kind
|
|
646
|
+
if (typeof patch.domain === 'string' && DOMAINS.includes(patch.domain)) next.domain = patch.domain
|
|
647
|
+
if (typeof patch.scope === 'string' && SCOPES.includes(patch.scope)) next.scope = patch.scope
|
|
648
|
+
if (Array.isArray(patch.tags) && patch.tags.every((tag) => typeof tag === 'string')) {
|
|
649
|
+
next.tags = patch.tags.map((tag) => tag.trim()).filter((tag) => tag.length > 0)
|
|
650
|
+
}
|
|
651
|
+
if (patch.archived === true) next.archived = true
|
|
652
|
+
if (patch.archived === false) next.archived = false
|
|
653
|
+
// Re-confirming a record clears a stale archive flag so it can be
|
|
654
|
+
// surfaced again without a second edit.
|
|
655
|
+
if (next.status === 'confirmed') next.archived = false
|
|
656
|
+
next.updatedAt = Date.now()
|
|
657
|
+
ledger.set(id, next)
|
|
658
|
+
return next
|
|
659
|
+
})
|
|
660
|
+
reply(res, 200, { ok: true, entry: wireEntry(updated) })
|
|
661
|
+
})
|
|
662
|
+
|
|
663
|
+
route('/solution-ledger/delete', async (req, res) => {
|
|
664
|
+
if (req.method !== 'POST') return reply(res, 405, { ok: false, error: 'method not allowed' })
|
|
665
|
+
const body = await readJsonBody(req)
|
|
666
|
+
const ids = Array.isArray(body.ids) ? body.ids.filter((id) => typeof id === 'string') : []
|
|
667
|
+
if (ids.length === 0) return reply(res, 400, { ok: false, error: 'no ids supplied' })
|
|
668
|
+
const removed = await ledger.mutate(() => {
|
|
669
|
+
let count = 0
|
|
670
|
+
for (const id of ids) if (ledger.drop(id)) count += 1
|
|
671
|
+
return count
|
|
672
|
+
})
|
|
673
|
+
reply(res, 200, { ok: true, removed })
|
|
674
|
+
})
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
// Push, not pull: a failing tool names its own problem in the same step it
|
|
678
|
+
// happens, which is the only moment the model is guaranteed to be looking.
|
|
679
|
+
ctx.on('tools/post-execute', async (exec, result, next) => {
|
|
680
|
+
const decision = await next()
|
|
681
|
+
try {
|
|
682
|
+
if (!resolved.pushOnToolError) return decision
|
|
683
|
+
if (decision?.kind !== 'accept') return decision
|
|
684
|
+
if (!looksFailed(result)) return decision
|
|
685
|
+
if (exec?.signal?.aborted === true) return decision
|
|
686
|
+
if (exec.name === 'solution_log' || exec.name === 'solution_search') return decision
|
|
687
|
+
|
|
688
|
+
const text = failureText(result)
|
|
689
|
+
if (text.trim().length < 8) return decision
|
|
690
|
+
|
|
691
|
+
const ranked = searchEntries(
|
|
692
|
+
ledger.all(),
|
|
693
|
+
{ text, platform: process.platform, cwd: exec?.agent?.session?.header?.cwd },
|
|
694
|
+
5,
|
|
695
|
+
)
|
|
696
|
+
const hit = ranked.find(
|
|
697
|
+
(candidate) => candidate.entry.status === 'confirmed' && candidate.score >= resolved.pushMinScore,
|
|
698
|
+
)
|
|
699
|
+
if (hit === undefined) return decision
|
|
700
|
+
|
|
701
|
+
const signature = `${exec.name}::${text.slice(0, 160)}`
|
|
702
|
+
if (recentPushes.has(signature)) return decision
|
|
703
|
+
recentPushes.add(signature)
|
|
704
|
+
if (recentPushes.size > 20) recentPushes.delete(recentPushes.values().next().value)
|
|
705
|
+
|
|
706
|
+
ledger.bumpHits([hit.entry.id])
|
|
707
|
+
const content = [...(Array.isArray(decision.content) ? decision.content : result.content ?? [])]
|
|
708
|
+
content.push({ type: 'text', text: buildNote(hit) })
|
|
709
|
+
return { ...decision, content }
|
|
710
|
+
} catch (error) {
|
|
711
|
+
// A failed lookup must never turn a real tool error into a worse one.
|
|
712
|
+
console.log('solution-ledger: failure note skipped:', String(error))
|
|
713
|
+
return decision
|
|
714
|
+
}
|
|
715
|
+
})
|
|
716
|
+
}
|