rvlib-shipkit 2.23.0 → 2.25.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.
Files changed (150) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/package.json +1 -1
  3. package/src/agent-time/live.ts +153 -0
  4. package/src/agent-time/render.ts +28 -14
  5. package/src/agent-time/report.ts +46 -25
  6. package/src/agent-time/store.ts +30 -10
  7. package/src/agent-time/timeline.ts +43 -15
  8. package/src/annex/offload.ts +16 -7
  9. package/src/asks/asks-queue.ts +32 -11
  10. package/src/check.ts +3 -1
  11. package/src/checks/SK004-gitignore-policy.check.ts +32 -11
  12. package/src/checks/SK027-agent-wiki-links.check.ts +1 -1
  13. package/src/checks/SK033-global-contribution.check.ts +1 -1
  14. package/src/checks/SK036-draft-media-size.check.ts +1 -1
  15. package/src/checks/SK040-release-words.check.ts +1 -1
  16. package/src/checks/SK042-post-kinds.check.ts +1 -1
  17. package/src/checks/SK044-behind-upstream.check.ts +38 -0
  18. package/src/cli/cmd_Annex.ts +12 -7
  19. package/src/cli/cmd_Asks.ts +2 -0
  20. package/src/cli/cmd_Assets.ts +5 -5
  21. package/src/cli/cmd_Backup.ts +16 -8
  22. package/src/cli/cmd_Bump.ts +1 -0
  23. package/src/cli/cmd_Capacity.ts +30 -0
  24. package/src/cli/cmd_Check.ts +1 -0
  25. package/src/cli/cmd_Checks.ts +13 -1
  26. package/src/cli/cmd_Ci.ts +3 -2
  27. package/src/cli/cmd_Commands.ts +61 -16
  28. package/src/cli/cmd_ConfigKeys.ts +17 -0
  29. package/src/cli/cmd_Home.ts +1 -30
  30. package/src/cli/cmd_Hooks.ts +1 -0
  31. package/src/cli/cmd_Keys.ts +4 -1
  32. package/src/cli/cmd_Lanes.ts +35 -0
  33. package/src/cli/cmd_Mv.ts +7 -7
  34. package/src/cli/cmd_Rec.ts +22 -7
  35. package/src/cli/cmd_Reflect.ts +1 -0
  36. package/src/cli/cmd_Releases.ts +1 -0
  37. package/src/cli/cmd_Review.ts +200 -49
  38. package/src/cli/cmd_Secret.ts +41 -2
  39. package/src/cli/cmd_Shot.ts +16 -4
  40. package/src/cli/cmd_Status.ts +7 -5
  41. package/src/cli/cmd_Time.ts +13 -5
  42. package/src/cli/cmd_Tmp.ts +82 -0
  43. package/src/cli/cmd_Veille.ts +10 -6
  44. package/src/cli/cmd_Wiki.ts +1 -0
  45. package/src/cli/family-help.ts +136 -0
  46. package/src/cli/family-pages.ts +0 -19
  47. package/src/cli/kit/calls.ts +35 -0
  48. package/src/cli/kit/project-cli.ts +2 -12
  49. package/src/cli/registry.ts +52 -7
  50. package/src/cli.ts +8 -4
  51. package/src/collections/pings.ts +1 -1
  52. package/src/core/capacity.ts +127 -0
  53. package/src/core/check-runner.ts +91 -16
  54. package/src/core/floor-resolve.ts +6 -2
  55. package/src/core/floor.ts +6 -2
  56. package/src/core/history-files.ts +18 -0
  57. package/src/core/jobs.ts +35 -16
  58. package/src/core/layout.ts +2 -2
  59. package/src/core/motherhome.ts +67 -9
  60. package/src/core/nearest.ts +16 -0
  61. package/src/core/remove-tree.ts +19 -0
  62. package/src/core/runs.ts +12 -3
  63. package/src/core/slots.ts +49 -12
  64. package/src/core/throwaway-worktree.ts +22 -4
  65. package/src/core/trace-audit.ts +21 -5
  66. package/src/drill/run.ts +5 -2
  67. package/src/home/daemon-jobs.ts +41 -4
  68. package/src/home/gui-app/ShipkitGui.swift +1 -0
  69. package/src/home/home-launchd.ts +11 -3
  70. package/src/home/home-routes.ts +11 -4
  71. package/src/home/machine-host.ts +65 -0
  72. package/src/home/machine-stores.ts +19 -17
  73. package/src/home/machine-temp.ts +485 -0
  74. package/src/home/other-macs.ts +74 -0
  75. package/src/home/run-daemon.ts +10 -2
  76. package/src/home/serve-web.ts +2 -2
  77. package/src/home/via-hub.ts +6 -1
  78. package/src/init-repo.ts +7 -3
  79. package/src/ledger/gate-checks.ts +3 -2
  80. package/src/ledger/git-key.ts +25 -4
  81. package/src/ledger/git-scan.ts +10 -0
  82. package/src/ledger/ledger.ts +6 -0
  83. package/src/ledger/store.ts +6 -0
  84. package/src/media-store/backup/daemon.ts +92 -20
  85. package/src/media-store/backup/keys.ts +21 -6
  86. package/src/media-store/backup/manifest.ts +52 -11
  87. package/src/media-store/backup/restore.ts +17 -10
  88. package/src/media-store/backup/run.ts +26 -17
  89. package/src/media-store/backup/sources.ts +168 -22
  90. package/src/media-store/backup/watch.ts +106 -0
  91. package/src/media-store/daemon.ts +36 -8
  92. package/src/media-store/hand.ts +3 -1
  93. package/src/mv/mv-md.ts +167 -56
  94. package/src/pb/run-pb.ts +2 -10
  95. package/src/plan/repo-source.ts +25 -14
  96. package/src/recordings/model.ts +1 -1
  97. package/src/reflect/transcript.ts +56 -11
  98. package/src/release/run-bump.ts +3 -2
  99. package/src/release/run-release.ts +12 -4
  100. package/src/releases/from-card.ts +45 -3
  101. package/src/releases/model.ts +6 -0
  102. package/src/releases/store.ts +8 -1
  103. package/src/repo-config.ts +5 -3
  104. package/src/review/cells.ts +26 -4
  105. package/src/review/format.ts +34 -10
  106. package/src/review/media-kind.ts +14 -11
  107. package/src/review/media-read.ts +6 -5
  108. package/src/review/model.ts +85 -4
  109. package/src/review/paste.ts +2 -1
  110. package/src/review/previews.ts +123 -36
  111. package/src/review/routes.ts +29 -18
  112. package/src/review/store.ts +89 -19
  113. package/src/review/threads.ts +7 -5
  114. package/src/review/trailer-model.ts +2 -2
  115. package/src/secrets/copy.ts +110 -0
  116. package/src/secrets/list.ts +17 -7
  117. package/src/serve/hub-app/home-strip.css +5 -0
  118. package/src/serve/hub-app/home-strip.tsx +18 -0
  119. package/src/serve/hub-app/hub-app.tsx +2 -1
  120. package/src/serve/hub-app/hub.css +14 -0
  121. package/src/serve/hub-app/inbox.css +1 -0
  122. package/src/serve/hub-app/pull-refresh.tsx +88 -0
  123. package/src/serve/hub-app/review/review-cells.tsx +52 -13
  124. package/src/serve/hub-app/review/review-list.tsx +6 -1
  125. package/src/serve/hub-app/review/review-st.ts +6 -5
  126. package/src/serve/hub-app/review/review-thread.tsx +3 -1
  127. package/src/serve/hub-app/review/review-views.tsx +18 -11
  128. package/src/serve/hub-app/review/thread-st.ts +82 -14
  129. package/src/serve/hub-app/review.css +15 -2
  130. package/src/serve/hub-runtime.ts +2 -1
  131. package/src/serve/run-serve.ts +4 -2
  132. package/src/serve/serve-hub.ts +9 -2
  133. package/src/shot/client.ts +4 -2
  134. package/src/shot/serve-shot.ts +71 -2
  135. package/src/shot/shooter.ts +65 -11
  136. package/src/shot/shot-ask.ts +32 -9
  137. package/src/suite/child-tools.ts +45 -0
  138. package/src/suite/judge-suites.ts +10 -22
  139. package/src/suite/select.ts +95 -9
  140. package/src/suite/suite-cli.ts +38 -14
  141. package/src/suite/suite-cores.ts +68 -0
  142. package/src/suite/suite-reads-preload.ts +8 -6
  143. package/src/suite/test-units.ts +31 -12
  144. package/src/trailer/graph.ts +2 -1
  145. package/src/ts/config.ts +21 -0
  146. package/src/ts/rename.ts +37 -13
  147. package/src/ts/workspaces.ts +45 -0
  148. package/src/wiki/run-wiki.ts +7 -2
  149. package/src/wiki/scan-md.ts +2 -1
  150. package/src/home/claude-temp.ts +0 -139
package/CHANGELOG.md CHANGED
@@ -1,3 +1,48 @@
1
+ ## 2.25.0
2
+
3
+ - **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.
4
+ - **A mistyped command answers in two lines** with the close command, the words after the slip kept (`did you mean sk review inbox ?`), where the parser printed every registered command. A family name (`sk gate --help`) lists its family, a word several commands start with lists them, and a known command on a line that does not fit answers with its usage.
5
+ - **`--help` typed after a command's arguments gives its help**, and help read through a pipe carries no colour codes.
6
+ - **`sk status <id> --wait`** holds until the detached gate has a verdict and prints it first: one call in place of a poll. With no id, status reads the latest run `--detach` started, never a job of the daemon. An unknown check id names the close ones.
7
+ - **`sk checks <word>` and `sk config-keys <word>`** keep the rows a word names.
8
+ - **The cache**: a stale lock a killed git left on the scan's index no longer costs a repo its whole cache. A check can mark an input `optional`, and a missing one keys as absent, so the built-in checks that read an optional file replay again. A workspace package a unit imports joins its keys, and another unit's run config no longer reruns every suite.
9
+ - **The daemon's plan** runs a check with no key when its reason changes or a tracked input moved, never at each save whatever moved: its own run wrote files, which was a loop.
10
+ - **The backup's look costs nothing while no source moves.** The daemon watches the sources; a look reads only what moved, a run reads only the files whose size or time moved, and a full walk runs every 30 min as a safety net. A review rule's log is no source.
11
+ - **The media store job** asks a stat before it starts a child: a pass that found nothing waits 5 min unless a store folder moves.
12
+ - **`sk shot`**: a page that navigates while it loads is shot where it lands, `--full` shoots the whole page, a file path is taken, a request the app refused prints its own line, and the warm shot service runs its new code once idle.
13
+ - **`sk mv`**: a longer path that only ends with the moved one is another file and stays; a page moved into a folder that already holds files no longer leaves the tree half moved; a plan, a changelog and a journal stay as written (`--history` rewrites them too), and `sk wiki lint` lets one name a path git once held.
14
+ - **`sk wiki lint`** sees a link with an anchor or a title.
15
+ - **Review**: `add-view` takes `add`'s view flags and never stores a flag as a label; a refusal names a step that works; `withdraw` and `done` on a card already closed say so and exit 0; a short id works in every verb; `withdraw` takes `--note` too; a media field reads on any `ReviewView`, and `'files' in view` still narrows.
16
+ - **`sk annex`** lists in well under a second with one line per repo (`--all` for every link); `sk backup runs` and `sk rec` answer with a count, then the newest.
17
+ - **`sk time`** finds its repo from a subfolder or a worktree, and its first line is the answer; `sk calls` names the command each run was.
18
+ - **The release gate's throwaway checkout** cleans a read only folder a check left in it.
19
+ - **`sk assets fill|add|gen`**: the help says a roll of a comfy asset is a job on the GPU box.
20
+
21
+ ## 2.24.0
22
+
23
+ - **A slot of the machine pool is one core.** A suite run holds one slot per worker it starts, by its kept suite time (one worker per 4 s, at most half the cores), and gives the slots back when its parallel phase ends. One gate used to start 8 workers per suite whatever its size, and the load that followed closed the pool to one check for the whole machine.
24
+ - **A short check never queues.** A check whose newest kept runs all ended under 2 s takes no slot, and it starts while longer checks wait.
25
+ - **The longest check starts first**, and takes a freed slot before a shorter check of the same run. A check with no kept run starts before it.
26
+ - **The pool keeps half its slots open at any load**, and a waiting check looks again at a growing interval, 250 ms at most, instead of every 25 ms.
27
+ - **A run says its wait apart from its work**: `waited for a machine slot: 94.0s with nothing of this run running`, with who held the pool first.
28
+ - **The suite budget reads the same work the same at any load.** A main thread a loaded machine ran slowly on a performance core is charged its instructions at the machine's quiet rate.
29
+ - **The traced audit runs every suite, selection off**, so the selection's own walk of the tree no longer lands in a unit's key.
30
+ - **`sk capacity`** says how many more lanes the machine can take now, from its cores, its load and the agents live on it.
31
+ - **The command page every session loads lists the everyday commands only** (`sk commands --everyday`): the commands marked essential, then every other family on one line with its page. Every command: `sk commands --compact`.
32
+ - **`sk mv`**: a folder move leaves the importers of a file of the same name alone; a page moved into a folder of its own name is rewritten once; the dry run prints per file the count of rewrites and the first rewritten line, and walks a whole `--map`.
33
+ - **Asks**: an ask's keys are read from its front matter only, so a body line that starts with `check:` is never run as a probe, and every writer sets its keys there.
34
+ - **A hub runs a gate only for its own tree**: `sk ci` in a clone no longer runs in another checkout of the same folder name.
35
+ - **A repo made by `sk start` or `sk init` has its commit gates armed** before its first commit.
36
+ - **A review verb outside a shipkit repo fails and names the folder**, where it used to write a stray store.
37
+ - **Review**: an agent posts an update on its card at any time (`sk review update`), with a before and an after as a pair; the hub shows it in the thread; a click on a lit verdict takes it back; a clip over 25 Mbit/s plays from a play copy.
38
+ - **`sk tmp`** reads the machine's temp folders with no walk, and one sweep deletes each idle unit no live process uses.
39
+ - **`sk secret copy --to <mac>`** puts this Mac's secrets into another Mac's keychain over ssh, `--unlock` in the same session; `sk secret list` says LOCK for a locked keychain.
40
+ - **Two Macs**: each Mac's tailnet name comes from tailscale, each lands only its own block of local projects, a backup restore reads its own Mac's runs, and the home strip links the other Mac's home.
41
+ - **SK044** warns when the branch is behind its upstream.
42
+ - **The test selection** follows an import into a workspace package outside the roots, a doc or a dot folder note nothing reads moves no suite, and a child that opens no file is no read.
43
+ - **`sk time`**: a background run is timed to its end, a parked run is its own bucket, and a share is of the whole wall.
44
+ - **The hub on a phone**: two fingers zoom every page, a pull down reloads it.
45
+
1
46
  ## 2.23.0
2
47
 
3
48
  - **The capture editor is one window.** The recent captures sit in a band under the editor while it is open, the one shown ringed, and are their own small panel while it is closed: never two windows. While its window is open the recorder is in ⌘Tab and the Dock, under its own icon (a viewfinder and a record dot on red), and a menu bar app again once it closes.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rvlib-shipkit",
3
- "version": "2.23.0",
3
+ "version": "2.25.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",
@@ -0,0 +1,153 @@
1
+ // WHO IS AT WORK ON THE MACHINE NOW, read from the transcripts every agent
2
+ // already writes: one row per live session and per live lane (a sub-agent),
3
+ // with what it does this second. No agent reports anything: the view costs
4
+ // no turn.
5
+ //
6
+ // The one constraint a reader breaks first: a transcript is read at its two
7
+ // ends only. A session's file reaches hundreds of megabytes, and this runs
8
+ // each time someone looks.
9
+ import { closeSync, openSync, readFileSync, readSync, statSync } from 'fs'
10
+ import type { TranscriptFile } from './store.ts'
11
+
12
+ const HEAD_BYTES = 64 * 1024
13
+ const TAIL_BYTES = 256 * 1024
14
+ /** a lane's file is read whole to count its calls up to this size; a larger one shows no count */
15
+ const COUNT_MAX_BYTES = 16 * 1024 * 1024
16
+
17
+ export type LiveState =
18
+ | { kind: 'tool'; what: string }
19
+ /** its request to the model is in flight */
20
+ | { kind: 'model' }
21
+ /** its turn ended: a lane is done, a session waits for its user */
22
+ | { kind: 'ended' }
23
+ | { kind: 'unknown' }
24
+
25
+ export type LiveRow = {
26
+ project: string
27
+ /** the folder it works in, as its first entry says: the repo's name comes from it */
28
+ cwd: string
29
+ session: string
30
+ /** '' for a session, the sub-agent's id for a lane */
31
+ agent: string
32
+ /** a lane's description as its orchestrator gave it, '' when none is kept */
33
+ name: string
34
+ model: string
35
+ startedAt: number | null
36
+ /** when its last entry was written, and what that entry says it does */
37
+ at: number
38
+ state: LiveState
39
+ /** tool calls so far, null when the file is too large to count */
40
+ calls: number | null
41
+ }
42
+
43
+ type Entry = { type?: string; timestamp?: string; message?: { content?: unknown } }
44
+ type Part = { type?: string; name?: string; input?: Record<string, unknown> }
45
+
46
+ const parts = (e: Entry): Part[] => (Array.isArray(e.message?.content) ? (e.message.content as Part[]) : [])
47
+
48
+ /** a tool call in a few words: the command's head, the file's name, a sub-agent's description */
49
+ export function callWords(p: Part): string {
50
+ const i = p.input ?? {}
51
+ const text = (v: unknown): string => (typeof v === 'string' ? v : '')
52
+ const head = text(i.command) || text(i.description) || (text(i.file_path).split('/').at(-1) ?? '') || text(i.pattern) || text(i.query) || text(i.skill)
53
+ const one = head.replace(/\s+/g, ' ').trim()
54
+ return `${p.name ?? 'tool'}${one === '' ? '' : `: ${one.length > 70 ? `${one.slice(0, 69)}…` : one}`}`
55
+ }
56
+
57
+ /** the call a sub-agent ends on: its report handed back to the session that started it */
58
+ const HAND_BACK = 'SubagentHandback'
59
+
60
+ /** what the last entries of a transcript say the agent does now. `lines` are its last lines, oldest first */
61
+ export function stateOf(lines: readonly string[]): { state: LiveState; at: number } {
62
+ // a result just came back, or a request is in flight: a model turn, unless the call before it was the hand back
63
+ let waiting: number | null = null
64
+ for (let n = lines.length - 1; n >= 0; n--) {
65
+ let e: Entry
66
+ try { e = JSON.parse(lines[n]!) as Entry } catch { continue }
67
+ const at = e.timestamp == null ? NaN : Date.parse(e.timestamp)
68
+ if (!Number.isFinite(at)) continue
69
+ if (e.type === 'api-request' || e.type === 'user') { waiting ??= at; continue }
70
+ if (e.type !== 'assistant') continue
71
+ const calls = parts(e).filter((p) => p.type === 'tool_use')
72
+ if (calls.some((p) => p.name === HAND_BACK)) return { state: { kind: 'ended' }, at: waiting ?? at }
73
+ if (waiting != null) return { state: { kind: 'model' }, at: waiting }
74
+ return calls.length > 0 ? { state: { kind: 'tool', what: calls.map(callWords).join(' + ') }, at } : { state: { kind: 'ended' }, at }
75
+ }
76
+ return waiting != null ? { state: { kind: 'model' }, at: waiting } : { state: { kind: 'unknown' }, at: 0 }
77
+ }
78
+
79
+ const slice = (path: string, from: number, bytes: number): string => {
80
+ const fd = openSync(path, 'r')
81
+ try {
82
+ const buf = Buffer.alloc(bytes)
83
+ return buf.subarray(0, readSync(fd, buf, 0, bytes, from)).toString('utf8')
84
+ } finally { closeSync(fd) }
85
+ }
86
+
87
+ /** one live transcript read at its two ends. `calls: false` skips the count, the one read of the whole file */
88
+ export function liveRow(f: TranscriptFile, o: { calls?: boolean } = {}): LiveRow {
89
+ const size = statSync(f.path).size
90
+ const tail = slice(f.path, Math.max(0, size - TAIL_BYTES), Math.min(size, TAIL_BYTES)).split('\n').filter((l) => l !== '')
91
+ // the first line of a tail cut mid file is a fragment
92
+ const { state, at } = stateOf(size > TAIL_BYTES ? tail.slice(1) : tail)
93
+ const head = slice(f.path, 0, Math.min(size, HEAD_BYTES))
94
+ const stamp = /"timestamp":"([^"]+)"/.exec(head)
95
+ const startedAt = stamp == null ? null : Date.parse(stamp[1]!)
96
+ const cwd = /"cwd":"([^"]+)"/.exec(head)?.[1] ?? ''
97
+ let name = ''
98
+ let model = ''
99
+ if (f.agent !== '') {
100
+ try {
101
+ const meta = JSON.parse(readFileSync(f.path.replace(/\.jsonl$/, '.meta.json'), 'utf8')) as { description?: unknown; model?: unknown; agentType?: unknown }
102
+ name = typeof meta.description === 'string' ? meta.description : typeof meta.agentType === 'string' ? meta.agentType : ''
103
+ model = typeof meta.model === 'string' ? meta.model : ''
104
+ } catch { /* an agent with no meta file keeps its id as its name */ }
105
+ }
106
+ const calls = o.calls === false || size > COUNT_MAX_BYTES ? null : (readFileSync(f.path, 'utf8').match(/"type":"tool_use"/g) ?? []).length
107
+ return { project: f.project, cwd, session: f.session, agent: f.agent, name, model, startedAt: startedAt != null && Number.isFinite(startedAt) ? startedAt : null, at: at > 0 ? at : f.mtime, state, calls }
108
+ }
109
+
110
+ const span = (ms: number): string => {
111
+ const s = Math.max(0, Math.round(ms / 1000))
112
+ return s < 60 ? `${s}s` : s < 3600 ? `${Math.floor(s / 60)}m` : `${Math.floor(s / 3600)}h${String(Math.floor((s % 3600) / 60)).padStart(2, '0')}`
113
+ }
114
+
115
+ const doing = (r: LiveRow, now: number): string => {
116
+ const age = span(now - r.at)
117
+ return r.state.kind === 'tool' ? `${r.state.what} (${age})`
118
+ : r.state.kind === 'model' ? `model turn (${age})`
119
+ : r.state.kind === 'ended' ? `${r.agent === '' ? 'waits for its user' : 'ended'} (${age})`
120
+ : `last wrote ${age} ago`
121
+ }
122
+
123
+ /** the repo a row belongs to: the name of the folder it works in, a linked worktree counted with its repo */
124
+ export const repoOf = (r: { cwd: string; project: string }): string =>
125
+ r.cwd === '' ? r.project : r.cwd.replace(/\/\.claude\/worktrees\/.*$/, '').split('/').filter((w) => w !== '').at(-1) ?? r.project
126
+
127
+ /** one row an agent: a session resumed from another folder writes the same transcript under both, the newest stands */
128
+ export function oneRowAnAgent<T extends { session: string; agent: string; mtime: number }>(files: readonly T[]): T[] {
129
+ const by = new Map<string, T>()
130
+ for (const f of files) {
131
+ const k = `${f.session}/${f.agent}`
132
+ const seen = by.get(k)
133
+ if (seen == null || f.mtime > seen.mtime) by.set(k, f)
134
+ }
135
+ return [...by.values()]
136
+ }
137
+
138
+ /** the rows as a table, repos in name order, a session before its lanes */
139
+ export function liveTable(rows: readonly LiveRow[], now: number): string[] {
140
+ if (rows.length === 0) return ['no agent wrote in the window']
141
+ const sorted = [...rows].sort((a, b) => repoOf(a).localeCompare(repoOf(b)) || a.session.localeCompare(b.session) || (a.agent === '' ? -1 : b.agent === '' ? 1 : (a.startedAt ?? 0) - (b.startedAt ?? 0)))
142
+ const cells = sorted.map((r) => [
143
+ repoOf(r),
144
+ r.agent === '' ? `session ${r.session.slice(0, 8)}` : ` ${r.name === '' ? r.agent.slice(0, 12) : r.name}${r.model === '' ? '' : ` [${r.model}]`}`,
145
+ r.startedAt == null ? '?' : span(now - r.startedAt),
146
+ r.calls == null ? '-' : String(r.calls),
147
+ doing(r, now),
148
+ ])
149
+ const head = ['repo', 'who', 'since', 'calls', 'now']
150
+ const w = head.map((h, i) => Math.max(h.length, ...cells.map((c) => c[i]!.length)))
151
+ const line = (c: string[]): string => c.map((x, i) => (i === c.length - 1 ? x : i === 3 ? x.padStart(w[i]!) : x.padEnd(w[i]!))).join(' ').trimEnd()
152
+ return [line(head), ...cells.map(line)]
153
+ }
@@ -2,7 +2,7 @@
2
2
  // view answers "where did the time go and what wastes it" in about 25 lines;
3
3
  // each sub view goes one level deeper on one question.
4
4
  import type { Breakdown } from './timeline.ts'
5
- import { type ShapeRow, type TimeReport, total } from './report.ts'
5
+ import { running, type ShapeRow, type TimeReport, total } from './report.ts'
6
6
  import type { TurnStats } from './turns.ts'
7
7
 
8
8
  export const VIEWS = ['summary', 'commands', 'tools', 'slow', 'fails', 'feedback', 'sessions', 'turns'] as const
@@ -38,9 +38,16 @@ const shapeRows = (rows: ShapeRow[]): string[][] =>
38
38
  function wallLine(b: Breakdown): string {
39
39
  const w = total(b, false)
40
40
  const part = (label: string, ms: number): string => `${label} ${pct(ms, w)} ${fmtMs(ms)}`
41
- return `wall ${fmtMs(w)}: ${[part('model', b.model), part('tools', b.tools), part('your allow', b.approval), part('sub-agent wait', b.subagent), part('background wait', b.background), part('waiting on you', b.human)].join(' · ')}`
41
+ const shown = (label: string, ms: number): string[] => (ms > 0 ? [part(label, ms)] : [])
42
+ return `wall ${fmtMs(w)}: ${[part('model', b.model), part('tools', b.tools), part('your allow', b.approval), part('sub-agent wait', b.subagent), part('background wait', b.background), ...shown('parked', b.parked), ...shown('unknown', b.unknown), part('waiting on you', b.human)].join(' · ')}`
42
43
  }
43
44
 
45
+ /** how each bucket is read from the transcript: one definition each */
46
+ const HOW = [
47
+ 'model = its API request in flight, from what woke it to its next own entry: reading its context, thinking, writing the call (not thinking alone) · tools = a call in flight · your allow = a call waiting for your allow · sub-agent wait = a foreground sub-agent in flight',
48
+ 'background wait = stopped until a task notification woke it, or stopped on its own run still open at the report · parked = stopped until a message woke it (the coordinator, a session) · waiting on you = stopped until your prompt · unknown = stopped, nothing recorded woke it',
49
+ ]
50
+
44
51
  function header(r: TimeReport): string[] {
45
52
  const span = r.from == null ? 'all recorded' : `since ${day(r.from)}`
46
53
  const repos = r.repos.length > 3 ? `${r.repos.length} repos` : r.repos.join(', ')
@@ -48,6 +55,7 @@ function header(r: TimeReport): string[] {
48
55
  return [
49
56
  `${repos} · ${span} · ${r.accounts.length} account${r.accounts.length === 1 ? '' : 's'} · ${n(r.sessions)} sessions${pruned} · ${n(r.subagentRuns)} sub-agent runs`,
50
57
  wallLine(r.wall),
58
+ ...HOW.map((h) => ` ${h}`),
51
59
  `idle (no prompt for ${30}m+) left out: ${fmtMs(r.wall.idle)}`,
52
60
  `${n(r.callCount)} tool calls, ${fmtMs(r.callMs)} of call time (parallel calls overlap, so it can pass the wall)`,
53
61
  ]
@@ -66,11 +74,11 @@ const perCall = (ms: number): string => (ms < 60_000 ? `${(ms / 1000).toFixed(1)
66
74
  /** the three turn metrics: model before each call, single reads, parallel */
67
75
  const turnMetrics = (t: TurnStats): string => `${perCall(t.calls === 0 ? 0 : t.model / t.calls)} of model before each call · ${share(t.reads, t.calls)} single reads · ${share(t.parallel, t.calls)} in parallel`
68
76
 
69
- /** what the work went to, verdict first: turns or commands, then the fix */
70
- function turnVerdict(t: TurnStats, model: number, tools: number): string[] {
71
- const work = model + tools
72
- if (model <= tools) return [`command speed, not turns: tools ${pct(tools, work)} of the work, model ${pct(model, work)}; the slow commands are below`]
73
- const out = [`turn count, not command speed: model ${pct(model, work)} of the work, ${turnMetrics(t)}`]
77
+ /** what the runs' wall went to, verdict first: turns or commands, then the fix.
78
+ * A share is of the whole wall, its own waits included, never of the work alone */
79
+ function turnVerdict(t: TurnStats, model: number, tools: number, wall: number): string[] {
80
+ if (model <= tools) return [`command speed, not turns: tools ${pct(tools, wall)} of their wall, model ${pct(model, wall)}; the slow commands are below`]
81
+ const out = [`turn count, not command speed: model ${pct(model, wall)} of their wall, ${turnMetrics(t)}`]
74
82
  if (t.reads >= 0.3 * t.calls && t.parallel < 0.1 * t.calls) out.push(' fix: fewer turns (several reads in one turn, a project command that returns the whole answer)')
75
83
  return out
76
84
  }
@@ -82,13 +90,16 @@ function turnsSection(r: TimeReport): { main: string[]; sub: string[] } {
82
90
  if (main.calls > 0) out.main.push(`main sessions, ${n(main.calls)} calls: ${turnMetrics(main)}`)
83
91
  if (sub.runs > 0) {
84
92
  const w = sub.work
85
- const busy = w.model + w.tools + w.approval + w.subagent + w.background
86
- const waits = busy - w.model - w.tools
87
- const [verdict, ...fix] = turnVerdict(sub, w.model, w.tools)
93
+ const wall = running(w)
94
+ const other = w.approval + w.subagent
95
+ const part = (label: string, ms: number): string => `${label} ${pct(ms, wall)} ${fmtMs(ms)}`
96
+ const parked = w.parked + w.human
97
+ const [verdict, ...fix] = turnVerdict(sub, w.model, w.tools, wall)
88
98
  out.sub.push(
89
99
  `sub-agents: ${verdict}`,
90
100
  ...fix,
91
- ` ${n(sub.runs)} runs worked ${fmtMs(busy)}: model ${fmtMs(w.model)} · tools ${fmtMs(w.tools)} · their own waits ${fmtMs(waits)} · ${n(sub.calls)} calls · a run p50 ${fmtMs(sub.runP50)} p90 ${fmtMs(sub.runP90)}, ${n(sub.callsP50)} calls p50`,
101
+ ` ${n(sub.runs)} runs, wall ${fmtMs(wall)}: ${[part('model', w.model), part('tools', w.tools), part('background wait', w.background), ...(w.unknown > 0 ? [part('unknown', w.unknown)] : []), ...(other > 0 ? [part('other waits', other)] : [])].join(' · ')}`,
102
+ ` ${parked > 0 ? `parked ${fmtMs(parked)} (stopped until a message woke it, left out of the wall) · ` : ''}${n(sub.calls)} calls · a run p50 ${fmtMs(sub.runP50)} p90 ${fmtMs(sub.runP90)}, ${n(sub.callsP50)} calls p50`,
92
103
  )
93
104
  }
94
105
  return out
@@ -102,6 +113,9 @@ function summary(r: TimeReport): string[] {
102
113
  if (turns.sub.length > 0) out.push('', ...turns.sub)
103
114
  if (r.insights.length > 0) out.push('', 'what costs the most (measured, biggest first; ~ = estimate)', ...r.insights.map((i) => ` ${`${i.estimate ? '~' : ''}${fmtMs(i.ms)}`.padStart(7)} ${i.text}`))
104
115
  out.push('', 'commands by total time (Bash shapes)', ...table(['shape', 'calls', 'total', 'p50', 'p95', 'max', 'fail'], shapeRows(bashOnly(r).slice(0, 8))))
116
+ const bg = bashOnly(r).filter((s) => s.shape.endsWith(' (bg)'))
117
+ const noEnd = bg.reduce((a, s) => a + s.noEnd, 0)
118
+ if (bg.length > 0) out.push(` (bg): a background run, timed from its start to its task notification${noEnd > 0 ? `; ${noEnd} background run${noEnd === 1 ? ' has' : 's have'} no end recorded (still running, or its session ended first), left out of the times` : ''}`)
105
119
  const p95 = [...bashOnly(r)].filter((s) => s.calls >= 5).sort((a, b) => b.p95 - a.p95).slice(0, 4)
106
120
  if (p95.length > 0) out.push('', 'slowest per call (p95, 5 calls or more)', ...p95.map((s) => ` ${fmtMs(s.p95).padStart(6)} ${s.shape} (${s.calls} calls, ${fmtMs(s.ms)} total)`))
107
121
  const waste = [...r.shapes].filter((s) => s.failed > 0).sort((a, b) => b.failedMs - a.failedMs || b.failed - a.failed).slice(0, 4)
@@ -137,7 +151,7 @@ export function render(r: TimeReport, view: View, top: number): string {
137
151
  out = summary(r)
138
152
  break
139
153
  case 'commands':
140
- out = [`${n(r.shapes.length)} shapes, by total time (every tool but sub-agents)`, ...table(['shape', 'calls', 'total', 'p50', 'p95', 'max', 'fail', 'rerun', 'timeout'], r.shapes.slice(0, top).map((s) => [...(shapeRows([s])[0] ?? []), `${s.retried || ''}`, `${s.timeouts || ''}`]))]
154
+ out = [`${n(r.shapes.length)} shapes, by total time (every tool but sub-agents; (bg) = a background run, start to its notification)`, ...table(['shape', 'calls', 'total', 'p50', 'p95', 'max', 'fail', 'rerun', 'timeout', 'no end'], r.shapes.slice(0, top).map((s) => [...(shapeRows([s])[0] ?? []), `${s.retried || ''}`, `${s.timeouts || ''}`, `${s.noEnd || ''}`]))]
141
155
  break
142
156
  case 'tools':
143
157
  out = [`${r.tools.length} tools, by total call time`, ...table(['tool', 'calls', 'total', 'p50', 'p95', 'max', 'fail'], shapeRows(r.tools.slice(0, top)))]
@@ -161,7 +175,7 @@ export function render(r: TimeReport, view: View, top: number): string {
161
175
  break
162
176
  }
163
177
  case 'sessions':
164
- out = [`${r.sessionRows.length} sessions, by wall (idle left out)`, ...table(['session', 'account', 'start', 'wall', 'model', 'tools', 'sub', 'bg', '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.human), `${s.calls}`, `${s.subagents}`, s.first.slice(0, 40)]))]
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)]))]
165
179
  break
166
180
  case 'turns': {
167
181
  const t = r.turns
@@ -171,7 +185,7 @@ export function render(r: TimeReport, view: View, top: number): string {
171
185
  ...ts.main,
172
186
  ...ts.sub,
173
187
  '',
174
- `the ${Math.min(top, t.rows.length)} runs that worked longest (work: model, tools, your allow; wall adds their waits on other agents; a sub-agent run is session and agent id)`,
188
+ `the ${Math.min(top, t.rows.length)} runs that worked longest (work: model, tools, your allow; wall adds its waits on its own work: background, sub-agents, unknown; parked and waiting on you left out; a sub-agent run is session and agent id)`,
175
189
  ...table(['run', 'account', 'start', 'work', 'wall', 'model', 'calls', 'turns', 'read', 'parallel', 'model/turn'], t.rows.slice(0, top).map((x) => {
176
190
  const turns = x.turns.calls - x.turns.parallel
177
191
  return [`${x.session.slice(0, 8)}${x.agent === '' ? '' : ` ${x.agent.replace(/^agent-/, '').slice(0, 8)}`}`, account(x.account), when(x.start), fmtMs(x.work), fmtMs(x.wall), fmtMs(x.turns.model), n(x.turns.calls), n(turns), share(x.turns.reads, x.turns.calls), share(x.turns.parallel, x.turns.calls), perCall(turns === 0 ? 0 : x.turns.model / turns)]
@@ -11,9 +11,16 @@ import type { Masker } from './mask.ts'
11
11
  import { type Signal, signalsOf } from './signals.ts'
12
12
  import type { FileRow, Loaded } from './store.ts'
13
13
  import { type ReadCost, type TurnStats, addTurns, emptyTurns, turnsOf } from './turns.ts'
14
- import { type Breakdown, type Call, type Mark, type Stream, FAILED, IDLE_MS, addBreakdown, callMs, type Closed, closeCalls, emptyBreakdown, quantileSorted, ranBefore, retries, wallBreakdown } from './timeline.ts'
14
+ 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
15
 
16
- export type ShapeRow = { shape: string; tool: string; calls: number; ms: number; approvals: number; approvalMs: number; p50: number; p95: number; max: number; failed: number; timeouts: number; blocked: number; retried: number; blind: number; failedMs: number }
16
+ /** `ms`, the quantiles and `failedMs` are run time (timeline.ts runMs): a
17
+ * background run's from its start to its notification. `noEnd`: background
18
+ * runs with no end recorded, counted in `calls`, left out of every time */
19
+ export type ShapeRow = { shape: string; tool: string; calls: number; ms: number; approvals: number; approvalMs: number; p50: number; p95: number; max: number; failed: number; timeouts: number; blocked: number; retried: number; blind: number; failedMs: number; noEnd: number }
20
+
21
+ /** a call's row in the commands table: a background run apart from the same
22
+ * command run in the foreground, its time being a different thing */
23
+ export const shapeKey = (c: { shape: string; bg: boolean }): string => (c.bg ? `${c.shape} (bg)` : c.shape)
17
24
 
18
25
  export type SlowCall = { ms: number; shape: string; cmd: string; at: number; account: string; session: string; agent: boolean; outcome: Outcome | null; open: boolean }
19
26
 
@@ -56,7 +63,7 @@ export type TimeReport = {
56
63
  insights: Insight[]
57
64
  }
58
65
 
59
- export type Insight = { id: 'classifier' | 'bash-edits' | 'polling' | 'failed' | 'approval'; ms: number; estimate: boolean; text: string }
66
+ export type Insight = { id: 'classifier' | 'bash-edits' | 'polling' | 'failed' | 'approval' | 'background'; ms: number; estimate: boolean; text: string }
60
67
 
61
68
  /** commands that cost nothing to run: their time is the harness around them */
62
69
  const CHEAP = new Set(['grep', 'sed', 'cat', 'ls', 'head', 'tail', 'wc', 'git status', 'echo', 'pwd', 'rg'])
@@ -92,21 +99,30 @@ export function insightsOf(calls: Closed[], wall: Breakdown, shapes: ShapeRow[])
92
99
  }
93
100
  const polls = bash.filter((c) => isPolling(c.shape))
94
101
  if (polls.length > 0) {
95
- const timeouts = polls.filter((c) => c.outcome === 'timeout').length
96
- const top = shapes.filter((s) => isPolling(s.shape)).slice(0, 3).map((s) => `${s.shape} ${fmt(s.ms)}`).join(', ')
97
- out.push({ id: 'polling', ms: polls.map(callMs).reduce((a, b) => a + b, 0), estimate: false, text: `${polls.length.toLocaleString('en-US')} polling waits (until and while loops, sleep), ${timeouts} hit the Bash timeout: ${top}` })
102
+ // a poll sent to the background (started there, or moved there at the
103
+ // Bash timeout) holds the agent only as its background wait
104
+ const inBg = polls.filter((c) => c.bg).length
105
+ const top = shapes.filter((s) => isPolling(s.shape) && !s.shape.endsWith(' (bg)')).slice(0, 3).map((s) => `${s.shape} ${fmt(s.ms)}`).join(', ')
106
+ out.push({ id: 'polling', ms: polls.map(callMs).reduce((a, b) => a + b, 0), estimate: false, text: `${polls.length.toLocaleString('en-US')} polling waits (until and while loops, sleep), ${inBg} of them in the background, started there or moved there at the Bash timeout: ${top}` })
98
107
  }
99
108
  const failed = bash.filter((c) => c.outcome != null && FAILED.has(c.outcome))
100
109
  if (failed.length > 0) {
101
110
  const rerun = shapes.reduce((a, s) => a + s.retried, 0)
102
111
  const blind = shapes.reduce((a, s) => a + s.blind, 0)
103
- out.push({ id: 'failed', ms: failed.map(callMs).reduce((a, b) => a + b, 0), estimate: false, text: `${failed.length.toLocaleString('en-US')} failed Bash runs (non zero exit, error, timeout), ${rerun} run again, ${blind} of them unchanged` })
112
+ out.push({ id: 'failed', ms: failed.map((c) => runMs(c) ?? callMs(c)).reduce((a, b) => a + b, 0), estimate: false, text: `${failed.length.toLocaleString('en-US')} failed Bash runs (non zero exit, error, timeout), ${rerun} run again, ${blind} of them unchanged` })
104
113
  }
105
114
  if (wall.approval > 0) {
106
115
  const n = calls.filter((c) => c.approval).length
107
116
  const top = [...shapes].filter((s) => s.approvals > 0).sort((a, b) => b.approvalMs - a.approvalMs).slice(0, 3).map((s) => `${s.shape} ${fmt(s.approvalMs)}`).join(', ')
108
117
  out.push({ id: 'approval', ms: wall.approval, estimate: false, text: `waiting for you to allow ${n} call${n === 1 ? '' : 's'}: ${top}` })
109
118
  }
119
+ const bgRuns = bash.filter((c) => c.bg)
120
+ if (bgRuns.length > 0) {
121
+ const timed = bgRuns.map(runMs).filter((x): x is number => x != null)
122
+ const open = bgRuns.length - timed.length
123
+ const top = shapes.filter((s) => s.tool === 'Bash' && s.shape.endsWith(' (bg)')).slice(0, 3).map((s) => `${s.shape} ${fmt(s.ms)} (max ${fmt(s.max)})`).join(', ')
124
+ out.push({ id: 'background', ms: timed.reduce((a, b) => a + b, 0), estimate: false, text: `${bgRuns.length.toLocaleString('en-US')} background commands, start to exit (the agent works beside them, or stops: background wait): ${top}${open > 0 ? `; ${open} with no end recorded` : ''}` })
125
+ }
110
126
  return out.sort((a, b) => b.ms - a.ms)
111
127
  }
112
128
 
@@ -167,11 +183,13 @@ function rowsBy(calls: { c: Closed; key: string }[], retriesByKey: Map<string, {
167
183
  else list.push(c)
168
184
  }
169
185
  return [...by].map(([key, cs]): ShapeRow => {
170
- const ms = new Float64Array(cs.length)
171
- const row: ShapeRow = { shape: key, tool: cs[0]?.tool ?? '', calls: cs.length, ms: 0, approvals: 0, approvalMs: 0, p50: 0, p95: 0, max: 0, failed: 0, timeouts: 0, blocked: 0, retried: 0, blind: 0, failedMs: 0 }
172
- cs.forEach((c, i) => {
173
- const d = callMs(c)
174
- ms[i] = d
186
+ const timed: number[] = []
187
+ const row: ShapeRow = { shape: key, tool: cs[0]?.tool ?? '', calls: cs.length, ms: 0, approvals: 0, approvalMs: 0, p50: 0, p95: 0, max: 0, failed: 0, timeouts: 0, blocked: 0, retried: 0, blind: 0, failedMs: 0, noEnd: 0 }
188
+ for (const c of cs) {
189
+ const run = runMs(c)
190
+ if (run == null) row.noEnd++
191
+ else timed.push(run)
192
+ const d = run ?? 0
175
193
  row.ms += d
176
194
  if (c.approval) {
177
195
  row.approvals++
@@ -183,9 +201,8 @@ function rowsBy(calls: { c: Closed; key: string }[], retriesByKey: Map<string, {
183
201
  }
184
202
  if (c.outcome === 'timeout') row.timeouts++
185
203
  if (c.outcome === 'blocked' || c.outcome === 'denied') row.blocked++
186
- })
187
- ms.sort()
188
- const sorted = Array.from(ms)
204
+ }
205
+ const sorted = timed.sort((a, b) => a - b)
189
206
  const r = retriesByKey.get(key)
190
207
  return { ...row, p50: quantileSorted(sorted, 0.5), p95: quantileSorted(sorted, 0.95), max: sorted[sorted.length - 1] ?? 0, retried: r?.retried ?? 0, blind: r?.blind ?? 0 }
191
208
  }).sort((a, b) => b.ms - a.ms || b.calls - a.calls)
@@ -207,7 +224,7 @@ export function buildReport(loaded: Loaded, q: { repos: string[]; from: number |
207
224
  const mainTurns = emptyTurns()
208
225
  const subTurns = emptyTurns()
209
226
  const subWork = emptyBreakdown()
210
- const runMs: number[] = []
227
+ const runWalls: number[] = []
211
228
  const runCalls: number[] = []
212
229
  const turnRows: TurnRow[] = []
213
230
  const readCosts = new Map<string, ReadCost>()
@@ -217,13 +234,13 @@ export function buildReport(loaded: Loaded, q: { repos: string[]; from: number |
217
234
  const turnModel = new Float64Array(g.closed.length)
218
235
  const b = wallBreakdown(g.stream, from, q.to, IDLE_MS, g.closed, turnModel)
219
236
  const t = turnsOf(g.closed, b.model, turnModel, readCosts)
220
- const work = b.model + b.tools + b.approval + b.subagent + b.background
237
+ const work = running(b)
221
238
  if (t.calls > 0) turnRows.push({ session: g.session, agent: g.agent, account: g.files[0]?.account ?? '', start: g.closed[0]?.start ?? 0, work: b.model + b.tools + b.approval, wall: work, turns: t })
222
239
  if (g.agent === '') addTurns(mainTurns, t)
223
240
  else {
224
241
  addTurns(subTurns, t)
225
242
  addBreakdown(subWork, b)
226
- runMs.push(work)
243
+ runWalls.push(work)
227
244
  runCalls.push(t.calls)
228
245
  }
229
246
  if (g.agent === '') {
@@ -242,20 +259,20 @@ export function buildReport(loaded: Loaded, q: { repos: string[]; from: number |
242
259
  } else subagentWork += work
243
260
  for (const c of g.closed) all.push({ c, g })
244
261
  for (const r of retries(g.closed)) {
245
- const x = retryShape.get(r.failed.shape) ?? { retried: 0, blind: 0 }
262
+ const x = retryShape.get(shapeKey(r.failed)) ?? { retried: 0, blind: 0 }
246
263
  x.retried++
247
264
  if (r.blind) x.blind++
248
- retryShape.set(r.failed.shape, x)
265
+ retryShape.set(shapeKey(r.failed), x)
249
266
  }
250
267
  }
251
268
 
252
269
  const bash = all.filter(({ c }) => c.tool === 'Bash')
253
- const shapes = rowsBy(all.filter(({ c }) => c.tool !== 'Agent' && c.tool !== 'Task').map(({ c }) => ({ c, key: c.shape })), retryShape)
270
+ const shapes = rowsBy(all.filter(({ c }) => c.tool !== 'Agent' && c.tool !== 'Task').map(({ c }) => ({ c, key: shapeKey(c) })), retryShape)
254
271
  // the Bash shapes first: they are the commands; other tools stay in the table
255
272
  shapes.sort((a, b) => b.ms - a.ms)
256
273
  const tools = rowsBy(all.map(({ c }) => ({ c, key: c.tool })), new Map())
257
- const slowest: SlowCall[] = topBy(bash, 40, ({ c }) => callMs(c))
258
- .map(({ c, g }) => ({ ms: callMs(c), shape: c.shape, cmd: mask(c.cmd.replace(/\s+/g, ' ').slice(0, 120)), at: c.start, account: g.files[0]?.account ?? '', session: g.session, agent: g.agent !== '', outcome: c.outcome, open: c.open }))
274
+ const slowest: SlowCall[] = topBy(bash, 40, ({ c }) => runMs(c) ?? callMs(c))
275
+ .map(({ c, g }) => ({ ms: runMs(c) ?? callMs(c), shape: shapeKey(c), cmd: mask(c.cmd.replace(/\s+/g, ' ').slice(0, 120)), at: c.start, account: g.files[0]?.account ?? '', session: g.session, agent: g.agent !== '', outcome: c.outcome, open: c.open }))
259
276
 
260
277
  // feedback: his prompts, deduped across copies, signals by rule, and for a
261
278
  // slowness complaint what every stream of that session was running
@@ -321,7 +338,7 @@ export function buildReport(loaded: Loaded, q: { repos: string[]; from: number |
321
338
  sessionRows: sessionRows.sort((a, b) => total(b.wall, false) - total(a.wall, false)),
322
339
  turns: {
323
340
  main: mainTurns,
324
- sub: { ...subTurns, runs: runMs.length, work: subWork, runP50: quantileSorted(runMs.sort((a, b) => a - b), 0.5), runP90: quantileSorted(runMs, 0.9), callsP50: quantileSorted(runCalls.sort((a, b) => a - b), 0.5) },
341
+ sub: { ...subTurns, runs: runWalls.length, work: subWork, runP50: quantileSorted(runWalls.sort((a, b) => a - b), 0.5), runP90: quantileSorted(runWalls, 0.9), callsP50: quantileSorted(runCalls.sort((a, b) => a - b), 0.5) },
325
342
  rows: topBy(turnRows, 200, (r) => r.work),
326
343
  reads: [...readCosts.values()].sort((a, b) => b.model - a.model),
327
344
  },
@@ -330,6 +347,10 @@ export function buildReport(loaded: Loaded, q: { repos: string[]; from: number |
330
347
  }
331
348
 
332
349
  /** the wall of a breakdown; idle left out unless asked */
333
- export const total = (b: Breakdown, idle: boolean): number => b.model + b.tools + b.approval + b.subagent + b.background + b.human + (idle ? b.idle : 0)
350
+ export const total = (b: Breakdown, idle: boolean): number => b.model + b.tools + b.approval + b.subagent + b.background + b.unknown + b.parked + b.human + (idle ? b.idle : 0)
351
+
352
+ /** a run's wall but its waits on someone to write to it (him, a message):
353
+ * what it spent working or stopped on its own work */
354
+ export const running = (b: Breakdown): number => total(b, false) - b.human - b.parked
334
355
 
335
356
  export { IDLE_MS }
@@ -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 = 7
30
+ export const INDEX_VERSION = 8
31
31
 
32
32
  export function agentTimeDbPath(): string {
33
33
  const env = process.env[AGENT_TIME_DB_ENV]
@@ -64,7 +64,8 @@ create table if not exists calls (
64
64
  code integer,
65
65
  approval integer not null default 0,
66
66
  perm text not null default '',
67
- read integer not null default 0
67
+ read integer not null default 0,
68
+ bg integer not null default 0
68
69
  );
69
70
  create index if not exists calls_file on calls (file_id, start);
70
71
  create table if not exists marks (
@@ -82,6 +83,12 @@ create table if not exists prompts (
82
83
  );
83
84
  create index if not exists prompts_file on prompts (file_id, at);
84
85
  create table if not exists meta (key text primary key, value text not null);
86
+ create table if not exists bg_ends (
87
+ id text primary key,
88
+ at integer not null,
89
+ outcome text not null,
90
+ code integer
91
+ );
85
92
  `
86
93
 
87
94
  export function openIndex(path = agentTimeDbPath()): Database {
@@ -102,6 +109,7 @@ function migrate(db: Database): void {
102
109
  if (!cols.includes('approval')) db.exec('alter table calls add column approval integer not null default 0')
103
110
  if (!cols.includes('perm')) db.exec("alter table calls add column perm text not null default ''")
104
111
  if (!cols.includes('read')) db.exec('alter table calls add column read integer not null default 0')
112
+ if (!cols.includes('bg')) db.exec('alter table calls add column bg integer not null default 0')
105
113
  // a tool use id is unique on the machine: a session copied into a second
106
114
  // account (to resume it there) holds the same calls, written once
107
115
  const unique = db.query("select 1 from sqlite_master where type = 'index' and name = 'calls_id'").get()
@@ -225,8 +233,11 @@ const statements = (db: Database) => ({
225
233
  setFile: db.query('update files set size = ?, mtime = ?, offset = ?, version = ?, first_at = coalesce(first_at, ?), last_at = coalesce(?, last_at), gone = 0 where id = ?'),
226
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 = ?')],
227
235
  resetFile: db.query('update files set offset = 0, first_at = null, last_at = null where id = ?'),
228
- insCall: db.query('insert or ignore into calls (file_id, id, start, end, tool, shape, cmd, outcome, code, approval, perm, read) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'),
229
- endCall: db.query('update calls set end = ?, outcome = ?, code = ?, approval = ?, perm = ? where id = ? and end is null'),
236
+ insCall: db.query('insert or ignore into calls (file_id, id, start, end, tool, shape, cmd, outcome, code, approval, perm, read, bg) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'),
237
+ endCall: db.query('update calls set end = ?, outcome = ?, code = ?, approval = ?, perm = ?, bg = ? where id = ? and end is null'),
238
+ // keyed by the call's id, not the file: the notification can sit in
239
+ // another file (the session's queue) read before the call's own
240
+ 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'),
230
241
  insMark: db.query('insert into marks (file_id, at, kind) values (?, ?, ?)'),
231
242
  insPrompt: db.query('insert into prompts (file_id, at, uuid, origin, text) values (?, ?, ?, ?, ?)'),
232
243
  })
@@ -236,7 +247,7 @@ const statements = (db: Database) => ({
236
247
  * the session in another account is ignored); a result for a call written by
237
248
  * an earlier read, or by the copy, closes that row */
238
249
  function writeEvents(st: Stmts, fileId: number, events: TranscriptEvent[]): { first: number | null; last: number | null } {
239
- const pending = new Map<string, { id: string; start: number; end: number | null; tool: string; detail: string; outcome: string | null; code: number | null; perm: string }>()
250
+ const pending = new Map<string, { id: string; start: number; end: number | null; tool: string; detail: string; outcome: string | null; code: number | null; perm: string; bg: boolean }>()
240
251
  let first: number | null = null
241
252
  let last: number | null = null
242
253
  const seen = (at: number): void => {
@@ -246,11 +257,12 @@ function writeEvents(st: Stmts, fileId: number, events: TranscriptEvent[]): { fi
246
257
  }
247
258
  for (const e of events) {
248
259
  seen(e.at)
249
- if (e.kind === 'use') pending.set(e.id, { id: e.id, start: e.at, end: null, tool: e.name, detail: e.detail, outcome: null, code: null, perm: '' })
260
+ if (e.kind === 'use') pending.set(e.id, { id: e.id, start: e.at, end: null, tool: e.name, detail: e.detail, outcome: null, code: null, perm: '', bg: false })
261
+ else if (e.kind === 'bgend') st.bgEnd.run(e.id, e.at, e.outcome, e.code)
250
262
  else if (e.kind === 'result') {
251
263
  const p = pending.get(e.id)
252
- if (p != null) Object.assign(p, { end: e.at, outcome: e.outcome, code: e.code, perm: e.perm })
253
- else st.endCall.run(e.at, e.outcome, e.code, e.perm === 'user' ? 1 : 0, e.perm, e.id)
264
+ if (p != null) Object.assign(p, { end: e.at, outcome: e.outcome, code: e.code, perm: e.perm, bg: e.bg })
265
+ else st.endCall.run(e.at, e.outcome, e.code, e.perm === 'user' ? 1 : 0, e.perm, e.bg ? 1 : 0, e.id)
254
266
  } else if (e.kind === 'prompt') {
255
267
  if (!Number.isNaN(e.at)) st.insPrompt.run(fileId, e.at, e.uuid, e.origin, e.text)
256
268
  if (e.origin === 'typed' && !Number.isNaN(e.at)) st.insMark.run(fileId, e.at, 'prompt')
@@ -258,7 +270,7 @@ function writeEvents(st: Stmts, fileId: number, events: TranscriptEvent[]): { fi
258
270
  }
259
271
  for (const p of pending.values()) {
260
272
  const shape = toolShape(p.tool, p.detail)
261
- st.insCall.run(fileId, p.id, p.start, p.end, p.tool, shape, p.detail, p.outcome, p.code, p.perm === 'user' ? 1 : 0, p.perm, isReadOnly({ tool: p.tool, shape, cmd: p.detail }) ? 1 : 0)
273
+ st.insCall.run(fileId, p.id, p.start, p.end, p.tool, shape, p.detail, p.outcome, p.code, p.perm === 'user' ? 1 : 0, p.perm, isReadOnly({ tool: p.tool, shape, cmd: p.detail }) ? 1 : 0, p.bg ? 1 : 0)
262
274
  }
263
275
  return { first, last }
264
276
  }
@@ -352,7 +364,15 @@ export function loadWindow(db: Database, keep: ProjectFilter, from: number, to:
352
364
  for (let i = 0; i < ids.length; i += CHUNK) {
353
365
  const part = ids.slice(i, i + CHUNK)
354
366
  const inList = part.map(() => '?').join(',')
355
- for (const c of db.query(`select file_id, id, start, end, tool, shape, cmd, outcome, code, approval = 1 as approval, perm, read = 1 as read from calls where file_id in (${inList}) and start between ? and ?`).all(...part, from, to) as (Call & { file_id: number })[]) {
367
+ // a background run's outcome is its notification's, once there is one
368
+ const rows = db
369
+ .query(
370
+ `select c.file_id, c.id, c.start, c.end, c.tool, c.shape, c.cmd, c.outcome, c.code, c.approval = 1 as approval, c.perm, c.read = 1 as read, c.bg = 1 as bg, b.at as bgAt, b.outcome as bgOutcome, b.code as bgCode
371
+ from calls c left join bg_ends b on c.bg = 1 and b.id = c.id where c.file_id in (${inList}) and c.start between ? and ?`,
372
+ )
373
+ .all(...part, from, to) as (Omit<Call, 'bgEnd'> & { file_id: number; bgAt: number | null; bgOutcome: Call['outcome']; bgCode: number | null })[]
374
+ for (const { bgAt, bgOutcome, bgCode, ...r } of rows) {
375
+ const c: Call & { file_id: number } = bgAt == null ? { ...r, bgEnd: null } : { ...r, bgEnd: bgAt, outcome: bgOutcome, code: bgCode }
356
376
  const list = calls.get(c.file_id) ?? []
357
377
  list.push(c)
358
378
  calls.set(c.file_id, list)