@xiangyixie/dsh-superagent 0.9.3 → 0.11.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/CHANGELOG.md +210 -0
- package/LICENSE +21 -21
- package/README.md +422 -42
- package/bin/archive.js +185 -0
- package/bin/doctor.js +84 -0
- package/bin/report.js +79 -79
- package/bin/watch.js +57 -57
- package/cordis.patch.yml +9 -9
- package/lib/control.js +495 -494
- package/lib/cost.js +267 -0
- package/lib/doctor.js +876 -0
- package/lib/errors.js +205 -199
- package/lib/index.js +767 -42
- package/lib/ledger.js +270 -0
- package/lib/lock.js +107 -0
- package/lib/memory.js +736 -0
- package/lib/notify.js +257 -0
- package/lib/orchestrator.js +1975 -127
- package/lib/report.js +350 -15
- package/lib/store.js +503 -15
- package/lib/templates.js +690 -0
- package/lib/usage.js +152 -152
- package/lib/watch.js +422 -70
- package/lib/workspace.js +433 -0
- package/package.json +16 -3
package/lib/templates.js
ADDED
|
@@ -0,0 +1,690 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Workflow templates for dsh-superagent.
|
|
3
|
+
*
|
|
4
|
+
* Most long goals have one of a few shapes: "fix this bug and prove it is
|
|
5
|
+
* fixed", "review this diff and repair what is broken", "update the docs to
|
|
6
|
+
* match the code", "research this question and write a report". Typing that
|
|
7
|
+
* shape by hand every time invites omissions, and letting the planner invent it
|
|
8
|
+
* from scratch makes two runs of the same task incomparable.
|
|
9
|
+
*
|
|
10
|
+
* A template is that shape written once: a fixed skeleton with named holes, the
|
|
11
|
+
* situations it fits, and the situations where it is the wrong tool. Expanding
|
|
12
|
+
* one produces a single goal string. That string enters the normal start path —
|
|
13
|
+
* the planner still decomposes it, subtasks are still ordered by the run's own
|
|
14
|
+
* plan, and every limit, budget, and quota still applies. There is deliberately
|
|
15
|
+
* no field for limits, providers, or overrides, and an unknown field is
|
|
16
|
+
* rejected, so a template can never widen what a run is allowed to do.
|
|
17
|
+
*
|
|
18
|
+
* Built-ins live in this file. A user template is
|
|
19
|
+
* `<stateDir>/templates/<id>.json` with exactly the same fields; it can be
|
|
20
|
+
* listed, shown, overwritten, and deleted, and it may not take a built-in's id.
|
|
21
|
+
*
|
|
22
|
+
* Placeholders are `{{name}}` and every declared parameter is required. A
|
|
23
|
+
* missing value is refused with the names of what is missing instead of being
|
|
24
|
+
* filled with a guessed default: a plausible default ("the failing test") is
|
|
25
|
+
* how a template silently produces a goal about the wrong thing.
|
|
26
|
+
*
|
|
27
|
+
* @module dsh-superagent/templates
|
|
28
|
+
*/
|
|
29
|
+
import fsp from 'node:fs/promises'
|
|
30
|
+
import path from 'node:path'
|
|
31
|
+
|
|
32
|
+
/** Placeholder syntax used by a skeleton. */
|
|
33
|
+
const ANY_PLACEHOLDER = /\{\{([^{}]*)\}\}/g
|
|
34
|
+
|
|
35
|
+
/** A template id is also a file name under `<stateDir>/templates`. */
|
|
36
|
+
const ID_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/
|
|
37
|
+
const NAME_PATTERN = /^[a-z][a-z0-9_]{0,31}$/
|
|
38
|
+
const MAX_ID_CHARS = 48
|
|
39
|
+
const MAX_TITLE_CHARS = 120
|
|
40
|
+
const MAX_WHEN_CHARS = 600
|
|
41
|
+
const MAX_NOT_CHARS = 400
|
|
42
|
+
const MAX_NOT_ITEMS = 8
|
|
43
|
+
const MAX_DESCRIPTION_CHARS = 300
|
|
44
|
+
const MAX_VARIABLES = 12
|
|
45
|
+
const MAX_SKELETON_CHARS = 8000
|
|
46
|
+
const MAX_GOAL_CHARS = 16000
|
|
47
|
+
|
|
48
|
+
/** Fields a template may set. Anything else is refused, not ignored. */
|
|
49
|
+
const TEMPLATE_FIELDS = new Set(['id', 'title', 'whenToUse', 'whenNotToUse', 'variables', 'skeleton'])
|
|
50
|
+
const VARIABLE_FIELDS = new Set(['name', 'description'])
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* A template problem with a stable code, so the tool can attach the right hint
|
|
54
|
+
* and a test can assert the failure instead of matching prose.
|
|
55
|
+
*/
|
|
56
|
+
export class TemplateError extends Error {
|
|
57
|
+
/**
|
|
58
|
+
* @param {string} code - stable identifier.
|
|
59
|
+
* @param {string} message - one actionable sentence.
|
|
60
|
+
* @param {{ parameters?: string[] }} [details] - names involved, when known.
|
|
61
|
+
*/
|
|
62
|
+
constructor(code, message, details = {}) {
|
|
63
|
+
super(message)
|
|
64
|
+
this.name = 'TemplateError'
|
|
65
|
+
this.code = code
|
|
66
|
+
if (details.parameters) this.parameters = details.parameters
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function invalid(message) {
|
|
71
|
+
return new TemplateError('invalid-template', message)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function asText(value) {
|
|
75
|
+
return typeof value === 'string' ? value.trim() : ''
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Collapse metadata to one bounded line; a title or reason is never multiline. */
|
|
79
|
+
function oneLine(value, limit) {
|
|
80
|
+
const text = String(value ?? '').replace(/\s+/g, ' ').trim()
|
|
81
|
+
if (!text) return ''
|
|
82
|
+
return [...text].slice(0, limit).join('')
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Placeholder names used by a skeleton, in first-appearance order. Names are
|
|
87
|
+
* returned verbatim so validation can report a malformed one instead of hiding
|
|
88
|
+
* it; expansion only happens after validation.
|
|
89
|
+
*
|
|
90
|
+
* @param {unknown} skeleton - template skeleton.
|
|
91
|
+
* @returns {string[]} placeholder names.
|
|
92
|
+
*/
|
|
93
|
+
export function placeholdersOf(skeleton) {
|
|
94
|
+
const names = []
|
|
95
|
+
for (const match of String(skeleton ?? '').matchAll(ANY_PLACEHOLDER)) {
|
|
96
|
+
const name = match[1].trim()
|
|
97
|
+
if (!names.includes(name)) names.push(name)
|
|
98
|
+
}
|
|
99
|
+
return names
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Coerce one template definition into the canonical shape.
|
|
104
|
+
*
|
|
105
|
+
* @param {unknown} input - parsed template (from code or a JSON file).
|
|
106
|
+
* @returns {object} canonical template.
|
|
107
|
+
* @throws {TemplateError} `invalid-template` with the first concrete problem.
|
|
108
|
+
*/
|
|
109
|
+
export function normalizeTemplate(input) {
|
|
110
|
+
if (!input || typeof input !== 'object' || Array.isArray(input)) {
|
|
111
|
+
throw invalid('a template must be a JSON object')
|
|
112
|
+
}
|
|
113
|
+
const unknown = Object.keys(input).filter(key => !TEMPLATE_FIELDS.has(key))
|
|
114
|
+
if (unknown.length > 0) {
|
|
115
|
+
throw invalid(
|
|
116
|
+
`unknown field(s) ${unknown.join(', ')}; a template may only set ${[...TEMPLATE_FIELDS].join(', ')} `
|
|
117
|
+
+ '(limits, providers, and overrides belong to the run, not the template)',
|
|
118
|
+
)
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const id = asText(input.id)
|
|
122
|
+
if (!ID_PATTERN.test(id) || id.length > MAX_ID_CHARS) {
|
|
123
|
+
throw invalid(`id must be a lowercase slug such as "bugfix-verify" (got ${JSON.stringify(input.id)})`)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const title = oneLine(input.title, MAX_TITLE_CHARS)
|
|
127
|
+
if (!title) throw invalid(`template "${id}" needs a one-line title`)
|
|
128
|
+
|
|
129
|
+
const whenToUse = oneLine(input.whenToUse, MAX_WHEN_CHARS)
|
|
130
|
+
if (!whenToUse) throw invalid(`template "${id}" needs whenToUse: the situation it fits`)
|
|
131
|
+
|
|
132
|
+
const notList = Array.isArray(input.whenNotToUse)
|
|
133
|
+
? input.whenNotToUse
|
|
134
|
+
: typeof input.whenNotToUse === 'string'
|
|
135
|
+
? [input.whenNotToUse]
|
|
136
|
+
: []
|
|
137
|
+
if (notList.length === 0) {
|
|
138
|
+
throw invalid(`template "${id}" needs at least one whenNotToUse entry: when this template is the wrong tool`)
|
|
139
|
+
}
|
|
140
|
+
if (notList.length > MAX_NOT_ITEMS) {
|
|
141
|
+
throw invalid(`template "${id}" lists more than ${MAX_NOT_ITEMS} whenNotToUse entries; keep the decisive ones`)
|
|
142
|
+
}
|
|
143
|
+
const whenNotToUse = notList.map((item, index) => {
|
|
144
|
+
const text = oneLine(item, MAX_NOT_CHARS)
|
|
145
|
+
if (!text) throw invalid(`template "${id}" has an empty whenNotToUse entry at index ${index}`)
|
|
146
|
+
return text
|
|
147
|
+
})
|
|
148
|
+
|
|
149
|
+
if (input.variables !== undefined && !Array.isArray(input.variables)) {
|
|
150
|
+
throw invalid(`template "${id}" has variables that are not a list`)
|
|
151
|
+
}
|
|
152
|
+
const rawVariables = input.variables ?? []
|
|
153
|
+
if (rawVariables.length > MAX_VARIABLES) {
|
|
154
|
+
throw invalid(`template "${id}" declares more than ${MAX_VARIABLES} parameters`)
|
|
155
|
+
}
|
|
156
|
+
const variables = []
|
|
157
|
+
const seen = new Set()
|
|
158
|
+
for (const [index, item] of rawVariables.entries()) {
|
|
159
|
+
if (!item || typeof item !== 'object' || Array.isArray(item)) {
|
|
160
|
+
throw invalid(`template "${id}" has a parameter at index ${index} that is not an object`)
|
|
161
|
+
}
|
|
162
|
+
const extra = Object.keys(item).filter(key => !VARIABLE_FIELDS.has(key))
|
|
163
|
+
if (extra.length > 0) {
|
|
164
|
+
throw invalid(`template "${id}" parameter ${JSON.stringify(item.name)} has unknown field(s) ${extra.join(', ')}`)
|
|
165
|
+
}
|
|
166
|
+
const name = asText(item.name)
|
|
167
|
+
if (!NAME_PATTERN.test(name)) {
|
|
168
|
+
throw invalid(`template "${id}" parameter ${JSON.stringify(item.name)} must be a lowercase name such as "reproduction"`)
|
|
169
|
+
}
|
|
170
|
+
if (seen.has(name)) throw invalid(`template "${id}" declares parameter "${name}" twice`)
|
|
171
|
+
seen.add(name)
|
|
172
|
+
const description = oneLine(item.description, MAX_DESCRIPTION_CHARS)
|
|
173
|
+
if (!description) throw invalid(`template "${id}" parameter "${name}" needs a description of the value to pass`)
|
|
174
|
+
variables.push({ name, description })
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const skeleton = typeof input.skeleton === 'string' ? input.skeleton.trim() : ''
|
|
178
|
+
if (!skeleton) throw invalid(`template "${id}" needs a skeleton`)
|
|
179
|
+
if (skeleton.length > MAX_SKELETON_CHARS) {
|
|
180
|
+
throw invalid(`template "${id}" skeleton is longer than ${MAX_SKELETON_CHARS} characters`)
|
|
181
|
+
}
|
|
182
|
+
for (const placeholder of placeholdersOf(skeleton)) {
|
|
183
|
+
if (!NAME_PATTERN.test(placeholder)) {
|
|
184
|
+
throw invalid(`template "${id}" uses {{${placeholder}}}, which is not a valid parameter name`)
|
|
185
|
+
}
|
|
186
|
+
if (!seen.has(placeholder)) {
|
|
187
|
+
throw invalid(
|
|
188
|
+
`template "${id}" uses {{${placeholder}}} in its skeleton but does not declare that parameter`,
|
|
189
|
+
)
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
const used = placeholdersOf(skeleton)
|
|
193
|
+
const unused = [...seen].filter(name => !used.includes(name))
|
|
194
|
+
if (unused.length > 0) {
|
|
195
|
+
throw invalid(
|
|
196
|
+
`template "${id}" declares ${unused.join(', ')} but never uses the placeholder(s) in its skeleton; `
|
|
197
|
+
+ 'a parameter nobody reads would be collected and silently dropped',
|
|
198
|
+
)
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
return { id, title, whenToUse, whenNotToUse, variables, skeleton }
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Validate a template without throwing, for a caller that has to report the
|
|
206
|
+
* problem instead of crashing on a hand-edited JSON file.
|
|
207
|
+
*
|
|
208
|
+
* @param {unknown} input - candidate template.
|
|
209
|
+
* @returns {{ ok: true, template: object } | { ok: false, error: TemplateError }}
|
|
210
|
+
*/
|
|
211
|
+
export function validateTemplate(input) {
|
|
212
|
+
try {
|
|
213
|
+
return { ok: true, template: normalizeTemplate(input) }
|
|
214
|
+
} catch (error) {
|
|
215
|
+
if (error instanceof TemplateError) return { ok: false, error }
|
|
216
|
+
throw error
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Turn one template parameter into the text that goes into the goal. A value
|
|
222
|
+
* that is absent, null, empty, or only whitespace is missing — never defaulted.
|
|
223
|
+
*/
|
|
224
|
+
function parameterText(value) {
|
|
225
|
+
if (typeof value === 'string') return value.trim()
|
|
226
|
+
if (typeof value === 'number' && Number.isFinite(value)) return String(value)
|
|
227
|
+
if (typeof value === 'boolean') return String(value)
|
|
228
|
+
return ''
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Expand one template into a goal.
|
|
233
|
+
*
|
|
234
|
+
* The result is plain goal text with nothing added: no template marker, no
|
|
235
|
+
* limit, no mode. The start path cannot tell it apart from a goal typed by the
|
|
236
|
+
* user, which is what keeps templates inside the existing planner, plan, and
|
|
237
|
+
* quota behaviour.
|
|
238
|
+
*
|
|
239
|
+
* @param {unknown} input - template definition (built-in or custom).
|
|
240
|
+
* @param {Record<string, unknown>} [values] - one value per declared parameter.
|
|
241
|
+
* @returns {{ goal: string, templateId: string, title: string, filled: string[] }}
|
|
242
|
+
* @throws {TemplateError} `invalid-template`, `unknown-parameters`,
|
|
243
|
+
* `missing-parameters`, or `goal-too-long`.
|
|
244
|
+
*/
|
|
245
|
+
export function expandTemplate(input, values = {}) {
|
|
246
|
+
// The store marks where a definition came from with `source`. That is not
|
|
247
|
+
// part of the definition a skeleton may set, so it is dropped here rather
|
|
248
|
+
// than declared as a field a saved template could also carry.
|
|
249
|
+
let definition = input
|
|
250
|
+
if (input && typeof input === 'object' && !Array.isArray(input) && 'source' in input) {
|
|
251
|
+
const { source: _source, ...rest } = input
|
|
252
|
+
definition = rest
|
|
253
|
+
}
|
|
254
|
+
const template = normalizeTemplate(definition)
|
|
255
|
+
if (values === undefined || values === null) values = {}
|
|
256
|
+
if (typeof values !== 'object' || Array.isArray(values)) {
|
|
257
|
+
throw new TemplateError('unknown-parameters', 'params must be an object of parameter values')
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
const declared = template.variables.map(variable => variable.name)
|
|
261
|
+
const supplied = Object.keys(values).filter(key => values[key] !== undefined)
|
|
262
|
+
const unknown = supplied.filter(key => !declared.includes(key))
|
|
263
|
+
if (unknown.length > 0) {
|
|
264
|
+
throw new TemplateError(
|
|
265
|
+
'unknown-parameters',
|
|
266
|
+
`template "${template.id}" has no parameter(s) ${unknown.sort().join(', ')}; `
|
|
267
|
+
+ `it declares ${declared.join(', ') || '(none)'}`,
|
|
268
|
+
{ parameters: unknown },
|
|
269
|
+
)
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
const missing = declared.filter(name => !parameterText(values[name]))
|
|
273
|
+
if (missing.length > 0) {
|
|
274
|
+
throw new TemplateError(
|
|
275
|
+
'missing-parameters',
|
|
276
|
+
`template "${template.id}" is missing required parameter(s): ${missing.join(', ')}; `
|
|
277
|
+
+ 'a template never assumes a default, so pass a value for each one',
|
|
278
|
+
{ parameters: missing },
|
|
279
|
+
)
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
const goal = template.skeleton.replace(ANY_PLACEHOLDER, (_match, rawName) => {
|
|
283
|
+
const name = String(rawName).trim()
|
|
284
|
+
return parameterText(values[name])
|
|
285
|
+
})
|
|
286
|
+
// Values are opaque text, so a value that itself contains `{{...}}` is left
|
|
287
|
+
// alone: someone documenting this syntax must be able to pass it as a value.
|
|
288
|
+
if (goal.length > MAX_GOAL_CHARS) {
|
|
289
|
+
throw new TemplateError(
|
|
290
|
+
'goal-too-long',
|
|
291
|
+
`template "${template.id}" expands to ${goal.length} characters, over the ${MAX_GOAL_CHARS} limit; `
|
|
292
|
+
+ 'shorten the skeleton or the values',
|
|
293
|
+
)
|
|
294
|
+
}
|
|
295
|
+
return { goal, templateId: template.id, title: template.title, filled: declared }
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* The built-in library. Each entry answers four questions: when it fits, the
|
|
300
|
+
* fixed skeleton, the holes in that skeleton, and when it is the wrong tool.
|
|
301
|
+
* The last one is not decoration: it is what stops a template from being
|
|
302
|
+
* applied to work it was never designed for.
|
|
303
|
+
*/
|
|
304
|
+
export const BUILTIN_TEMPLATES = Object.freeze([
|
|
305
|
+
Object.freeze(normalizeTemplate({
|
|
306
|
+
id: 'bugfix-verify',
|
|
307
|
+
title: 'Fix a bug and verify the fix',
|
|
308
|
+
whenToUse: 'A defect has a known symptom and a way to reproduce it, and the work is to find the cause, '
|
|
309
|
+
+ 'fix it, and prove the fix with a test.',
|
|
310
|
+
whenNotToUse: [
|
|
311
|
+
'The task is a new feature or a redesign, not a defect against expected behaviour.',
|
|
312
|
+
'The failure cannot be reproduced yet; investigate first, then come back with a reproduction.',
|
|
313
|
+
'The fix needs a product or API decision that only the user can make before any code changes.',
|
|
314
|
+
],
|
|
315
|
+
variables: [
|
|
316
|
+
{ name: 'symptom', description: 'What goes wrong, quoted from the actual output' },
|
|
317
|
+
{ name: 'reproduction', description: 'The exact steps or command that trigger it' },
|
|
318
|
+
{ name: 'expected', description: 'What correct behaviour looks like' },
|
|
319
|
+
{ name: 'scope', description: 'Files or components that may be changed, and what is off limits' },
|
|
320
|
+
],
|
|
321
|
+
skeleton: [
|
|
322
|
+
'Fix the following bug and prove the fix works.',
|
|
323
|
+
'',
|
|
324
|
+
'Symptom:',
|
|
325
|
+
'{{symptom}}',
|
|
326
|
+
'',
|
|
327
|
+
'How to reproduce it:',
|
|
328
|
+
'{{reproduction}}',
|
|
329
|
+
'',
|
|
330
|
+
'Expected behaviour:',
|
|
331
|
+
'{{expected}}',
|
|
332
|
+
'',
|
|
333
|
+
'Allowed change scope:',
|
|
334
|
+
'{{scope}}',
|
|
335
|
+
'',
|
|
336
|
+
'Work in this order, and do not skip a step:',
|
|
337
|
+
'1. Reproduce the failure and quote the exact error output.',
|
|
338
|
+
'2. Find the root cause and state it in one sentence before changing any file.',
|
|
339
|
+
'3. Make the smallest change that fixes the cause, inside the allowed scope only.',
|
|
340
|
+
'4. Add or update a regression test that fails without the fix and passes with it.',
|
|
341
|
+
'5. Run the relevant test suite and report the real pass and fail numbers.',
|
|
342
|
+
'',
|
|
343
|
+
'In the final report: the root cause, the files changed with a one-line reason for each, the regression test,',
|
|
344
|
+
'the exact commands you ran, and their output. Do not refactor unrelated code, do not change the public API',
|
|
345
|
+
'unless the symptom makes that unavoidable, and do not claim a fix you did not run.',
|
|
346
|
+
].join('\n'),
|
|
347
|
+
})),
|
|
348
|
+
Object.freeze(normalizeTemplate({
|
|
349
|
+
id: 'review-fix',
|
|
350
|
+
title: 'Review code and fix the confirmed defects',
|
|
351
|
+
whenToUse: 'A diff, file, or module needs review, and the reviewer is expected to repair the defects it '
|
|
352
|
+
+ 'finds rather than only list them.',
|
|
353
|
+
whenNotToUse: [
|
|
354
|
+
'The review must stay read-only, for example a pre-merge audit that another person will act on.',
|
|
355
|
+
'Nobody can say what the code is supposed to do; clarify the intended behaviour first.',
|
|
356
|
+
'The target is generated or vendored code that must not be edited.',
|
|
357
|
+
],
|
|
358
|
+
variables: [
|
|
359
|
+
{ name: 'target', description: 'The diff, files, or module to review' },
|
|
360
|
+
{ name: 'focus', description: 'What to judge it against: correctness, security, performance, compatibility' },
|
|
361
|
+
{ name: 'verification', description: 'The command or check that proves a fix works' },
|
|
362
|
+
],
|
|
363
|
+
skeleton: [
|
|
364
|
+
'Review the following code, then fix the real defects you find.',
|
|
365
|
+
'',
|
|
366
|
+
'Target:',
|
|
367
|
+
'{{target}}',
|
|
368
|
+
'',
|
|
369
|
+
'What to review it against:',
|
|
370
|
+
'{{focus}}',
|
|
371
|
+
'',
|
|
372
|
+
'How to verify a fix:',
|
|
373
|
+
'{{verification}}',
|
|
374
|
+
'',
|
|
375
|
+
'Work in this order:',
|
|
376
|
+
'1. Read the target before judging it, and list the files you actually read.',
|
|
377
|
+
'2. Report each finding as `file:line — severity — what breaks, under which input, with evidence`.',
|
|
378
|
+
'3. Separate confirmed defects from style preferences, and never report a preference as a defect.',
|
|
379
|
+
'4. Fix only the confirmed defects, smallest change first, and touch no unrelated file.',
|
|
380
|
+
'5. Verify every fix with the check given above; if a fix cannot be verified, say exactly why.',
|
|
381
|
+
'6. Re-run the relevant tests and report the real pass and fail numbers.',
|
|
382
|
+
'',
|
|
383
|
+
'Deliver: the findings with their fate (fixed, or not fixed and why), the diff summary, and the verification',
|
|
384
|
+
'output. If a finding needs a product decision instead of a code change, say so and leave that code alone.',
|
|
385
|
+
].join('\n'),
|
|
386
|
+
})),
|
|
387
|
+
Object.freeze(normalizeTemplate({
|
|
388
|
+
id: 'docs-examples',
|
|
389
|
+
title: 'Update docs and examples to match the code',
|
|
390
|
+
whenToUse: 'Code or configuration changed and the docs, README, or runnable examples now describe the old '
|
|
391
|
+
+ 'behaviour.',
|
|
392
|
+
whenNotToUse: [
|
|
393
|
+
'The docs describe a feature that does not exist yet; build the feature first.',
|
|
394
|
+
'The task is a marketing or positioning rewrite rather than a correctness update.',
|
|
395
|
+
'The examples need a live account, credential, or paid service that this run cannot use.',
|
|
396
|
+
],
|
|
397
|
+
variables: [
|
|
398
|
+
{ name: 'change', description: 'What changed in the code or configuration' },
|
|
399
|
+
{ name: 'audience', description: 'Who reads these docs and what they already know' },
|
|
400
|
+
{ name: 'sources', description: 'The files that hold the current truth' },
|
|
401
|
+
],
|
|
402
|
+
skeleton: [
|
|
403
|
+
'Update the documentation and examples so they match what the code actually does.',
|
|
404
|
+
'',
|
|
405
|
+
'What changed:',
|
|
406
|
+
'{{change}}',
|
|
407
|
+
'',
|
|
408
|
+
'Reader:',
|
|
409
|
+
'{{audience}}',
|
|
410
|
+
'',
|
|
411
|
+
'Where the current truth lives:',
|
|
412
|
+
'{{sources}}',
|
|
413
|
+
'',
|
|
414
|
+
'Work in this order:',
|
|
415
|
+
'1. Read the current docs, the examples, and the source they describe.',
|
|
416
|
+
'2. List every statement that is now wrong, missing, or misleading, with its file and line.',
|
|
417
|
+
'3. Rewrite only those parts, keeping the existing voice, structure, and formatting conventions.',
|
|
418
|
+
'4. Update runnable examples and commands so a reader can copy them verbatim; delete an example that cannot work.',
|
|
419
|
+
'5. Run every command you publish where the environment allows it, and quote the output.',
|
|
420
|
+
'6. Search for the old names, flags, or paths you replaced and fix the occurrences you missed.',
|
|
421
|
+
'',
|
|
422
|
+
'Deliver: the files changed, a short before and after for each substantive edit, and the verification results.',
|
|
423
|
+
'Do not document behaviour you could not confirm in the source, and do not add new marketing claims.',
|
|
424
|
+
].join('\n'),
|
|
425
|
+
})),
|
|
426
|
+
Object.freeze(normalizeTemplate({
|
|
427
|
+
id: 'research-report',
|
|
428
|
+
title: 'Research a question and write a report',
|
|
429
|
+
whenToUse: 'The answer is not in the repository, several sources must be compared, and the outcome is a '
|
|
430
|
+
+ 'written report with evidence and a recommendation.',
|
|
431
|
+
whenNotToUse: [
|
|
432
|
+
'The work is to change code, not to answer a question.',
|
|
433
|
+
'The question has one factual answer that a single lookup settles.',
|
|
434
|
+
'The question needs private data or credentials the run is not allowed to use.',
|
|
435
|
+
],
|
|
436
|
+
variables: [
|
|
437
|
+
{ name: 'question', description: 'The question the report must answer' },
|
|
438
|
+
{ name: 'scope', description: 'Time range, sources to use or skip, and hard constraints' },
|
|
439
|
+
{ name: 'purpose', description: 'The decision this report serves, so the recommendation is concrete' },
|
|
440
|
+
],
|
|
441
|
+
skeleton: [
|
|
442
|
+
'Research the following question and return one evidence-backed report.',
|
|
443
|
+
'',
|
|
444
|
+
'Question:',
|
|
445
|
+
'{{question}}',
|
|
446
|
+
'',
|
|
447
|
+
'Scope and constraints:',
|
|
448
|
+
'{{scope}}',
|
|
449
|
+
'',
|
|
450
|
+
'What the report must serve:',
|
|
451
|
+
'{{purpose}}',
|
|
452
|
+
'',
|
|
453
|
+
'Work in this order:',
|
|
454
|
+
'1. Split the question into the sub-questions that must be answered, and say what evidence would answer each.',
|
|
455
|
+
'2. Gather evidence from primary sources where possible, and record the source and date for every claim.',
|
|
456
|
+
'3. Note where sources disagree or the evidence is thin, instead of picking the convenient answer.',
|
|
457
|
+
'4. Answer the question, then state what remains unknown and what would resolve it.',
|
|
458
|
+
'5. End with the concrete recommendation or next action that the purpose above calls for.',
|
|
459
|
+
'',
|
|
460
|
+
'The final report must stand alone for a reader who has not seen this goal: question, findings with sources,',
|
|
461
|
+
'disagreement and uncertainty, and a recommendation. Use a table for anything that compares more than two',
|
|
462
|
+
'options. Do not invent numbers or citations, and do not present a search plan as a result.',
|
|
463
|
+
].join('\n'),
|
|
464
|
+
})),
|
|
465
|
+
])
|
|
466
|
+
|
|
467
|
+
/** One line per template, for tool output. */
|
|
468
|
+
export function formatTemplateList(result, limit = 50) {
|
|
469
|
+
const templates = result.templates ?? []
|
|
470
|
+
if (templates.length === 0) return `no workflow templates (${result.dir ?? 'template directory not initialized'})`
|
|
471
|
+
const rows = templates.slice(0, limit).map(template => {
|
|
472
|
+
const params = template.variables.map(variable => variable.name).join(', ') || 'none'
|
|
473
|
+
return `${template.id} [${template.source}] ${template.title} (params: ${params})`
|
|
474
|
+
})
|
|
475
|
+
const lines = [
|
|
476
|
+
`${templates.length} template(s): ${result.builtin ?? 0} built-in, ${result.custom ?? 0} custom in ${result.dir}`,
|
|
477
|
+
...rows,
|
|
478
|
+
]
|
|
479
|
+
if (result.bad > 0) {
|
|
480
|
+
lines.push('', `${result.bad} template file(s) were unreadable or invalid and are skipped; `
|
|
481
|
+
+ 'call action="show" on a built-in to see the accepted format')
|
|
482
|
+
}
|
|
483
|
+
return lines.join('\n')
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/** Full definition of one template, including the skeleton. */
|
|
487
|
+
export function formatTemplateDetail(template) {
|
|
488
|
+
const params = template.variables.length > 0
|
|
489
|
+
? template.variables.map(variable => `- ${variable.name}: ${variable.description}`).join('\n')
|
|
490
|
+
: '- none (the skeleton is complete as written)'
|
|
491
|
+
return [
|
|
492
|
+
`${template.id} [${template.source}] — ${template.title}`,
|
|
493
|
+
'',
|
|
494
|
+
`use when: ${template.whenToUse}`,
|
|
495
|
+
'',
|
|
496
|
+
'do not use when:',
|
|
497
|
+
...template.whenNotToUse.map(item => `- ${item}`),
|
|
498
|
+
'',
|
|
499
|
+
'parameters (all required):',
|
|
500
|
+
params,
|
|
501
|
+
'',
|
|
502
|
+
'skeleton:',
|
|
503
|
+
template.skeleton,
|
|
504
|
+
].join('\n')
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/**
|
|
508
|
+
* Template storage under one state root. Built-ins are read from this module;
|
|
509
|
+
* custom templates are JSON files that use the exact same fields.
|
|
510
|
+
*
|
|
511
|
+
* @param {string} root - absolute state directory (`<root>/templates` is used).
|
|
512
|
+
* @param {{ warn?: (message: string) => void }} [options] - diagnostics sink.
|
|
513
|
+
*/
|
|
514
|
+
export function createTemplateStore(root, { warn = () => {} } = {}) {
|
|
515
|
+
const dir = path.join(root, 'templates')
|
|
516
|
+
const fileOf = id => path.join(dir, `${id}.json`)
|
|
517
|
+
|
|
518
|
+
/**
|
|
519
|
+
* Create the directory and keep it out of git even when the state directory
|
|
520
|
+
* sits inside a repository, the same way the memory notebook does.
|
|
521
|
+
*/
|
|
522
|
+
async function initDir() {
|
|
523
|
+
await fsp.mkdir(dir, { recursive: true })
|
|
524
|
+
const ignore = path.join(dir, '.gitignore')
|
|
525
|
+
try {
|
|
526
|
+
await fsp.access(ignore)
|
|
527
|
+
} catch {
|
|
528
|
+
await fsp.writeFile(ignore, '*\n', 'utf8')
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
function builtinOf(id) {
|
|
533
|
+
return BUILTIN_TEMPLATES.find(template => template.id === id) ?? null
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
return {
|
|
537
|
+
root,
|
|
538
|
+
dir,
|
|
539
|
+
fileOf,
|
|
540
|
+
|
|
541
|
+
/** Create the directory and its .gitignore. */
|
|
542
|
+
async init() {
|
|
543
|
+
await initDir()
|
|
544
|
+
},
|
|
545
|
+
|
|
546
|
+
/**
|
|
547
|
+
* Every usable template, built-ins first by id, with its source. A
|
|
548
|
+
* hand-edited file that is corrupt, invalid, or uses a built-in id is
|
|
549
|
+
* skipped and counted instead of taking the whole listing down.
|
|
550
|
+
*
|
|
551
|
+
* @returns {Promise<{ templates: object[], builtin: number, custom: number, bad: number, dir: string }>}
|
|
552
|
+
*/
|
|
553
|
+
async list() {
|
|
554
|
+
const builtins = BUILTIN_TEMPLATES.map(template => ({ ...template, source: 'builtin' }))
|
|
555
|
+
const taken = new Set(builtins.map(template => template.id))
|
|
556
|
+
const custom = []
|
|
557
|
+
let bad = 0
|
|
558
|
+
let names = []
|
|
559
|
+
try {
|
|
560
|
+
names = await fsp.readdir(dir)
|
|
561
|
+
} catch (error) {
|
|
562
|
+
if (error?.code !== 'ENOENT') throw error
|
|
563
|
+
}
|
|
564
|
+
for (const name of names.sort()) {
|
|
565
|
+
if (!name.endsWith('.json') || name.startsWith('.')) continue
|
|
566
|
+
const id = name.slice(0, -'.json'.length)
|
|
567
|
+
if (!ID_PATTERN.test(id)) {
|
|
568
|
+
bad++
|
|
569
|
+
warn(`skipping template file ${name}: the name is not a template id`)
|
|
570
|
+
continue
|
|
571
|
+
}
|
|
572
|
+
let parsed
|
|
573
|
+
try {
|
|
574
|
+
parsed = JSON.parse(await fsp.readFile(fileOf(id), 'utf8'))
|
|
575
|
+
} catch (error) {
|
|
576
|
+
bad++
|
|
577
|
+
warn(`skipping template file ${name}: ${error?.message ?? error}`)
|
|
578
|
+
continue
|
|
579
|
+
}
|
|
580
|
+
const result = validateTemplate(parsed)
|
|
581
|
+
if (!result.ok) {
|
|
582
|
+
bad++
|
|
583
|
+
warn(`skipping template file ${name}: ${result.error.message}`)
|
|
584
|
+
continue
|
|
585
|
+
}
|
|
586
|
+
if (result.template.id !== id) {
|
|
587
|
+
bad++
|
|
588
|
+
warn(`skipping template file ${name}: it defines id "${result.template.id}"`)
|
|
589
|
+
continue
|
|
590
|
+
}
|
|
591
|
+
if (taken.has(id)) {
|
|
592
|
+
bad++
|
|
593
|
+
warn(`skipping template file ${name}: a built-in template already has that id`)
|
|
594
|
+
continue
|
|
595
|
+
}
|
|
596
|
+
custom.push({ ...result.template, source: 'custom' })
|
|
597
|
+
}
|
|
598
|
+
return {
|
|
599
|
+
templates: [...builtins, ...custom].sort((a, b) => a.id.localeCompare(b.id)),
|
|
600
|
+
builtin: builtins.length,
|
|
601
|
+
custom: custom.length,
|
|
602
|
+
bad,
|
|
603
|
+
dir,
|
|
604
|
+
}
|
|
605
|
+
},
|
|
606
|
+
|
|
607
|
+
/**
|
|
608
|
+
* Read one template by id. A built-in id always resolves to the built-in,
|
|
609
|
+
* even if a file with that name exists.
|
|
610
|
+
*
|
|
611
|
+
* @param {string} id - template id.
|
|
612
|
+
* @returns {Promise<object | null>} template with `source`, or null.
|
|
613
|
+
*/
|
|
614
|
+
async get(id) {
|
|
615
|
+
const key = asText(id)
|
|
616
|
+
if (!ID_PATTERN.test(key) || key.length > MAX_ID_CHARS) return null
|
|
617
|
+
const builtin = builtinOf(key)
|
|
618
|
+
if (builtin) return { ...builtin, source: 'builtin' }
|
|
619
|
+
let parsed
|
|
620
|
+
try {
|
|
621
|
+
parsed = JSON.parse(await fsp.readFile(fileOf(key), 'utf8'))
|
|
622
|
+
} catch {
|
|
623
|
+
return null
|
|
624
|
+
}
|
|
625
|
+
const result = validateTemplate(parsed)
|
|
626
|
+
if (!result.ok || result.template.id !== key) return null
|
|
627
|
+
return { ...result.template, source: 'custom' }
|
|
628
|
+
},
|
|
629
|
+
|
|
630
|
+
/**
|
|
631
|
+
* Write a custom template, replacing an earlier file with the same id.
|
|
632
|
+
*
|
|
633
|
+
* @param {unknown} input - full template definition.
|
|
634
|
+
* @returns {Promise<{ id: string, path: string, replaced: boolean }>}
|
|
635
|
+
* @throws {TemplateError} when the definition is invalid or uses a built-in id.
|
|
636
|
+
*/
|
|
637
|
+
async save(input) {
|
|
638
|
+
const result = validateTemplate(input)
|
|
639
|
+
if (!result.ok) throw result.error
|
|
640
|
+
const template = result.template
|
|
641
|
+
if (builtinOf(template.id)) {
|
|
642
|
+
throw new TemplateError(
|
|
643
|
+
'builtin-template',
|
|
644
|
+
`"${template.id}" is a built-in template and cannot be overwritten; save your version under a new id`,
|
|
645
|
+
)
|
|
646
|
+
}
|
|
647
|
+
await initDir()
|
|
648
|
+
const file = fileOf(template.id)
|
|
649
|
+
let replaced = false
|
|
650
|
+
try {
|
|
651
|
+
await fsp.access(file)
|
|
652
|
+
replaced = true
|
|
653
|
+
} catch {
|
|
654
|
+
// A new template, not a replacement.
|
|
655
|
+
}
|
|
656
|
+
const tmp = path.join(dir, `.${template.id}.${process.pid}.${Date.now()}.tmp`)
|
|
657
|
+
await fsp.writeFile(tmp, `${JSON.stringify(template, null, 2)}\n`, 'utf8')
|
|
658
|
+
await fsp.rename(tmp, file)
|
|
659
|
+
return { id: template.id, path: file, replaced }
|
|
660
|
+
},
|
|
661
|
+
|
|
662
|
+
/**
|
|
663
|
+
* Delete a custom template. Built-ins cannot be deleted: removing one would
|
|
664
|
+
* change what every later session sees, and a built-in can always be ignored
|
|
665
|
+
* by not naming it.
|
|
666
|
+
*
|
|
667
|
+
* @param {string} id - template id.
|
|
668
|
+
* @returns {Promise<{ id: string, removed: boolean }>}
|
|
669
|
+
*/
|
|
670
|
+
async remove(id) {
|
|
671
|
+
const key = asText(id)
|
|
672
|
+
if (!ID_PATTERN.test(key) || key.length > MAX_ID_CHARS) {
|
|
673
|
+
throw new TemplateError('unknown-template', `"${id}" is not a template id`)
|
|
674
|
+
}
|
|
675
|
+
if (builtinOf(key)) {
|
|
676
|
+
throw new TemplateError(
|
|
677
|
+
'builtin-template',
|
|
678
|
+
`"${key}" is a built-in template and cannot be deleted; create a custom template instead`,
|
|
679
|
+
)
|
|
680
|
+
}
|
|
681
|
+
try {
|
|
682
|
+
await fsp.unlink(fileOf(key))
|
|
683
|
+
return { id: key, removed: true }
|
|
684
|
+
} catch (error) {
|
|
685
|
+
if (error?.code === 'ENOENT') return { id: key, removed: false }
|
|
686
|
+
throw error
|
|
687
|
+
}
|
|
688
|
+
},
|
|
689
|
+
}
|
|
690
|
+
}
|