rvlib-shipkit 2.22.1 → 2.24.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 (139) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/package.json +1 -1
  3. package/src/agent-time/render.ts +28 -14
  4. package/src/agent-time/report.ts +46 -25
  5. package/src/agent-time/store.ts +30 -10
  6. package/src/agent-time/timeline.ts +43 -15
  7. package/src/annex/annex.ts +3 -0
  8. package/src/annex/born.ts +464 -0
  9. package/src/annex/flush.ts +46 -0
  10. package/src/annex/offload.ts +171 -38
  11. package/src/annex/snapshots.ts +53 -0
  12. package/src/annex/tidy.ts +368 -0
  13. package/src/asks/asks-queue.ts +32 -11
  14. package/src/checks/SK041-annex-links.check.ts +4 -2
  15. package/src/checks/SK043-scratch-on-the-mac.check.ts +45 -0
  16. package/src/checks/SK044-behind-upstream.check.ts +38 -0
  17. package/src/cli/cmd_Annex.ts +60 -9
  18. package/src/cli/cmd_Asks.ts +2 -0
  19. package/src/cli/cmd_Backup.ts +7 -5
  20. package/src/cli/cmd_Bump.ts +1 -0
  21. package/src/cli/cmd_Capacity.ts +26 -0
  22. package/src/cli/cmd_Check.ts +1 -0
  23. package/src/cli/cmd_Checks.ts +1 -0
  24. package/src/cli/cmd_Ci.ts +1 -0
  25. package/src/cli/cmd_Commands.ts +50 -14
  26. package/src/cli/cmd_Home.ts +0 -1
  27. package/src/cli/cmd_Hooks.ts +1 -0
  28. package/src/cli/cmd_Mv.ts +1 -0
  29. package/src/cli/cmd_Rec.ts +17 -7
  30. package/src/cli/cmd_Reflect.ts +1 -0
  31. package/src/cli/cmd_Releases.ts +1 -0
  32. package/src/cli/cmd_Review.ts +124 -17
  33. package/src/cli/cmd_Secret.ts +41 -2
  34. package/src/cli/cmd_Shot.ts +1 -0
  35. package/src/cli/cmd_Status.ts +1 -0
  36. package/src/cli/cmd_Time.ts +3 -1
  37. package/src/cli/cmd_Tmp.ts +82 -0
  38. package/src/cli/cmd_Wiki.ts +1 -0
  39. package/src/cli/registry.ts +13 -1
  40. package/src/collections/pings.ts +1 -1
  41. package/src/core/capacity.ts +71 -0
  42. package/src/core/check-runner.ts +86 -15
  43. package/src/core/machine-db.ts +8 -0
  44. package/src/core/motherhome.ts +67 -9
  45. package/src/core/slots.ts +49 -12
  46. package/src/core/trace-audit.ts +4 -1
  47. package/src/drill/run.ts +5 -2
  48. package/src/home/daemon-jobs.ts +10 -3
  49. package/src/home/global-units.ts +3 -0
  50. package/src/home/gui-app/ShipkitGui.swift +1 -0
  51. package/src/home/home-launchd.ts +11 -3
  52. package/src/home/home-routes.ts +11 -4
  53. package/src/home/machine-host.ts +65 -0
  54. package/src/home/machine-stores.ts +30 -4
  55. package/src/home/machine-temp.ts +493 -0
  56. package/src/home/other-macs.ts +74 -0
  57. package/src/home/pm.ts +4 -1
  58. package/src/home/run-daemon.ts +10 -2
  59. package/src/home/run-pm.ts +1 -0
  60. package/src/home/serve-web.ts +2 -2
  61. package/src/home/via-hub.ts +6 -1
  62. package/src/identities/identities.ts +92 -24
  63. package/src/init-repo.ts +7 -3
  64. package/src/ledger/ledger.ts +6 -0
  65. package/src/ledger/store.ts +6 -0
  66. package/src/media-store/backup/keys.ts +21 -6
  67. package/src/media-store/backup/manifest.ts +52 -11
  68. package/src/media-store/backup/restore.ts +17 -10
  69. package/src/media-store/backup/run.ts +5 -2
  70. package/src/media-store/backup/sources.ts +2 -1
  71. package/src/media-store/daemon.ts +2 -2
  72. package/src/media-store/purge.ts +4 -0
  73. package/src/mv/mv-md.ts +121 -42
  74. package/src/recordings/load.ts +3 -3
  75. package/src/recordings/model.ts +7 -0
  76. package/src/recordings/open.ts +12 -0
  77. package/src/recordings/presets.ts +12 -5
  78. package/src/recordings/recorder-app/Capture.swift +34 -5
  79. package/src/recordings/recorder-app/Clip.swift +126 -17
  80. package/src/recordings/recorder-app/Editor.swift +177 -7
  81. package/src/recordings/recorder-app/Hud.swift +189 -0
  82. package/src/recordings/recorder-app/Tray.swift +179 -36
  83. package/src/recordings/recorder-app/icon.svg +16 -0
  84. package/src/recordings/recorder-app/main.swift +349 -18
  85. package/src/recordings/recorder-app.ts +8 -4
  86. package/src/recordings/recorder.shipkit.ts +2 -1
  87. package/src/recordings/routes.ts +52 -6
  88. package/src/recordings/run-recorder.ts +2 -1
  89. package/src/recordings/share.ts +27 -0
  90. package/src/recordings/take.ts +36 -4
  91. package/src/recordings/view.ts +11 -0
  92. package/src/reflect/transcript.ts +56 -11
  93. package/src/releases/from-card.ts +45 -3
  94. package/src/releases/model.ts +6 -0
  95. package/src/releases/store.ts +8 -1
  96. package/src/repo-config.ts +14 -4
  97. package/src/review/cells.ts +24 -3
  98. package/src/review/format.ts +33 -9
  99. package/src/review/media-kind.ts +14 -11
  100. package/src/review/media-read.ts +6 -5
  101. package/src/review/model.ts +104 -7
  102. package/src/review/paste.ts +2 -1
  103. package/src/review/previews.ts +123 -36
  104. package/src/review/routes.ts +29 -18
  105. package/src/review/store.ts +74 -12
  106. package/src/review/threads.ts +7 -5
  107. package/src/secrets/copy.ts +110 -0
  108. package/src/secrets/list.ts +17 -7
  109. package/src/serve/hub-app/home-strip.css +5 -0
  110. package/src/serve/hub-app/home-strip.tsx +18 -0
  111. package/src/serve/hub-app/hub-app.tsx +2 -1
  112. package/src/serve/hub-app/hub.css +18 -0
  113. package/src/serve/hub-app/inbox.css +1 -0
  114. package/src/serve/hub-app/pull-refresh.tsx +88 -0
  115. package/src/serve/hub-app/recordings-st.ts +135 -24
  116. package/src/serve/hub-app/recordings-view.tsx +293 -54
  117. package/src/serve/hub-app/recordings.css +77 -24
  118. package/src/serve/hub-app/review/review-cells.tsx +52 -13
  119. package/src/serve/hub-app/review/review-list.tsx +6 -1
  120. package/src/serve/hub-app/review/review-st.ts +6 -5
  121. package/src/serve/hub-app/review/review-thread.tsx +3 -1
  122. package/src/serve/hub-app/review/review-views.tsx +18 -11
  123. package/src/serve/hub-app/review/thread-st.ts +82 -14
  124. package/src/serve/hub-app/review.css +15 -2
  125. package/src/serve/hub-runtime.ts +2 -1
  126. package/src/serve/run-serve.ts +4 -2
  127. package/src/serve/serve-hub.ts +9 -2
  128. package/src/shipkit-files.ts +5 -0
  129. package/src/social/drafts.ts +4 -3
  130. package/src/social/load.ts +7 -2
  131. package/src/social/publish/discord.ts +10 -3
  132. package/src/suite/child-tools.ts +45 -0
  133. package/src/suite/judge-suites.ts +10 -22
  134. package/src/suite/select.ts +83 -8
  135. package/src/suite/suite-cli.ts +38 -14
  136. package/src/suite/suite-cores.ts +68 -0
  137. package/src/suite/suite-reads-preload.ts +8 -6
  138. package/src/ts/config.ts +44 -0
  139. package/src/ts/rename.ts +11 -1
package/CHANGELOG.md CHANGED
@@ -1,3 +1,47 @@
1
+ ## 2.24.0
2
+
3
+ - **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.
4
+ - **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.
5
+ - **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.
6
+ - **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.
7
+ - **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.
8
+ - **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.
9
+ - **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.
10
+ - **`sk capacity`** says how many more lanes the machine can take now, from its cores, its load and the agents live on it.
11
+ - **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`.
12
+ - **`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`.
13
+ - **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.
14
+ - **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.
15
+ - **A repo made by `sk start` or `sk init` has its commit gates armed** before its first commit.
16
+ - **A review verb outside a shipkit repo fails and names the folder**, where it used to write a stray store.
17
+ - **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.
18
+ - **`sk tmp`** reads the machine's temp folders with no walk, and one sweep deletes each idle unit no live process uses.
19
+ - **`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.
20
+ - **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.
21
+ - **SK044** warns when the branch is behind its upstream.
22
+ - **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.
23
+ - **`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.
24
+ - **The hub on a phone**: two fingers zoom every page, a pull down reloads it.
25
+
26
+ ## 2.23.0
27
+
28
+ - **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.
29
+ - **Every save is a version.** ⌘S renders the edit as v1, v2 and so on, each kept with its time and the text that made it; the Edit menu loads any of them again. A save with nothing changed renders nothing, cuts no version and uploads nothing, and a save keeps the editor as it was (playhead, tool, undo). A save goes up at once instead of waiting for the media store's next pass.
30
+ - **Where a capture stands**, one row under the toolbar: on the disk, which save plays, up in the Space, and its WebP, each with a light (done, running, not yet, waiting on a save).
31
+ - **⌘C in the editor** copies the capture as the toolbar's pick: the file, WebP (a screenshot as WebP HQ, a video up to 60 s as an animated WebP) or a private link. The WebP is made on its first copy and kept until another save plays; a screenshot shot with WebP HQ as its clipboard format has it from the shot.
32
+ - **A clipboard indicator** in the screen's corner and in the Capture window says only what the clipboard read back: copied, then the format and the size it serves, or that another copy took its place.
33
+ - **A cuts lane** under the play bar: paint the parts to cut, as many as wanted, and playback skips them; a drag from a red part puts that span back. It replaces the two trim handles.
34
+ - **All captures as a grid** in the Capture window: the grid button, G, or « All captures » in the band.
35
+ - **The editor reads better**: drawn tool icons in one bar, one toolbar row, copy colours dark enough for white text (the tray's too), and a two tone line around the capture so its edge shows on any ground. Tooltips stay inside the window.
36
+ - **Recent captures**: a × on a thumb's hover deletes the capture (two clicks), and `recorder.trayKey` is a global hotkey that shows or hides them.
37
+ - **The record bar keeps its mic and system sound** as they were left, per preset, across restarts.
38
+ - **The editor opens the instant a take ends**, a spinner over it while the take is filed; a capture hotkey pressed twice never stacks two captures.
39
+ - **A global process can start with pm**: `atLogin: true` starts it whenever pm starts cold (a login, a reboot, a kill), which the recorder uses so its hotkeys survive. pm and the recorder log the signal that stopped them.
40
+ - **Annex: scratch goes to the annex by itself** for a repo that opts in, behind the owner's switch; a move never loses a file, and a drive counts as back only with its marker.
41
+ - **Retention**: the sweep trims Claude Code's session temp folders, behind a switch, the newest sessions kept.
42
+ - **Review**: one bare `sk review watch` per repo, and an agent's card is answered by its lane alone, never twice.
43
+ - **Identities**: every account inherits its list of links, built from the other accounts' live links.
44
+
1
45
  ## 2.22.1
2
46
 
3
47
  - **A screenshot is on the clipboard the instant it is shot.** The recorder writes the clipboard before any encode, its file, PNG and WebP made behind it; a paste that comes first waits for them, so a quick ⌘V never pastes the clipboard from before, whatever the format.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rvlib-shipkit",
3
- "version": "2.22.1",
3
+ "version": "2.24.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",
@@ -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)
@@ -23,21 +23,29 @@ export type Call = {
23
23
  perm: string
24
24
  /** it only read (turns.ts isReadOnly, judged when indexed) */
25
25
  read: boolean
26
+ /** the call returned while its command ran on in the background: `end`
27
+ * is when it returned, `bgEnd` when the run ended (its task notification),
28
+ * null while no end is recorded */
29
+ bg: boolean
30
+ bgEnd: number | null
26
31
  }
27
32
 
28
- export type Mark = { at: number; kind: 'prompt' | 'wake' | 'message' | 'reply' }
33
+ /** `end`: the agent ended its turn (a text block, stop_reason end_turn) */
34
+ export type Mark = { at: number; kind: 'prompt' | 'wake' | 'message' | 'reply' | 'end' }
29
35
 
30
36
  export type Stream = { calls: Call[]; marks: Mark[] }
31
37
 
32
- /** where a slice of wall time went */
33
- export type Bucket = 'model' | 'tools' | 'approval' | 'subagent' | 'background' | 'human' | 'idle'
38
+ /** where a slice of wall time went. `human`: stopped until his typed prompt;
39
+ * `parked`: stopped until a message relayed in (the coordinator, another
40
+ * session), so a lane that handed back and waits to be written to */
41
+ export type Bucket = 'model' | 'tools' | 'approval' | 'subagent' | 'background' | 'parked' | 'human' | 'idle' | 'unknown'
34
42
 
35
43
  export type Breakdown = Record<Bucket, number>
36
44
 
37
45
  /** a wait on him longer than this is the session parked, not a wait */
38
46
  export const IDLE_MS = 30 * 60 * 1000
39
47
 
40
- export const emptyBreakdown = (): Breakdown => ({ model: 0, tools: 0, approval: 0, subagent: 0, background: 0, human: 0, idle: 0 })
48
+ export const emptyBreakdown = (): Breakdown => ({ model: 0, tools: 0, approval: 0, subagent: 0, background: 0, parked: 0, human: 0, idle: 0, unknown: 0 })
41
49
 
42
50
  /** a foreground sub-agent call: the session waits on another agent's work */
43
51
  export const isAgentCall = (c: Call): boolean => c.tool === 'Agent' || c.tool === 'Task'
@@ -61,7 +69,7 @@ export type Closed = Call & { stop: number; open: boolean }
61
69
 
62
70
  /** sorted by start */
63
71
  export function closeCalls(s: Stream): Closed[] {
64
- const turns = s.marks.filter((m) => m.kind !== 'reply').map((m) => m.at).sort((a, b) => a - b)
72
+ const turns = s.marks.filter((m) => m.kind !== 'reply' && m.kind !== 'end').map((m) => m.at).sort((a, b) => a - b)
65
73
  let last = 0
66
74
  for (const m of s.marks) if (m.at > last) last = m.at
67
75
  for (const c of s.calls) if ((c.end ?? c.start) > last) last = c.end ?? c.start
@@ -77,20 +85,32 @@ export function closeCalls(s: Stream): Closed[] {
77
85
  /** the call's own duration in ms */
78
86
  export const callMs = (c: { start: number; stop: number }): number => Math.max(0, c.stop - c.start)
79
87
 
88
+ /** how long the command really ran: a background run from its start to its
89
+ * notification (null while none is recorded), any other call its own time */
90
+ export const runMs = (c: Closed): number | null => (!c.bg ? callMs(c) : c.bgEnd == null ? null : Math.max(0, c.bgEnd - c.start))
91
+
80
92
  type Point = { at: number; d: 'start' | 'stop' | Mark['kind']; lane: 'tool' | 'agent' | 'approval'; ix: number }
81
93
 
82
94
  /** the wall of one stream cut into buckets, clipped to [from, to]. Between two
83
95
  * boundaries: a tool in flight → tools; only calls waiting for his allow →
84
96
  * approval; only a sub-agent in flight → subagent;
85
97
  * nothing in flight and the next thing is his prompt → human (idle past
86
- * IDLE_MS); the next thing is a wake (a task notification, a hand-back) →
87
- * background; a message relayed in counts as a prompt (a sub-agent that
88
- * handed back sits parked until the coordinator or he writes to it); anything else → the model was working.
98
+ * IDLE_MS); a message relayed in → parked (idle past IDLE_MS: a sub-agent
99
+ * that handed back sits there until the coordinator writes to it); a wake (a
100
+ * task notification, a hand-back) → background. Else, when the agent ended
101
+ * its turn (an `end` mark) and nothing since: it was stopped, and no record
102
+ * says on what → unknown (idle past IDLE_MS); else the agent was in its turn,
103
+ * its API request in flight → model.
104
+ *
105
+ * Past the stream's last event nothing counts, a run that ended included,
106
+ * but one case: the report runs (`to`, finite) while the stream is stopped
107
+ * on a background run of its own that has no end yet, its stop under
108
+ * IDLE_MS old → background up to `to`.
89
109
  *
90
110
  * `turnModel` (one slot per closed call) receives the model stretch that
91
111
  * ended in each call: the turn that issued it, split evenly over the calls
92
- * of one batch. A stretch that ends in his prompt or a wake was the final
93
- * reply and goes to no call */
112
+ * of one batch. A stretch that ends in his prompt, a wake or the turn's end
113
+ * was the final reply and goes to no call */
94
114
  export function wallBreakdown(s: Stream, from = -Infinity, to = Infinity, idleMs = IDLE_MS, closed: Closed[] = closeCalls(s), turnModel?: Float64Array): Breakdown {
95
115
  const out = emptyBreakdown()
96
116
  const points: Point[] = []
@@ -104,6 +124,7 @@ export function wallBreakdown(s: Stream, from = -Infinity, to = Infinity, idleMs
104
124
  let agents = 0
105
125
  let approvals = 0
106
126
  let pending = 0
127
+ let stopped = false
107
128
  const issued: number[] = []
108
129
  let i = 0
109
130
  while (i < points.length) {
@@ -117,14 +138,19 @@ export function wallBreakdown(s: Stream, from = -Infinity, to = Infinity, idleMs
117
138
  else if (p.lane === 'approval') approvals += n
118
139
  else tools += n
119
140
  if (p.d === 'start') issued.push(p.ix)
120
- else if (p.d === 'prompt' || p.d === 'wake' || p.d === 'message') ended = true
141
+ else if (p.d === 'prompt' || p.d === 'wake' || p.d === 'message' || p.d === 'end') ended = true
142
+ if (p.d !== 'stop') stopped = p.d === 'end'
121
143
  i++
122
144
  }
123
145
  if (turnModel != null) {
124
146
  if (issued.length > 0) for (const ix of issued) turnModel[ix] = (turnModel[ix] ?? 0) + pending / issued.length
125
147
  if (issued.length > 0 || ended) pending = 0
126
148
  }
127
- if (i >= points.length) break
149
+ if (i >= points.length) {
150
+ const waitsOnItsOwn = stopped && Number.isFinite(to) && to - at <= idleMs && closed.some((c) => c.bg && c.start <= at && (c.bgEnd == null || c.bgEnd > at))
151
+ if (waitsOnItsOwn) out.background += Math.max(0, to - Math.max(at, from))
152
+ break
153
+ }
128
154
  const nextAt = (points[i] as Point).at
129
155
  const a = Math.max(at, from)
130
156
  const b = Math.min(nextAt, to)
@@ -136,16 +162,18 @@ export function wallBreakdown(s: Stream, from = -Infinity, to = Infinity, idleMs
136
162
  else if (agents > 0) bucket = 'subagent'
137
163
  else {
138
164
  let next = i
139
- let prompt = false
165
+ let typed = false
166
+ let message = false
140
167
  let wake = false
141
168
  while (next < points.length && (points[next] as Point).at === nextAt) {
142
169
  const d = (points[next] as Point).d
143
- if (d === 'prompt' || d === 'message') prompt = true
170
+ if (d === 'prompt') typed = true
171
+ if (d === 'message') message = true
144
172
  if (d === 'wake') wake = true
145
173
  next++
146
174
  }
147
175
  const gap = nextAt - at
148
- bucket = prompt ? (gap > idleMs ? 'idle' : 'human') : wake ? 'background' : 'model'
176
+ bucket = typed ? (gap > idleMs ? 'idle' : 'human') : message ? (gap > idleMs ? 'idle' : 'parked') : wake ? 'background' : !stopped ? 'model' : gap > idleMs ? 'idle' : 'unknown'
149
177
  }
150
178
  out[bucket] += len
151
179
  if (bucket === 'model') pending += len
@@ -24,6 +24,9 @@ export type AnnexSpec = {
24
24
  maxGb?: number
25
25
  /** the free space its drive keeps, in GB (ANNEX_FREE_MIN when none is given) */
26
26
  keepFreeGb?: number
27
+ /** the most its scratch (`offload/`: born and offloaded folders) may hold, in GB: past it, files untouched for
28
+ * SCRATCH_KEEP_DAYS go, oldest first (tidy.ts). None: only `keepFreeGb` trims it */
29
+ scratchMaxGb?: number
27
30
  }
28
31
 
29
32
  export const keepFree = (spec: AnnexSpec): number => (spec.keepFreeGb === undefined ? ANNEX_FREE_MIN : spec.keepFreeGb * GB)