@andrioid/paseo-attention-span 0.6.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/OVERVIEW.md +3 -1
  2. package/client/attention-screen.tsx +61 -1174
  3. package/client/coverage-settings.tsx +5 -4
  4. package/client/data.ts +4 -2
  5. package/client/feedback.tsx +21 -25
  6. package/client/history.tsx +12 -50
  7. package/client/item-actions.ts +363 -0
  8. package/client/item-row.tsx +450 -0
  9. package/client/new-issue.tsx +244 -0
  10. package/client/next-up.tsx +22 -183
  11. package/client/pickers.tsx +237 -0
  12. package/client/session-menu.ts +3 -11
  13. package/client/sessions.ts +58 -57
  14. package/client/setup.tsx +2 -1
  15. package/client/sheet.tsx +92 -15
  16. package/client/ui.tsx +23 -14
  17. package/client/wrap-up.tsx +151 -85
  18. package/docs/architecture.md +22 -11
  19. package/docs/screenshots/desktop-dark-doing-acknowledge.png +0 -0
  20. package/docs/screenshots/desktop-dark-doing-clear.png +0 -0
  21. package/docs/screenshots/desktop-dark-doing-issue-sheet.png +0 -0
  22. package/docs/screenshots/desktop-dark-doing-reviewers.png +0 -0
  23. package/docs/screenshots/desktop-dark-doing-sheet.png +0 -0
  24. package/docs/screenshots/desktop-dark-doing-wrap-dirty.png +0 -0
  25. package/docs/screenshots/desktop-dark-doing-wrap-multi.png +0 -0
  26. package/docs/screenshots/desktop-dark-doing-wrap.png +0 -0
  27. package/docs/screenshots/desktop-dark-doing.png +0 -0
  28. package/docs/screenshots/desktop-dark-next-up-setup.png +0 -0
  29. package/docs/screenshots/desktop-dark-next-up.png +0 -0
  30. package/docs/screenshots/desktop-dark-settings.png +0 -0
  31. package/docs/screenshots/phone-dark-doing.png +0 -0
  32. package/docs/screenshots/phone-light-next-up-filtered.png +0 -0
  33. package/index.client.tsx +19 -0
  34. package/index.server.ts +43 -26
  35. package/package.json +2 -1
  36. package/requirements.yaml +8 -3
  37. package/server/actions.ts +2 -1
  38. package/server/archive.ts +146 -67
  39. package/server/archived.ts +12 -16
  40. package/server/changes.ts +34 -54
  41. package/server/classify.ts +142 -136
  42. package/server/feedback.ts +2 -6
  43. package/server/fetch.ts +262 -0
  44. package/server/fixture.ts +83 -14
  45. package/server/github-types.ts +3 -1
  46. package/server/markdown.ts +3 -1
  47. package/server/port.ts +46 -0
  48. package/server/queries.ts +33 -23
  49. package/server/service.ts +155 -272
  50. package/server/setup.ts +15 -14
  51. package/server/store.ts +94 -80
  52. package/server/update.ts +34 -13
  53. package/server/view.ts +16 -15
  54. package/shared/archive.ts +116 -13
  55. package/shared/attention.ts +50 -18
  56. package/shared/changes.ts +2 -1
  57. package/shared/config.ts +2 -6
  58. package/shared/drafting.ts +17 -0
  59. package/shared/feedback.ts +6 -5
  60. package/shared/format.ts +2 -1
  61. package/shared/history-report.ts +2 -1
  62. package/shared/item-sessions.ts +76 -0
  63. package/shared/item-view.ts +223 -0
  64. package/shared/linked-sessions.ts +59 -8
  65. package/shared/names.ts +17 -0
  66. package/shared/new-issue.ts +129 -0
  67. package/shared/next-up-filter.ts +137 -0
  68. package/shared/paging.ts +16 -0
  69. package/shared/rpc.ts +23 -10
  70. package/shared/setup.ts +3 -1
  71. package/shared/wrap-up.ts +20 -23
@@ -1,5 +1,5 @@
1
1
  // Sessions started outside Attention Span, on the item their workspace belongs to [SES-08].
2
- import type { AgentSummary } from "./attention";
2
+ import type { AgentSummary, AttentionView } from "./attention";
3
3
 
4
4
  // The parts of a Paseo agent entry this needs.
5
5
  export interface PaseoAgentEntry {
@@ -8,6 +8,7 @@ export interface PaseoAgentEntry {
8
8
  archivedAt?: string | null;
9
9
  status: string;
10
10
  requiresAttention?: boolean;
11
+ attentionReason?: string | null;
11
12
  title?: string | null;
12
13
  workspaceId?: string | null;
13
14
  updatedAt?: string | null;
@@ -18,11 +19,27 @@ export interface PaseoWorkspaceEntry {
18
19
  id: string;
19
20
  workspaceKind: string;
20
21
  archivingAt?: string | null;
22
+ gitRuntime?: { currentBranch?: string | null; remoteUrl?: string | null } | null;
21
23
  githubRuntime?: { pullRequest?: { url: string; number?: number } | null } | null;
22
24
  }
23
25
 
24
26
  // Agents another agent started belong to that agent's session, not to the item.
25
- const PARENT_AGENT_LABEL = "paseo.parent-agent-id";
27
+ export const PARENT_AGENT_LABEL = "paseo.parent-agent-id";
28
+
29
+ // The unarchived sub-agents under these sessions, and theirs in turn: part of their session, so archived with it and never
30
+ // "another session" in its worktree [ATT-22]. An archived one in between is walked through, where the list has it, so an
31
+ // open sub-agent below it is still found. Deepest last.
32
+ export function subAgentsOf<A extends Pick<PaseoAgentEntry, "id" | "labels" | "archivedAt">>(agents: A[], sessionIds: string[]): A[] {
33
+ const found: A[] = [];
34
+ const seen = new Set(sessionIds);
35
+ for (let parents = [...seen]; parents.length; ) {
36
+ const children = agents.filter((agent) => !seen.has(agent.id) && parents.includes(agent.labels?.[PARENT_AGENT_LABEL] ?? ""));
37
+ for (const child of children) seen.add(child.id);
38
+ found.push(...children);
39
+ parents = children.map((child) => child.id);
40
+ }
41
+ return found.filter((agent) => !agent.archivedAt);
42
+ }
26
43
 
27
44
  // "owner/name#number" for a GitHub pull request URL.
28
45
  export function pullRequestKey(url: string): string | null {
@@ -30,10 +47,40 @@ export function pullRequestKey(url: string): string | null {
30
47
  return match ? `${match[1]}#${match[2]}` : null;
31
48
  }
32
49
 
33
- // Unlabelled agents, keyed to the PR Paseo linked their workspace to, or else to the item of the
34
- // Attention Span session whose worktree they share. Main and local checkouts never pass an item on,
35
- // and a worktree with sessions for two items passes on neither.
36
- export function linkedSessions(labelled: AgentSummary[], agents: PaseoAgentEntry[], workspaces: PaseoWorkspaceEntry[]): AgentSummary[] {
50
+ // "owner/name" of a GitHub remote, https or ssh.
51
+ function repoOfRemote(url: string | null | undefined): string | null {
52
+ return /github\.com[:/]([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/i.exec(url ?? "")?.[1] ?? null;
53
+ }
54
+
55
+ const branchKey = (repo: string, branch: string) => `${repo.toLowerCase()}\0${branch}`;
56
+
57
+ // My merged and closed PRs by repo and branch, the latest close winning when a branch was used twice: where a session on
58
+ // a worktree finds its item once Paseo no longer links the worktree to the PR [ATT-22, SES-08].
59
+ // A branch an open PR of mine is on maps to nothing: Paseo links that PR itself, and a session there is the open PR's work.
60
+ export function closedBranches(view: Partial<Pick<AttentionView, "history" | "ownClosed" | "doing" | "waiting">>): Map<string, string> {
61
+ const found: { key: string; repo: string; branch: string; at: string }[] = [];
62
+ for (const item of [...(view.history ?? []), ...(view.ownClosed ?? [])]) {
63
+ if (item.section !== "done" || !item.closedAt) continue;
64
+ if (item.kind === "pr" && item.target.headRefName) found.push({ key: item.key, repo: item.repo, branch: item.target.headRefName, at: item.closedAt });
65
+ for (const child of item.children) {
66
+ if (child.headRefName) found.push({ key: child.key, repo: child.key.split("#")[0], branch: child.headRefName, at: child.mergedAt ?? item.closedAt });
67
+ }
68
+ }
69
+ const open = new Set(
70
+ [...(view.doing ?? []).flatMap((section) => section.items), ...(view.waiting ?? []).flatMap((group) => group.items)].flatMap((item) => [
71
+ ...(item.target.headRefName ? [branchKey(item.target.repo, item.target.headRefName)] : []),
72
+ ...(item.target.stack ?? []).flatMap((pr) => (pr.head ? [branchKey(item.target.repo, pr.head)] : [])),
73
+ ]),
74
+ );
75
+ found.sort((a, b) => a.at.localeCompare(b.at));
76
+ return new Map(found.map(({ key, repo, branch }) => [branchKey(repo, branch), key] as const).filter(([branch]) => !open.has(branch)));
77
+ }
78
+
79
+ // Unlabelled agents, keyed to the PR Paseo linked their workspace to, or else to the item of the Attention Span session
80
+ // whose worktree they share, or else to my merged or closed PR whose branch the worktree is on (`branches`, from
81
+ // closedBranches). Main and local checkouts never pass an item on, and a worktree with sessions for two items passes on
82
+ // neither.
83
+ export function linkedSessions(labelled: AgentSummary[], agents: PaseoAgentEntry[], workspaces: PaseoWorkspaceEntry[], branches = new Map<string, string>()): AgentSummary[] {
37
84
  const known = new Set(labelled.map((agent) => agent.id));
38
85
  const items = new Map<string, Set<string>>();
39
86
  for (const agent of labelled) {
@@ -47,8 +94,12 @@ export function linkedSessions(labelled: AgentSummary[], agents: PaseoAgentEntry
47
94
  if (workspace.archivingAt) continue;
48
95
  const pr = workspace.githubRuntime?.pullRequest;
49
96
  const linked = pr ? pullRequestKey(pr.url) : null;
50
- const shared = workspace.workspaceKind === "worktree" ? items.get(workspace.id) : undefined;
51
- const key = linked ?? (shared?.size === 1 ? [...shared][0] : null);
97
+ const worktree = workspace.workspaceKind === "worktree";
98
+ const shared = worktree ? items.get(workspace.id) : undefined;
99
+ const repo = repoOfRemote(workspace.gitRuntime?.remoteUrl);
100
+ const branch = workspace.gitRuntime?.currentBranch;
101
+ const closed = worktree && !shared && repo && branch ? branches.get(branchKey(repo, branch)) : undefined;
102
+ const key = linked ?? (shared?.size === 1 ? [...shared][0] : null) ?? closed ?? null;
52
103
  if (key) itemOf.set(workspace.id, key);
53
104
  }
54
105
  return agents.flatMap((agent) => {
@@ -0,0 +1,17 @@
1
+ // GitHub's logins, owner and repo names, and so item keys ("owner/name#number"), ignore case; so do org issue field
2
+ // names, as people type them in config.json. Compare them only through these.
3
+
4
+ // The same name, whatever its case; nothing matches a missing one.
5
+ export function sameName(a: string | null | undefined, b: string | null | undefined): boolean {
6
+ return !!a && !!b && a.toLowerCase() === b.toLowerCase();
7
+ }
8
+
9
+ // Each name once, ignoring case, in the first spelling seen.
10
+ export function uniqueKeys(keys: string[]): string[] {
11
+ const unique = new Map<string, string>();
12
+ for (const key of keys) if (!unique.has(key.toLowerCase())) unique.set(key.toLowerCase(), key);
13
+ return [...unique.values()];
14
+ }
15
+
16
+ // Names for looking up, ignoring case: `keySet(keys).has(key.toLowerCase())`.
17
+ export const keySet = (keys: Iterable<string>): Set<string> => new Set([...keys].map((key) => key.toLowerCase()));
@@ -0,0 +1,129 @@
1
+ // A new issue in a repository I cover, drafted by an agent in my checkout from a line or two in a sheet [ISS-01, ISS-02].
2
+ // Built in, like feedback's prompts, because it carries the approval rules [SAFE-01].
3
+
4
+ import type { AttentionConfig } from "./config";
5
+ import { APPROVE, askUntilClear, fill, quote, SKIMMABLE } from "./drafting";
6
+
7
+ // The item label of a new issue session, by repository.
8
+ export const newIssueItemKey = (repo: string) => `new-issue:${repo.toLowerCase()}`;
9
+ // Tagged, so a session can tell itself apart from another draft for the same repository when it archives itself.
10
+ export const newIssueTitle = (repo: string, tag: string) => `New issue: ${repo} (${tag})`;
11
+ export const newIssueTag = () => Math.random().toString(36).slice(2, 7);
12
+
13
+ // What the sheet starts from: the choices remembered from last time, and the repositories it offers [ISS-01].
14
+ export interface NewIssueInfo {
15
+ repos: string[];
16
+ repo: string | null;
17
+ profileId: string | null;
18
+ }
19
+
20
+ const owner = (repo: string) => repo.split("/")[0].toLowerCase();
21
+
22
+ // The repositories Attention Span covers: the ones chosen, and those of my Paseo projects and of the items it shows that fall
23
+ // under a chosen org or my own account. With nothing chosen it covers everything involving me, so all of them [ISS-01].
24
+ export function newIssueRepos(
25
+ config: Pick<AttentionConfig, "orgs" | "repos" | "nextUp">,
26
+ projectRepos: string[],
27
+ shownRepos: string[],
28
+ login: string | null,
29
+ ): string[] {
30
+ const { orgs, repos, nextUp } = config;
31
+ const chosen = [...repos, ...nextUp.repos];
32
+ const owners = new Set([...orgs, ...nextUp.orgs, ...(nextUp.mine && login ? [login] : [])].map((name) => name.toLowerCase()));
33
+ const nothingChosen = chosen.length === 0 && owners.size === 0 && !nextUp.mine;
34
+ const known = [...projectRepos, ...shownRepos].filter((repo) => nothingChosen || owners.has(owner(repo)));
35
+ // The items shown are covered by definition, whichever rule found them.
36
+ const all = [...chosen, ...known, ...shownRepos].filter((repo) => /^[^/\s]+\/[^/\s]+$/.test(repo));
37
+ // Spelled as I chose it, where I did.
38
+ const unique = new Map<string, string>();
39
+ for (const repo of all) if (!unique.has(repo.toLowerCase())) unique.set(repo.toLowerCase(), repo);
40
+ return [...unique.values()].sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
41
+ }
42
+
43
+ const find = (repos: string[], repo: string | null | undefined) => (repo ? repos.find((other) => other.toLowerCase() === repo.toLowerCase()) : undefined);
44
+
45
+ // The repository the sheet starts on: the one of the workspace I came from, else the one Next up is narrowed to, else the
46
+ // one I filed in last, else the only one there is [ISS-01].
47
+ export function prefillRepo(repos: string[], from: { workspace?: string | null; nextUp?: string | null; last?: string | null }): string | null {
48
+ return find(repos, from.workspace) ?? find(repos, from.nextUp) ?? find(repos, from.last) ?? (repos.length === 1 ? repos[0] : null);
49
+ }
50
+
51
+ export interface SessionMessage {
52
+ from: "me" | "agent";
53
+ text: string;
54
+ }
55
+
56
+ // What the session I came from was doing, when I let it come along [ISS-01].
57
+ export interface SourceSession {
58
+ title: string | null;
59
+ workspace: string | null;
60
+ branch: string | null;
61
+ messages: SessionMessage[];
62
+ }
63
+
64
+ const MESSAGES = 4;
65
+ const MESSAGE_CHARS = 800;
66
+
67
+ // The last few things said in a session, each cut short, from its timeline entries.
68
+ export function lastMessages(entries: { item: { type: string; text?: string } }[], count = MESSAGES): SessionMessage[] {
69
+ return entries
70
+ .flatMap(({ item }): SessionMessage[] => {
71
+ const text = item.text?.trim();
72
+ if (!text || (item.type !== "user_message" && item.type !== "assistant_message")) return [];
73
+ return [{ from: item.type === "user_message" ? "me" : "agent", text: text.length > MESSAGE_CHARS ? `${text.slice(0, MESSAGE_CHARS).trimEnd()}…` : text }];
74
+ })
75
+ .slice(-count);
76
+ }
77
+
78
+ export interface NewIssueInput {
79
+ message: string;
80
+ repo: string;
81
+ // My checkout the agent runs in, which may hold another repository's code [SES-07].
82
+ dir: string;
83
+ codeRepo: string;
84
+ source: SourceSession | null;
85
+ // The session's own title, which it finds itself by.
86
+ title: string;
87
+ }
88
+
89
+ const PROMPT = `You're helping me file an issue in {{repo}} on GitHub.
90
+
91
+ I wrote:
92
+ > {{message}}
93
+ {{source}}
94
+ How to work:
95
+ - {{where}} Read the code to ground the issue, citing files as path:line, but change nothing: no edits, commits, branches or pushes. Put the body and any other scratch files in a temporary directory outside the checkout (\`mktemp -d\`).
96
+ - Reply in the language I write in. Write the issue in the language {{repo}}'s issues are written in, in my voice ("I …").
97
+ - ${askUntilClear("a maintainer acting on the issue")}
98
+ - Before drafting, search open issues for the same thing with a few phrasings (\`gh issue list --repo {{repo}} --state open --search "…"\`). If one looks like a duplicate, give its link and ask with your question tool: File anyway / Comment there instead / Cancel. A comment is a post too: draft it and get my approval the same way.
99
+ - Follow {{repo}}'s issue templates if it has any ({{templates}}): pick the one that fits and keep its headings, turning a form (.yml) into markdown with its fields as headings. Without a template: ${SKIMMABLE}
100
+ - Pick labels only from the ones {{repo}} has (\`gh label list --repo {{repo}}\`), and an issue type only if it has types (\`gh api graphql\` with \`repository(owner, name) { issueTypes(first: 25) { nodes { id name } } }\`). Leave out whatever doesn't clearly fit. Don't assign anyone or add it to a project.
101
+
102
+ ${APPROVE}
103
+ - Issue: \`gh issue create --repo {{repo}} --title … --body-file … --label …\`, then set the type you chose with the \`updateIssueIssueType\` mutation (\`gh api graphql\`).
104
+ - Comment: \`gh issue comment <number> --repo {{repo}} --body-file …\`.
105
+
106
+ Reply with the link, then close this session: archive this agent with Paseo's archive_agent tool. Find its ID with list_agents: the one agent titled exactly "{{title}}". If no agent or more than one has that title, archive nothing. Archive only the agent, never the workspace: it's my checkout. Without that tool, or when you can't tell which agent you are, say it's done and stop.`;
107
+
108
+ function sourceText(source: SourceSession | null): string {
109
+ if (!source) return "";
110
+ const where = [source.title ? `the Paseo session "${source.title}"` : "a Paseo session", source.workspace ? `in ${source.workspace}` : null, source.branch ? `on branch ${source.branch}` : null]
111
+ .filter(Boolean)
112
+ .join(" ");
113
+ const said = source.messages.map((message) => `> **${message.from === "me" ? "Me" : "Agent"}:** ${quote(message.text)}`).join("\n>\n");
114
+ const messages = said ? ` Its last messages, which may be about more than this issue:\n\n${said}\n` : "\n";
115
+ return `\nI started this from ${where}.${messages}Use only what the issue needs from it, and nothing private.\n`;
116
+ }
117
+
118
+ export function newIssuePrompt(input: NewIssueInput): string {
119
+ const where =
120
+ input.codeRepo.toLowerCase() === input.repo.toLowerCase()
121
+ ? `You are in my checkout of ${input.repo} at ${input.dir}.`
122
+ : `You are in my checkout of ${input.codeRepo} at ${input.dir}, where ${input.repo}'s code lives; the issue goes to ${input.repo}.`;
123
+ // The checkout holds the code repository's templates, which aren't the issues' when the two are apart [SES-07].
124
+ const templates =
125
+ input.codeRepo.toLowerCase() === input.repo.toLowerCase()
126
+ ? `\`.github/ISSUE_TEMPLATE/\` in the checkout; if it's not there, \`gh api repos/${input.repo}/contents/.github/ISSUE_TEMPLATE\``
127
+ : `\`gh api repos/${input.repo}/contents/.github/ISSUE_TEMPLATE\`; not the checkout's, which are ${input.codeRepo}'s`;
128
+ return fill(PROMPT, { repo: input.repo, message: quote(input.message), source: sourceText(input.source), where, templates, title: input.title });
129
+ }
@@ -0,0 +1,137 @@
1
+ // Next up's Filter: which ticks still count, which unclaimed issues they leave, and what the sheet offers [NXT-03, NXT-09, NXT-12].
2
+ // Drawn by client/sheet.tsx's FilterSheet.
3
+ import { type GithubColor, type NextUpIssue, type ProjectInfo, projectFilterId, projectFilterIds } from "./attention";
4
+ import type { NextUpSource } from "./config";
5
+
6
+ export type FilterKind = "sources" | "projects" | "scopes";
7
+ export type FilterChange = { scopes?: string[]; sources?: string[]; projectFilter?: string[] };
8
+
9
+ export interface FilterOption {
10
+ id: string;
11
+ label: string;
12
+ // A project's statuses sit under it, each with its board color.
13
+ indent?: boolean;
14
+ color?: GithubColor;
15
+ // A status no unclaimed issue has right now.
16
+ dim?: boolean;
17
+ // A project, ticked as a whole, partly, or not, by its statuses.
18
+ strong?: boolean;
19
+ state?: "on" | "partial" | "off";
20
+ // Always ticked, with a note why, like History's Finished [HIS-07].
21
+ disabled?: boolean;
22
+ note?: string;
23
+ }
24
+
25
+ export interface FilterGroup {
26
+ kind: FilterKind;
27
+ title: string;
28
+ options: FilterOption[];
29
+ active: string[];
30
+ }
31
+
32
+ export interface NextUpFilterInput {
33
+ unclaimed: NextUpIssue[];
34
+ // What I ticked, as saved; none means all.
35
+ selected: string[];
36
+ sources: NextUpSource[];
37
+ selectedSources: string[];
38
+ projects: ProjectInfo[];
39
+ selectedProjects: string[];
40
+ }
41
+
42
+ export interface NextUpFilter {
43
+ shown: NextUpIssue[];
44
+ // How many ticks the Filter button counts; a project ticked whole counts once.
45
+ picked: number;
46
+ groups: FilterGroup[];
47
+ // Unclaimed's line when nothing's left.
48
+ empty: string;
49
+ // What a tick changes, to save.
50
+ toggle: (kind: FilterKind, id: string) => FilterChange;
51
+ }
52
+
53
+ export const CLEAR_FILTER: FilterChange = { scopes: [], sources: [], projectFilter: [] };
54
+
55
+ export function nextUpFilter({ unclaimed, selected, sources, selectedSources, projects, selectedProjects }: NextUpFilterInput): NextUpFilter {
56
+ const scopes = [...new Set(unclaimed.map((issue) => issue.scope).filter((scope): scope is string => !!scope))].sort();
57
+ // A picked scope with no issues left is ignored [NXT-03].
58
+ const active = selected.filter((scope) => scopes.includes(scope));
59
+ // Sources filter only when there's more than one; a picked source no longer in settings is ignored [NXT-09].
60
+ const activeSources = sources.length > 1 ? selectedSources.filter((id) => sources.some((source) => source.id === id)) : [];
61
+ // A picked status no longer offered is ignored [NXT-03, NXT-12].
62
+ const tree = projectTree(unclaimed, projects);
63
+ const leaves = tree.flatMap((node) => node.children.map((child) => child.id));
64
+ const activeProjects = selectedProjects.filter((id) => leaves.includes(id));
65
+ const shown = unclaimed.filter(
66
+ (issue) =>
67
+ (active.length === 0 || (issue.scope && active.includes(issue.scope))) &&
68
+ (activeSources.length === 0 || issue.sources.some((id) => activeSources.includes(id))) &&
69
+ (activeProjects.length === 0 || projectFilterIds(issue).some((id) => activeProjects.includes(id))),
70
+ );
71
+ const flip = (list: string[], id: string) => (list.includes(id) ? list.filter((other) => other !== id) : [...list, id]);
72
+ // A project ticks or clears all its statuses at once; partly ticked, it clears them.
73
+ const toggleProject = (id: string): FilterChange => {
74
+ const children = tree.find((node) => node.id === id)?.children.map((child) => child.id);
75
+ if (!children) return { projectFilter: flip(activeProjects, id) };
76
+ const any = children.some((child) => activeProjects.includes(child));
77
+ return { projectFilter: any ? activeProjects.filter((other) => !children.includes(other)) : [...activeProjects, ...children] };
78
+ };
79
+ const toggle = (kind: FilterKind, id: string): FilterChange =>
80
+ kind === "scopes" ? { scopes: flip(active, id) } : kind === "sources" ? { sources: flip(activeSources, id) } : toggleProject(id);
81
+ const projectsPicked = tree.reduce((sum, node) => {
82
+ const on = node.children.filter((child) => activeProjects.includes(child.id)).length;
83
+ return sum + (on === node.children.length ? 1 : on);
84
+ }, 0);
85
+ const projectOptions: FilterOption[] = tree.flatMap((node) => {
86
+ if (node.children.length === 1 && node.children[0].id === node.id) return [{ id: node.id, label: node.title }];
87
+ const on = node.children.filter((child) => activeProjects.includes(child.id)).length;
88
+ return [
89
+ { id: node.id, label: node.title, strong: true, state: on === 0 ? "off" : on === node.children.length ? "on" : "partial" },
90
+ ...node.children.map((child) => ({ ...child, indent: true })),
91
+ ];
92
+ });
93
+ const groups: FilterGroup[] = [
94
+ ...(sources.length > 1 ? [{ kind: "sources" as const, title: "Source", options: sources, active: activeSources }] : []),
95
+ ...(projectOptions.length > 0 ? [{ kind: "projects" as const, title: "Project", options: projectOptions, active: activeProjects }] : []),
96
+ ...(scopes.length > 0 ? [{ kind: "scopes" as const, title: "Scope", options: scopes.map((scope) => ({ id: scope, label: scope })), active }] : []),
97
+ ];
98
+ const narrowedBy = [activeSources.length ? "sources" : null, activeProjects.length ? "projects" : null, active.length ? "scopes" : null].filter(Boolean);
99
+ return {
100
+ shown,
101
+ picked: active.length + activeSources.length + projectsPicked,
102
+ groups,
103
+ empty: `No unclaimed issues${narrowedBy.length ? ` in these ${narrowedBy.join(" and ")}` : ""}.`,
104
+ toggle,
105
+ };
106
+ }
107
+
108
+ // A project in the filter with its statuses under it, all of them in the board's order, dimmed where no unclaimed issue has
109
+ // one; "No status" where some issue on it has none, and "No project" last, where some issue is on none [NXT-03, NXT-12].
110
+ // Only projects the unclaimed issues are on; none at all when projects can't be read.
111
+ interface ProjectNode {
112
+ id: string;
113
+ title: string;
114
+ children: FilterOption[];
115
+ }
116
+
117
+ function projectTree(unclaimed: NextUpIssue[], projects: ProjectInfo[]): ProjectNode[] {
118
+ if (!unclaimed.some((issue) => issue.projects)) return [];
119
+ const on = (project: ProjectInfo) => unclaimed.flatMap((issue) => (issue.projects ?? []).filter((p) => p.id === project.id));
120
+ const nodes: ProjectNode[] = projects.flatMap((project) => {
121
+ const items = on(project);
122
+ if (items.length === 0) return [];
123
+ const statuses = project.statuses.map((status) => ({
124
+ id: projectFilterId(project, status.name),
125
+ label: status.name,
126
+ color: status.color,
127
+ dim: !items.some((item) => item.status === status.name),
128
+ }));
129
+ // A status the board no longer offers still filters, after the board's own.
130
+ const gone = [...new Set(items.map((item) => item.status).filter((name): name is string => !!name && !project.statuses.some((s) => s.name === name)))];
131
+ const none = items.some((item) => !item.status) ? [{ id: projectFilterId(project, null), label: "No status" }] : [];
132
+ return [{ id: project.id, title: project.title, children: [...statuses, ...gone.map((name) => ({ id: projectFilterId(project, name), label: name })), ...none] }];
133
+ });
134
+ const loose = unclaimed.some((issue) => issue.projects && issue.projects.length === 0);
135
+ const noProject = projectFilterId(null);
136
+ return loose ? [...nodes, { id: noProject, title: "No project", children: [{ id: noProject, label: "No project" }] }] : nodes;
137
+ }
@@ -0,0 +1,16 @@
1
+ // Every page of a Paseo list; a failed page fails the whole list, so it's never mistaken for a shorter one [ATT-22].
2
+ export interface Page<E> {
3
+ entries: E[];
4
+ pageInfo: { hasMore: boolean; nextCursor?: string | null };
5
+ }
6
+
7
+ export async function everyPage<E>(list: (page: { limit: number; cursor?: string }) => Promise<Page<E>>): Promise<E[]> {
8
+ const entries: E[] = [];
9
+ let cursor: string | undefined;
10
+ for (;;) {
11
+ const result = await list({ limit: 200, ...(cursor ? { cursor } : {}) });
12
+ entries.push(...result.entries);
13
+ if (!result.pageInfo.hasMore || !result.pageInfo.nextCursor) return entries;
14
+ cursor = result.pageInfo.nextCursor;
15
+ }
16
+ }
package/shared/rpc.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  import { defineRpc } from "@getpaseo/plugin";
2
2
  import { z } from "zod";
3
- import type { AttentionView, ItemDetails, ProjectsAccess, ReviewerChoices, Target } from "./attention";
4
- import type { ArchiveOutcome } from "./archive";
3
+ import { type AttentionView, FeedId, HistoryFilter, IssueCloseReason, type ItemDetails, type ProjectsAccess, type ReviewerChoices, type Target } from "./attention";
4
+ import { type ArchiveOutcome, ArchiveTarget } from "./archive";
5
5
  import { SessionKind } from "./config";
6
- import type { ConfigStatus, CoverageCheck, IssueField, SetupStatus } from "./setup";
6
+ import { type ConfigStatus, type CoverageCheck, CoverageKind, type IssueField, type SetupStatus } from "./setup";
7
7
  import type { FeedbackInfo } from "./feedback";
8
8
  import type { ReadyProvider } from "./providers";
9
9
  import type { UpdateNotice } from "./update";
@@ -14,11 +14,12 @@ const target = z.custom<Target>();
14
14
  const done = z.object({ ok: z.literal(true) });
15
15
 
16
16
  // The cached view. Feeds older than their schedule are refreshed from GitHub first; `refresh` fetches that feed now (⟳);
17
- // `cached` skips GitHub altogether, for a view that only needs what the server already knows.
17
+ // `cached` skips GitHub altogether, for a view that only needs what the server already knows. `timeZone` is the device's
18
+ // IANA zone, which History's weeks follow [HIS-01].
18
19
  export const getAttention = defineRpc({
19
20
  name: "attention.get",
20
21
  input: z
21
- .object({ refresh: z.enum(["live", "history"]).optional(), cached: z.boolean().optional() })
22
+ .object({ refresh: FeedId.optional(), cached: z.boolean().optional(), timeZone: z.string().optional() })
22
23
  .refine((input) => !(input.refresh && input.cached), "refresh and cached don't go together"),
23
24
  output: view,
24
25
  });
@@ -28,16 +29,25 @@ export const undismissItem = defineRpc({ name: "attention.undismiss", input: z.o
28
29
  // Clears Changed by others notes, one or all of them; `on: false` brings them back for Undo. Nothing changes on GitHub [HIS-07].
29
30
  export const gotIt = defineRpc({ name: "attention.got-it", input: z.object({ ids: z.array(z.string()), on: z.boolean() }), output: view });
30
31
  // Reviewed and Changed by others in History's weeks; remembered in state.json [HIS-07].
31
- export const setHistoryFilter = defineRpc({ name: "history.filter", input: z.object({ filter: z.array(z.enum(["reviewed", "changed"])) }), output: view });
32
- // Archives a Wrap up row's sessions, acknowledging what others did to the work [ATT-22]. `confirm` is the unsaved-work sheet.
32
+ export const setHistoryFilter = defineRpc({ name: "history.filter", input: z.object({ filter: z.array(HistoryFilter) }), output: view });
33
+ // Archives a Wrap up row's sessions, acknowledging what others did to the work [ATT-22]. `confirm` is the sheet that named
34
+ // unsaved work, and `terminals` the open terminals it named.
33
35
  export const archiveSessions = defineRpc({
34
36
  name: "attention.archive",
35
37
  input: z.object({
36
- targets: z.array(z.object({ itemKey: z.string(), agentIds: z.array(z.string()), keys: z.array(z.string()) })),
38
+ targets: z.array(ArchiveTarget),
37
39
  confirm: z.boolean(),
40
+ terminals: z.array(z.string()).default([]),
38
41
  }),
39
42
  output: z.custom<ArchiveOutcome>(),
40
43
  });
44
+ // A kept worktree tried again on its own, with the same sheet; or dismissed, leaving the worktree be [ATT-22].
45
+ export const archiveWorktree = defineRpc({
46
+ name: "attention.archive-worktree",
47
+ input: z.object({ workspaceId: z.string(), confirm: z.boolean(), terminals: z.array(z.string()).default([]) }),
48
+ output: z.custom<ArchiveOutcome>(),
49
+ });
50
+ export const dismissKept = defineRpc({ name: "attention.dismiss-kept", input: z.object({ workspaceId: z.string() }), output: view });
41
51
  export const restoreDismissed = defineRpc({ name: "attention.restore-dismissed", input: z.object({}), output: view });
42
52
  // Adds one entry to codeRepos in config.json [SES-07].
43
53
  export const setCodeRepo = defineRpc({ name: "config.set-code-repo", input: z.object({ issueRepo: z.string(), codeRepo: z.string() }), output: view });
@@ -45,7 +55,7 @@ export const setCodeRepo = defineRpc({ name: "config.set-code-repo", input: z.ob
45
55
  export const setupStatus = defineRpc({ name: "setup.status", input: z.object({}), output: z.custom<SetupStatus>() });
46
56
  // The settings screen: the orgs and repos in config.json, each checked on GitHub as it's added [SRC-02].
47
57
  export const getCoverage = defineRpc({ name: "config.coverage", input: z.object({}), output: z.custom<ConfigStatus>() });
48
- export const checkCoverage = defineRpc({ name: "config.check-coverage", input: z.object({ kind: z.enum(["org", "repo"]), name: z.string() }), output: z.custom<CoverageCheck>() });
58
+ export const checkCoverage = defineRpc({ name: "config.check-coverage", input: z.object({ kind: CoverageKind, name: z.string() }), output: z.custom<CoverageCheck>() });
49
59
  export const setCoverage = defineRpc({ name: "config.set-coverage", input: z.object({ orgs: z.array(z.string()), repos: z.array(z.string()) }), output: done });
50
60
  // Where Next up looks, chosen in settings [NXT-04]; orgs are picked from the ones I belong to.
51
61
  export const setNextUpSources = defineRpc({ name: "config.set-next-up", input: z.object({ mine: z.boolean(), orgs: z.array(z.string()), repos: z.array(z.string()) }), output: done });
@@ -73,7 +83,7 @@ export const closePullRequest = defineRpc({ name: "pr.close", input: z.object({
73
83
  export const claimIssue = defineRpc({ name: "issue.claim", input: z.object({ key: z.string(), target }), output: view });
74
84
  export const unclaimIssue = defineRpc({ name: "issue.unclaim", input: z.object({ key: z.string(), target }), output: view });
75
85
  // Close an issue from Next up; reopen is its Undo [NXT-11].
76
- export const closeIssue = defineRpc({ name: "issue.close", input: z.object({ key: z.string(), target, reason: z.enum(["completed", "not_planned"]), comment: z.string().optional() }), output: view });
86
+ export const closeIssue = defineRpc({ name: "issue.close", input: z.object({ key: z.string(), target, reason: IssueCloseReason, comment: z.string().optional() }), output: view });
77
87
  export const reopenIssue = defineRpc({ name: "issue.reopen", input: z.object({ key: z.string(), target }), output: view });
78
88
  // `ready: false` and `on: false` are the Undo of each.
79
89
  export const setReady = defineRpc({ name: "pr.ready", input: z.object({ key: z.string(), target, ready: z.boolean() }), output: view });
@@ -113,3 +123,6 @@ export const checkUpdate = defineRpc({ name: "update.check", input: z.object({})
113
123
  // Starts `paseo plugin update` for the version on offer; it restarts the plugin when it's done.
114
124
  export const applyUpdate = defineRpc({ name: "update.apply", input: z.object({ latest: z.string() }), output: done });
115
125
  export const skipUpdate = defineRpc({ name: "update.skip", input: z.object({ latest: z.string() }), output: done });
126
+
127
+ // What the New issue sheet starts with next time: the repository and agent profile it just started with [ISS-01].
128
+ export const setNewIssueChoice = defineRpc({ name: "new-issue.choice", input: z.object({ repo: z.string(), profileId: z.string().nullable() }), output: done });
package/shared/setup.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { z } from "zod";
1
2
  import type { FieldRole } from "./config";
2
3
 
3
4
  // What getting started needs, for the setup checklist [SET-01] and the settings screen [SRC-02].
@@ -32,7 +33,8 @@ export function blocks(status: SetupStatus): boolean {
32
33
 
33
34
  // An org or repo checked on GitHub before it's saved: its exact name, or why it can't be added.
34
35
  export type CoverageCheck = { name: string; error: null } | { name: null; error: string };
35
- export type CoverageKind = "org" | "repo";
36
+ export const CoverageKind = z.enum(["org", "repo"]);
37
+ export type CoverageKind = z.infer<typeof CoverageKind>;
36
38
 
37
39
  // A single-select issue field Next up can use, merged by name across the orgs that have it [NXT-04].
38
40
  export interface IssueField {
package/shared/wrap-up.ts CHANGED
@@ -1,6 +1,8 @@
1
- import { type AgentSummary, type AttentionView, isIdle, type Item, keySet, matchSessions, memberKeys, type RememberedGroups, type SessionWorkspace, type WrapItem } from "./attention";
1
+ import { type AgentSummary, type AttentionView, isIdle, type Item, matchSessions, memberKeys, type RememberedGroups, type WrapItem } from "./attention";
2
+ import { type UnsavedSession, unsavedOf } from "./archive";
2
3
  import { ago } from "./format";
3
4
  import { changeText } from "./changes";
5
+ import { keySet } from "./names";
4
6
 
5
7
  // Wrap up: finished or out-of-my-hands work whose unarchived Paseo sessions are all idle [ATT-22]. Pure, so the rules are
6
8
  // testable. It's assembled on the client, which already polls Paseo's sessions for the screen and the sidebar's count; the
@@ -8,27 +10,19 @@ import { changeText } from "./changes";
8
10
 
9
11
  export type SessionCleanliness = "clean" | "dirty" | "unknown";
10
12
 
11
- // What archiving would lose in a session's worktree, from Paseo's snapshot: clean only when it says both that nothing is
12
- // uncommitted and that nothing is ahead. The server asks git again before archiving [ATT-22].
13
- export function sessionCleanliness(agent: AgentSummary): SessionCleanliness {
13
+ // What archiving a session would lose, from Paseo's reading of its worktree; the server asks git again before archiving.
14
+ // Previews count the files [ATT-22].
15
+ export function sessionUnsaved(agent: AgentSummary): UnsavedSession | null {
14
16
  const workspace = agent.workspace;
15
- if (!workspace) return "unknown";
16
- if (workspace.dirty === true || (workspace.ahead ?? 0) > 0) return "dirty";
17
- if (workspace.dirty === false && workspace.ahead === 0) return "clean";
18
- return "unknown";
17
+ return unsavedOf({ agentId: agent.id, title: agent.title }, workspace && { ...workspace, files: workspace.dirtyFiles, lines: workspace.dirtyLines });
19
18
  }
20
19
 
21
- // "uncommitted changes and 1 unpushed commit on branch": what the multi-session sheet says about a session, from Paseo's
22
- // snapshot, which doesn't count files.
23
- export function unsavedText(agent: AgentSummary): string {
24
- const workspace: SessionWorkspace | undefined = agent.workspace;
25
- if (sessionCleanliness(agent) === "unknown") return "Couldn't check for unsaved changes";
26
- const parts: string[] = [];
27
- if (workspace?.dirty) parts.push("uncommitted changes");
28
- const ahead = workspace?.ahead ?? 0;
29
- if (ahead > 0) parts.push(`${ahead} unpushed commit${ahead === 1 ? "" : "s"}`);
30
- const what = parts.join(" and ") || "unsaved changes";
31
- return workspace?.branch ? `${what} on ${workspace.branch}` : what;
20
+ // Dirty as soon as Paseo says something is unsaved, even when it couldn't tell the other half; unknown only when it knows
21
+ // of nothing unsaved but can't say it's clean.
22
+ export function sessionCleanliness(agent: AgentSummary): SessionCleanliness {
23
+ const unsaved = sessionUnsaved(agent);
24
+ if (!unsaved) return "clean";
25
+ return unsaved.files || unsaved.uncommitted || unsaved.commits ? "dirty" : "unknown";
32
26
  }
33
27
 
34
28
  // A row with one session, clean: Archive session archives it at once, whatever happened on GitHub [ATT-22].
@@ -37,7 +31,7 @@ export function cleanSingle(item: WrapItem): boolean {
37
31
  }
38
32
 
39
33
  // What finishing looked like, in the same words the cards use [HIS-05, HIS-07].
40
- function finishText(item: Item, now: Date): string {
34
+ export function finishText(item: Item, now: Date): string {
41
35
  if (item.change) return changeText(item.change, now);
42
36
  const at = item.closedAt ?? item.othersActivityAt;
43
37
  const age = `${ago(at, now)} ago`;
@@ -64,10 +58,12 @@ export function rememberGroups(groups: RememberedGroups, items: Pick<Item, "key"
64
58
 
65
59
  // The finished work and changes that could appear in Wrap up: my done and reviewed items, my own unmerged closes, work that
66
60
  // left my hands, and a change on finished work that History hasn't fetched yet [ATT-22, HIS-01, HIS-07]. A done item beats
67
- // the note about it.
61
+ // the note about it. A merged PR from the live feed only stands in until History lists it, alone or under its issue, so
62
+ // it never makes a row of its own beside its issue's [FRESH-03].
68
63
  function candidates(view: WrapView): Item[] {
64
+ const listed = new Set(view.history.flatMap((item) => [item.key, ...item.children.map((child) => child.key)]).map((key) => key.toLowerCase()));
69
65
  const seen = new Set<string>();
70
- const ordered = [...view.history, ...(view.ownClosed ?? [])].sort((a, b) => Number(a.section === "changed") - Number(b.section === "changed"));
66
+ const ordered = [...view.history, ...(view.ownClosed ?? []).filter((item) => !listed.has(item.key.toLowerCase()))].sort((a, b) => Number(a.section === "changed") - Number(b.section === "changed"));
71
67
  return ordered.filter((item) => {
72
68
  // A reopened PR is open again, not work to wrap up.
73
69
  if (item.section === "changed" && (!item.change || item.change.kind === "reopened")) return false;
@@ -96,7 +92,8 @@ export function wrapItems(view: WrapView, agents: AgentSummary[], now = new Date
96
92
  const sessions = matchSessions(agents, keys);
97
93
  if (sessions.length === 0) continue;
98
94
  // The group's sessions must all be idle, none may serve work that's still active, and a session belongs to one row only.
99
- if (sessions.some((agent) => !isIdle(agent) || serving(agent.itemKey) || used.has(agent.id)) || keys.some(serving)) continue;
95
+ // A sub-agent still working keeps its session's row out too.
96
+ if (sessions.some((agent) => !isIdle(agent) || agent.subAgents?.working || serving(agent.itemKey) || used.has(agent.id)) || keys.some(serving)) continue;
100
97
  for (const agent of sessions) used.add(agent.id);
101
98
  rows.push({
102
99
  item: {