project-brain 0.43.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.
- package/README.md +97 -11
- package/package.json +6 -6
- package/templates/claude-tui/activity-pane/.claude-plugin/plugin.json +7 -0
- package/templates/claude-tui/activity-pane/hooks/feat-agents.tsx +179 -0
- package/templates/claude-tui/activity-pane/hooks/feat-blocked.tsx +232 -0
- package/templates/claude-tui/activity-pane/hooks/feat-ci.tsx +400 -0
- package/templates/claude-tui/activity-pane/hooks/feat-context.tsx +283 -0
- package/templates/claude-tui/activity-pane/hooks/feat-notify.tsx +145 -0
- package/templates/claude-tui/activity-pane/hooks/feat-progress.tsx +413 -0
- package/templates/claude-tui/activity-pane/hooks/feat-running.tsx +528 -0
- package/templates/claude-tui/activity-pane/hooks/feat-savings.tsx +533 -0
- package/templates/claude-tui/activity-pane/hooks/hooks.json +1 -0
- package/templates/claude-tui/activity-pane/hooks/register.tsx +2141 -0
- package/templates/claude-tui/activity-pane/types/index.d.ts +201 -0
- package/templates/claude-tui/context-gate/.claude-plugin/plugin.json +7 -0
- package/templates/claude-tui/context-gate/hooks/hooks.json +1 -0
- package/templates/claude-tui/context-gate/hooks/register.tsx +355 -0
- package/templates/claude-tui/context-gate/types/index.d.ts +28 -0
- package/templates/claude-tui/skill-listing/.claude-plugin/plugin.json +7 -0
- package/templates/claude-tui/skill-listing/hooks/hooks.json +1 -0
- package/templates/claude-tui/skill-listing/hooks/register.tsx +300 -0
- package/templates/claude-tui/skill-listing/types/index.d.ts +22 -0
- package/templates/model-routing.md +10 -0
- package/templates/skills/brain-design-review/SKILL.md +65 -0
- package/templates/skills/brain-design-review/references/audit.md +56 -0
- package/templates/skills/brain-design-review/references/fix-loop.md +36 -0
- package/templates/skills/brain-design-review/references/probes.md +80 -0
- package/templates/skills/brain-qa-only/SKILL.md +59 -0
- package/templates/skills/brain-qa-only/references/report.md +63 -0
- package/templates/skills/brain-worktree/SKILL.md +18 -0
|
@@ -0,0 +1,533 @@
|
|
|
1
|
+
import type { Hook } from 'claude-code'
|
|
2
|
+
import { atom, read, update } from 'claude-code'
|
|
3
|
+
|
|
4
|
+
import type { Api, Row, Span, Tone } from './register'
|
|
5
|
+
import { clean, compact, fit, span } from './register'
|
|
6
|
+
|
|
7
|
+
/** One piece the context gate kept out of this session. */
|
|
8
|
+
export type GateDrop = { at: number; event: string; chars: number; score?: number; head: string }
|
|
9
|
+
export type GateSummary = { count: number; chars: number; last: GateDrop[] }
|
|
10
|
+
|
|
11
|
+
export type PromptPick = { at: number; skills: string[] }
|
|
12
|
+
export type DelegationPick = { agentId: string; description: string; skills: string[] }
|
|
13
|
+
export type SkillPicks = { prompts: PromptPick[]; delegations: DelegationPick[] }
|
|
14
|
+
|
|
15
|
+
export type ListingMode = 'jev' | 'stats' | 'passthrough'
|
|
16
|
+
export type LaneState = 'up' | 'mismatch' | 'dead' | 'pending' | 'off'
|
|
17
|
+
export type LaneView = { state: LaneState; reason?: string; at?: number }
|
|
18
|
+
|
|
19
|
+
/** What each project-brain filter did this session; an absent part draws as "—". */
|
|
20
|
+
export type SavingsState = {
|
|
21
|
+
at: number
|
|
22
|
+
gate?: GateSummary
|
|
23
|
+
picks?: SkillPicks
|
|
24
|
+
listing?: ListingMode
|
|
25
|
+
lane?: LaneView
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export type SavingsPart = SavingsState & { now: number }
|
|
29
|
+
|
|
30
|
+
/** A delegation the live transcript still holds, before its subagent's skills block is read. */
|
|
31
|
+
export type LiveDelegation = { agentId: string; description: string; prompt?: string }
|
|
32
|
+
|
|
33
|
+
/** One transcript entry still in the live conversation, oldest first. */
|
|
34
|
+
export type LiveEntry = Record<string, unknown>
|
|
35
|
+
|
|
36
|
+
const SECTION_KEY = 'savings-section'
|
|
37
|
+
const GATE_LAST = 3
|
|
38
|
+
const PROMPTS_SHOWN = 5
|
|
39
|
+
const DELEGATIONS_SHOWN = 5
|
|
40
|
+
/** Below the engine's 4 MiB stdout cap, so the tail always arrives whole. */
|
|
41
|
+
const TRANSCRIPT_TAIL_BYTES = 3 * 1024 * 1024
|
|
42
|
+
/** The skills block opens the subagent's first message, so its first line's head holds it. */
|
|
43
|
+
const SUBAGENT_HEAD_BYTES = 32 * 1024
|
|
44
|
+
const MAX_PICK_FAILURES = 3
|
|
45
|
+
const MIN_USAGE_INVOCATIONS = 10
|
|
46
|
+
|
|
47
|
+
export const LISTING_PLUGIN_KEY = 'project-brain-skill-listing@project-brain'
|
|
48
|
+
export const DELEGATION_SKILLS_HEADING = 'Skills for this task, picked for it (load one with the Skill tool when you reach the part it covers):'
|
|
49
|
+
const SKILL_LINE = /^Suggested skill: (\S+) — /
|
|
50
|
+
const LANE_OFF_VALUES = new Set(['off', 'none', 'false', '0', 'disabled'])
|
|
51
|
+
|
|
52
|
+
const EMPTY: SavingsState = { at: 0 }
|
|
53
|
+
|
|
54
|
+
const savingsAtom = atom({ plugin: 'project-brain-activity', key: 'savings' } as const, EMPTY, { shape: 'savings-1' })
|
|
55
|
+
|
|
56
|
+
// A reload resets these: it only costs one extra read of each source.
|
|
57
|
+
let refreshing: Promise<void> | undefined
|
|
58
|
+
let transcriptSeen: { path: string; mtimeMs: number; size: number } | undefined
|
|
59
|
+
const subagentSkills = new Map<string, string[]>()
|
|
60
|
+
|
|
61
|
+
const isObject = (value: unknown): value is Record<string, unknown> =>
|
|
62
|
+
typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
63
|
+
|
|
64
|
+
const parseJson = (text: string): unknown => {
|
|
65
|
+
try {
|
|
66
|
+
return JSON.parse(text)
|
|
67
|
+
} catch {
|
|
68
|
+
return undefined
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// ---------------------------------------------------------------- context gate
|
|
73
|
+
|
|
74
|
+
/** This session's drops from `context-gate-log.json`: how many, their characters, and the newest few. */
|
|
75
|
+
export const gateSummaryOf = (text: string, sessionId: string, keep = GATE_LAST): GateSummary | undefined => {
|
|
76
|
+
const raw = parseJson(text)
|
|
77
|
+
if (!isObject(raw) || !Array.isArray(raw.dropped)) return undefined
|
|
78
|
+
const mine: GateDrop[] = []
|
|
79
|
+
for (const entry of raw.dropped) {
|
|
80
|
+
if (!isObject(entry) || entry.session !== sessionId) continue
|
|
81
|
+
const drop: GateDrop = {
|
|
82
|
+
at: typeof entry.at === 'number' ? entry.at : 0,
|
|
83
|
+
event: typeof entry.event === 'string' ? clean(entry.event).slice(0, 40) : '',
|
|
84
|
+
chars: typeof entry.chars === 'number' && entry.chars > 0 ? entry.chars : 0,
|
|
85
|
+
head: typeof entry.head === 'string' ? clean(entry.head).replace(/\s+/g, ' ').trim().slice(0, 160) : '',
|
|
86
|
+
}
|
|
87
|
+
if (typeof entry.score === 'number') drop.score = entry.score
|
|
88
|
+
mine.push(drop)
|
|
89
|
+
}
|
|
90
|
+
const ordered = [...mine].sort((a, b) => a.at - b.at)
|
|
91
|
+
return { count: mine.length, chars: mine.reduce((sum, one) => sum + one.chars, 0), last: ordered.slice(-keep).reverse() }
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// ---------------------------------------------------------------- skill picks
|
|
95
|
+
|
|
96
|
+
/** Skill names on `Suggested skill: <name> — …` lines, in order, each once. */
|
|
97
|
+
export const skillNamesIn = (text: string): string[] => {
|
|
98
|
+
const names: string[] = []
|
|
99
|
+
for (const line of text.split('\n')) {
|
|
100
|
+
const name = SKILL_LINE.exec(line.trim())?.[1]
|
|
101
|
+
if (name !== undefined && !names.includes(name)) names.push(name)
|
|
102
|
+
}
|
|
103
|
+
return names
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** The skills block a delegation's prompt opens with: the heading, then its consecutive skill lines. */
|
|
107
|
+
export const delegationSkillsIn = (text: string): string[] => {
|
|
108
|
+
const at = text.indexOf(DELEGATION_SKILLS_HEADING)
|
|
109
|
+
if (at < 0) return []
|
|
110
|
+
const names: string[] = []
|
|
111
|
+
for (const line of text.slice(at + DELEGATION_SKILLS_HEADING.length).split('\n').slice(1)) {
|
|
112
|
+
const name = SKILL_LINE.exec(line.trim())?.[1]
|
|
113
|
+
if (name === undefined) break
|
|
114
|
+
if (!names.includes(name)) names.push(name)
|
|
115
|
+
}
|
|
116
|
+
return names
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* The entries still in the live conversation: the `parentUuid` chain walked back from the newest
|
|
121
|
+
* entry, the same walk the suggest hook makes. A compaction boundary has no parent, so it stops there.
|
|
122
|
+
*/
|
|
123
|
+
export const liveEntriesOf = (tail: string): LiveEntry[] => {
|
|
124
|
+
const byId = new Map<string, LiveEntry>()
|
|
125
|
+
let leaf: string | undefined
|
|
126
|
+
for (const line of tail.split('\n')) {
|
|
127
|
+
if (!line.slice(0, 200).includes('"parentUuid"')) continue
|
|
128
|
+
const entry = parseJson(line)
|
|
129
|
+
if (!isObject(entry) || typeof entry.uuid !== 'string') continue
|
|
130
|
+
byId.set(entry.uuid, entry)
|
|
131
|
+
leaf = entry.uuid
|
|
132
|
+
}
|
|
133
|
+
const chain: LiveEntry[] = []
|
|
134
|
+
const seen = new Set<string>()
|
|
135
|
+
for (let id = leaf; id !== undefined && !seen.has(id); ) {
|
|
136
|
+
const entry = byId.get(id)
|
|
137
|
+
if (entry === undefined) break
|
|
138
|
+
seen.add(id)
|
|
139
|
+
chain.push(entry)
|
|
140
|
+
id = typeof entry.parentUuid === 'string' ? entry.parentUuid : undefined
|
|
141
|
+
}
|
|
142
|
+
return chain.reverse()
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** A hook's printed output: plain lines, or the JSON document whose `additionalContext` carries them. */
|
|
146
|
+
const hookTextsOf = (attachment: Record<string, unknown>): string[] => {
|
|
147
|
+
const values = [attachment.stdout, ...(Array.isArray(attachment.content) ? attachment.content : [attachment.content])]
|
|
148
|
+
const texts: string[] = []
|
|
149
|
+
for (const value of values) {
|
|
150
|
+
if (typeof value !== 'string') continue
|
|
151
|
+
texts.push(value)
|
|
152
|
+
if (!value.trimStart().startsWith('{')) continue
|
|
153
|
+
const doc = parseJson(value)
|
|
154
|
+
const context = isObject(doc) && isObject(doc.hookSpecificOutput) ? doc.hookSpecificOutput.additionalContext : undefined
|
|
155
|
+
if (typeof context === 'string') texts.push(context)
|
|
156
|
+
}
|
|
157
|
+
return texts
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const timeOf = (entry: LiveEntry): number => {
|
|
161
|
+
const parsed = typeof entry.timestamp === 'string' ? Date.parse(entry.timestamp) : NaN
|
|
162
|
+
return Number.isFinite(parsed) ? parsed : 0
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** The skills each prompt's suggest hook injected, one record per prompt that got any. */
|
|
166
|
+
export const promptPicksOf = (entries: LiveEntry[]): PromptPick[] => {
|
|
167
|
+
const picks: PromptPick[] = []
|
|
168
|
+
for (const entry of entries) {
|
|
169
|
+
if (entry.type !== 'attachment' || !isObject(entry.attachment) || entry.attachment.hookEvent !== 'UserPromptSubmit') continue
|
|
170
|
+
const skills = skillNamesIn(hookTextsOf(entry.attachment).join('\n'))
|
|
171
|
+
if (skills.length > 0) picks.push({ at: timeOf(entry), skills })
|
|
172
|
+
}
|
|
173
|
+
return picks
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Every delegation whose result the live conversation still holds, by its subagent's id. */
|
|
177
|
+
export const delegationsOf = (entries: LiveEntry[]): LiveDelegation[] => {
|
|
178
|
+
const found = new Map<string, LiveDelegation>()
|
|
179
|
+
for (const entry of entries) {
|
|
180
|
+
const result = entry.toolUseResult
|
|
181
|
+
if (!isObject(result) || typeof result.agentId !== 'string' || !/^[A-Za-z0-9_-]{1,64}$/.test(result.agentId)) continue
|
|
182
|
+
const delegation: LiveDelegation = {
|
|
183
|
+
agentId: result.agentId,
|
|
184
|
+
description: typeof result.description === 'string' ? clean(result.description).slice(0, 80) : '',
|
|
185
|
+
}
|
|
186
|
+
if (typeof result.prompt === 'string') delegation.prompt = result.prompt
|
|
187
|
+
found.set(result.agentId, delegation)
|
|
188
|
+
}
|
|
189
|
+
return [...found.values()]
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** The skills block in the head of a subagent transcript, whose first line may arrive cut short. */
|
|
193
|
+
export const subagentSkillsOf = (head: string): string[] => {
|
|
194
|
+
const first = head.split('\n')[0] ?? ''
|
|
195
|
+
const entry = parseJson(first)
|
|
196
|
+
if (isObject(entry) && isObject(entry.message)) {
|
|
197
|
+
const content = entry.message.content
|
|
198
|
+
const text = typeof content === 'string'
|
|
199
|
+
? content
|
|
200
|
+
: Array.isArray(content) ? content.map(part => (isObject(part) && typeof part.text === 'string' ? part.text : '')).join('\n') : ''
|
|
201
|
+
return delegationSkillsIn(text)
|
|
202
|
+
}
|
|
203
|
+
return delegationSkillsIn(first.replace(/\\n/g, '\n').replace(/\\"/g, '"'))
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// ---------------------------------------------------------------- skill listing
|
|
207
|
+
|
|
208
|
+
export type ListingInputs = {
|
|
209
|
+
settings: string
|
|
210
|
+
skills: string
|
|
211
|
+
health: string
|
|
212
|
+
reranker: string
|
|
213
|
+
usage: string
|
|
214
|
+
envToken?: string
|
|
215
|
+
envPicker?: string
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const pluginEnabled = (settings: unknown, key: string): boolean =>
|
|
219
|
+
isObject(settings) && isObject(settings.enabledPlugins) && settings.enabledPlugins[key] === true
|
|
220
|
+
|
|
221
|
+
const suggestHookActive = (settings: unknown): boolean => {
|
|
222
|
+
if (!isObject(settings) || settings.disableAllHooks === true || !isObject(settings.hooks)) return false
|
|
223
|
+
const groups = settings.hooks.UserPromptSubmit
|
|
224
|
+
return Array.isArray(groups) && groups.some(group =>
|
|
225
|
+
isObject(group) && Array.isArray(group.hooks) && group.hooks.some(hook => isObject(hook) && typeof hook.command === 'string' && hook.command.includes('project-brain suggest')))
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
const tokenShaped = (envToken: string | undefined, fileText: string): boolean => {
|
|
229
|
+
const shaped = (value: unknown) => typeof value === 'string' && /^\S{8,}$/.test(value)
|
|
230
|
+
if (shaped(envToken)) return true
|
|
231
|
+
const raw = parseJson(fileText)
|
|
232
|
+
return isObject(raw) && shaped(raw.token)
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const picksHealthy = (text: string): boolean => {
|
|
236
|
+
const raw = parseJson(text)
|
|
237
|
+
return !isObject(raw) || typeof raw.failures !== 'number' || raw.failures < MAX_PICK_FAILURES
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const usageRanks = (text: string): boolean => {
|
|
241
|
+
const raw = parseJson(text)
|
|
242
|
+
if (!isObject(raw) || typeof raw.generatedAt !== 'number' || !isObject(raw.skills)) return false
|
|
243
|
+
const total = Object.values(raw.skills).reduce<number>((sum, entry) => sum + (isObject(entry) && typeof entry.count === 'number' ? entry.count : 0), 0)
|
|
244
|
+
return total >= MIN_USAGE_INVOCATIONS
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* The main loop's listing mode, from the inputs the skill-listing mod reads: `jev` when the picker is
|
|
249
|
+
* ready and the suggest hook installed; else `stats`, which passes the listing through until
|
|
250
|
+
* `skill-usage.json` has enough history to rank by. Undefined when the mod is not enabled.
|
|
251
|
+
*/
|
|
252
|
+
export const listingModeOf = (inputs: ListingInputs): ListingMode | undefined => {
|
|
253
|
+
const settings = parseJson(inputs.settings)
|
|
254
|
+
if (!pluginEnabled(settings, LISTING_PLUGIN_KEY)) return undefined
|
|
255
|
+
const config = parseJson(inputs.skills)
|
|
256
|
+
const pickerOn = !(isObject(config) && config.picker === false) && inputs.envPicker !== '0'
|
|
257
|
+
const ready = pickerOn && tokenShaped(inputs.envToken, inputs.reranker) && picksHealthy(inputs.health)
|
|
258
|
+
if (ready && suggestHookActive(settings)) return 'jev'
|
|
259
|
+
return usageRanks(inputs.usage) ? 'stats' : 'passthrough'
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// ---------------------------------------------------------------- interactive lane
|
|
263
|
+
|
|
264
|
+
/** The configured interactive host, without trailing slashes; undefined when the lane is off. */
|
|
265
|
+
export const interactiveHostOf = (configText: string): string | undefined => {
|
|
266
|
+
const raw = parseJson(configText)
|
|
267
|
+
const value = isObject(raw) && typeof raw.interactiveHost === 'string' ? raw.interactiveHost.trim() : ''
|
|
268
|
+
if (value === '' || LANE_OFF_VALUES.has(value.toLowerCase())) return undefined
|
|
269
|
+
return value.replace(/\/+$/, '')
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** The verdict file prefix `lane.ts` writes for a host: `<slug(host)>__<slug(model)>.json`. */
|
|
273
|
+
export const laneFilePrefix = (host: string): string => `${host.replace(/[^a-z0-9]+/gi, '_')}__`
|
|
274
|
+
|
|
275
|
+
/** The newest verdict for the configured host; off without a host, undefined while none was written. */
|
|
276
|
+
export const laneOf = (configText: string, verdicts: { name: string; text: string }[]): LaneView | undefined => {
|
|
277
|
+
const host = interactiveHostOf(configText)
|
|
278
|
+
if (host === undefined) return { state: 'off' }
|
|
279
|
+
const prefix = laneFilePrefix(host)
|
|
280
|
+
let newest: LaneView | undefined
|
|
281
|
+
for (const file of verdicts) {
|
|
282
|
+
if (!file.name.startsWith(prefix) || !file.name.endsWith('.json')) continue
|
|
283
|
+
const raw = parseJson(file.text)
|
|
284
|
+
if (!isObject(raw) || typeof raw.at !== 'number') continue
|
|
285
|
+
const state = raw.state === 'ok' ? 'up' : raw.state === 'mismatch' || raw.state === 'dead' || raw.state === 'pending' ? raw.state : undefined
|
|
286
|
+
if (state === undefined || (newest?.at ?? -1) >= raw.at) continue
|
|
287
|
+
newest = { state, at: raw.at }
|
|
288
|
+
if (typeof raw.reason === 'string' && raw.reason.trim() !== '') newest.reason = clean(raw.reason).slice(0, 160)
|
|
289
|
+
}
|
|
290
|
+
return newest
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// ---------------------------------------------------------------- rows
|
|
294
|
+
|
|
295
|
+
const agoLabel = (ms: number): string => {
|
|
296
|
+
const secs = Math.max(0, Math.round(ms / 1000))
|
|
297
|
+
if (secs < 60) return `hace ${secs} s`
|
|
298
|
+
const mins = Math.round(secs / 60)
|
|
299
|
+
if (mins < 60) return `hace ${mins} min`
|
|
300
|
+
const hours = Math.round(mins / 60)
|
|
301
|
+
return hours < 48 ? `hace ${hours} h` : `hace ${Math.round(hours / 24)} d`
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
const LISTING_LABEL: Record<ListingMode, string> = {
|
|
305
|
+
jev: 'jev · solo nombres, Jev trae cada skill',
|
|
306
|
+
stats: 'stats · descripciones de las más usadas',
|
|
307
|
+
passthrough: 'passthrough · sin historial, listado completo',
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
const LANE_LOOK: Record<LaneState, { text: string; color: Tone }> = {
|
|
311
|
+
up: { text: '✓ activa', color: 'success' },
|
|
312
|
+
mismatch: { text: '✗ no coincide', color: 'error' },
|
|
313
|
+
dead: { text: '✗ caída', color: 'error' },
|
|
314
|
+
pending: { text: '… verificando', color: 'warning' },
|
|
315
|
+
off: { text: 'apagada', color: 'subtle' },
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
const pickedCount = (picks: SkillPicks): number => picks.prompts.reduce((sum, one) => sum + one.skills.length, 0) + picks.delegations.reduce((sum, one) => sum + one.skills.length, 0)
|
|
319
|
+
|
|
320
|
+
const laneBroken = (lane: LaneView | undefined): boolean => lane?.state === 'mismatch' || lane?.state === 'dead'
|
|
321
|
+
|
|
322
|
+
export const headerLabelSavings = (part: SavingsState): string => {
|
|
323
|
+
const parts = ['Filtros']
|
|
324
|
+
if (part.gate && part.gate.count > 0) parts.push(`⊘ ${part.gate.count} · ≈${compact(Math.round(part.gate.chars / 4))} tok`)
|
|
325
|
+
if (part.picks) parts.push(`${pickedCount(part.picks)} skills`)
|
|
326
|
+
if (part.lane) parts.push(`lane ${part.lane.state === 'up' ? '✓' : laneBroken(part.lane) ? '✗' : part.lane.state === 'off' ? 'off' : '…'}`)
|
|
327
|
+
return parts.join(' · ')
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
export const rowsSavings = (
|
|
331
|
+
part: SavingsPart,
|
|
332
|
+
ctx: { width: number; accent: string; isOpen: (key: string, byDefault: boolean) => boolean },
|
|
333
|
+
): Row[] => {
|
|
334
|
+
const width = Math.max(20, ctx.width)
|
|
335
|
+
const label = headerLabelSavings(part)
|
|
336
|
+
const open = ctx.isOpen(SECTION_KEY, false)
|
|
337
|
+
const header: Row = {
|
|
338
|
+
key: SECTION_KEY,
|
|
339
|
+
cells: [{ spans: [span(fit(`${open ? '▼' : '▶'} ${label}`, width))], action: { kind: 'toggle', key: SECTION_KEY }, label, key: `btn-${SECTION_KEY}` }],
|
|
340
|
+
}
|
|
341
|
+
if (!open) return [header]
|
|
342
|
+
|
|
343
|
+
const line = (key: string, value: string, style: Omit<Span, 'text'> = {}): Row => ({ key, cells: [{ spans: [span(fit(value, width), style)] }] })
|
|
344
|
+
const labeled = (key: string, name: string, value: string, style: Omit<Span, 'text'> = {}): Row => {
|
|
345
|
+
const head = ` ${name}: `
|
|
346
|
+
return { key, cells: [{ spans: [span(fit(head, width), { dim: true }), ...(head.length < width ? [span(fit(value, width - head.length), style)] : [])] }] }
|
|
347
|
+
}
|
|
348
|
+
const body: Row[] = []
|
|
349
|
+
|
|
350
|
+
const { gate } = part
|
|
351
|
+
if (gate === undefined) body.push(labeled('savings-gate', 'Context gate', '—', { dim: true }))
|
|
352
|
+
else if (gate.count === 0) body.push(labeled('savings-gate', 'Context gate', 'sin descartes en esta sesión', { dim: true }))
|
|
353
|
+
else {
|
|
354
|
+
const pieces = gate.count === 1 ? '1 pieza descartada' : `${gate.count} piezas descartadas`
|
|
355
|
+
body.push(labeled('savings-gate', 'Context gate', `${pieces} · ${compact(gate.chars)} car. (≈${compact(Math.round(gate.chars / 4))} tokens)`))
|
|
356
|
+
gate.last.forEach((drop, index) => {
|
|
357
|
+
const score = drop.score === undefined ? ' — ' : drop.score.toFixed(2)
|
|
358
|
+
body.push(line(`savings-drop-${index}`, ` ${score} ${drop.event} · ${drop.head}`, { dim: true }))
|
|
359
|
+
})
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
const { picks } = part
|
|
363
|
+
if (picks === undefined) body.push(labeled('savings-prompts', 'Skills por prompt', '—', { dim: true }))
|
|
364
|
+
else {
|
|
365
|
+
body.push(labeled('savings-prompts', 'Skills por prompt', picks.prompts.length === 0 ? 'ninguna en el contexto vivo' : `${picks.prompts.length} prompts`, picks.prompts.length === 0 ? { dim: true } : {}))
|
|
366
|
+
picks.prompts.slice(-PROMPTS_SHOWN).reverse().forEach((one, index) => {
|
|
367
|
+
const when = one.at > 0 && part.now > 0 ? `${agoLabel(part.now - one.at)} · ` : ''
|
|
368
|
+
body.push(line(`savings-prompt-${index}`, ` ${when}${one.skills.join(', ')}`))
|
|
369
|
+
})
|
|
370
|
+
body.push(labeled('savings-delegations', 'Skills por delegación', picks.delegations.length === 0 ? 'ninguna en el contexto vivo' : `${picks.delegations.length} delegaciones`, picks.delegations.length === 0 ? { dim: true } : {}))
|
|
371
|
+
picks.delegations.slice(-DELEGATIONS_SHOWN).reverse().forEach((one, index) => {
|
|
372
|
+
const skills = one.skills.length === 0 ? 'sin skills' : one.skills.join(', ')
|
|
373
|
+
body.push(line(`savings-delegation-${index}`, ` ${one.description || one.agentId} → ${skills}`, one.skills.length === 0 ? { dim: true } : {}))
|
|
374
|
+
})
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
body.push(part.listing === undefined
|
|
378
|
+
? labeled('savings-listing', 'Listado de skills', '—', { dim: true })
|
|
379
|
+
: labeled('savings-listing', 'Listado de skills', LISTING_LABEL[part.listing], part.listing === 'passthrough' ? { dim: true } : {}))
|
|
380
|
+
|
|
381
|
+
const { lane } = part
|
|
382
|
+
if (lane === undefined) body.push(labeled('savings-lane', 'Lane Ollama interactiva', '—', { dim: true }))
|
|
383
|
+
else {
|
|
384
|
+
const look = LANE_LOOK[lane.state]
|
|
385
|
+
const when = lane.at !== undefined && part.now > 0 ? ` · ${agoLabel(part.now - lane.at)}` : ''
|
|
386
|
+
body.push(labeled('savings-lane', 'Lane Ollama interactiva', `${look.text}${when}`, { color: look.color }))
|
|
387
|
+
if (lane.state === 'mismatch' && lane.reason) body.push(line('savings-lane-reason', ` ${lane.reason}`, { dim: true }))
|
|
388
|
+
}
|
|
389
|
+
return [header, ...body]
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/** Footer tokens only when a filter did something worth seeing, or the lane broke. */
|
|
393
|
+
export const footerSavings = (part: SavingsState): Span[] => {
|
|
394
|
+
const spans: Span[] = []
|
|
395
|
+
if (part.gate && part.gate.count > 0) spans.push(span(`⊘ ${part.gate.count} filtrados`, { color: 'suggestion' }))
|
|
396
|
+
if (laneBroken(part.lane)) spans.push(span('lane ✗', { color: 'error' }))
|
|
397
|
+
return spans
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
// ---------------------------------------------------------------- reads
|
|
401
|
+
|
|
402
|
+
export async function readSavings($: Api): Promise<SavingsPart> {
|
|
403
|
+
const [state, now] = await Promise.all([read($, savingsAtom).catch(() => EMPTY), $.clock.now().catch(() => 0)])
|
|
404
|
+
return { ...state, now }
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
async function readText($: Api, path: string): Promise<string> {
|
|
408
|
+
try {
|
|
409
|
+
return await $.fs.read(path)
|
|
410
|
+
} catch {
|
|
411
|
+
return ''
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/** A file's tail through `tail -c`, or the whole file when it is smaller than that. */
|
|
416
|
+
async function tailOf($: Api, path: string, bytes: number, size: number): Promise<string> {
|
|
417
|
+
if (size <= bytes) return readText($, path)
|
|
418
|
+
const out = await $.process.run(['/usr/bin/tail', '-c', String(bytes), path], { timeoutMs: 3000 })
|
|
419
|
+
return out.exitCode === 0 ? out.stdout : ''
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
async function readGate($: Api, home: string, sessionId: string): Promise<GateSummary | undefined> {
|
|
423
|
+
const text = await readText($, `${home}/.project-brain/context-gate-log.json`)
|
|
424
|
+
return text === '' ? undefined : gateSummaryOf(text, sessionId)
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
async function skillsOfSubagent($: Api, dir: string, delegation: LiveDelegation): Promise<string[]> {
|
|
428
|
+
const inline = delegation.prompt === undefined ? [] : delegationSkillsIn(delegation.prompt)
|
|
429
|
+
if (inline.length > 0) return inline
|
|
430
|
+
const known = subagentSkills.get(delegation.agentId)
|
|
431
|
+
if (known !== undefined) return known
|
|
432
|
+
const out = await $.process.run(['/usr/bin/head', '-c', String(SUBAGENT_HEAD_BYTES), `${dir}/agent-${delegation.agentId}.jsonl`], { timeoutMs: 2000 }).catch(() => undefined)
|
|
433
|
+
if (out === undefined || out.exitCode !== 0) return []
|
|
434
|
+
const skills = subagentSkillsOf(out.stdout)
|
|
435
|
+
subagentSkills.set(delegation.agentId, skills)
|
|
436
|
+
return skills
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/** Re-reads the transcript tail only when the file changed; undefined keeps the stored picks. */
|
|
440
|
+
async function readPicks($: Api, claudeDir: string, sessionId: string): Promise<SkillPicks | undefined | null> {
|
|
441
|
+
const root = await $.session.root()
|
|
442
|
+
const base = `${claudeDir}/projects/${root.replace(/[^A-Za-z0-9]/g, '-')}/${sessionId}`
|
|
443
|
+
const path = `${base}.jsonl`
|
|
444
|
+
const stat = await $.fs.stat(path).catch(() => undefined)
|
|
445
|
+
if (stat === undefined || stat.kind !== 'file') return null
|
|
446
|
+
const size = stat.size ?? 0
|
|
447
|
+
const mtimeMs = stat.mtimeMs ?? 0
|
|
448
|
+
if (transcriptSeen?.path === path && transcriptSeen.size === size && transcriptSeen.mtimeMs === mtimeMs) return undefined
|
|
449
|
+
const tail = await tailOf($, path, TRANSCRIPT_TAIL_BYTES, size)
|
|
450
|
+
const entries = liveEntriesOf(tail)
|
|
451
|
+
const delegations: DelegationPick[] = []
|
|
452
|
+
for (const one of delegationsOf(entries)) {
|
|
453
|
+
const skills = await skillsOfSubagent($, `${base}/subagents`, one).catch(() => [])
|
|
454
|
+
delegations.push({ agentId: one.agentId, description: one.description, skills })
|
|
455
|
+
}
|
|
456
|
+
transcriptSeen = { path, size, mtimeMs }
|
|
457
|
+
return { prompts: promptPicksOf(entries), delegations }
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
async function readListing($: Api, home: string, claudeDir: string): Promise<ListingMode | undefined> {
|
|
461
|
+
const [settings, skills, health, reranker, usage, envToken, envPicker] = await Promise.all([
|
|
462
|
+
readText($, `${claudeDir}/settings.json`),
|
|
463
|
+
readText($, `${home}/.project-brain/skills.json`),
|
|
464
|
+
readText($, `${home}/.project-brain/skill-pick-health.json`),
|
|
465
|
+
readText($, `${home}/.project-brain/reranker.json`),
|
|
466
|
+
readText($, `${home}/.project-brain/skill-usage.json`),
|
|
467
|
+
$.env.get('TYPESAFE_API_KEY').catch(() => undefined),
|
|
468
|
+
$.env.get('BRAIN_SKILL_PICKER').catch(() => undefined),
|
|
469
|
+
])
|
|
470
|
+
const inputs: ListingInputs = { settings, skills, health, reranker, usage }
|
|
471
|
+
if (envToken !== undefined) inputs.envToken = envToken
|
|
472
|
+
if (envPicker !== undefined) inputs.envPicker = envPicker
|
|
473
|
+
return listingModeOf(inputs)
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
async function readLane($: Api, home: string): Promise<LaneView | undefined> {
|
|
477
|
+
const config = await readText($, `${home}/.project-brain/ollama.json`)
|
|
478
|
+
const host = interactiveHostOf(config)
|
|
479
|
+
if (host === undefined) return { state: 'off' }
|
|
480
|
+
const dir = `${home}/.project-brain/lane`
|
|
481
|
+
const prefix = laneFilePrefix(host)
|
|
482
|
+
const listed = await $.fs.list(dir).catch(() => [])
|
|
483
|
+
const files = listed.filter(entry => entry.kind === 'file' && entry.name.startsWith(prefix) && entry.name.endsWith('.json')).slice(0, 20)
|
|
484
|
+
const verdicts = await Promise.all(files.map(async entry => ({ name: entry.name, text: await readText($, `${dir}/${entry.name}`) })))
|
|
485
|
+
return laneOf(config, verdicts)
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
async function refreshSavings($: Api): Promise<void> {
|
|
489
|
+
if (refreshing) return refreshing
|
|
490
|
+
refreshing = (async () => {
|
|
491
|
+
const [home, sessionId, configDir, at] = await Promise.all([
|
|
492
|
+
$.env.get('HOME').catch(() => undefined),
|
|
493
|
+
$.session.id().catch(() => ''),
|
|
494
|
+
$.env.get('CLAUDE_CONFIG_DIR').catch(() => undefined),
|
|
495
|
+
$.clock.now(),
|
|
496
|
+
])
|
|
497
|
+
if (!home) return
|
|
498
|
+
const claudeDir = configDir || `${home}/.claude`
|
|
499
|
+
const [gate, picks, listing, lane] = await Promise.all([
|
|
500
|
+
sessionId ? readGate($, home, sessionId).catch(() => undefined) : Promise.resolve(undefined),
|
|
501
|
+
sessionId ? readPicks($, claudeDir, sessionId).catch(() => null) : Promise.resolve(null),
|
|
502
|
+
readListing($, home, claudeDir).catch(() => undefined),
|
|
503
|
+
readLane($, home).catch(() => undefined),
|
|
504
|
+
])
|
|
505
|
+
await update($, savingsAtom, previous => {
|
|
506
|
+
const next: SavingsState = { at }
|
|
507
|
+
if (gate !== undefined) next.gate = gate
|
|
508
|
+
const keptPicks = picks === undefined ? previous.picks : picks ?? undefined
|
|
509
|
+
if (keptPicks !== undefined) next.picks = keptPicks
|
|
510
|
+
if (listing !== undefined) next.listing = listing
|
|
511
|
+
if (lane !== undefined) next.lane = lane
|
|
512
|
+
return next
|
|
513
|
+
})
|
|
514
|
+
})()
|
|
515
|
+
.catch(() => undefined)
|
|
516
|
+
.finally(() => {
|
|
517
|
+
refreshing = undefined
|
|
518
|
+
})
|
|
519
|
+
return refreshing
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
export async function savingsSessionStart($: Api, e: Parameters<Hook<'session.start'>>[1], next: Parameters<Hook<'session.start'>>[2]): Promise<Awaited<ReturnType<Hook<'session.start'>>>> {
|
|
523
|
+
const result = await next(e)
|
|
524
|
+
transcriptSeen = undefined
|
|
525
|
+
void refreshSavings($).catch(() => undefined)
|
|
526
|
+
return result
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
export async function savingsTurnComplete($: Api, e: Parameters<Hook<'turn.complete'>>[1], next: Parameters<Hook<'turn.complete'>>[2]): Promise<Awaited<ReturnType<Hook<'turn.complete'>>>> {
|
|
530
|
+
const result = await next(e)
|
|
531
|
+
if (e.agentId === undefined) void refreshSavings($).catch(() => undefined)
|
|
532
|
+
return result
|
|
533
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{ "modules": ["./register.tsx"] }
|