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