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,232 @@
|
|
|
1
|
+
import type { Hook } from 'claude-code'
|
|
2
|
+
import { atom, read, update } from 'claude-code'
|
|
3
|
+
import type { Register } from 'claude-code'
|
|
4
|
+
|
|
5
|
+
import type { Api, Row, Span } from './register'
|
|
6
|
+
import { clean, fit, ICONS, shortName, span } from './register'
|
|
7
|
+
|
|
8
|
+
/** Who refused the call: the person, the auto-mode classifier, a settings rule or mode, or a hook. */
|
|
9
|
+
export type DenialCategory = 'user' | 'classifier' | 'rule' | 'hook'
|
|
10
|
+
|
|
11
|
+
export type Denial = {
|
|
12
|
+
id: string
|
|
13
|
+
at: number
|
|
14
|
+
tool: string
|
|
15
|
+
summary: string
|
|
16
|
+
category: DenialCategory
|
|
17
|
+
reason: string
|
|
18
|
+
label?: string
|
|
19
|
+
agentId?: string
|
|
20
|
+
agent?: string
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export type BlockedPart = { list: Denial[]; turnStartedAt: number }
|
|
24
|
+
|
|
25
|
+
/** What a structured signal said about a call before its `tool.call` resolved. */
|
|
26
|
+
export type DenialHint = { category: DenialCategory; reason: string }
|
|
27
|
+
|
|
28
|
+
type On = Parameters<Register>[0]
|
|
29
|
+
|
|
30
|
+
const KEEP = 100
|
|
31
|
+
const RECENT_MS = 10 * 60_000
|
|
32
|
+
const REASON_CHARS = 160
|
|
33
|
+
const SUMMARY_CHARS = 200
|
|
34
|
+
const HINTS_MAX = 50
|
|
35
|
+
const SECTION_KEY = 'blocked-section'
|
|
36
|
+
const SUMMARY_FIELDS = ['command', 'file_path', 'notebook_path', 'pattern', 'url', 'query', 'description', 'skill', 'prompt'] as const
|
|
37
|
+
|
|
38
|
+
export const CATEGORY_ORDER: DenialCategory[] = ['user', 'classifier', 'rule', 'hook']
|
|
39
|
+
|
|
40
|
+
const CATEGORY_LABELS: Record<DenialCategory, string> = {
|
|
41
|
+
user: 'Rechazadas por ti',
|
|
42
|
+
classifier: 'Modo automático',
|
|
43
|
+
rule: 'Reglas de permisos',
|
|
44
|
+
hook: 'Hooks',
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const blockedList = atom({ plugin: 'project-brain-activity', key: 'blockedList' } as const, [] as Denial[], { shape: 'blocked-list-1' })
|
|
48
|
+
const blockedTurn = atom({ plugin: 'project-brain-activity', key: 'blockedTurn' } as const, 0, { shape: 'blocked-turn-1' })
|
|
49
|
+
|
|
50
|
+
// Hints from tool.check and classic.PermissionDenied, keyed by tool_use_id, read when the call resolves.
|
|
51
|
+
// A reload drops them: that call then falls back to its result text.
|
|
52
|
+
const hints = new Map<string, DenialHint>()
|
|
53
|
+
|
|
54
|
+
const oneLine = (raw: string): string => clean(raw).replace(/\s+/g, ' ').trim()
|
|
55
|
+
const shorten = (raw: string, max: number): string => {
|
|
56
|
+
const flat = oneLine(raw)
|
|
57
|
+
return flat.length <= max ? flat : `${flat.slice(0, max - 1)}…`
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The classifier's `[Label]`, read only from the reason's first 400 characters. */
|
|
61
|
+
export const labelOf = (text: string): string | undefined => {
|
|
62
|
+
const head = text.slice(0, 400)
|
|
63
|
+
const found = /Reason:\s*\[([A-Za-z][A-Za-z0-9 &/-]{0,48})\]/.exec(head) ?? /\[([A-Z][A-Za-z0-9 &/-]{0,48})\]/.exec(head)
|
|
64
|
+
return found?.[1] === undefined ? undefined : oneLine(found[1])
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The fallback when no structured hint arrived: bounded matches on the start of
|
|
69
|
+
* the refusal text core hands the model. `isDeny` is a `{ deny }` result, a hook's
|
|
70
|
+
* refusal unless the text says otherwise.
|
|
71
|
+
*/
|
|
72
|
+
export const categoryOfText = (text: string, isDeny: boolean): DenialCategory | undefined => {
|
|
73
|
+
const head = text.slice(0, 300)
|
|
74
|
+
if (/auto mode classifier/i.test(head)) return 'classifier'
|
|
75
|
+
if (/^(Error: )?The user doesn't want to (proceed|take this action)/.test(head)) return 'user'
|
|
76
|
+
if (/^(Error: )?PreToolUse:\S{1,80} hook error:/.test(head)) return 'hook'
|
|
77
|
+
if (/^(Error: )?Permission (for this (action|command)|to use \S{1,80}).{0,80}(was|has been) denied/.test(head)) return 'rule'
|
|
78
|
+
return isDeny ? 'hook' : undefined
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** A tool.check verdict as a hint: a deny names its hook or its rule; anything else is none. */
|
|
82
|
+
export const hintOfCheck = (verdict: { decision: string; reason?: string; rule?: string; hook?: string; setting?: string }): DenialHint | undefined => {
|
|
83
|
+
if (verdict.decision !== 'deny') return undefined
|
|
84
|
+
if (verdict.hook !== undefined) return { category: 'hook', reason: verdict.reason ?? verdict.hook }
|
|
85
|
+
const named = verdict.rule ?? verdict.setting
|
|
86
|
+
return { category: 'rule', reason: verdict.reason ?? (named === undefined ? '' : `regla ${named}`) }
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The command, path or query the call carried, flattened and bounded. */
|
|
90
|
+
export const summaryOf = (input: Record<string, unknown>): string => {
|
|
91
|
+
for (const field of SUMMARY_FIELDS) {
|
|
92
|
+
const value = input[field]
|
|
93
|
+
if (typeof value === 'string' && value.trim() !== '') return shorten(value, SUMMARY_CHARS)
|
|
94
|
+
}
|
|
95
|
+
return ''
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** The reason line kept for a denial: the hint's, else the refusal's first sentence. */
|
|
99
|
+
export const reasonOf = (category: DenialCategory, hintReason: string | undefined, text: string): string => {
|
|
100
|
+
if (category === 'user') return 'rechazada por ti'
|
|
101
|
+
const source = hintReason !== undefined && hintReason !== '' ? hintReason : text
|
|
102
|
+
if (category === 'classifier') return shorten(source.replace(/^Error: /, '').replace(/ If you have other tasks[\s\S]*$/, ''), REASON_CHARS)
|
|
103
|
+
return shorten(source.replace(/^Error: /, ''), REASON_CHARS)
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export const addDenial = (list: Denial[], denial: Denial): Denial[] => [...list.filter(one => one.id !== denial.id), denial].slice(-KEEP)
|
|
107
|
+
|
|
108
|
+
/** Denials by category in CATEGORY_ORDER, newest first inside each; empty groups dropped. */
|
|
109
|
+
export const groupDenials = (list: Denial[]): { category: DenialCategory; items: Denial[] }[] =>
|
|
110
|
+
CATEGORY_ORDER.map(category => ({ category, items: list.filter(one => one.category === category).sort((a, b) => b.at - a.at) })).filter(group => group.items.length > 0)
|
|
111
|
+
|
|
112
|
+
const remember = (id: string | undefined, hint: DenialHint | undefined): void => {
|
|
113
|
+
if (id === undefined || hint === undefined) return
|
|
114
|
+
hints.set(id, hint)
|
|
115
|
+
while (hints.size > HINTS_MAX) {
|
|
116
|
+
const oldest = hints.keys().next().value
|
|
117
|
+
if (oldest === undefined) break
|
|
118
|
+
hints.delete(oldest)
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const text = (value: unknown): string => (typeof value === 'string' ? value : '')
|
|
123
|
+
|
|
124
|
+
export const registerBlocked = (on: On): void => {
|
|
125
|
+
|
|
126
|
+
on('tool.check', async ($, e, next) => {
|
|
127
|
+
const verdict = await next(e)
|
|
128
|
+
try {
|
|
129
|
+
remember(e.tool_use_id, hintOfCheck(verdict))
|
|
130
|
+
} catch {
|
|
131
|
+
// Observing only.
|
|
132
|
+
}
|
|
133
|
+
return verdict
|
|
134
|
+
})
|
|
135
|
+
|
|
136
|
+
on('classic.PermissionDenied', async ($, e, next) => {
|
|
137
|
+
const result = await next(e)
|
|
138
|
+
try {
|
|
139
|
+
remember(e.tool_use_id, { category: 'classifier', reason: text(e.reason) })
|
|
140
|
+
} catch {
|
|
141
|
+
// Observing only.
|
|
142
|
+
}
|
|
143
|
+
return result
|
|
144
|
+
})
|
|
145
|
+
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export async function readBlocked($: Api): Promise<BlockedPart> {
|
|
149
|
+
return { list: await read($, blockedList), turnStartedAt: await read($, blockedTurn) }
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export const rowsBlocked = (part: BlockedPart, ctx: { width: number; accent: string; isOpen: (key: string, byDefault: boolean) => boolean }): Row[] => {
|
|
153
|
+
const { width } = ctx
|
|
154
|
+
if (part.list.length === 0) return []
|
|
155
|
+
const open = ctx.isOpen(SECTION_KEY, true)
|
|
156
|
+
const title = `Bloqueos · ${part.list.length}`
|
|
157
|
+
const rows: Row[] = [
|
|
158
|
+
{
|
|
159
|
+
key: SECTION_KEY,
|
|
160
|
+
cells: [{ spans: [span(fit(`${open ? '▼' : '▶'} ${title}`, width))], action: { kind: 'toggle', key: SECTION_KEY }, label: title, key: `btn-${SECTION_KEY}` }],
|
|
161
|
+
},
|
|
162
|
+
]
|
|
163
|
+
if (!open) return rows
|
|
164
|
+
for (const group of groupDenials(part.list)) {
|
|
165
|
+
rows.push({ key: `blocked-group-${group.category}`, cells: [{ spans: [span(fit(` ${CATEGORY_LABELS[group.category]} · ${group.items.length}`, width), { color: ctx.accent, bold: true })] }] })
|
|
166
|
+
for (const one of group.items) {
|
|
167
|
+
const head = `${one.tool}${one.summary === '' ? '' : ` ${one.summary}`}`
|
|
168
|
+
rows.push({
|
|
169
|
+
key: `blocked-row-${one.id}`,
|
|
170
|
+
cells: [{ spans: [span(' '), span(`${ICONS.denied} `, { color: 'permission' }), span(fit(clean(head), width - 6))] }],
|
|
171
|
+
})
|
|
172
|
+
const why = [one.label === undefined ? '' : `[${one.label}]`, one.label !== undefined && one.category === 'classifier' ? '' : one.reason, one.agent === undefined ? '' : `agente ${one.agent}`]
|
|
173
|
+
.filter(part => part !== '')
|
|
174
|
+
.join(' · ')
|
|
175
|
+
if (why !== '') rows.push({ key: `blocked-why-${one.id}`, cells: [{ spans: [span(fit(` ${clean(why)}`, width), { dim: true })] }] })
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
return rows
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export const headerBlocked = (part: BlockedPart, now: number): Span[] => {
|
|
182
|
+
const since = Math.min(now - RECENT_MS, part.turnStartedAt > 0 ? part.turnStartedAt : Number.POSITIVE_INFINITY)
|
|
183
|
+
const recent = part.list.filter(one => one.at >= since).length
|
|
184
|
+
return recent === 0 ? [] : [span(`${ICONS.denied} ${recent}`, { color: 'permission', bold: true })]
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export async function blockedTurnStart($: Api, e: Parameters<Hook<'turn.start'>>[1], next: Parameters<Hook<'turn.start'>>[2]): Promise<Awaited<ReturnType<Hook<'turn.start'>>>> {
|
|
188
|
+
try {
|
|
189
|
+
if (e.agentId === undefined) {
|
|
190
|
+
const now = await $.clock.now()
|
|
191
|
+
await update($, blockedTurn, () => now)
|
|
192
|
+
}
|
|
193
|
+
} catch {
|
|
194
|
+
// Observing only: a failed write leaves the header on its 10-minute window.
|
|
195
|
+
}
|
|
196
|
+
return next(e)
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export async function blockedToolCall($: Api, e: Parameters<Hook<'tool.call'>>[1], next: Parameters<Hook<'tool.call'>>[2]): Promise<Awaited<ReturnType<Hook<'tool.call'>>>> {
|
|
200
|
+
const ran = await next(e)
|
|
201
|
+
try {
|
|
202
|
+
const isDeny = ran.deny !== undefined
|
|
203
|
+
if (!isDeny && ran.isError !== true) return ran
|
|
204
|
+
const id = e.tool_use_id
|
|
205
|
+
const hint = id === undefined ? undefined : hints.get(id)
|
|
206
|
+
if (id !== undefined) hints.delete(id)
|
|
207
|
+
const body = isDeny ? ran.deny : text(ran.text) || text(ran.result)
|
|
208
|
+
const category = hint?.category ?? categoryOfText(body, isDeny)
|
|
209
|
+
if (category === undefined) return ran
|
|
210
|
+
const at = await $.clock.now()
|
|
211
|
+
const label = category === 'classifier' ? labelOf(hint?.reason ?? '') ?? labelOf(body) : undefined
|
|
212
|
+
const denial: Denial = {
|
|
213
|
+
id: id ?? `blocked-${at}`,
|
|
214
|
+
at,
|
|
215
|
+
tool: shorten(e.tool, 60),
|
|
216
|
+
summary: summaryOf(e as unknown as Record<string, unknown>),
|
|
217
|
+
category,
|
|
218
|
+
reason: reasonOf(category, hint?.reason, body),
|
|
219
|
+
...(label === undefined ? {} : { label }),
|
|
220
|
+
}
|
|
221
|
+
const loopId = e.agentId
|
|
222
|
+
if (loopId !== undefined) {
|
|
223
|
+
denial.agentId = loopId
|
|
224
|
+
const info = (await $.agent.list().catch(() => [])).find(one => one.id === loopId)
|
|
225
|
+
if (info) denial.agent = shorten(shortName({ description: info.description, ...(info.name ? { name: info.name } : {}) }), 40)
|
|
226
|
+
}
|
|
227
|
+
await update($, blockedList, list => addDenial(list, denial))
|
|
228
|
+
} catch {
|
|
229
|
+
// Observing only: the call's outcome stands whatever this bookkeeping does.
|
|
230
|
+
}
|
|
231
|
+
return ran
|
|
232
|
+
}
|
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
import type { Hook } from 'claude-code'
|
|
2
|
+
import { atom, read, update } from 'claude-code'
|
|
3
|
+
import type { Register } from 'claude-code'
|
|
4
|
+
|
|
5
|
+
import type { Api, Row, Run, Span } from './register'
|
|
6
|
+
import { clean, fit, gitTop, span } from './register'
|
|
7
|
+
import { notify } from './feat-notify'
|
|
8
|
+
|
|
9
|
+
export type CiJob = { name: string; status: string; conclusion: string; failedStep?: string }
|
|
10
|
+
|
|
11
|
+
export type CiRun = {
|
|
12
|
+
id: number
|
|
13
|
+
workflow: string
|
|
14
|
+
title: string
|
|
15
|
+
status: string
|
|
16
|
+
conclusion: string
|
|
17
|
+
branch: string
|
|
18
|
+
createdAt: string
|
|
19
|
+
url: string
|
|
20
|
+
jobs?: CiJob[]
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export type CiState = 'idle' | 'ready' | 'unavailable'
|
|
24
|
+
|
|
25
|
+
export type CiView = {
|
|
26
|
+
state: CiState
|
|
27
|
+
reason?: string
|
|
28
|
+
upstream?: string
|
|
29
|
+
ahead?: number
|
|
30
|
+
behind?: number
|
|
31
|
+
sha?: string
|
|
32
|
+
runs: CiRun[]
|
|
33
|
+
checkedAt: number
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export type CiPart = { view: CiView; now: number }
|
|
37
|
+
|
|
38
|
+
const EMPTY: CiView = { state: 'idle', runs: [], checkedAt: 0 }
|
|
39
|
+
|
|
40
|
+
const ciView = atom({ plugin: 'project-brain-activity', key: 'ciStatus' } as const, EMPTY, { shape: 'ci-status-1' })
|
|
41
|
+
|
|
42
|
+
const PANE_ID = 'activity'
|
|
43
|
+
export const ACTIVE_MS = 30_000
|
|
44
|
+
export const IDLE_MS = 300_000
|
|
45
|
+
const RUN_TIMEOUT_MS = 15_000
|
|
46
|
+
const MAX_OUTPUT = 1_000_000
|
|
47
|
+
const MAX_RUNS = 5
|
|
48
|
+
const MAX_JOBS = 20
|
|
49
|
+
|
|
50
|
+
// Timers and the in-flight check are not drawn state: a reload restarts them.
|
|
51
|
+
let ticker: { cancel: () => void } | undefined
|
|
52
|
+
let checking: Promise<void> | undefined
|
|
53
|
+
let isDirty = false
|
|
54
|
+
|
|
55
|
+
// ---------------------------------------------------------------- parsing
|
|
56
|
+
|
|
57
|
+
const str = (value: unknown): string => (typeof value === 'string' ? clean(value) : '')
|
|
58
|
+
|
|
59
|
+
const PENDING = new Set(['queued', 'in_progress', 'waiting', 'requested', 'pending'])
|
|
60
|
+
|
|
61
|
+
export const isRunActive = (run: Pick<CiRun, 'status'>): boolean => PENDING.has(run.status)
|
|
62
|
+
|
|
63
|
+
export const isViewActive = (view: CiView): boolean => view.runs.some(isRunActive)
|
|
64
|
+
|
|
65
|
+
export const pollEvery = (view: CiView): number => (isViewActive(view) ? ACTIVE_MS : IDLE_MS)
|
|
66
|
+
|
|
67
|
+
const parseJson = (stdout: string): unknown => {
|
|
68
|
+
if (stdout.length > MAX_OUTPUT) return undefined
|
|
69
|
+
try {
|
|
70
|
+
return JSON.parse(stdout)
|
|
71
|
+
} catch {
|
|
72
|
+
return undefined
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** `gh run list --json …`: the newest run of each workflow, newest first. */
|
|
77
|
+
export const parseRuns = (stdout: string): CiRun[] => {
|
|
78
|
+
const raw = parseJson(stdout)
|
|
79
|
+
if (!Array.isArray(raw)) return []
|
|
80
|
+
const runs = raw
|
|
81
|
+
.filter((one): one is Record<string, unknown> => typeof one === 'object' && one !== null && typeof one.databaseId === 'number')
|
|
82
|
+
.map(
|
|
83
|
+
(one): CiRun => ({
|
|
84
|
+
id: one.databaseId as number,
|
|
85
|
+
workflow: str(one.workflowName) || str(one.name) || 'workflow',
|
|
86
|
+
title: str(one.name),
|
|
87
|
+
status: str(one.status),
|
|
88
|
+
conclusion: str(one.conclusion),
|
|
89
|
+
branch: str(one.headBranch),
|
|
90
|
+
createdAt: str(one.createdAt),
|
|
91
|
+
url: str(one.url),
|
|
92
|
+
}),
|
|
93
|
+
)
|
|
94
|
+
.sort((a, b) => b.createdAt.localeCompare(a.createdAt))
|
|
95
|
+
const seen = new Set<string>()
|
|
96
|
+
return runs.filter(run => !seen.has(run.workflow) && (seen.add(run.workflow), true)).slice(0, MAX_RUNS)
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** `gh run view <id> --json jobs`: each job with the first step that failed. */
|
|
100
|
+
export const parseJobs = (stdout: string): CiJob[] | undefined => {
|
|
101
|
+
const raw = parseJson(stdout) as { jobs?: unknown } | undefined
|
|
102
|
+
if (!raw || !Array.isArray(raw.jobs)) return undefined
|
|
103
|
+
return raw.jobs
|
|
104
|
+
.filter((one): one is Record<string, unknown> => typeof one === 'object' && one !== null)
|
|
105
|
+
.slice(0, MAX_JOBS)
|
|
106
|
+
.map(one => {
|
|
107
|
+
const steps = Array.isArray(one.steps) ? (one.steps as Record<string, unknown>[]) : []
|
|
108
|
+
const failed = steps.find(step => step && (step.conclusion === 'failure' || step.conclusion === 'timed_out'))
|
|
109
|
+
const job: CiJob = { name: str(one.name) || 'job', status: str(one.status), conclusion: str(one.conclusion) }
|
|
110
|
+
if (failed) job.failedStep = str(failed.name)
|
|
111
|
+
return job
|
|
112
|
+
})
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** `git rev-list --left-right --count @{u}...HEAD` prints `behind<TAB>ahead`. */
|
|
116
|
+
export const parseAheadBehind = (stdout: string): { ahead: number; behind: number } | undefined => {
|
|
117
|
+
const match = /^(\d+)\s+(\d+)\s*$/.exec(stdout.trim())
|
|
118
|
+
return match ? { behind: Number(match[1]), ahead: Number(match[2]) } : undefined
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Why `gh` could not answer, as one short line. */
|
|
122
|
+
export const ghReason = (stderr: string): string => {
|
|
123
|
+
if (/auth login|not logged|authentication|GH_TOKEN/i.test(stderr)) return 'gh no tiene sesión iniciada (gh auth login)'
|
|
124
|
+
if (/known GitHub host|no git remotes|not a git repository/i.test(stderr)) return 'el remoto no es de GitHub'
|
|
125
|
+
const first = clean(stderr).split('\n').find(line => line.trim() !== '')
|
|
126
|
+
return first ? `gh falló: ${first.trim().slice(0, 120)}` : 'gh no respondió'
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Runs that were seen pending before and are finished now. */
|
|
130
|
+
export const finishedRuns = (before: CiRun[], after: CiRun[]): CiRun[] =>
|
|
131
|
+
after.filter(run => !isRunActive(run) && before.some(prev => prev.id === run.id && isRunActive(prev)))
|
|
132
|
+
|
|
133
|
+
/** Conclusions that are neither a pass nor a failure: drawn as a dash, toasted by name. */
|
|
134
|
+
const NEUTRAL_LABEL: Record<string, string> = { cancelled: 'cancelado', skipped: 'omitido', neutral: 'neutral' }
|
|
135
|
+
|
|
136
|
+
export const verdictOfRun = (run: Pick<CiRun, 'conclusion'>): 'PASS' | 'FAIL' | 'NEUTRAL' =>
|
|
137
|
+
run.conclusion === 'success' ? 'PASS' : Object.hasOwn(NEUTRAL_LABEL, run.conclusion) ? 'NEUTRAL' : 'FAIL'
|
|
138
|
+
|
|
139
|
+
export const toastOfRun = (run: Pick<CiRun, 'conclusion' | 'workflow'>): string => {
|
|
140
|
+
const verdict = verdictOfRun(run)
|
|
141
|
+
return `CI ${verdict === 'NEUTRAL' ? NEUTRAL_LABEL[run.conclusion] : verdict} · ${run.workflow}`
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** The one-line OS notification a finished run raises, naming the first failed job. */
|
|
145
|
+
export const notifyLineOfRun = (run: Pick<CiRun, 'conclusion' | 'workflow' | 'jobs'>): string => {
|
|
146
|
+
const verdict = verdictOfRun(run)
|
|
147
|
+
if (verdict === 'PASS') return `✓ CI ${run.workflow} pasó`
|
|
148
|
+
if (verdict === 'NEUTRAL') return `– CI ${run.workflow} ${NEUTRAL_LABEL[run.conclusion]}`
|
|
149
|
+
const job = run.jobs?.find(one => one.conclusion !== '' && one.conclusion !== 'success' && !Object.hasOwn(NEUTRAL_LABEL, one.conclusion))
|
|
150
|
+
return `✗ CI ${run.workflow} falló${job ? ` · job ${job.name}` : ''}`
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// ---------------------------------------------------------------- loading
|
|
154
|
+
|
|
155
|
+
const call = (run: Run, argv: readonly string[], cwd: string) => run(argv, { cwd, timeoutMs: RUN_TIMEOUT_MS }).catch(() => undefined)
|
|
156
|
+
|
|
157
|
+
/** Reads ahead/behind, then the runs of the newest pushed commit and their jobs. */
|
|
158
|
+
export const loadCi = async (run: Run, previous: CiView, now: number): Promise<CiView> => {
|
|
159
|
+
const top = await gitTop(run)
|
|
160
|
+
if (top === undefined) return { state: 'unavailable', reason: 'no hay repositorio git', runs: [], checkedAt: now }
|
|
161
|
+
const remotes = await call(run, ['git', 'remote'], top)
|
|
162
|
+
if (!remotes || remotes.exitCode !== 0 || remotes.stdout.trim() === '') return { state: 'unavailable', reason: 'el repositorio no tiene remoto', runs: [], checkedAt: now }
|
|
163
|
+
|
|
164
|
+
const view: CiView = { state: 'ready', runs: [], checkedAt: now }
|
|
165
|
+
const upstream = await call(run, ['git', 'rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'], top)
|
|
166
|
+
if (upstream?.exitCode === 0) {
|
|
167
|
+
view.upstream = clean(upstream.stdout.trim()).slice(0, 120)
|
|
168
|
+
const counts = await call(run, ['git', 'rev-list', '--left-right', '--count', '@{u}...HEAD'], top)
|
|
169
|
+
const parsed = counts?.exitCode === 0 ? parseAheadBehind(counts.stdout) : undefined
|
|
170
|
+
if (parsed) Object.assign(view, parsed)
|
|
171
|
+
}
|
|
172
|
+
const ref = view.upstream !== undefined && (view.ahead ?? 0) > 0 ? '@{u}' : 'HEAD'
|
|
173
|
+
const sha = await call(run, ['git', 'rev-parse', ref], top)
|
|
174
|
+
if (sha?.exitCode !== 0 || !/^[0-9a-f]{7,64}$/.test(sha.stdout.trim())) return view
|
|
175
|
+
view.sha = sha.stdout.trim()
|
|
176
|
+
|
|
177
|
+
const listed = await call(run, ['gh', 'run', 'list', '--commit', view.sha, '--limit', '20', '--json', 'databaseId,name,status,conclusion,workflowName,headBranch,createdAt,url'], top)
|
|
178
|
+
if (listed === undefined) return { ...view, state: 'unavailable', reason: 'gh no está instalado' }
|
|
179
|
+
if (listed.exitCode !== 0) return { ...view, state: 'unavailable', reason: ghReason(listed.stderr) }
|
|
180
|
+
|
|
181
|
+
const known = new Map(previous.runs.map(one => [one.id, one]))
|
|
182
|
+
view.runs = await Promise.all(
|
|
183
|
+
parseRuns(listed.stdout).map(async one => {
|
|
184
|
+
const cached = known.get(one.id)
|
|
185
|
+
// A finished run's jobs no longer change.
|
|
186
|
+
if (cached?.jobs !== undefined && !isRunActive(cached) && !isRunActive(one)) return { ...one, jobs: cached.jobs }
|
|
187
|
+
const detail = await call(run, ['gh', 'run', 'view', String(one.id), '--json', 'jobs'], top)
|
|
188
|
+
const jobs = detail?.exitCode === 0 ? parseJobs(detail.stdout) : undefined
|
|
189
|
+
return jobs === undefined ? (cached?.jobs ? { ...one, jobs: cached.jobs } : one) : { ...one, jobs }
|
|
190
|
+
}),
|
|
191
|
+
)
|
|
192
|
+
return view
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function refresh($: Api): Promise<void> {
|
|
196
|
+
checking ??= (async () => {
|
|
197
|
+
isDirty = false
|
|
198
|
+
const [previous, now] = await Promise.all([read($, ciView), $.clock.now()])
|
|
199
|
+
const next = await loadCi((argv, init) => $.process.run(argv, init), previous, now)
|
|
200
|
+
await update($, ciView, () => next)
|
|
201
|
+
for (const run of finishedRuns(previous.runs, next.runs)) {
|
|
202
|
+
$.ui.toast(toastOfRun(run))
|
|
203
|
+
void notify($, { key: `ci:${run.id}`, text: notifyLineOfRun(run) }).catch(() => undefined)
|
|
204
|
+
}
|
|
205
|
+
})()
|
|
206
|
+
.catch(() => undefined)
|
|
207
|
+
.finally(() => {
|
|
208
|
+
checking = undefined
|
|
209
|
+
})
|
|
210
|
+
return checking
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
async function isPaneUp($: Api): Promise<boolean> {
|
|
214
|
+
const panes = await $.ui.panes().catch(() => [])
|
|
215
|
+
return panes.some(pane => pane.id === PANE_ID && pane.isPlaced)
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** Every 30 s: checks when the pane is up and the view is due (30 s active, 5 min idle, or a push happened). */
|
|
219
|
+
async function tick($: Api): Promise<void> {
|
|
220
|
+
if (checking !== undefined || !(await isPaneUp($))) return
|
|
221
|
+
const [view, now] = await Promise.all([read($, ciView), $.clock.now()])
|
|
222
|
+
if (isDirty || now - view.checkedAt >= pollEvery(view) - 1000) await refresh($)
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function startTicker($: Api): void {
|
|
226
|
+
ticker?.cancel()
|
|
227
|
+
ticker = $.clock.every(ACTIVE_MS, () => {
|
|
228
|
+
void tick($).catch(() => undefined)
|
|
229
|
+
})
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** A check outside the timer, when one is due: the pane was just opened, a session started, a turn ended. */
|
|
233
|
+
export async function ciKick($: Api): Promise<void> {
|
|
234
|
+
try {
|
|
235
|
+
if (ticker === undefined) startTicker($)
|
|
236
|
+
} catch {
|
|
237
|
+
// No timer: kicks still check.
|
|
238
|
+
}
|
|
239
|
+
await tick($).catch(() => undefined)
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
const PUSHES = /\bgit\b[^;&|]*\bpush\b|\bgh\s+(?:pr\s+merge|workflow\s+run|run\s+rerun)\b/
|
|
243
|
+
|
|
244
|
+
export const registerCi = (on: Parameters<Register>[0]): void => {
|
|
245
|
+
|
|
246
|
+
on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
|
|
247
|
+
const result = await next(e)
|
|
248
|
+
try {
|
|
249
|
+
const command = (e as unknown as Record<string, unknown>).command
|
|
250
|
+
if (typeof command === 'string' && PUSHES.test(command)) isDirty = true
|
|
251
|
+
} catch {
|
|
252
|
+
// Never block the call over a status hint.
|
|
253
|
+
}
|
|
254
|
+
return result
|
|
255
|
+
})
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** Atoms only: checks start from the timer and from `ciKick`, never from a draw. */
|
|
259
|
+
export async function readCi($: Api): Promise<CiPart> {
|
|
260
|
+
const [view, now] = await Promise.all([read($, ciView), $.clock.now()])
|
|
261
|
+
return { view, now }
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// ---------------------------------------------------------------- rows
|
|
265
|
+
|
|
266
|
+
type Look = { glyph: string; color: string }
|
|
267
|
+
|
|
268
|
+
export const runLook = (run: Pick<CiRun, 'status' | 'conclusion'>): Look => {
|
|
269
|
+
if (isRunActive(run)) return { glyph: '◷', color: 'warning' }
|
|
270
|
+
if (run.conclusion === 'success') return { glyph: '✓', color: 'success' }
|
|
271
|
+
if (verdictOfRun(run) === 'NEUTRAL') return { glyph: '–', color: 'subtle' }
|
|
272
|
+
return { glyph: '✗', color: 'error' }
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
const jobLook = (job: CiJob): Look => runLook(job)
|
|
276
|
+
|
|
277
|
+
const pushLine = (view: CiView): string => {
|
|
278
|
+
if (view.upstream === undefined) return 'Sin rama remota: haz git push -u para seguirla'
|
|
279
|
+
const ahead = view.ahead ?? 0
|
|
280
|
+
const behind = view.behind ?? 0
|
|
281
|
+
if (ahead === 0 && behind === 0) return `Al día con ${view.upstream}`
|
|
282
|
+
const parts = [ahead > 0 ? `↑ ${ahead} por subir` : '', behind > 0 ? `↓ ${behind} por bajar` : ''].filter(Boolean)
|
|
283
|
+
return `${parts.join(' · ')} · ${view.upstream}`
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
const agoText = (iso: string, now: number): string => {
|
|
287
|
+
const at = Date.parse(iso)
|
|
288
|
+
if (Number.isNaN(at)) return ''
|
|
289
|
+
const minutes = Math.max(0, Math.round((now - at) / 60_000))
|
|
290
|
+
if (minutes < 1) return 'ahora'
|
|
291
|
+
if (minutes < 60) return `hace ${minutes} min`
|
|
292
|
+
const hours = Math.round(minutes / 60)
|
|
293
|
+
return hours < 48 ? `hace ${hours} h` : `hace ${Math.round(hours / 24)} d`
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** The fold arrow, the workflow and a letter of it before the age shows: below that the age goes first. */
|
|
297
|
+
const LABEL_MIN = 4
|
|
298
|
+
const JOB_INDENT_FROM = 8
|
|
299
|
+
|
|
300
|
+
/** How a run row splits its width: the label, one glyph column, then a space and the age when both fit. */
|
|
301
|
+
export const runRowLayout = (width: number, ago: string): { labelWidth: number; ago: string } => {
|
|
302
|
+
const room = Math.max(1, width) - 1
|
|
303
|
+
if (ago !== '' && room - ago.length - 1 >= LABEL_MIN) return { labelWidth: room - ago.length - 1, ago }
|
|
304
|
+
return { labelWidth: room, ago: '' }
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
export const rowsCi = (
|
|
308
|
+
part: CiPart,
|
|
309
|
+
ctx: { width: number; accent: string; isOpen: (key: string, byDefault: boolean) => boolean },
|
|
310
|
+
): Row[] => {
|
|
311
|
+
const { view, now } = part
|
|
312
|
+
const width = Math.max(1, ctx.width)
|
|
313
|
+
const line = (key: string, value: string, style: Omit<Span, 'text'> = {}): Row => ({ key, cells: [{ spans: [span(fit(value, width), style)] }] })
|
|
314
|
+
|
|
315
|
+
if (view.state === 'idle') return [line('ci-loading', 'CI · consultando…', { dim: true })]
|
|
316
|
+
if (view.state === 'unavailable' && view.upstream === undefined) return [line('ci-off', `CI no disponible: ${view.reason ?? 'sin datos'}`, { dim: true })]
|
|
317
|
+
|
|
318
|
+
const ahead = view.ahead ?? 0
|
|
319
|
+
const rows: Row[] = [line('ci-push', pushLine(view), { color: ahead > 0 ? 'warning' : 'subtle' })]
|
|
320
|
+
if (view.state === 'unavailable') {
|
|
321
|
+
rows.push(line('ci-off', `CI no disponible: ${view.reason ?? 'sin datos'}`, { dim: true }))
|
|
322
|
+
return rows
|
|
323
|
+
}
|
|
324
|
+
const short = view.sha?.slice(0, 7) ?? ''
|
|
325
|
+
if (view.runs.length === 0) {
|
|
326
|
+
rows.push(line('ci-none', `CI · sin ejecuciones para ${short}`, { dim: true }))
|
|
327
|
+
return rows
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
for (const run of view.runs) {
|
|
331
|
+
const look = runLook(run)
|
|
332
|
+
const key = `ci-run-${run.id}`
|
|
333
|
+
const open = ctx.isOpen(key, look.glyph !== '✓')
|
|
334
|
+
const label = `CI · ${run.workflow} `
|
|
335
|
+
const layout = runRowLayout(width, agoText(run.createdAt, now))
|
|
336
|
+
rows.push({
|
|
337
|
+
key,
|
|
338
|
+
cells: [
|
|
339
|
+
{
|
|
340
|
+
spans: [
|
|
341
|
+
...(layout.labelWidth > 0 ? [span(fit(`${open ? '▼' : '▶'} ${label}`, layout.labelWidth))] : []),
|
|
342
|
+
span(look.glyph, { color: look.color, bold: true }),
|
|
343
|
+
],
|
|
344
|
+
action: { kind: 'toggle', key },
|
|
345
|
+
label: open ? 'Ocultar jobs' : 'Ver jobs',
|
|
346
|
+
key: `btn-${key}`,
|
|
347
|
+
},
|
|
348
|
+
],
|
|
349
|
+
...(layout.ago === '' ? {} : { right: [span(layout.ago, { dim: true })] }),
|
|
350
|
+
})
|
|
351
|
+
if (!open) continue
|
|
352
|
+
rows.push(line(`${key}-meta`, ` ${run.branch || '—'} · ${short}${ahead > 0 ? ' (último commit subido)' : ''}`, { dim: true }))
|
|
353
|
+
if (run.jobs === undefined) {
|
|
354
|
+
rows.push(line(`${key}-nojobs`, ' sin detalle de jobs', { dim: true }))
|
|
355
|
+
continue
|
|
356
|
+
}
|
|
357
|
+
run.jobs.forEach((job, index) => {
|
|
358
|
+
const jl = jobLook(job)
|
|
359
|
+
const indent = width >= JOB_INDENT_FROM ? ' ' : ''
|
|
360
|
+
const nameWidth = width - indent.length - 1
|
|
361
|
+
rows.push({
|
|
362
|
+
key: `${key}-job-${index}`,
|
|
363
|
+
cells: [{ spans: [span(indent), span(jl.glyph, { color: jl.color }), ...(nameWidth >= 2 ? [span(fit(` ${job.name}`, nameWidth))] : [])] }],
|
|
364
|
+
})
|
|
365
|
+
if (job.failedStep) rows.push(line(`${key}-job-${index}-step`, ` falló en: ${job.failedStep}`, { color: 'error' }))
|
|
366
|
+
})
|
|
367
|
+
}
|
|
368
|
+
return rows
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/** A compact token for the footer: the overall CI glyph and the commits left to push. */
|
|
372
|
+
export const footerCi = (part: CiPart): Span[] => {
|
|
373
|
+
const { view } = part
|
|
374
|
+
if (view.state !== 'ready') return []
|
|
375
|
+
const spans: Span[] = []
|
|
376
|
+
if (view.runs.length > 0) {
|
|
377
|
+
const looks = view.runs.map(runLook)
|
|
378
|
+
const worst = looks.find(one => one.glyph === '✗') ?? looks.find(one => one.glyph === '◷') ?? looks[0]!
|
|
379
|
+
spans.push(span('CI ', { dim: true }), span(worst.glyph, { color: worst.color, bold: true }))
|
|
380
|
+
}
|
|
381
|
+
if ((view.ahead ?? 0) > 0) spans.push(span(`${spans.length > 0 ? ' ' : ''}↑${view.ahead}`, { color: 'warning' }))
|
|
382
|
+
return spans
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
export async function ciSessionStart($: Api, e: Parameters<Hook<'session.start'>>[1], next: Parameters<Hook<'session.start'>>[2]): Promise<Awaited<ReturnType<Hook<'session.start'>>>> {
|
|
386
|
+
try {
|
|
387
|
+
startTicker($)
|
|
388
|
+
} catch {
|
|
389
|
+
// No timer: turn ends and pane opens still check.
|
|
390
|
+
}
|
|
391
|
+
const result = await next(e)
|
|
392
|
+
void ciKick($).catch(() => undefined)
|
|
393
|
+
return result
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
export async function ciTurnComplete($: Api, e: Parameters<Hook<'turn.complete'>>[1], next: Parameters<Hook<'turn.complete'>>[2]): Promise<Awaited<ReturnType<Hook<'turn.complete'>>>> {
|
|
397
|
+
const result = await next(e)
|
|
398
|
+
if (e.agentId === undefined) void ciKick($).catch(() => undefined)
|
|
399
|
+
return result
|
|
400
|
+
}
|