Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

649 linesCodeBlameRaw
1//! What sessions touched, and the issues and pull requests they worked on.
2//!
3//! A session is tied to an issue or pull request in as many ways as it
4//! was (`LinkVia`): attached when it started or updated, a claim it made,
5//! a pull request it opened or a branch or commit of one, a
6//! `G1t-Session:` trailer on a commit pushed to one, and `#N` in its
7//! prompt, its task or a subagent's. Each way is a row of
8//! `session_links`; reading a session gathers its whole tree's
9//! (`gather_links`). Files two sessions touched make them overlap
10//! (`overlap.detected`, once per pair).
11
12use std::collections::{HashMap, HashSet};
13
14use g1t_contracts::Outcome;
15use g1t_contracts::repos::{Commit, LogArgs, RepoPath};
16use g1t_contracts::time::rfc3339;
17use g1t_contracts::work::*;
18use g1t_kit::now_ms;
19use serde::Deserialize;
20use worker::Result;
21
22use super::updates::push_delivery;
23use super::{SESSION_COLUMNS, SessionRow};
24use crate::Work;
25
26/// The start (`?2` characters) of the first prompt each session in `?1`
27/// (a JSON list of ids) recorded, by the session's own numbering.
28pub(crate) const FIRST_PROMPTS: &str = "SELECT session_id, text FROM (
29 SELECT ids.value AS session_id,
30 (SELECT substr(e.text, 1, ?2) FROM session_entries e
31 WHERE e.session_id = ids.value AND e.kind = 'prompt' ORDER BY e.session_seq LIMIT 1) AS text
32 FROM json_each(?1) AS ids)
33 WHERE text IS NOT NULL";
34
35/// The most `#N` of one text looked up.
36const MAX_REFS: usize = 10;
37/// The most issues and pull requests a session's links name.
38const MAX_LINKED: usize = 40;
39/// The most commits of one push read for trailers.
40const MAX_TRAILER_COMMITS: u32 = 20;
41/// The most subagents a tree shows.
42pub(crate) const MAX_TREE: u32 = 200;
43
44/// Ties session `?1` of repository `?2` to issue or pull request (`?3`)
45/// `?4` by way of `?5`, at `?6`; nothing when it is tied that way already.
46pub(crate) const INSERT_LINK: &str = "INSERT INTO session_links (session_id, repo_id, kind, number, via, at)
47 VALUES (?1, ?2, ?3, ?4, ?5, ?6) ON CONFLICT DO NOTHING";
48
49/// Records that session `?1` of repository `?2` touched (`?3`) `?4`, at
50/// `?5`; returns it only the first time.
51pub(crate) const INSERT_TOUCH: &str = "INSERT INTO session_touches (session_id, repo_id, kind, value, at)
52 VALUES (?1, ?2, ?3, ?4, ?5) ON CONFLICT DO NOTHING RETURNING kind, value";
53
54/// Session `?1`'s subagents, and theirs, in the order they started.
55pub(crate) fn tree_sql() -> String {
56 format!(
57 "WITH RECURSIVE tree(id) AS (
58 SELECT id FROM sessions WHERE parent_id = ?1
59 UNION SELECT s.id FROM sessions s JOIN tree ON s.parent_id = tree.id)
60 SELECT {SESSION_COLUMNS} FROM sessions WHERE id IN (SELECT id FROM tree)
61 ORDER BY started_at, id LIMIT {MAX_TREE}"
62 )
63}
64
65/// Ends session `?1`'s subagents still going, and theirs, at `?2` for
66/// `?3`: only once `?1` itself ended at `?2`, so in the batch that ends it,
67/// a call that lost the race to end it ends nothing.
68pub(crate) fn end_tree_sql() -> String {
69 format!(
70 "WITH RECURSIVE tree(id) AS (
71 SELECT id FROM sessions WHERE parent_id = ?1
72 UNION SELECT s.id FROM sessions s JOIN tree ON s.parent_id = tree.id)
73 UPDATE sessions SET state = 'ended', ended_at = ?2, end_reason = ?3, last_seen_at = ?2
74 WHERE id IN (SELECT id FROM tree) AND state = 'active'
75 AND EXISTS (SELECT 1 FROM sessions WHERE id = ?1 AND state = 'ended' AND ended_at = ?2)
76 RETURNING {SESSION_COLUMNS}"
77 )
78}
79
80/// Session `?1`'s line: its parents up to the top, and its subagents and
81/// theirs. Never told of overlapping with each other.
82pub(crate) const FAMILY: &str = "WITH RECURSIVE
83 up(id, parent) AS (
84 SELECT id, parent_id FROM sessions WHERE id = ?1
85 UNION SELECT s.id, s.parent_id FROM sessions s JOIN up ON s.id = up.parent),
86 down(id) AS (
87 SELECT id FROM sessions WHERE parent_id = ?1
88 UNION SELECT s.id FROM sessions s JOIN down ON s.parent_id = down.id)
89 SELECT id FROM up UNION SELECT id FROM down";
90
91/// The files of `?2` (JSON) that active sessions of repository `?1` other
92/// than `?3` touched.
93pub(crate) const TOUCHED_BY_OTHERS: &str = "SELECT t.session_id AS session_id, t.value AS value
94 FROM session_touches t JOIN sessions s ON s.id = t.session_id
95 WHERE t.repo_id = ?1 AND t.kind = 'file' AND t.value IN (SELECT value FROM json_each(?2))
96 AND t.session_id <> ?3 AND s.state = 'active'";
97
98/// The sessions of repository `?1` that pushed the branch of one of the
99/// pull requests `?2` (JSON numbers).
100pub(crate) const BRANCH_SESSIONS: &str = "SELECT DISTINCT t.session_id AS id FROM session_touches t
101 JOIN pulls p ON p.repo_id = t.repo_id AND p.source_branch = t.value
102 AND p.fork_repo_id IS NULL AND p.head_repo_id IS NULL
103 WHERE t.repo_id = ?1 AND t.kind = 'branch' AND p.number IN (SELECT value FROM json_each(?2)) LIMIT 200";
104
105/// Announces the pair `?2`, `?3` of repository `?1` as overlapping on
106/// `?4` (JSON) at `?5`: returns it the first time, and again whenever a
107/// file it was not announced for joins, so a pair that first met on a
108/// trivial file still hears when it starts changing the same code.
109pub(crate) const INSERT_OVERLAP: &str = "INSERT INTO session_overlaps (repo_id, low, high, files, noticed_at)
110 VALUES (?1, ?2, ?3, ?4, ?5)
111 ON CONFLICT (repo_id, low, high) DO UPDATE SET
112 files = (SELECT json_group_array(value) FROM (
113 SELECT value FROM json_each(session_overlaps.files)
114 UNION SELECT value FROM json_each(excluded.files))),
115 noticed_at = excluded.noticed_at
116 WHERE EXISTS (SELECT 1 FROM json_each(excluded.files) AS added
117 WHERE added.value NOT IN (SELECT value FROM json_each(session_overlaps.files)))
118 RETURNING low";
119
120#[derive(Deserialize)]
121struct IdRow {
122 id: String,
123}
124
125#[derive(Deserialize)]
126struct NumberOnly {
127 number: u32,
128}
129
130#[derive(Deserialize)]
131pub(crate) struct LinkRow {
132 session_id: String,
133 kind: String,
134 number: u32,
135 via: String,
136}
137
138#[derive(Deserialize)]
139pub(crate) struct TouchRow {
140 session_id: String,
141 kind: String,
142 value: String,
143 at: String,
144}
145
146#[derive(Deserialize)]
147struct PairRow {
148 session_id: String,
149 value: String,
150}
151
152#[derive(Deserialize)]
153struct SkillRow {
154 session_id: String,
155 name: String,
156 uses: u32,
157}
158
159fn kind_name(kind: LinkKind) -> &'static str {
160 match kind {
161 LinkKind::Issue => "issue",
162 LinkKind::Pull => "pull",
163 }
164}
165
166impl Work {
167 /// Ties `session_id` to an issue or pull request one way. Never fails
168 /// what it follows: a problem is logged.
169 pub(crate) async fn link(&self, session_id: &str, repo_id: &str, kind: LinkKind, number: u32, via: LinkVia) {
170 let at = rfc3339(now_ms());
171 let linked = async {
172 self.db
173 .prepare(INSERT_LINK)
174 .bind(&[session_id.into(), repo_id.into(), kind_name(kind).into(), number.into(), via.as_str().into(), at.into()])?
175 .run()
176 .await
177 };
178 if let Err(error) = linked.await {
179 worker::console_error!("session {session_id}: not tied to {} #{number}: {error}", kind_name(kind));
180 }
181 }
182
183 /// Ties a session to the issues and pull requests `#N` in `text` names
184 /// that the repository has.
185 pub(crate) async fn link_refs(&self, session_id: &str, repo_id: &str, text: &str) -> Result<()> {
186 for number in refs_in(text).into_iter().take(MAX_REFS) {
187 if self.issue(repo_id, number).await?.is_some() {
188 self.link(session_id, repo_id, LinkKind::Issue, number, LinkVia::Ref).await;
189 } else if self.pull(repo_id, number).await?.is_some() {
190 self.link(session_id, repo_id, LinkKind::Pull, number, LinkVia::Ref).await;
191 }
192 }
193 Ok(())
194 }
195
196 /// Ties a session to the pull requests of `branch`.
197 pub(crate) async fn link_branch(&self, session_id: &str, repo_id: &str, branch: &str) -> Result<()> {
198 let pulls = self
199 .db
200 .prepare(
201 "SELECT number FROM pulls WHERE repo_id = ? AND source_branch = ?
202 AND fork_repo_id IS NULL AND head_repo_id IS NULL",
203 )
204 .bind(&[repo_id.into(), branch.into()])?
205 .all()
206 .await?
207 .results::<NumberOnly>()?;
208 for pull in pulls {
209 self.link(session_id, repo_id, LinkKind::Pull, pull.number, LinkVia::Branch).await;
210 }
211 Ok(())
212 }
213
214 /// Ties a session to the pull requests whose head is `commit` (a full
215 /// or abbreviated hash).
216 pub(crate) async fn link_commit(&self, session_id: &str, repo_id: &str, commit: &str) -> Result<()> {
217 let pulls = self
218 .db
219 .prepare("SELECT number FROM pulls WHERE repo_id = ? AND head_commit IS NOT NULL AND substr(head_commit, 1, length(?2)) = ?2")
220 .bind(&[repo_id.into(), commit.into()])?
221 .all()
222 .await?
223 .results::<NumberOnly>()?;
224 for pull in pulls {
225 self.link(session_id, repo_id, LinkKind::Pull, pull.number, LinkVia::Commit).await;
226 }
227 Ok(())
228 }
229
230 /// Records what a session touched, ties it to what that names, and
231 /// tells it and the other sessions on the same files that they
232 /// overlap. Returns how many were new.
233 pub(crate) async fn record_touches(&self, session: &Session, touches: &[NewTouch]) -> Result<u32> {
234 let touches = tidy_touches(touches);
235 if touches.is_empty() {
236 return Ok(0);
237 }
238 let at = rfc3339(now_ms());
239 let mut statements = Vec::with_capacity(touches.len());
240 for touch in &touches {
241 statements.push(self.db.prepare(INSERT_TOUCH).bind(&[
242 session.id.as_str().into(),
243 session.repo_id.as_str().into(),
244 touch.kind.as_str().into(),
245 touch.value.as_str().into(),
246 at.as_str().into(),
247 ])?);
248 }
249 let mut new: Vec<NewTouch> = Vec::new();
250 for result in self.db.batch(statements).await? {
251 for row in result.results::<serde_json::Value>()? {
252 if let (Some(kind), Some(value)) = (row["kind"].as_str().and_then(TouchKind::parse), row["value"].as_str()) {
253 new.push(NewTouch { kind, value: value.to_owned() });
254 }
255 }
256 }
257 let mut files = Vec::new();
258 for touch in &new {
259 let number = touch.value.parse::<u32>().ok();
260 match (touch.kind, number) {
261 (TouchKind::Pull, Some(number)) => self.link(&session.id, &session.repo_id, LinkKind::Pull, number, LinkVia::Opened).await,
262 (TouchKind::Issue, Some(number)) => {
263 if self.issue(&session.repo_id, number).await?.is_some() {
264 self.link(&session.id, &session.repo_id, LinkKind::Issue, number, LinkVia::Ref).await;
265 }
266 }
267 (TouchKind::Branch, _) => self.link_branch(&session.id, &session.repo_id, &touch.value).await?,
268 (TouchKind::Commit, _) => self.link_commit(&session.id, &session.repo_id, &touch.value).await?,
269 (TouchKind::File, _) => files.push(touch.value.clone()),
270 _ => {}
271 }
272 }
273 if !files.is_empty() {
274 self.announce_session_overlaps(session, &files).await?;
275 }
276 Ok(new.len() as u32)
277 }
278
279 /// The ids of a session's line: its parents and its subagents.
280 pub(crate) async fn family(&self, session_id: &str) -> Result<HashSet<String>> {
281 Ok(self
282 .db
283 .prepare(FAMILY)
284 .bind(&[session_id.into()])?
285 .all()
286 .await?
287 .results::<IdRow>()?
288 .into_iter()
289 .map(|row| row.id)
290 .collect())
291 }
292
293 /// Tells `session` and each other active session that touched one of
294 /// `files` (outside its own line) that they overlap, once per pair.
295 async fn announce_session_overlaps(&self, session: &Session, files: &[String]) -> Result<()> {
296 let touched: Vec<(String, String)> = self
297 .db
298 .prepare(TOUCHED_BY_OTHERS)
299 .bind(&[session.repo_id.as_str().into(), serde_json::to_string(files)?.into(), session.id.as_str().into()])?
300 .all()
301 .await?
302 .results::<PairRow>()?
303 .into_iter()
304 .map(|row| (row.session_id, row.value))
305 .collect();
306 if touched.is_empty() {
307 return Ok(());
308 }
309 let family = self.family(&session.id).await?;
310 let at = rfc3339(now_ms());
311 for (other_id, files) in session_overlaps(&session.id, &family, &touched) {
312 let (low, high) = session_pair(&session.id, &other_id);
313 let Some(other) = self.session_row(&session.repo_id, &other_id).await? else {
314 continue;
315 };
316 let other = other.at(now_ms());
317 let ours = SessionOverlapDetected {
318 repo_id: session.repo_id.clone(),
319 number: session.pull.or(session.issue),
320 session_id: session.id.clone(),
321 other_session_id: other.id.clone(),
322 other_actor: other.actor.username.clone(),
323 files: files.clone(),
324 issue: session.issue,
325 other_issue: other.issue,
326 };
327 let theirs = SessionOverlapDetected {
328 number: other.pull.or(other.issue),
329 session_id: other.id.clone(),
330 other_session_id: session.id.clone(),
331 other_actor: session.actor.username.clone(),
332 issue: other.issue,
333 other_issue: session.issue,
334 ..ours.clone()
335 };
336 // The pair is noticed once, and each side told, in one change.
337 let mut statements = vec![self
338 .db
339 .prepare(INSERT_OVERLAP)
340 .bind(&[session.repo_id.as_str().into(), low.as_str().into(), high.as_str().into(), serde_json::to_string(&files)?.into(), at.as_str().into()])?];
341 let guard = "EXISTS (SELECT 1 FROM session_overlaps WHERE repo_id = ?7 AND low = ?8 AND high = ?9 AND noticed_at = ?10)";
342 let mut sent = Vec::new();
343 for event in [&ours, &theirs] {
344 let delivery = self.delivery(
345 "overlap.detected",
346 &session.repo_id,
347 serde_json::to_value(event)?,
348 &format!("{low}:{high}:{at}:{}", event.session_id),
349 guard,
350 vec![session.repo_id.as_str().into(), low.as_str().into(), high.as_str().into(), at.as_str().into()],
351 )?;
352 sent.push(push_delivery(&mut statements, delivery));
353 }
354 let new = match self.db.batch(statements).await?.into_iter().next() {
355 Some(result) => !result.results::<serde_json::Value>()?.is_empty(),
356 None => false,
357 };
358 if !new {
359 continue;
360 }
361 let actor = Some(session.actor.id.clone());
362 for (event, sent) in [ours, theirs].into_iter().zip(sent) {
363 self.delivered(sent, "overlap.detected", &session.repo_id, actor.clone(), serde_json::to_value(event)?).await?;
364 }
365 }
366 Ok(())
367 }
368
369 /// A session's subagents, and theirs, in the order they started, each
370 /// with how many it started.
371 pub(crate) async fn subagents_of(&self, session_id: &str, now: u64) -> Result<Vec<Session>> {
372 let rows = self.db.prepare(tree_sql()).bind(&[session_id.into()])?.all().await?.results::<SessionRow>()?;
373 let mut children: Vec<Session> = rows.into_iter().map(|row| row.at(now)).collect();
374 count_subagents(&mut children);
375 Ok(children)
376 }
377
378 /// How many subagents each of `sessions` started, filled in.
379 pub(crate) async fn fill_subagents(&self, sessions: &mut [Session]) -> Result<()> {
380 if sessions.is_empty() {
381 return Ok(());
382 }
383 let ids: Vec<&str> = sessions.iter().map(|session| session.id.as_str()).collect();
384 #[derive(Deserialize)]
385 struct Count {
386 parent_id: String,
387 n: u32,
388 }
389 let counts = self
390 .db
391 .prepare("SELECT parent_id, COUNT(*) AS n FROM sessions WHERE parent_id IN (SELECT value FROM json_each(?)) GROUP BY parent_id")
392 .bind(&[serde_json::to_string(&ids)?.into()])?
393 .all()
394 .await?
395 .results::<Count>()?;
396 let counts: HashMap<String, u32> = counts.into_iter().map(|count| (count.parent_id, count.n)).collect();
397 for session in sessions {
398 session.subagents = counts.get(&session.id).copied().unwrap_or_default();
399 }
400 Ok(())
401 }
402
403 /// Gives each session with no title the start of the first prompt it
404 /// recorded, as `first_prompt`, for saying what it is for.
405 pub(crate) async fn fill_first_prompts(&self, sessions: &mut [Session]) -> Result<()> {
406 let ids: Vec<&str> = sessions.iter().filter(|session| session.title.is_none()).map(|session| session.id.as_str()).collect();
407 if ids.is_empty() {
408 return Ok(());
409 }
410 #[derive(Deserialize)]
411 struct First {
412 session_id: String,
413 text: String,
414 }
415 let found = self
416 .db
417 .prepare(FIRST_PROMPTS)
418 .bind(&[serde_json::to_string(&ids)?.into(), (MAX_FIRST_PROMPT_CHARS as u32).into()])?
419 .all()
420 .await?
421 .results::<First>()?;
422 let found: HashMap<String, String> = found.into_iter().map(|first| (first.session_id, first.text)).collect();
423 for session in sessions.iter_mut().filter(|session| session.title.is_none()) {
424 session.first_prompt = found.get(&session.id).map(|text| text.trim().to_owned()).filter(|text| !text.is_empty());
425 }
426 Ok(())
427 }
428
429 /// What a tree of sessions touched, its links, and the skills it used.
430 pub(crate) async fn tree_facts(&self, repo_id: &str, ids: &[String]) -> Result<(Vec<SessionTouch>, Vec<SessionLink>, Vec<SessionSkill>)> {
431 let ids_json = serde_json::to_string(ids)?;
432 let touches = self
433 .db
434 .prepare(
435 "SELECT session_id, kind, value, at FROM session_touches
436 WHERE session_id IN (SELECT value FROM json_each(?)) ORDER BY at, rowid LIMIT 1000",
437 )
438 .bind(&[ids_json.as_str().into()])?
439 .all()
440 .await?
441 .results::<TouchRow>()?;
442 // A pull request opened on a branch after the session pushed it.
443 let branches: HashSet<(String, String)> = touches
444 .iter()
445 .filter(|touch| touch.kind == "branch")
446 .map(|touch| (touch.session_id.clone(), touch.value.clone()))
447 .collect();
448 for (session_id, branch) in branches.iter().take(20) {
449 self.link_branch(session_id, repo_id, branch).await?;
450 }
451 let records: Vec<LinkRecord> = self
452 .db
453 .prepare(
454 "SELECT session_id, kind, number, via FROM session_links
455 WHERE session_id IN (SELECT value FROM json_each(?)) ORDER BY at",
456 )
457 .bind(&[ids_json.as_str().into()])?
458 .all()
459 .await?
460 .results::<LinkRow>()?
461 .into_iter()
462 .filter_map(|row| {
463 let kind = match row.kind.as_str() {
464 "issue" => LinkKind::Issue,
465 "pull" => LinkKind::Pull,
466 _ => return None,
467 };
468 Some(LinkRecord { session_id: row.session_id, kind, number: row.number, via: LinkVia::parse(&row.via)? })
469 })
470 .collect();
471 let mut known = HashMap::new();
472 let mut wanted: Vec<(LinkKind, u32)> = Vec::new();
473 for record in &records {
474 if !wanted.contains(&(record.kind, record.number)) {
475 wanted.push((record.kind, record.number));
476 }
477 }
478 for (kind, number) in wanted.into_iter().take(MAX_LINKED) {
479 let found = match kind {
480 LinkKind::Issue => self.issue(repo_id, number).await?.map(|issue| (issue.title, state_name(&issue.state))),
481 LinkKind::Pull => self.pull(repo_id, number).await?.map(|pull| (pull.title, state_name(&pull.status))),
482 };
483 if let Some(found) = found {
484 known.insert((kind, number), found);
485 }
486 }
487 let links = gather_links(&records, &known);
488 let skills = self
489 .db
490 .prepare(
491 "SELECT session_id, text AS name, COUNT(*) AS uses FROM session_entries
492 WHERE session_id IN (SELECT value FROM json_each(?)) AND kind = 'skill'
493 GROUP BY session_id, text ORDER BY MIN(session_seq)",
494 )
495 .bind(&[ids_json.as_str().into()])?
496 .all()
497 .await?
498 .results::<SkillRow>()?
499 .into_iter()
500 .map(|row| SessionSkill { session_id: row.session_id, name: row.name, uses: row.uses })
501 .collect();
502 let touched = touches
503 .into_iter()
504 .filter_map(|row| {
505 Some(SessionTouch { session_id: row.session_id, kind: TouchKind::parse(&row.kind)?, value: row.value, at: row.at })
506 })
507 .collect();
508 Ok((touched, links, skills))
509 }
510
511 /// After a push moved `pulls` on `branch` to `after`: the sessions that
512 /// pushed that branch, and those its new commits name in
513 /// `G1t-Session:` trailers, are tied to them. Never fails the push's
514 /// handling: a problem is logged.
515 pub(crate) async fn link_push(&self, repo_id: &str, branch: &str, after: &str, commits: Option<u32>, pulls: &[Pull]) {
516 if pulls.is_empty() {
517 return;
518 }
519 let linked = async {
520 let pushed_by = self
521 .db
522 .prepare("SELECT DISTINCT session_id AS id FROM session_touches WHERE repo_id = ? AND kind = 'branch' AND value = ?")
523 .bind(&[repo_id.into(), branch.into()])?
524 .all()
525 .await?
526 .results::<IdRow>()?;
527 for session in &pushed_by {
528 for pull in pulls {
529 self.link(&session.id, repo_id, LinkKind::Pull, pull.number, LinkVia::Branch).await;
530 }
531 }
532 // Trailers are read only while someone records sessions here.
533 let recording = self
534 .db
535 .prepare("SELECT id FROM sessions WHERE repo_id = ? AND state = 'active' LIMIT 1")
536 .bind(&[repo_id.into()])?
537 .first::<IdRow>(None)
538 .await?;
539 if recording.is_none() {
540 return Ok::<(), worker::Error>(());
541 }
542 let Some(pull) = pulls.first() else { return Ok(()) };
543 let path: Option<RepoPath> =
544 g1t_kit::call(&self.repos, "path_by_id", &g1t_contracts::repos::PathByIdArgs { id: repo_id.to_owned() }).await?;
545 let Some(path) = path else { return Ok(()) };
546 let log = LogArgs {
547 path,
548 viewer: self.owner_viewer(pull).await?,
549 git_ref: Some(after.to_owned()),
550 limit: commits.unwrap_or(MAX_TRAILER_COMMITS).clamp(1, MAX_TRAILER_COMMITS),
551 };
552 let Outcome::Ok(history) = g1t_kit::call::<_, Outcome<Vec<Commit>>>(&self.repos, "log", &log).await? else {
553 return Ok(());
554 };
555 let mut named: Vec<String> = Vec::new();
556 for commit in &history {
557 for id in session_trailers(&commit.message) {
558 if !named.contains(&id) {
559 named.push(id);
560 }
561 }
562 }
563 for id in named {
564 if self.session_row(repo_id, &id).await?.is_none() {
565 continue;
566 }
567 for pull in pulls {
568 self.link(&id, repo_id, LinkKind::Pull, pull.number, LinkVia::Trailer).await;
569 }
570 }
571 Ok(())
572 };
573 if let Err(error) = linked.await {
574 worker::console_error!("push to {branch}: sessions not tied to its pull requests: {error}");
575 }
576 }
577
578 /// Sessions tied to an issue or pull request (`kind`, `number`) by a
579 /// link, by id.
580 pub(crate) async fn linked_sessions(&self, repo_id: &str, kind: LinkKind, number: u32) -> Result<Vec<String>> {
581 Ok(self
582 .db
583 .prepare("SELECT DISTINCT session_id AS id FROM session_links WHERE repo_id = ? AND kind = ? AND number = ? LIMIT 200")
584 .bind(&[repo_id.into(), kind_name(kind).into(), number.into()])?
585 .all()
586 .await?
587 .results::<IdRow>()?
588 .into_iter()
589 .map(|row| row.id)
590 .collect())
591 }
592
593 /// Sessions that pushed one of `pulls`' branches, by id: tied to them
594 /// even when the pull request was opened after the push.
595 pub(crate) async fn branch_sessions(&self, repo_id: &str, pulls: &[u32]) -> Result<Vec<String>> {
596 if pulls.is_empty() {
597 return Ok(Vec::new());
598 }
599 Ok(self
600 .db
601 .prepare(BRANCH_SESSIONS)
602 .bind(&[repo_id.into(), serde_json::to_string(pulls)?.into()])?
603 .all()
604 .await?
605 .results::<IdRow>()?
606 .into_iter()
607 .map(|row| row.id)
608 .collect())
609 }
610
611 /// Sessions by id, as they read now.
612 pub(crate) async fn sessions_by_id(&self, repo_id: &str, ids: &[String]) -> Result<Vec<Session>> {
613 if ids.is_empty() {
614 return Ok(Vec::new());
615 }
616 let now = now_ms();
617 Ok(self
618 .db
619 .prepare(format!(
620 "SELECT {SESSION_COLUMNS} FROM sessions WHERE repo_id = ? AND id IN (SELECT value FROM json_each(?))"
621 ))
622 .bind(&[repo_id.into(), serde_json::to_string(ids)?.into()])?
623 .all()
624 .await?
625 .results::<SessionRow>()?
626 .into_iter()
627 .map(|row| row.at(now))
628 .collect())
629 }
630}
631
632/// An issue's state or a pull request's status, as its JSON name.
633fn state_name<T: serde::Serialize>(state: &T) -> String {
634 serde_json::to_value(state).ok().and_then(|value| value.as_str().map(str::to_owned)).unwrap_or_default()
635}
636
637/// Fills in how many subagents each session of a tree started, from the
638/// tree itself.
639pub(crate) fn count_subagents(sessions: &mut [Session]) {
640 let mut counts: HashMap<String, u32> = HashMap::new();
641 for session in sessions.iter() {
642 if let Some(parent) = &session.parent_id {
643 *counts.entry(parent.clone()).or_default() += 1;
644 }
645 }
646 for session in sessions.iter_mut() {
647 session.subagents = counts.get(&session.id).copied().unwrap_or_default();
648 }
649}