rvlib-shipkit 2.25.0 → 2.26.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 +13 -0
- package/package.json +2 -2
- package/src/agent-time/hooks.ts +329 -0
- package/src/agent-time/render.ts +14 -2
- package/src/agent-time/report.ts +56 -4
- package/src/agent-time/store.ts +59 -5
- package/src/checks/SK045-slow-hooks.check.ts +47 -0
- package/src/checks/SK046-hook-records.check.ts +76 -0
- package/src/cli/cmd_Backup.ts +3 -1
- package/src/cli/cmd_Mv.ts +1 -1
- package/src/cli/cmd_Releases.ts +30 -0
- package/src/cli/cmd_Review.ts +23 -4
- package/src/cli/cmd_Time.ts +8 -2
- package/src/cli/registry.ts +2 -1
- package/src/commands/runner.ts +5 -1
- package/src/core/history-files.ts +9 -5
- package/src/core/signal-name.ts +6 -0
- package/src/core/trace-audit.ts +6 -1
- package/src/core/transient.ts +6 -0
- package/src/drill/run.ts +1 -1
- package/src/ledger/gate-checks.ts +23 -2
- package/src/ledger/git-key.ts +3 -3
- package/src/ledger/git-scan.ts +49 -7
- package/src/media-store/backup/daemon.ts +11 -0
- package/src/media-store/backup/sources.ts +1 -4
- package/src/reflect/transcript.ts +21 -3
- package/src/releases/model.ts +18 -0
- package/src/releases/store.ts +13 -1
- package/src/repo-config.ts +11 -1
- package/src/review/inbox-hook.ts +35 -0
- package/src/review/model.ts +12 -6
- package/src/suite/judge-suites.ts +77 -10
- package/src/suite/suite-cli.ts +72 -31
- package/src/wiki/run-wiki.ts +2 -1
- package/src/wiki/scan-md.ts +42 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,16 @@
|
|
|
1
|
+
## 2.26.0
|
|
2
|
+
|
|
3
|
+
- **A slow hook is refused.** SK045 fails a repo whose hook on every tool call (`PreToolUse`, `PostToolUse`) takes over 150 ms on a no-op Bash call, and fails a hook on a save as soon as it is wired, unless `repo.config.ts` names it under `instantHooks` with the reason it is instant. SK046 warns on the runs the harness recorded. `sk time hooks` shows what each hook cost.
|
|
4
|
+
- **A suite that fails only in a loaded pool runs again alone** before the gate goes red: it passes alone, the gate warns and names the file and the load; it fails alone too, the machine was quiet, or more than three suites failed, the red stands.
|
|
5
|
+
- **The cache**: a submodule declared as an input keys by the commit it stands at while it is filled and holds no change of its own; an ignored file named as an input keeps its key after the first scan; a write in flight (`.dist.tmp-<pid>`) is never proposed as an ignored input.
|
|
6
|
+
- **A defect of a toolkit check never fails another repo's gate**: the check runs there with no cache and says whose defect it is; the repo that hosts the toolkit still fails on it.
|
|
7
|
+
- **Review**: once no watch of a card's lane or session lives, whoever reads the answer marks it seen; `sk review inbox --hook` runs the inbox as a Claude Code hook on a prompt and at a turn's end; the worker that blocked a raised item takes it back or closes it.
|
|
8
|
+
- **`sk releases remove <card id | title>`** takes one change out of the next release file.
|
|
9
|
+
- **`sk wiki lint`** checks that an anchor names a heading of its page; a changelog or a journal keeps a link as written.
|
|
10
|
+
- **`sk mv`** leaves archived repros and field notes as written too.
|
|
11
|
+
- **`sk backup --check`** reads the local files the daemon's looks keep, three times faster.
|
|
12
|
+
- **The bun types follow the machine's bun** (`@types/bun` ^1.4.4).
|
|
13
|
+
|
|
1
14
|
## 2.25.0
|
|
2
15
|
|
|
3
16
|
- **A repo adjusts its own lane count.** `sk capacity` answers how many lanes this repo runs now from the cores, the 1 minute load and the agents at work: never zero, `--max <n>` is the count the owner gave, and only a machine at twice its cores of load stops a lane. `sk lanes` shows each live session and lane, since when, and what it does.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "rvlib-shipkit",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.26.0",
|
|
4
4
|
"funding": "https://github.com/sponsors/rvion",
|
|
5
5
|
"description": "All-in-one repo companion: ci gate (task DAG), auto-discovered health checks, release-contract fulfillness, asks queue, md-wiki tools, asset atelier, live tui",
|
|
6
6
|
"license": "MIT",
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
"./src/*": "./src/*"
|
|
24
24
|
},
|
|
25
25
|
"devDependencies": {
|
|
26
|
-
"@types/bun": "^1.
|
|
26
|
+
"@types/bun": "^1.4.4",
|
|
27
27
|
"@types/react": "^19.2.17",
|
|
28
28
|
"@types/react-dom": "^19.2.3",
|
|
29
29
|
"@types/sanitize-html": "^2.16.1",
|
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
// HOOKS ON THE AGENT'S PATH: what the settings wire to run on each tool call or
|
|
2
|
+
// each turn, the budget of each cadence, the probe a gate may run, and the
|
|
3
|
+
// verdicts of SK045 (the gate) and SK046 (the recorded runs, a warning).
|
|
4
|
+
// `sk time hooks` reads the same declarations.
|
|
5
|
+
//
|
|
6
|
+
// The constraint a reader breaks first: the harness records a hook's run only
|
|
7
|
+
// when the hook printed something, so a silent hook has no record, and a hook
|
|
8
|
+
// the probe may not run (one on a save may write) has no measure at all.
|
|
9
|
+
import { createHash } from 'crypto'
|
|
10
|
+
import { existsSync, readFileSync, realpathSync, statSync } from 'fs'
|
|
11
|
+
import { homedir } from 'os'
|
|
12
|
+
import { dirname, isAbsolute, join, relative, resolve } from 'path'
|
|
13
|
+
import { gitBin } from '../core/git-bin.ts'
|
|
14
|
+
import { houseOfIndex } from '../home/home-paths.ts'
|
|
15
|
+
import { discoverConfigRoots } from '../reflect/prompt-corpus.ts'
|
|
16
|
+
import { homeRepo, houseIndex } from '../serve/project-gutter.ts'
|
|
17
|
+
|
|
18
|
+
/** how often a hook stands in the agent's way */
|
|
19
|
+
export type Cadence = 'call' | 'turn' | 'other'
|
|
20
|
+
|
|
21
|
+
const CADENCE: Record<string, Cadence> = { PreToolUse: 'call', PostToolUse: 'call', PostToolUseFailure: 'call', UserPromptSubmit: 'turn', Stop: 'turn', SubagentStop: 'turn' }
|
|
22
|
+
export const cadenceOf = (event: string): Cadence => CADENCE[event] ?? 'other'
|
|
23
|
+
|
|
24
|
+
/** a hook on every tool call: bun's own start is about 60 ms on a loaded Mac,
|
|
25
|
+
* so this leaves a guard room to read a file or two, and a whole tree
|
|
26
|
+
* typecheck (a median near a second) is far over */
|
|
27
|
+
export const CALL_BUDGET_MS = 150
|
|
28
|
+
/** a hook on each prompt or turn end runs once per many calls: ten times
|
|
29
|
+
* more, and over it warns, never fails */
|
|
30
|
+
export const TURN_BUDGET_MS = 1000
|
|
31
|
+
/** recorded runs a median needs before it judges */
|
|
32
|
+
export const MIN_RUNS = 5
|
|
33
|
+
/** records older than this describe another machine load and another tree */
|
|
34
|
+
export const RECORD_DAYS = 30
|
|
35
|
+
/** probe runs after one warm up: the fastest is a floor no load explains */
|
|
36
|
+
export const PROBE_RUNS = 5
|
|
37
|
+
|
|
38
|
+
export type HookSource = 'repo' | 'local' | 'user'
|
|
39
|
+
|
|
40
|
+
/** one hook as a settings file declares it; `command` is '' for a hook of
|
|
41
|
+
* another type, named by `type` */
|
|
42
|
+
export type DeclaredHook = { event: string; matcher: string; type: string; command: string; timeoutS: number | null; source: HookSource; file: string }
|
|
43
|
+
|
|
44
|
+
type RawSettings = { hooks?: Record<string, { matcher?: unknown; hooks?: { type?: unknown; command?: unknown; timeout?: unknown }[] }[]> }
|
|
45
|
+
|
|
46
|
+
/** the hooks of one settings text; throws on text that is not JSON */
|
|
47
|
+
export function parseHooks(text: string, source: HookSource, file: string): DeclaredHook[] {
|
|
48
|
+
const j = JSON.parse(text) as RawSettings
|
|
49
|
+
const out: DeclaredHook[] = []
|
|
50
|
+
for (const [event, entries] of Object.entries(j?.hooks ?? {})) {
|
|
51
|
+
if (!Array.isArray(entries)) continue
|
|
52
|
+
for (const e of entries) {
|
|
53
|
+
const matcher = typeof e?.matcher === 'string' ? e.matcher : ''
|
|
54
|
+
for (const h of Array.isArray(e?.hooks) ? e.hooks : []) {
|
|
55
|
+
const type = typeof h?.type === 'string' ? h.type : 'command'
|
|
56
|
+
const command = type === 'command' && typeof h?.command === 'string' ? h.command : ''
|
|
57
|
+
out.push({ event, matcher, type, command, timeoutS: typeof h?.timeout === 'number' ? h.timeout : null, source, file })
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return out
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export const REPO_SETTINGS = ['.claude/settings.json', '.claude/settings.local.json'] as const
|
|
65
|
+
|
|
66
|
+
/** the hooks a repo's own settings declare, and the files that did not parse */
|
|
67
|
+
export function repoHooks(root: string): { hooks: DeclaredHook[]; broken: string[] } {
|
|
68
|
+
const hooks: DeclaredHook[] = []
|
|
69
|
+
const broken: string[] = []
|
|
70
|
+
for (const rel of REPO_SETTINGS) {
|
|
71
|
+
const text = readOrNull(join(root, rel))
|
|
72
|
+
if (text == null) continue
|
|
73
|
+
try {
|
|
74
|
+
hooks.push(...parseHooks(text, rel.endsWith('.local.json') ? 'local' : 'repo', rel))
|
|
75
|
+
} catch {
|
|
76
|
+
broken.push(rel)
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return { hooks, broken }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** the settings file of every Claude Code account on the machine */
|
|
83
|
+
export function userSettingsFiles(home = homedir()): string[] {
|
|
84
|
+
return discoverConfigRoots(home).map((r) => join(dirname(r.projects), 'settings.json')).filter((f) => existsSync(f))
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** the hooks every account declares for every repo; one entry per distinct
|
|
88
|
+
* hook, its file the first account that declares it */
|
|
89
|
+
export function userHooks(home = homedir()): DeclaredHook[] {
|
|
90
|
+
const seen = new Map<string, DeclaredHook>()
|
|
91
|
+
for (const f of userSettingsFiles(home)) {
|
|
92
|
+
const text = readOrNull(f)
|
|
93
|
+
if (text == null) continue
|
|
94
|
+
let hooks: DeclaredHook[]
|
|
95
|
+
try {
|
|
96
|
+
hooks = parseHooks(text, 'user', f.startsWith(`${home}/`) ? `~/${relative(home, f)}` : f)
|
|
97
|
+
} catch {
|
|
98
|
+
continue
|
|
99
|
+
}
|
|
100
|
+
for (const h of hooks) if (!seen.has(hookKey(h))) seen.set(hookKey(h), h)
|
|
101
|
+
}
|
|
102
|
+
return [...seen.values()]
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** this repo is the house, the one gate that judges the machine's own hooks */
|
|
106
|
+
export function isHouse(root: string): boolean {
|
|
107
|
+
const index = houseIndex(homeRepo(root), homedir())
|
|
108
|
+
return index != null && houseOfIndex(index) === root
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** a settings file that does not parse still applies: the check says so */
|
|
112
|
+
export function hasHooks(root: string): boolean {
|
|
113
|
+
const r = repoHooks(root)
|
|
114
|
+
return r.hooks.length > 0 || r.broken.length > 0 || (isHouse(root) && userHooks().length > 0)
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export const hookKey = (h: { event: string; matcher?: string; command: string }): string => `${h.event}\u0000${h.matcher ?? ''}\u0000${h.command}`
|
|
118
|
+
|
|
119
|
+
/** Claude Code's matcher: none, `*` or `.*` takes every tool, else a regex on the whole tool name */
|
|
120
|
+
export function matcherMatches(matcher: string, tool: string): boolean {
|
|
121
|
+
const m = matcher.trim()
|
|
122
|
+
if (m === '' || m === '*' || m === '.*') return true
|
|
123
|
+
try {
|
|
124
|
+
return new RegExp(`^(?:${m})$`).test(tool)
|
|
125
|
+
} catch {
|
|
126
|
+
return m === tool
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export const matcherLabel = (matcher: string): string => (['', '*', '.*'].includes(matcher.trim()) ? 'every tool' : matcher)
|
|
131
|
+
|
|
132
|
+
// ── the probe ──────────────────────────────────────────────────────────────
|
|
133
|
+
|
|
134
|
+
const PROBE_ID = 'shipkit-hook-probe'
|
|
135
|
+
|
|
136
|
+
/** the probe runs a hook only on what the harness itself sends for a Bash
|
|
137
|
+
* `true`, a call that changes nothing, so it does no more than a real no-op
|
|
138
|
+
* call does. A hook whose matcher takes no Bash call is never run: on a
|
|
139
|
+
* made up save it may write, and its cost hangs on the file it is given */
|
|
140
|
+
export const probeable = (h: DeclaredHook): boolean => h.command !== '' && (h.event === 'PreToolUse' || h.event === 'PostToolUse') && matcherMatches(h.matcher, 'Bash')
|
|
141
|
+
|
|
142
|
+
export function probeInput(h: DeclaredHook, root: string): string {
|
|
143
|
+
const base = { session_id: PROBE_ID, transcript_path: '', cwd: root, permission_mode: 'default', hook_event_name: h.event, tool_name: 'Bash', tool_input: { command: 'true', description: 'a no-op' }, tool_use_id: PROBE_ID }
|
|
144
|
+
return JSON.stringify(h.event === 'PostToolUse' ? { ...base, tool_response: { stdout: '', stderr: '', interrupted: false, isImage: false } } : base)
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export type Probe = { ms: number[]; code: number | null; timedOut: boolean }
|
|
148
|
+
|
|
149
|
+
/** the env a probed hook gets: the caller's, minus the live session's own
|
|
150
|
+
* channel (its id, messaging socket and token, pid), plus the project dir */
|
|
151
|
+
export function probeEnv(from: Record<string, string | undefined>, root: string): Record<string, string | undefined> {
|
|
152
|
+
const env: Record<string, string | undefined> = {}
|
|
153
|
+
for (const [k, v] of Object.entries(from)) if (!k.startsWith('CLAUDE_CODE_') && k !== 'CLAUDE_PID') env[k] = v
|
|
154
|
+
env.CLAUDE_PROJECT_DIR = root
|
|
155
|
+
return env
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** the hook run as the harness runs it (a shell, the repo as its project dir,
|
|
159
|
+
* the input on stdin), once to warm up and PROBE_RUNS times measured */
|
|
160
|
+
export async function probeHook(h: DeclaredHook, root: string, runs = PROBE_RUNS): Promise<Probe> {
|
|
161
|
+
const env = probeEnv(process.env, root)
|
|
162
|
+
const input = Buffer.from(probeInput(h, root))
|
|
163
|
+
const capMs = Math.min(h.timeoutS ?? 60, 5) * 1000
|
|
164
|
+
const ms: number[] = []
|
|
165
|
+
let code: number | null = null
|
|
166
|
+
for (let i = 0; i <= runs; i++) {
|
|
167
|
+
const t0 = performance.now()
|
|
168
|
+
const p = Bun.spawn(['/bin/sh', '-c', h.command], { cwd: root, env, stdin: input, stdout: 'ignore', stderr: 'ignore' })
|
|
169
|
+
const timer = setTimeout(() => p.kill(9), capMs)
|
|
170
|
+
code = await p.exited
|
|
171
|
+
clearTimeout(timer)
|
|
172
|
+
const took = performance.now() - t0
|
|
173
|
+
if (took >= capMs) return { ms: [...ms, took], code, timedOut: true }
|
|
174
|
+
// exit 2 is a block, an answer like any other; anything else but 0 means it did not run as meant
|
|
175
|
+
if (code !== 0 && code !== 2) return { ms, code, timedOut: false }
|
|
176
|
+
if (i > 0) ms.push(took)
|
|
177
|
+
}
|
|
178
|
+
return { ms, code, timedOut: false }
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// ── when the hook last changed ─────────────────────────────────────────────
|
|
182
|
+
|
|
183
|
+
/** the files a command names: its quoted or bare paths, the project dir and ~ expanded */
|
|
184
|
+
export function scriptsOf(command: string, root: string, home = homedir()): string[] {
|
|
185
|
+
const out: string[] = []
|
|
186
|
+
for (const raw of command.replace(/["']/g, '').split(/\s+/)) {
|
|
187
|
+
const t = raw.replace(/\$\{?CLAUDE_PROJECT_DIR\}?/g, root).replace(/^~(?=\/)/, home)
|
|
188
|
+
if (!t.includes('/')) continue
|
|
189
|
+
const p = isAbsolute(t) ? t : resolve(root, t)
|
|
190
|
+
try {
|
|
191
|
+
if (statSync(p).isFile()) out.push(p)
|
|
192
|
+
} catch { /* not a file */ }
|
|
193
|
+
}
|
|
194
|
+
return out
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** when the files a hook runs last changed: a tracked file its last commit
|
|
198
|
+
* while it is clean, any other its mtime; null when it names none. A record
|
|
199
|
+
* older than this timed another version of the hook */
|
|
200
|
+
export function changedAt(command: string, root: string, home = homedir()): number | null {
|
|
201
|
+
let at: number | null = null
|
|
202
|
+
for (const f of scriptsOf(command, root, home)) {
|
|
203
|
+
const real = safeReal(f)
|
|
204
|
+
const rel = relative(root, real)
|
|
205
|
+
let t: number | null = null
|
|
206
|
+
if (!rel.startsWith('..') && !rel.split('/').includes('node_modules')) {
|
|
207
|
+
const dirty = Bun.spawnSync([gitBin(), 'status', '--porcelain', '--', rel], { cwd: root, stdout: 'pipe', stderr: 'ignore' })
|
|
208
|
+
if (dirty.exitCode === 0 && dirty.stdout.toString().trim() === '') {
|
|
209
|
+
const log = Bun.spawnSync([gitBin(), 'log', '-1', '--format=%ct', '--', rel], { cwd: root, stdout: 'pipe', stderr: 'ignore' })
|
|
210
|
+
const s = Number(log.stdout.toString().trim())
|
|
211
|
+
if (log.exitCode === 0 && s > 0) t = s * 1000
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
if (t == null) t = statSync(real).mtimeMs
|
|
215
|
+
if (at == null || t > at) at = t
|
|
216
|
+
}
|
|
217
|
+
return at
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** what a cached answer is keyed on: the settings texts and the stamp of each file their hooks run */
|
|
221
|
+
export function hooksKey(root: string, settings: string[], home = homedir()): string {
|
|
222
|
+
const h = createHash('sha1')
|
|
223
|
+
for (const f of settings) {
|
|
224
|
+
const text = readOrNull(isAbsolute(f) ? f : join(root, f))
|
|
225
|
+
h.update(`${f}\u0000${text ?? '-'}\u0000`)
|
|
226
|
+
if (text == null) continue
|
|
227
|
+
let hooks: DeclaredHook[] = []
|
|
228
|
+
try {
|
|
229
|
+
hooks = parseHooks(text, 'repo', f)
|
|
230
|
+
} catch { /* the body reports it */ }
|
|
231
|
+
for (const x of hooks)
|
|
232
|
+
for (const s of scriptsOf(x.command, root, home)) {
|
|
233
|
+
const st = statSync(safeReal(s))
|
|
234
|
+
h.update(`${s}:${st.size}:${Math.floor(st.mtimeMs)}\u0000`)
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
return h.digest('hex').slice(0, 16)
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// ── the verdict ────────────────────────────────────────────────────────────
|
|
241
|
+
|
|
242
|
+
export type Measure = { runs: number; p50: number; p90: number; max: number; total: number }
|
|
243
|
+
|
|
244
|
+
export function measureOf(ms: number[]): Measure | null {
|
|
245
|
+
if (ms.length === 0) return null
|
|
246
|
+
const s = [...ms].sort((a, b) => a - b)
|
|
247
|
+
const q = (p: number): number => s[Math.min(s.length - 1, Math.floor(p * s.length))] ?? 0
|
|
248
|
+
return { runs: s.length, p50: q(0.5), p90: q(0.9), max: s[s.length - 1] ?? 0, total: s.reduce((a, b) => a + b, 0) }
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
export type Verdict = { level: 'ok' | 'warn' | 'fail'; text: string; fix?: string }
|
|
252
|
+
|
|
253
|
+
/** 40 ms, 1.3 s */
|
|
254
|
+
export const fmtHookMs = (ms: number): string => (ms < 1000 ? `${Math.round(ms)} ms` : `${(ms / 1000).toFixed(1)} s`)
|
|
255
|
+
|
|
256
|
+
const recordedWords = (m: Measure): string => `median ${fmtHookMs(m.p50)} over ${m.runs} recorded run${m.runs === 1 ? '' : 's'} (p90 ${fmtHookMs(m.p90)}, worst ${fmtHookMs(m.max)})`
|
|
257
|
+
|
|
258
|
+
const probeWords = (p: Probe): string => {
|
|
259
|
+
const m = measureOf(p.ms)
|
|
260
|
+
return m == null ? 'no probe run' : `fastest ${fmtHookMs(Math.min(...p.ms))}, median ${fmtHookMs(m.p50)} of ${m.runs} probe runs on a no-op Bash call`
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
export const hookLabel = (h: DeclaredHook): string =>
|
|
264
|
+
`${cadenceOf(h.event) === 'call' ? `${h.event} on ${matcherLabel(h.matcher)}` : h.event} (${h.file}): ${h.command === '' ? `a ${h.type} hook` : `\`${h.command}\``}`
|
|
265
|
+
|
|
266
|
+
/** the key of repo.config.ts that declares a hook the gate cannot time */
|
|
267
|
+
export const INSTANT_KEY = 'instantHooks'
|
|
268
|
+
|
|
269
|
+
const NOT_RECORDED = 'the harness records a hook run only when the hook prints something'
|
|
270
|
+
const AS_A_CHECK = 'work over the tree runs as a check when the step is done: sk ci --only <check>'
|
|
271
|
+
|
|
272
|
+
/** SK045's verdict on one per call hook, from what the gate itself can tell:
|
|
273
|
+
* its probe, or the repo's word that it answers at once. `instant` is the
|
|
274
|
+
* reason the repo declares, `machine` (a user level hook) turns a fail into a warn */
|
|
275
|
+
export function judgeGate(h: DeclaredHook, probe: Probe | null, opts: { instant?: string; machine?: boolean } = {}): Verdict {
|
|
276
|
+
const label = hookLabel(h)
|
|
277
|
+
const red = opts.machine ? 'warn' : 'fail'
|
|
278
|
+
const lift = h.source === 'user' ? `drop it from ${h.file}` : `remove its entry in ${h.file}`
|
|
279
|
+
if (probe == null) {
|
|
280
|
+
if (opts.instant != null) return { level: 'ok', text: `${label}: declared instant in repo.config.ts (${opts.instant}); its recorded runs: SK046` }
|
|
281
|
+
return {
|
|
282
|
+
level: red,
|
|
283
|
+
text: `${label}: a hook on every ${matcherLabel(h.matcher)} call that the gate cannot time (it runs only a hook that takes a Bash call: a made up save may write, and its cost hangs on the file), and repo.config.ts does not declare it instant`,
|
|
284
|
+
fix: `${lift}, or declare it in repo.config.ts ${INSTANT_KEY} with the reason it answers at once; ${AS_A_CHECK}`,
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
if (probe.timedOut || (probe.ms.length > 0 && Math.min(...probe.ms) > CALL_BUDGET_MS && (probe.code === 0 || probe.code === 2)))
|
|
288
|
+
return {
|
|
289
|
+
level: red,
|
|
290
|
+
text: `${label}: ${probe.timedOut ? `a probe run on a no-op Bash call took over ${fmtHookMs(probe.ms[probe.ms.length - 1] ?? 0)}` : probeWords(probe)}, over the ${CALL_BUDGET_MS} ms budget of a hook on every tool call${h.source === 'user' ? ' (a hook of every session on the machine)' : ''}`,
|
|
291
|
+
fix: `make it read its input and decide under ${CALL_BUDGET_MS} ms, or ${lift}; ${AS_A_CHECK}`,
|
|
292
|
+
}
|
|
293
|
+
if (probe.code !== 0 && probe.code !== 2)
|
|
294
|
+
return { level: 'warn', text: `${label}: its probe exited ${probe.code} on a no-op Bash call, so every call it applies to runs a broken hook`, fix: `run it by hand on a Bash call's input and fix its command, or ${lift}` }
|
|
295
|
+
return { level: 'ok', text: `${label}: ${probeWords(probe)}` }
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/** SK046's verdict on one hook from the runs the harness recorded: a warning
|
|
299
|
+
* past the budget of its cadence, never a fail (the index is the world) */
|
|
300
|
+
export function judgeRecords(h: DeclaredHook, recorded: number[], behind?: string): Verdict {
|
|
301
|
+
const label = hookLabel(h)
|
|
302
|
+
const rec = measureOf(recorded)
|
|
303
|
+
const cadence = cadenceOf(h.event)
|
|
304
|
+
const budget = cadence === 'call' ? CALL_BUDGET_MS : TURN_BUDGET_MS
|
|
305
|
+
if (rec == null) return { level: 'ok', text: `${label}: no timed run recorded (${NOT_RECORDED})${behind == null ? '' : `; ${behind}`}` }
|
|
306
|
+
if (rec.runs >= MIN_RUNS && rec.p50 > budget)
|
|
307
|
+
return {
|
|
308
|
+
level: 'warn',
|
|
309
|
+
text: `${label}: ${recordedWords(rec)}, over the ${fmtHookMs(budget)} budget of a hook on every ${cadence === 'call' ? 'tool call' : 'prompt or turn end'}`,
|
|
310
|
+
fix: `make it read its input and decide under ${fmtHookMs(budget)}, or remove it; ${AS_A_CHECK}`,
|
|
311
|
+
}
|
|
312
|
+
return { level: 'ok', text: `${label}: ${recordedWords(rec)}${rec.runs < MIN_RUNS ? `, ${MIN_RUNS} needed to judge` : ''}` }
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function readOrNull(path: string): string | null {
|
|
316
|
+
try {
|
|
317
|
+
return readFileSync(path, 'utf8')
|
|
318
|
+
} catch {
|
|
319
|
+
return null
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function safeReal(p: string): string {
|
|
324
|
+
try {
|
|
325
|
+
return realpathSync(p)
|
|
326
|
+
} catch {
|
|
327
|
+
return p
|
|
328
|
+
}
|
|
329
|
+
}
|
package/src/agent-time/render.ts
CHANGED
|
@@ -5,7 +5,7 @@ import type { Breakdown } from './timeline.ts'
|
|
|
5
5
|
import { running, type ShapeRow, type TimeReport, total } from './report.ts'
|
|
6
6
|
import type { TurnStats } from './turns.ts'
|
|
7
7
|
|
|
8
|
-
export const VIEWS = ['summary', 'commands', 'tools', 'slow', 'fails', 'feedback', 'sessions', 'turns'] as const
|
|
8
|
+
export const VIEWS = ['summary', 'commands', 'tools', 'slow', 'fails', 'feedback', 'sessions', 'turns', 'hooks'] as const
|
|
9
9
|
export type View = (typeof VIEWS)[number]
|
|
10
10
|
|
|
11
11
|
/** 0.4s, 12s, 4m10s, 3.2h */
|
|
@@ -123,7 +123,7 @@ function summary(r: TimeReport): string[] {
|
|
|
123
123
|
out.push('', ...feedbackHead(r))
|
|
124
124
|
const slow = r.feedback.hits.filter((h) => h.signals.some((s) => s.signal === 'slow')).slice(-3)
|
|
125
125
|
for (const h of slow) out.push(complaint(h))
|
|
126
|
-
out.push('', 'more: sk time commands | tools | slow | fails | feedback | sessions | turns, --json')
|
|
126
|
+
out.push('', 'more: sk time commands | tools | slow | fails | feedback | sessions | turns | hooks, --json')
|
|
127
127
|
return out
|
|
128
128
|
}
|
|
129
129
|
|
|
@@ -177,6 +177,18 @@ export function render(r: TimeReport, view: View, top: number): string {
|
|
|
177
177
|
case 'sessions':
|
|
178
178
|
out = [`${r.sessionRows.length} sessions, by wall (idle left out)`, ...table(['session', 'account', 'start', 'wall', 'model', 'tools', 'sub', 'bg', 'parked', 'unknown', 'you', 'calls', 'agents', 'first prompt'], r.sessionRows.slice(0, top).map((s) => [s.session.slice(0, 8), account(s.account), when(s.start), fmtMs(total(s.wall, false)), fmtMs(s.wall.model), fmtMs(s.wall.tools), fmtMs(s.wall.subagent), fmtMs(s.wall.background), fmtMs(s.wall.parked), fmtMs(s.wall.unknown), fmtMs(s.wall.human), `${s.calls}`, `${s.subagents}`, s.first.slice(0, 40)]))]
|
|
179
179
|
break
|
|
180
|
+
case 'hooks': {
|
|
181
|
+
const ms = (x: number): string => (x < 1000 ? `${Math.round(x)}ms` : fmtMs(x))
|
|
182
|
+
out = [
|
|
183
|
+
`${r.hooks.length} hook command${r.hooks.length === 1 ? '' : 's'}, by cost (~waited: the mean of its timed runs times the calls it applies to, an estimate: high where the hook returns early without a record, low where it is slow and silent)`,
|
|
184
|
+
' only runs the harness timed: it writes a record only when the hook printed something, so a silent hook is missing and the runs under count',
|
|
185
|
+
" a hook's time sits inside the call or the turn it ran on; calls: between its first and last recorded run, by its declared matcher, * by the tools it was recorded on",
|
|
186
|
+
...table(['hook', 'event', 'runs', 'median', 'mean', 'p90', 'worst', 'total', 'errors', 'calls', '~waited'], r.hooks.slice(0, top).map((h) => [h.command.slice(0, 56), h.event, n(h.runs), ms(h.p50), ms(h.mean), ms(h.p90), ms(h.max), fmtMs(h.total), h.errors === 0 ? '' : `${h.errors}`, h.calls == null ? '-' : `${n(h.calls)}${h.byMatcher ? '' : '*'}`, h.calls == null ? '-' : `~${fmtMs(h.mean * h.calls)}`])),
|
|
187
|
+
]
|
|
188
|
+
if (r.hooks.some((h) => h.placed))
|
|
189
|
+
out.push(' `command hook <n>`: some harness versions name a hook by its place in the settings, never its command, and the place is not stable across edits and accounts, so those runs cannot be tied to a command. Such a row and a named row on the same event and tools can be one hook over the same calls: never add their ~waited')
|
|
190
|
+
break
|
|
191
|
+
}
|
|
180
192
|
case 'turns': {
|
|
181
193
|
const t = r.turns
|
|
182
194
|
const reads = t.reads.reduce((a, x) => a + x.model, 0)
|
package/src/agent-time/report.ts
CHANGED
|
@@ -9,7 +9,8 @@ import { type PromptEntry, dedupePrompts } from '../reflect/prompt-corpus.ts'
|
|
|
9
9
|
import type { Outcome } from '../reflect/transcript.ts'
|
|
10
10
|
import type { Masker } from './mask.ts'
|
|
11
11
|
import { type Signal, signalsOf } from './signals.ts'
|
|
12
|
-
import type { FileRow, Loaded } from './store.ts'
|
|
12
|
+
import type { FileRow, HookRun, Loaded } from './store.ts'
|
|
13
|
+
import { cadenceOf, matcherMatches } from './hooks.ts'
|
|
13
14
|
import { type ReadCost, type TurnStats, addTurns, emptyTurns, turnsOf } from './turns.ts'
|
|
14
15
|
import { type Breakdown, type Call, type Mark, type Stream, FAILED, IDLE_MS, addBreakdown, callMs, type Closed, closeCalls, emptyBreakdown, quantileSorted, ranBefore, retries, runMs, wallBreakdown } from './timeline.ts'
|
|
15
16
|
|
|
@@ -61,9 +62,57 @@ export type TimeReport = {
|
|
|
61
62
|
turns: TurnReport
|
|
62
63
|
/** the measured waste, biggest first: each with the number behind it */
|
|
63
64
|
insights: Insight[]
|
|
65
|
+
hooks: HookRow[]
|
|
64
66
|
}
|
|
65
67
|
|
|
66
|
-
|
|
68
|
+
/** one hook command on one event, from the runs the harness timed (only the
|
|
69
|
+
* runs that printed). `calls`: the tool calls it applies to between its
|
|
70
|
+
* first and its last recorded run, by its declared matcher, else by the tools it was recorded
|
|
71
|
+
* on (`byMatcher` false); null on a turn event */
|
|
72
|
+
export type HookRow = { event: string; command: string; tools: string[]; runs: number; mean: number; p50: number; p90: number; max: number; total: number; errors: number; first: number; calls: number | null; byMatcher: boolean; placed: boolean }
|
|
73
|
+
|
|
74
|
+
/** some harness versions name a hook by its place in the settings (`command
|
|
75
|
+
* hook 2`), never its command: the place shifts as entries are added or
|
|
76
|
+
* differ per account, so those runs cannot be tied to a command */
|
|
77
|
+
export const PLACED = /^command hook \d+$/
|
|
78
|
+
|
|
79
|
+
/** key of a declared hook's matcher, by its event and command */
|
|
80
|
+
export const hookMatcherKey = (event: string, command: string): string => `${event}\u0000${command}`
|
|
81
|
+
|
|
82
|
+
export function hookRowsOf(runs: HookRun[], calls: { tool: string; start: number; end: number | null }[], matchers: Map<string, string>, mask: Masker): HookRow[] {
|
|
83
|
+
const by = new Map<string, HookRun[]>()
|
|
84
|
+
for (const r of runs) pushTo(by, hookMatcherKey(r.event, r.command), r)
|
|
85
|
+
return [...by.values()].map((rs): HookRow => {
|
|
86
|
+
const first = rs[0] as HookRun
|
|
87
|
+
const ms = rs.map((r) => r.ms).sort((a, b) => a - b)
|
|
88
|
+
const tools = [...new Set(rs.map((r) => r.tool).filter((t) => t !== ''))].sort()
|
|
89
|
+
const matcher = matchers.get(hookMatcherKey(first.event, first.command)) ?? null
|
|
90
|
+
const start = Math.min(...rs.map((r) => r.at))
|
|
91
|
+
const last = Math.max(...rs.map((r) => r.at))
|
|
92
|
+
const applies = (tool: string): boolean => (matcher != null ? matcherMatches(matcher, tool) : tools.includes(tool))
|
|
93
|
+
const n = cadenceOf(first.event) === 'call' ? calls.filter((c) => (c.end ?? c.start) >= start && c.start <= last && applies(c.tool)).length : null
|
|
94
|
+
const total = ms.reduce((a, b) => a + b, 0)
|
|
95
|
+
return { event: first.event, command: mask(first.command), tools, runs: ms.length, mean: total / ms.length, p50: quantileSorted(ms, 0.5), p90: quantileSorted(ms, 0.9), max: ms[ms.length - 1] ?? 0, total, errors: rs.filter((r) => r.error).length, first: start, calls: n, byMatcher: matcher != null, placed: PLACED.test(first.command) }
|
|
96
|
+
}).sort((a, b) => hookCost(b) - hookCost(a))
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** an estimate of what a hook cost: the mean of its timed runs times the
|
|
100
|
+
* calls it applies to. It errs high where the hook returns early on calls
|
|
101
|
+
* that left no record (a silent run is never timed), low where it is slow
|
|
102
|
+
* and silent; never less than what was recorded */
|
|
103
|
+
export const hookCost = (h: HookRow): number => Math.max(h.total, h.calls == null ? 0 : h.mean * h.calls)
|
|
104
|
+
|
|
105
|
+
/** hook time is material past a minute recorded or five estimated */
|
|
106
|
+
export function hookInsight(rows: HookRow[]): Insight | null {
|
|
107
|
+
const top = rows[0]
|
|
108
|
+
if (top == null) return null
|
|
109
|
+
const est = top.calls == null ? 0 : top.mean * top.calls
|
|
110
|
+
if (top.total < 60_000 && est < 300_000) return null
|
|
111
|
+
const on = top.calls == null ? '' : `; it applies to ${top.calls.toLocaleString('en-US')} calls${top.byMatcher ? '' : ' (by the tools it was recorded on)'}, ~${fmt(est)} at the mean of its timed runs (an estimate: high where it returns early without a record)`
|
|
112
|
+
return { id: 'hooks', ms: Math.max(top.total, est), estimate: est > top.total, text: `the hook ${top.command.slice(0, 60)} on ${top.event}: ${top.runs.toLocaleString('en-US')} timed runs recorded, median ${fmt(top.p50)}, ${fmt(top.total)} in all${on} (sk time hooks)` }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export type Insight = { id: 'classifier' | 'bash-edits' | 'polling' | 'failed' | 'approval' | 'background' | 'hooks'; ms: number; estimate: boolean; text: string }
|
|
67
116
|
|
|
68
117
|
/** commands that cost nothing to run: their time is the harness around them */
|
|
69
118
|
const CHEAP = new Set(['grep', 'sed', 'cat', 'ls', 'head', 'tail', 'wc', 'git status', 'echo', 'pwd', 'rg'])
|
|
@@ -208,7 +257,7 @@ function rowsBy(calls: { c: Closed; key: string }[], retriesByKey: Map<string, {
|
|
|
208
257
|
}).sort((a, b) => b.ms - a.ms || b.calls - a.calls)
|
|
209
258
|
}
|
|
210
259
|
|
|
211
|
-
export function buildReport(loaded: Loaded, q: { repos: string[]; from: number | null; to: number; repoOf: (project: string) => string }, mask: Masker): TimeReport {
|
|
260
|
+
export function buildReport(loaded: Loaded, q: { repos: string[]; from: number | null; to: number; repoOf: (project: string) => string; hookMatchers?: Map<string, string> }, mask: Masker): TimeReport {
|
|
212
261
|
const from = q.from ?? -Infinity
|
|
213
262
|
const groups = mergeStreams(loaded)
|
|
214
263
|
const accounts = new Set<string>()
|
|
@@ -319,6 +368,8 @@ export function buildReport(loaded: Loaded, q: { repos: string[]; from: number |
|
|
|
319
368
|
const queued = kept.filter((p) => p.origin === 'queued').length
|
|
320
369
|
|
|
321
370
|
const mains = groups.filter((g) => g.agent === '')
|
|
371
|
+
const hooks = hookRowsOf(loaded.hooks, all.map(({ c }) => c), q.hookMatchers ?? new Map(), mask)
|
|
372
|
+
const hookLine = hookInsight(hooks)
|
|
322
373
|
return {
|
|
323
374
|
repos: q.repos,
|
|
324
375
|
from: q.from,
|
|
@@ -342,7 +393,8 @@ export function buildReport(loaded: Loaded, q: { repos: string[]; from: number |
|
|
|
342
393
|
rows: topBy(turnRows, 200, (r) => r.work),
|
|
343
394
|
reads: [...readCosts.values()].sort((a, b) => b.model - a.model),
|
|
344
395
|
},
|
|
345
|
-
insights: insightsOf(all.map(({ c }) => c), wall, shapes),
|
|
396
|
+
insights: [...insightsOf(all.map(({ c }) => c), wall, shapes), ...(hookLine == null ? [] : [hookLine])].sort((a, b) => b.ms - a.ms),
|
|
397
|
+
hooks,
|
|
346
398
|
}
|
|
347
399
|
}
|
|
348
400
|
|
package/src/agent-time/store.ts
CHANGED
|
@@ -27,7 +27,7 @@ import type { Call, Mark } from './timeline.ts'
|
|
|
27
27
|
export const AGENT_TIME_DB_ENV = 'SHIPKIT_AGENT_TIME_DB'
|
|
28
28
|
|
|
29
29
|
/** bumped when what a row holds changes: every file is read again */
|
|
30
|
-
export const INDEX_VERSION =
|
|
30
|
+
export const INDEX_VERSION = 9
|
|
31
31
|
|
|
32
32
|
export function agentTimeDbPath(): string {
|
|
33
33
|
const env = process.env[AGENT_TIME_DB_ENV]
|
|
@@ -83,6 +83,19 @@ create table if not exists prompts (
|
|
|
83
83
|
);
|
|
84
84
|
create index if not exists prompts_file on prompts (file_id, at);
|
|
85
85
|
create table if not exists meta (key text primary key, value text not null);
|
|
86
|
+
create table if not exists hooks (
|
|
87
|
+
file_id integer not null,
|
|
88
|
+
id text not null,
|
|
89
|
+
at integer not null,
|
|
90
|
+
event text not null,
|
|
91
|
+
tool text not null,
|
|
92
|
+
command text not null,
|
|
93
|
+
ms integer not null,
|
|
94
|
+
code integer,
|
|
95
|
+
error integer not null default 0
|
|
96
|
+
);
|
|
97
|
+
create unique index if not exists hooks_run on hooks (id, event, command);
|
|
98
|
+
create index if not exists hooks_file on hooks (file_id, at);
|
|
86
99
|
create table if not exists bg_ends (
|
|
87
100
|
id text primary key,
|
|
88
101
|
at integer not null,
|
|
@@ -231,7 +244,7 @@ const statements = (db: Database) => ({
|
|
|
231
244
|
get: db.query('select id, size, mtime, offset, version from files where path = ?'),
|
|
232
245
|
insFile: db.query('insert into files (path, account, project, session, agent, size, mtime, offset, version, first_at, last_at) values (?, ?, ?, ?, ?, 0, 0, 0, 0, null, null) returning id'),
|
|
233
246
|
setFile: db.query('update files set size = ?, mtime = ?, offset = ?, version = ?, first_at = coalesce(first_at, ?), last_at = coalesce(?, last_at), gone = 0 where id = ?'),
|
|
234
|
-
clear: [db.query('delete from calls where file_id = ?'), db.query('delete from marks where file_id = ?'), db.query('delete from prompts where file_id = ?')],
|
|
247
|
+
clear: [db.query('delete from calls where file_id = ?'), db.query('delete from marks where file_id = ?'), db.query('delete from prompts where file_id = ?'), db.query('delete from hooks where file_id = ?')],
|
|
235
248
|
resetFile: db.query('update files set offset = 0, first_at = null, last_at = null where id = ?'),
|
|
236
249
|
insCall: db.query('insert or ignore into calls (file_id, id, start, end, tool, shape, cmd, outcome, code, approval, perm, read, bg) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'),
|
|
237
250
|
endCall: db.query('update calls set end = ?, outcome = ?, code = ?, approval = ?, perm = ?, bg = ? where id = ? and end is null'),
|
|
@@ -240,6 +253,8 @@ const statements = (db: Database) => ({
|
|
|
240
253
|
bgEnd: db.query('insert into bg_ends (id, at, outcome, code) values (?, ?, ?, ?) on conflict (id) do update set at = excluded.at, outcome = excluded.outcome, code = excluded.code where excluded.at < bg_ends.at'),
|
|
241
254
|
insMark: db.query('insert into marks (file_id, at, kind) values (?, ?, ?)'),
|
|
242
255
|
insPrompt: db.query('insert into prompts (file_id, at, uuid, origin, text) values (?, ?, ?, ?, ?)'),
|
|
256
|
+
// one run is one call and one command: a copy of the session in another account is the same run
|
|
257
|
+
insHook: db.query('insert or ignore into hooks (file_id, id, at, event, tool, command, ms, code, error) values (?, ?, ?, ?, ?, ?, ?, ?, ?)'),
|
|
243
258
|
})
|
|
244
259
|
|
|
245
260
|
/** write the events of a chunk of lines: a call is written once its result
|
|
@@ -266,7 +281,8 @@ function writeEvents(st: Stmts, fileId: number, events: TranscriptEvent[]): { fi
|
|
|
266
281
|
} else if (e.kind === 'prompt') {
|
|
267
282
|
if (!Number.isNaN(e.at)) st.insPrompt.run(fileId, e.at, e.uuid, e.origin, e.text)
|
|
268
283
|
if (e.origin === 'typed' && !Number.isNaN(e.at)) st.insMark.run(fileId, e.at, 'prompt')
|
|
269
|
-
} else st.
|
|
284
|
+
} else if (e.kind === 'hook') st.insHook.run(fileId, e.id === '' ? String(e.at) : e.id, e.at, e.event, e.tool, e.command, Math.round(e.ms), e.code, e.error ? 1 : 0)
|
|
285
|
+
else st.insMark.run(fileId, e.at, e.kind)
|
|
270
286
|
}
|
|
271
287
|
for (const p of pending.values()) {
|
|
272
288
|
const shape = toolShape(p.tool, p.detail)
|
|
@@ -330,6 +346,44 @@ export function indexTranscripts(db: Database, files: TranscriptFile[], onProgre
|
|
|
330
346
|
return { scanned: files.length, read: todo.length, bytes: readBytes, ms: Math.round(performance.now() - t0), gone: 0 }
|
|
331
347
|
}
|
|
332
348
|
|
|
349
|
+
/** the files to read now, newest first, while their unread bytes fit
|
|
350
|
+
* `maxBytes`, and the unread bytes left for a later run: a bounded catch up
|
|
351
|
+
* that a gate can afford, each file committing alone */
|
|
352
|
+
export function catchUpPlan(db: Database, files: TranscriptFile[], maxBytes: number): { take: TranscriptFile[]; behind: number } {
|
|
353
|
+
const get = db.query('select size, mtime, offset, version from files where path = ?')
|
|
354
|
+
const take: TranscriptFile[] = []
|
|
355
|
+
let room = maxBytes
|
|
356
|
+
let behind = 0
|
|
357
|
+
for (const f of [...files].sort((a, b) => b.mtime - a.mtime)) {
|
|
358
|
+
const prev = get.get(f.path) as IndexedFile | null
|
|
359
|
+
const how = freshness(prev, f)
|
|
360
|
+
if (how === 'skip') continue
|
|
361
|
+
const bytes = how === 'append' && prev != null ? f.size - prev.offset : f.size
|
|
362
|
+
if (bytes <= room) {
|
|
363
|
+
take.push(f)
|
|
364
|
+
room -= bytes
|
|
365
|
+
} else behind += bytes
|
|
366
|
+
}
|
|
367
|
+
return { take, behind }
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** one timed hook run as the index holds it */
|
|
371
|
+
export type HookRun = { file_id: number; project: string; at: number; event: string; tool: string; command: string; ms: number; code: number | null; error: boolean }
|
|
372
|
+
|
|
373
|
+
/** the timed hook runs of the matching projects since `from` */
|
|
374
|
+
export function hookRuns(db: Database, keep: ProjectFilter, from: number, to = Number.MAX_SAFE_INTEGER): HookRun[] {
|
|
375
|
+
const files = (db.query('select id, project from files').all() as { id: number; project: string }[]).filter((f) => keep(f.project))
|
|
376
|
+
const projectOf = new Map(files.map((f) => [f.id, f.project]))
|
|
377
|
+
const ids = files.map((f) => f.id)
|
|
378
|
+
const out: HookRun[] = []
|
|
379
|
+
for (let i = 0; i < ids.length; i += 500) {
|
|
380
|
+
const part = ids.slice(i, i + 500)
|
|
381
|
+
const rows = db.query(`select file_id, at, event, tool, command, ms, code, error = 1 as error from hooks where file_id in (${part.map(() => '?').join(',')}) and at between ? and ?`).all(...part, from, to) as Omit<HookRun, 'project'>[]
|
|
382
|
+
for (const r of rows) out.push({ ...r, error: Boolean(r.error), project: projectOf.get(r.file_id) ?? '' })
|
|
383
|
+
}
|
|
384
|
+
return out.sort((a, b) => a.at - b.at)
|
|
385
|
+
}
|
|
386
|
+
|
|
333
387
|
/** the files the index holds that are no longer on disk, marked so the
|
|
334
388
|
* report can say how much history outlived the harness */
|
|
335
389
|
export function markGone(db: Database, onDisk: TranscriptFile[], keep: ProjectFilter): number {
|
|
@@ -350,7 +404,7 @@ export function markGone(db: Database, onDisk: TranscriptFile[], keep: ProjectFi
|
|
|
350
404
|
|
|
351
405
|
export type FileRow = { id: number; path: string; account: string; project: string; session: string; agent: string; first_at: number | null; last_at: number | null; gone: number }
|
|
352
406
|
|
|
353
|
-
export type Loaded = { files: FileRow[]; calls: Map<number, Call[]>; marks: Map<number, Mark[]>; prompts: { file_id: number; at: number; origin: 'typed' | 'queued'; text: string }[] }
|
|
407
|
+
export type Loaded = { files: FileRow[]; calls: Map<number, Call[]>; marks: Map<number, Mark[]>; prompts: { file_id: number; at: number; origin: 'typed' | 'queued'; text: string }[]; hooks: HookRun[] }
|
|
354
408
|
|
|
355
409
|
/** every row of the matching projects with activity in [from, to] */
|
|
356
410
|
export function loadWindow(db: Database, keep: ProjectFilter, from: number, to: number): Loaded {
|
|
@@ -384,7 +438,7 @@ export function loadWindow(db: Database, keep: ProjectFilter, from: number, to:
|
|
|
384
438
|
}
|
|
385
439
|
prompts.push(...(db.query(`select file_id, at, origin, text from prompts where file_id in (${inList}) and at between ? and ?`).all(...part, from, to) as Loaded['prompts']))
|
|
386
440
|
}
|
|
387
|
-
return { files, calls, marks, prompts }
|
|
441
|
+
return { files, calls, marks, prompts, hooks: hookRuns(db, keep, from, to) }
|
|
388
442
|
}
|
|
389
443
|
|
|
390
444
|
/** the repo a project dir belongs to: its slug without the worktree suffix,
|