project-brain 0.44.0 → 0.45.1

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.
@@ -0,0 +1,300 @@
1
+ import type { Hook, Register } from 'claude-code'
2
+
3
+ import type { Listing, ListingEntry, ListingMode, SkillsConfig, SkillUsage } from '../types'
4
+
5
+ type Api = Parameters<Hook<'prompt.attachment'>>[0]
6
+
7
+ const DAY_MS = 24 * 60 * 60_000
8
+ const USAGE_REFRESH_TIMEOUT_MS = 120_000
9
+ /** Past the CLI's own 5 s self-timeout, so it is the CLI that gives up and the delegation goes out unchanged. */
10
+ const DELEGATION_TIMEOUT_MS = 6_000
11
+
12
+ export const DEFAULT_CONFIG: SkillsConfig = { picker: true, general: [], keepTop: 15, keepRecentDays: 7 }
13
+
14
+ export const OTHER_SKILLS_PREFIX = '- Other skills (name only; invoke by name when one fits the request): '
15
+
16
+ /**
17
+ * `- name: description`, `- name (alias): description` or `- name`. Names carry no spaces, so the
18
+ * first `: ` ends the name even in `plugin:skill`.
19
+ */
20
+ const ENTRY = /^- (\S+?)(?:: | \(\S+\)(?:: |$)|$)/
21
+
22
+ /** The listing's skills in order, each with its continuation lines; null when the text holds none. */
23
+ export function parseListing(text: string): Listing | null {
24
+ const preamble: string[] = []
25
+ const entries: ListingEntry[] = []
26
+ for (const line of text.split('\n')) {
27
+ const name = ENTRY.exec(line)?.[1]
28
+ if (name !== undefined) entries.push({ name, lines: [line] })
29
+ else if (entries.length === 0) preamble.push(line)
30
+ else entries[entries.length - 1]!.lines.push(line)
31
+ }
32
+ return entries.length === 0 ? null : { preamble, entries }
33
+ }
34
+
35
+ /**
36
+ * Full lines for the skills in `keep`, in their original order, then every other name on one
37
+ * trailing line. Every name survives; the text comes back unchanged when nothing would be cut.
38
+ */
39
+ export function compactListing(text: string, keep: ReadonlySet<string>): string {
40
+ const listing = parseListing(text)
41
+ if (listing === null) return text
42
+ const kept = listing.entries.filter(entry => keep.has(entry.name))
43
+ const named = listing.entries.filter(entry => !keep.has(entry.name)).map(entry => entry.name)
44
+ if (named.length === 0) return text
45
+ const trailing = (lines: string[]) => {
46
+ let end = lines.length
47
+ while (end > 0 && lines[end - 1]!.trim() === '') end--
48
+ return lines.slice(0, end)
49
+ }
50
+ return [
51
+ ...listing.preamble,
52
+ ...kept.flatMap(entry => trailing(entry.lines)),
53
+ `${OTHER_SKILLS_PREFIX}${named.join(', ')}`,
54
+ ].join('\n')
55
+ }
56
+
57
+ /**
58
+ * The skills that keep their full line. With the Jev picker, only the general-use ones: the picker
59
+ * brings each prompt's skills in full. Without it, also the `brain-*` core, the most used and the
60
+ * recently used, counted only among `listed` so a slash command like `/clear` never takes a slot.
61
+ */
62
+ export function keepSet(listed: string[], mode: ListingMode, config: SkillsConfig, usage: SkillUsage | null, now: number): Set<string> {
63
+ const names = new Set(listed)
64
+ const general = config.general.filter(name => names.has(name))
65
+ if (mode === 'jev' || usage === null) return new Set(general)
66
+ const used = Object.entries(usage.skills).filter(([name]) => names.has(name))
67
+ const top = [...used].sort((a, b) => b[1].count - a[1].count || b[1].lastUsed - a[1].lastUsed).slice(0, config.keepTop)
68
+ const recentSince = now - config.keepRecentDays * DAY_MS
69
+ return new Set([
70
+ ...general,
71
+ ...listed.filter(name => name.startsWith('brain-')),
72
+ ...top.map(([name]) => name),
73
+ ...used.filter(([, entry]) => entry.lastUsed >= recentSince).map(([name]) => name),
74
+ ])
75
+ }
76
+
77
+ const isObject = (value: unknown): value is Record<string, unknown> =>
78
+ typeof value === 'object' && value !== null && !Array.isArray(value)
79
+
80
+ const positiveInt = (value: unknown, fallback: number): number =>
81
+ typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : fallback
82
+
83
+ export function parseConfig(text: string): SkillsConfig {
84
+ try {
85
+ const raw: unknown = JSON.parse(text)
86
+ if (!isObject(raw)) return DEFAULT_CONFIG
87
+ return {
88
+ picker: typeof raw.picker === 'boolean' ? raw.picker : DEFAULT_CONFIG.picker,
89
+ general: Array.isArray(raw.general) ? raw.general.filter((name): name is string => typeof name === 'string') : [],
90
+ keepTop: positiveInt(raw.keepTop, DEFAULT_CONFIG.keepTop),
91
+ keepRecentDays: positiveInt(raw.keepRecentDays, DEFAULT_CONFIG.keepRecentDays),
92
+ }
93
+ } catch {
94
+ return DEFAULT_CONFIG
95
+ }
96
+ }
97
+
98
+ /** Fewer recorded invocations than this rank nothing: the listing passes through until there is history. */
99
+ export const MIN_USAGE_INVOCATIONS = 10
100
+
101
+ export function parseUsage(text: string): SkillUsage | null {
102
+ try {
103
+ const raw: unknown = JSON.parse(text)
104
+ if (!isObject(raw) || typeof raw.generatedAt !== 'number' || !isObject(raw.skills)) return null
105
+ const usage = raw as SkillUsage
106
+ const total = Object.values(usage.skills).reduce((sum, entry) => sum + (typeof entry?.count === 'number' ? entry.count : 0), 0)
107
+ return total >= MIN_USAGE_INVOCATIONS ? usage : null
108
+ } catch {
109
+ return null
110
+ }
111
+ }
112
+
113
+ /** After this many Jev failures in a row the listing keeps descriptions until a pick succeeds again. */
114
+ export const MAX_PICK_FAILURES = 3
115
+
116
+ /** `~/.project-brain/skill-pick-health.json`, written by the suggest CLI after every Jev request it makes. */
117
+ export function picksHealthy(text: string): boolean {
118
+ try {
119
+ const raw: unknown = JSON.parse(text)
120
+ return !isObject(raw) || typeof raw.failures !== 'number' || raw.failures < MAX_PICK_FAILURES
121
+ } catch {
122
+ return true
123
+ }
124
+ }
125
+
126
+ /** A token worth trying: one non-empty string with no whitespace, read from the env or from `{ "token": … }`. */
127
+ export function tokenShaped(envToken: string | undefined, fileText: string): boolean {
128
+ const shaped = (value: unknown) => typeof value === 'string' && /^\S{8,}$/.test(value)
129
+ if (shaped(envToken)) return true
130
+ try {
131
+ const raw: unknown = JSON.parse(fileText)
132
+ return isObject(raw) && shaped(raw.token)
133
+ } catch {
134
+ return false
135
+ }
136
+ }
137
+
138
+ /** Whether Claude Code would run the suggest hook: installed under UserPromptSubmit, and hooks not disabled. */
139
+ export function suggestHookActive(settingsText: string): boolean {
140
+ try {
141
+ const raw: unknown = JSON.parse(settingsText)
142
+ if (!isObject(raw) || raw.disableAllHooks === true || !isObject(raw.hooks)) return false
143
+ const groups = raw.hooks.UserPromptSubmit
144
+ if (!Array.isArray(groups)) return false
145
+ return groups.some(group =>
146
+ isObject(group) && Array.isArray(group.hooks) && group.hooks.some(hook => isObject(hook) && typeof hook.command === 'string' && hook.command.includes('project-brain suggest')))
147
+ } catch {
148
+ return false
149
+ }
150
+ }
151
+
152
+ /**
153
+ * The listing for one attachment. `stats` without usage numbers passes the text through: cutting
154
+ * descriptions with nothing to rank them by would hide the skills the owner relies on.
155
+ */
156
+ export function rewriteListing(text: string, mode: ListingMode, config: SkillsConfig, usage: SkillUsage | null, now: number): string {
157
+ if (mode === 'stats' && usage === null) return text
158
+ const listing = parseListing(text)
159
+ if (listing === null) return text
160
+ return compactListing(text, keepSet(listing.entries.map(entry => entry.name), mode, config, usage, now))
161
+ }
162
+
163
+ const ENTRY_HEAD = /^- \S+?(?: \(\S+\))?(?:: |$)/
164
+
165
+ /**
166
+ * Each listed skill's description, as Claude Code worded it. The picker reads them from
167
+ * `skill-listing.json` so built-in and connector skills, which have no SKILL.md on disk, can be picked too.
168
+ */
169
+ export function listedDescriptions(text: string): Record<string, string> {
170
+ const listing = parseListing(text)
171
+ if (listing === null) return {}
172
+ return Object.fromEntries(
173
+ listing.entries.map(entry => {
174
+ const [head = '', ...rest] = entry.lines
175
+ return [entry.name, [head.replace(ENTRY_HEAD, ''), ...rest].join('\n').trim()]
176
+ })
177
+ )
178
+ }
179
+
180
+ async function readOr($: Api, path: string, fallback: string): Promise<string> {
181
+ try {
182
+ return await $.fs.read(path)
183
+ } catch {
184
+ return fallback
185
+ }
186
+ }
187
+
188
+ /** Jev can pick skills: on in config and env, a token of the right shape, and no run of recent failures. */
189
+ async function pickerReady($: Api, config: SkillsConfig, home: string): Promise<boolean> {
190
+ if (!config.picker || (await $.env.get('BRAIN_SKILL_PICKER')) === '0') return false
191
+ const fileToken = await readOr($, `${home}/.project-brain/reranker.json`, '')
192
+ if (!tokenShaped(await $.env.get('TYPESAFE_API_KEY'), fileToken)) return false
193
+ return picksHealthy(await readOr($, `${home}/.project-brain/skill-pick-health.json`, ''))
194
+ }
195
+
196
+ /** Subagents whose spawn carried a skills block, and the spawns still resolving their ids. */
197
+ const pickedAgents = new Set<string>()
198
+ const pendingSpawns = new Set<Promise<unknown>>()
199
+ /** How long a subagent's listing waits for its own spawn to report its id before falling back to `stats`. */
200
+ const SPAWN_WAIT_MS = 1_500
201
+
202
+ async function spawnCarriedSkills($: Api, agentId: string): Promise<boolean> {
203
+ if (pickedAgents.has(agentId)) return true
204
+ if (pendingSpawns.size === 0) return false
205
+ await Promise.race([Promise.allSettled([...pendingSpawns]), $.clock.sleep(SPAWN_WAIT_MS)])
206
+ return pickedAgents.has(agentId)
207
+ }
208
+
209
+ /**
210
+ * `jev` when something brings this loop's skills back in full: on the main loop the suggest hook,
211
+ * per prompt; in a subagent the skills block its spawn carried. Anything else keeps descriptions.
212
+ */
213
+ async function modeOf($: Api, config: SkillsConfig, home: string, agentId: string | undefined): Promise<ListingMode> {
214
+ if (!(await pickerReady($, config, home))) return 'stats'
215
+ if (agentId !== undefined) return (await spawnCarriedSkills($, agentId)) ? 'jev' : 'stats'
216
+ const claudeDir = (await $.env.get('CLAUDE_CONFIG_DIR')) || `${home}/.claude`
217
+ return suggestHookActive(await readOr($, `${claudeDir}/settings.json`, '')) ? 'jev' : 'stats'
218
+ }
219
+
220
+ async function rememberDescriptions($: Api, home: string, text: string, now: number): Promise<void> {
221
+ const path = `${home}/.project-brain/skill-listing.json`
222
+ let known: Record<string, string> = {}
223
+ try {
224
+ const raw: unknown = JSON.parse(await readOr($, path, '{}'))
225
+ if (isObject(raw) && isObject(raw.skills)) known = raw.skills as Record<string, string>
226
+ } catch {
227
+ // Unreadable: rebuilt from this listing.
228
+ }
229
+ const merged = { ...known, ...listedDescriptions(text) }
230
+ if (JSON.stringify(merged) === JSON.stringify(known)) return
231
+ await $.fs.write(path, `${JSON.stringify({ updatedAt: now, skills: merged }, null, 2)}\n`)
232
+ }
233
+
234
+ async function compactAttachment($: Api, text: string, agentId: string | undefined): Promise<string> {
235
+ const home = await $.env.get('HOME')
236
+ if (!home) return text
237
+ const now = await $.clock.now()
238
+ await rememberDescriptions($, home, text, now).catch(() => undefined)
239
+ const config = parseConfig(await readOr($, `${home}/.project-brain/skills.json`, ''))
240
+ const usage = parseUsage(await readOr($, `${home}/.project-brain/skill-usage.json`, ''))
241
+ return rewriteListing(text, await modeOf($, config, home, agentId), config, usage, now)
242
+ }
243
+
244
+ /**
245
+ * The skills block goes first, so a delegation that ends with its own output contract still ends
246
+ * with it; the prompt comes back unchanged when nothing was picked or anything failed.
247
+ */
248
+ export const withDelegationSkills = (prompt: string, block: string): string =>
249
+ block.trim() === '' ? prompt : `${block.trim()}\n\n${prompt}`
250
+
251
+ /** The CLI owns the pick (one Jev request, the same floor and ceiling as the prompt hook); the mod only carries its answer. */
252
+ async function delegationSkills($: Api, prompt: string, description: string): Promise<string> {
253
+ const home = await $.env.get('HOME')
254
+ if (!home) return ''
255
+ const config = parseConfig(await readOr($, `${home}/.project-brain/skills.json`, ''))
256
+ if (!(await pickerReady($, config, home))) return ''
257
+ const { exitCode, stdout } = await $.process.run(['project-brain', 'suggest', '--agent', '--stdin'], {
258
+ stdin: JSON.stringify({ prompt, description }),
259
+ timeoutMs: DELEGATION_TIMEOUT_MS,
260
+ })
261
+ return exitCode === 0 ? stdout : ''
262
+ }
263
+
264
+ /** Daily at most: the CLI skips a file under a day old, and a second session waits on the first one's lock. */
265
+ async function refreshUsage($: Api): Promise<void> {
266
+ await $.process.run(['project-brain', 'skill-usage', '--write', '--if-stale'], { timeoutMs: USAGE_REFRESH_TIMEOUT_MS })
267
+ }
268
+
269
+ export const register: Register = on => {
270
+ on('session.start', async ($, e, next) => {
271
+ void refreshUsage($ as unknown as Api).catch(() => undefined)
272
+ return next(e)
273
+ })
274
+
275
+ on('prompt.attachment', { type: 'skill_listing' }, async ($, e, next) => {
276
+ if (e.origin.kind !== 'engine') return next(e)
277
+ try {
278
+ return next({ ...e, text: await compactAttachment($, e.text, e.agentId) })
279
+ } catch {
280
+ return next(e)
281
+ }
282
+ })
283
+
284
+ on('agent.spawn', async ($, e, next) => {
285
+ let block = ''
286
+ try {
287
+ block = (await delegationSkills($ as unknown as Api, e.prompt, e.description)).trim()
288
+ } catch {
289
+ block = ''
290
+ }
291
+ const spawning = next(block === '' ? e : { ...e, prompt: withDelegationSkills(e.prompt, block) })
292
+ if (block === '') return spawning
293
+ const tracked = spawning.then(spawned => {
294
+ if (spawned.agentId !== undefined) pickedAgents.add(spawned.agentId)
295
+ })
296
+ pendingSpawns.add(tracked)
297
+ void tracked.catch(() => undefined).finally(() => pendingSpawns.delete(tracked))
298
+ return spawning
299
+ }).catch(($, e, next) => next(e))
300
+ }
@@ -0,0 +1,22 @@
1
+ /** `~/.project-brain/skill-usage.json`, written by `project-brain skill-usage --write`. */
2
+ export type SkillUsage = {
3
+ generatedAt: number
4
+ windowDays: number
5
+ skills: Record<string, { count: number; lastUsed: number }>
6
+ }
7
+
8
+ /** `~/.project-brain/skills.json`, shared with the suggest hook's skill picker. */
9
+ export type SkillsConfig = {
10
+ picker: boolean
11
+ general: string[]
12
+ keepTop: number
13
+ keepRecentDays: number
14
+ }
15
+
16
+ /** One skill of the listing: its first line and any continuation lines of its description. */
17
+ export type ListingEntry = { name: string; lines: string[] }
18
+
19
+ export type Listing = { preamble: string[]; entries: ListingEntry[] }
20
+
21
+ /** `jev`: the per-prompt picker supplies descriptions. `stats`: the most-used skills keep theirs. */
22
+ export type ListingMode = 'jev' | 'stats'
@@ -25,6 +25,16 @@ cheaper inline. Delegate when the work is 4+ files of exploration, or any
25
25
  read-then-write pair where the reading would otherwise land in your context and
26
26
  stay there.
27
27
 
28
+ ### Close every delegation with the report contract
29
+
30
+ A sub-agent's hand-back stays in your context until it compacts, so ask for a
31
+ short one and keep the detail on disk. End the delegation prompt with this
32
+ block, unless the prompt already sets its own output format (JSON, a schema):
33
+
34
+ ```
35
+ {{reportContract}}
36
+ ```
37
+
28
38
  ### Escalate, don't start deep
29
39
 
30
40
  Run the cheapest tier the task table allows. On a failed or empty result,