workdash 0.1.0__py3-none-any.whl

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.
workdash/__init__.py ADDED
@@ -0,0 +1,12 @@
1
+ """workdash package."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ try:
6
+ __version__ = version("workdash")
7
+ except PackageNotFoundError:
8
+ __version__ = "0.0.0+unknown"
9
+
10
+ from .workdash import main
11
+
12
+ __all__ = ["main", "__version__"]
workdash/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Module entrypoint for ``python -m workdash``."""
2
+
3
+ from .workdash import main
4
+
5
+ raise SystemExit(main())
@@ -0,0 +1,184 @@
1
+ """Analysis cache access."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import json
7
+ import os
8
+ import re
9
+ import tempfile
10
+ from datetime import UTC, datetime
11
+ from pathlib import Path
12
+ from typing import TypedDict
13
+
14
+ from .models import WorkItem, WorkItemType
15
+
16
+ ANALYSIS_CACHE_SCHEMA_VERSION = 3
17
+ _UNSAFE_FILENAME_CHARS = re.compile(r"[^A-Za-z0-9._-]+")
18
+
19
+
20
+ class AnalysisCacheWorkItemDocument(TypedDict):
21
+ """Serialized work item metadata stored alongside an analysis."""
22
+
23
+ item_type: str
24
+ repo: str
25
+ number: int
26
+ updated_at: str
27
+
28
+
29
+ class AnalysisCacheDocument(TypedDict):
30
+ """Full JSON document persisted for an analysis cache entry."""
31
+
32
+ schema_version: int
33
+ work_item: AnalysisCacheWorkItemDocument
34
+
35
+
36
+ def sanitize_cache_filename_component(component: str) -> str:
37
+ """Map an arbitrary text component to a filesystem-safe cache token."""
38
+
39
+ sanitized = _UNSAFE_FILENAME_CHARS.sub("_", component.strip()).strip("._-")
40
+ return sanitized or "unknown"
41
+
42
+
43
+ def _split_repository(repo: str) -> tuple[str, str]:
44
+ owner, separator, repository = repo.partition("/")
45
+ if separator != "/" or not owner or not repository:
46
+ raise ValueError(f"Work item repo must be in 'owner/repo' format: {repo!r}")
47
+ return owner, repository
48
+
49
+
50
+ class AnalysisCache:
51
+ """Filesystem-backed cache for per-work-item analysis output.
52
+
53
+ Cache entries are keyed by ``(item_type, repo, number, updated_at)`` so
54
+ any change to the GitHub ``updated_at`` timestamp invalidates the entry
55
+ and forces the next analysis to re-run.
56
+ """
57
+
58
+ def __init__(self, root: Path) -> None:
59
+ self.root = root
60
+
61
+ def build_cache_path(self, item: WorkItem) -> Path:
62
+ """Return the cache file path for a work item."""
63
+
64
+ owner, repository = _split_repository(item.repo)
65
+ item_prefix = "ISSUE" if item.item_type == WorkItemType.ISSUE else "PR"
66
+ filename = (
67
+ f"{sanitize_cache_filename_component(owner)}_"
68
+ f"{sanitize_cache_filename_component(repository)}_"
69
+ f"{item_prefix}{item.number}.json"
70
+ )
71
+ return self.root / "analyses" / filename
72
+
73
+ def build_analysis_path(self, item: WorkItem) -> Path:
74
+ """Return the markdown analysis file path for a work item."""
75
+
76
+ return self.build_cache_path(item).with_suffix(".md")
77
+
78
+ def build_cache_document(self, item: WorkItem) -> AnalysisCacheDocument:
79
+ """Build the JSON payload shape for storing a cache entry."""
80
+
81
+ return {
82
+ "schema_version": ANALYSIS_CACHE_SCHEMA_VERSION,
83
+ "work_item": {
84
+ "item_type": item.item_type.value,
85
+ "repo": item.repo,
86
+ "number": item.number,
87
+ "updated_at": item.updated_at.isoformat(),
88
+ },
89
+ }
90
+
91
+ def _load_cached_payload(self, item: WorkItem) -> bool:
92
+ """Return ``True`` when the cache entry is present and matches ``item``."""
93
+
94
+ path = self.build_cache_path(item)
95
+ if not path.exists():
96
+ return False
97
+
98
+ try:
99
+ raw_document = json.loads(path.read_text(encoding="utf-8"))
100
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError):
101
+ return False
102
+
103
+ if not isinstance(raw_document, dict):
104
+ return False
105
+ if raw_document.get("schema_version") != ANALYSIS_CACHE_SCHEMA_VERSION:
106
+ return False
107
+
108
+ work_item = raw_document.get("work_item")
109
+ if not isinstance(work_item, dict):
110
+ return False
111
+ cached_item_type = work_item.get("item_type")
112
+ cached_repo = work_item.get("repo")
113
+ cached_number = work_item.get("number")
114
+ cached_updated_at = work_item.get("updated_at")
115
+ if (
116
+ cached_item_type not in {WorkItemType.ISSUE.value, WorkItemType.PR.value}
117
+ or not isinstance(cached_repo, str)
118
+ or not isinstance(cached_number, int)
119
+ or not isinstance(cached_updated_at, str)
120
+ ):
121
+ return False
122
+ return not (
123
+ cached_item_type != item.item_type.value
124
+ or cached_repo != item.repo
125
+ or cached_number != item.number
126
+ or cached_updated_at != item.updated_at.isoformat()
127
+ )
128
+
129
+ def is_valid(self, item: WorkItem) -> bool:
130
+ """Check whether a valid cache entry exists for a work item."""
131
+
132
+ return self._load_cached_payload(item)
133
+
134
+ def load_analysis_date(self, item: WorkItem) -> datetime | None:
135
+ """Return the modification time of the analysis markdown file, if valid."""
136
+
137
+ if not self._load_cached_payload(item):
138
+ return None
139
+ md_path = self.build_analysis_path(item)
140
+ if not md_path.exists():
141
+ return None
142
+ try:
143
+ mtime = md_path.stat().st_mtime
144
+ except OSError:
145
+ return None
146
+ return datetime.fromtimestamp(mtime, tz=UTC)
147
+
148
+ def load_analysis(self, item: WorkItem) -> str | None:
149
+ if not self._load_cached_payload(item):
150
+ return None
151
+ md_path = self.build_analysis_path(item)
152
+ if not md_path.exists():
153
+ return None
154
+ try:
155
+ content = md_path.read_text(encoding="utf-8")
156
+ except (OSError, UnicodeDecodeError):
157
+ return None
158
+ return content if content.strip() else None
159
+
160
+ def save(self, item: WorkItem, analysis: str | None = None) -> None:
161
+ path = self.build_cache_path(item)
162
+ path.parent.mkdir(parents=True, exist_ok=True)
163
+
164
+ file_descriptor, temporary_path = tempfile.mkstemp(
165
+ prefix=f"{path.name}.",
166
+ suffix=".tmp",
167
+ dir=path.parent,
168
+ )
169
+ try:
170
+ with os.fdopen(file_descriptor, "w", encoding="utf-8") as handle:
171
+ json.dump(
172
+ self.build_cache_document(item),
173
+ handle,
174
+ ensure_ascii=True,
175
+ indent=2,
176
+ )
177
+ os.replace(temporary_path, path)
178
+ except Exception:
179
+ with contextlib.suppress(OSError):
180
+ os.unlink(temporary_path)
181
+ raise
182
+
183
+ if analysis:
184
+ self.build_analysis_path(item).write_text(analysis, encoding="utf-8")
workdash/analyzer.py ADDED
@@ -0,0 +1,229 @@
1
+ """Codex issue and pull request analysis generation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import logging
7
+ import os
8
+ import shlex
9
+ import subprocess
10
+ import tempfile
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ from .models import WorkItem, WorkItemType
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+ _DEFAULT_AGENT_COMMAND_TOKENS = ("codex", "exec")
19
+ _ISSUE_CONTEXT_JSON_FIELDS = (
20
+ "number,title,body,author,assignees,labels,url,state,createdAt,updatedAt,comments"
21
+ )
22
+ _PR_CONTEXT_JSON_FIELDS = (
23
+ "number,title,body,author,assignees,labels,url,state,createdAt,updatedAt,"
24
+ "isDraft,reviewDecision,additions,deletions,changedFiles,headRefName,baseRefName,"
25
+ "comments,reviews,latestReviews"
26
+ )
27
+ _PROMPTS_DIR = Path(__file__).parent / "prompts"
28
+
29
+
30
+ def _load_prompt_template(name: str) -> str:
31
+ return (_PROMPTS_DIR / name).read_text(encoding="utf-8")
32
+
33
+
34
+ class Analyzer:
35
+ """Generate analysis by collecting GitHub context and invoking a coding agent."""
36
+
37
+ def __init__(self, agent_command_tokens: list[str] | None = None) -> None:
38
+ self.agent_command_tokens = (
39
+ agent_command_tokens
40
+ if agent_command_tokens is not None
41
+ else list(_DEFAULT_AGENT_COMMAND_TOKENS)
42
+ )
43
+
44
+ def _run_gh_context_command(
45
+ self,
46
+ *,
47
+ item: WorkItem,
48
+ command: list[str],
49
+ ) -> dict[str, Any]:
50
+ try:
51
+ completed = subprocess.run(
52
+ command,
53
+ check=True,
54
+ capture_output=True,
55
+ text=True,
56
+ )
57
+ except FileNotFoundError as error:
58
+ raise RuntimeError(
59
+ "Failed to gather GitHub context with gh: gh CLI is not installed or not on PATH."
60
+ ) from error
61
+ except subprocess.CalledProcessError as error:
62
+ stderr = (error.stderr or "").strip()
63
+ raise RuntimeError(
64
+ f"Failed to gather gh context for {item.item_type.value} "
65
+ f"{item.repo}#{item.number}: "
66
+ f"{stderr or f'process exited with code {error.returncode}'}"
67
+ ) from error
68
+ try:
69
+ payload = json.loads(completed.stdout)
70
+ except json.JSONDecodeError as error:
71
+ raise RuntimeError(
72
+ f"Failed to parse gh context JSON for {item.item_type.value} "
73
+ f"{item.repo}#{item.number}: {error.msg}"
74
+ ) from error
75
+ if not isinstance(payload, dict):
76
+ raise RuntimeError(
77
+ f"Invalid gh context payload for {item.item_type.value} "
78
+ f"{item.repo}#{item.number}: expected a JSON object."
79
+ )
80
+ return payload
81
+
82
+ def _collect_github_context(self, item: WorkItem) -> dict[str, Any]:
83
+ if item.item_type == WorkItemType.ISSUE:
84
+ command = [
85
+ "gh",
86
+ "issue",
87
+ "view",
88
+ str(item.number),
89
+ "--repo",
90
+ item.repo,
91
+ "--json",
92
+ _ISSUE_CONTEXT_JSON_FIELDS,
93
+ ]
94
+ return self._run_gh_context_command(item=item, command=command)
95
+
96
+ return self._run_gh_context_command(
97
+ item=item,
98
+ command=[
99
+ "gh",
100
+ "pr",
101
+ "view",
102
+ str(item.number),
103
+ "--repo",
104
+ item.repo,
105
+ "--json",
106
+ _PR_CONTEXT_JSON_FIELDS,
107
+ ],
108
+ )
109
+
110
+ def _fetch_pr_diff(self, item: WorkItem) -> str:
111
+ """Fetch the unified diff for a pull request via ``gh pr diff``."""
112
+
113
+ command = ["gh", "pr", "diff", str(item.number), "--repo", item.repo]
114
+ try:
115
+ completed = subprocess.run(
116
+ command,
117
+ check=True,
118
+ capture_output=True,
119
+ text=True,
120
+ )
121
+ except FileNotFoundError as error:
122
+ raise RuntimeError(
123
+ "Failed to gather GitHub diff context with gh: "
124
+ "gh CLI is not installed or not on PATH."
125
+ ) from error
126
+ except subprocess.CalledProcessError as error:
127
+ stderr = (error.stderr or "").strip()
128
+ raise RuntimeError(
129
+ f"Failed to gather gh diff context for {item.item_type.value} "
130
+ f"{item.repo}#{item.number}: "
131
+ f"{stderr or f'process exited with code {error.returncode}'}"
132
+ ) from error
133
+ return completed.stdout
134
+
135
+ def _build_agent_prompt(
136
+ self,
137
+ item: WorkItem,
138
+ github_context: dict[str, Any],
139
+ *,
140
+ diff_path: str | None = None,
141
+ ) -> str:
142
+ template_name = (
143
+ "analyze_issue.txt" if item.item_type == WorkItemType.ISSUE else "analyze_pr.txt"
144
+ )
145
+ template = _load_prompt_template(template_name)
146
+ format_kwargs: dict[str, Any] = {
147
+ "item_type": item.item_type.value,
148
+ "kind": item.kind.value,
149
+ "repo": item.repo,
150
+ "number": item.number,
151
+ "title": item.title,
152
+ "url": item.url,
153
+ "github_context_json": json.dumps(
154
+ github_context, ensure_ascii=True, indent=2, sort_keys=True
155
+ ),
156
+ }
157
+ if item.item_type != WorkItemType.ISSUE:
158
+ format_kwargs["diff_path"] = diff_path or ""
159
+ return template.format(**format_kwargs)
160
+
161
+ def _run_analysis_command(
162
+ self, *, item: WorkItem, prompt: str, command_tokens: list[str]
163
+ ) -> str:
164
+ user_shell = os.environ.get("SHELL", "/bin/sh")
165
+ shell_command = shlex.join([*command_tokens, prompt])
166
+ try:
167
+ completed = subprocess.run(
168
+ [user_shell, "-ic", shell_command],
169
+ check=True,
170
+ capture_output=True,
171
+ text=True,
172
+ stdin=subprocess.DEVNULL,
173
+ start_new_session=True,
174
+ )
175
+ except FileNotFoundError as error:
176
+ raise RuntimeError(
177
+ f"Failed to generate analysis: shell '{user_shell}' not found."
178
+ ) from error
179
+ except subprocess.CalledProcessError as error:
180
+ stderr = (error.stderr or "").strip()
181
+ raise RuntimeError(
182
+ f"Failed to generate analysis for {item.item_type.value} "
183
+ f"{item.repo}#{item.number}: "
184
+ f"{stderr or f'process exited with code {error.returncode}'}"
185
+ ) from error
186
+ return completed.stdout
187
+
188
+ def analyze(self, item: WorkItem, command_tokens: list[str] | None = None) -> str | None:
189
+ """Collect GitHub context, build the prompt, and run analysis.
190
+
191
+ For pull requests, the full unified diff is fetched via ``gh pr diff``
192
+ and written to a temp file whose path is injected into the prompt, so
193
+ the agent can read it without its own ``gh`` access and without
194
+ pushing the argv above the kernel's per-string limit.
195
+
196
+ :param list[str] | None command_tokens: Override the default command
197
+ tokens used to invoke the analysis backend.
198
+ """
199
+
200
+ github_context = self._collect_github_context(item)
201
+ tokens = command_tokens if command_tokens is not None else self.agent_command_tokens
202
+
203
+ diff_file_path: str | None = None
204
+ if item.item_type != WorkItemType.ISSUE:
205
+ diff_text = self._fetch_pr_diff(item)
206
+ with tempfile.NamedTemporaryFile(
207
+ mode="w",
208
+ encoding="utf-8",
209
+ suffix=".diff",
210
+ prefix=f"workdash-{item.repo.replace('/', '-')}-{item.number}-",
211
+ delete=False,
212
+ ) as diff_file:
213
+ diff_file.write(diff_text)
214
+ diff_file_path = diff_file.name
215
+
216
+ try:
217
+ prompt = self._build_agent_prompt(item, github_context, diff_path=diff_file_path)
218
+ output = self._run_analysis_command(item=item, prompt=prompt, command_tokens=tokens)
219
+ finally:
220
+ if diff_file_path is not None:
221
+ try:
222
+ os.unlink(diff_file_path)
223
+ except OSError:
224
+ logger.warning("Failed to remove temporary diff file %s", diff_file_path)
225
+
226
+ content = output.strip()
227
+ if not content:
228
+ return None
229
+ return content
workdash/backend.py ADDED
@@ -0,0 +1,248 @@
1
+ """Backend orchestration for loading and ranking work items."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import shlex
6
+ from collections.abc import Callable
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+
10
+ from .analysis_cache import AnalysisCache
11
+ from .analyzer import Analyzer
12
+ from .config import WorkdashConfig
13
+ from .github_client import (
14
+ GitHubClient,
15
+ TransientFetchError,
16
+ _noop_progress_callback,
17
+ merge_normalized_work_items,
18
+ normalize_assigned_issues,
19
+ normalize_authored_pull_requests,
20
+ normalize_recent_tracked_items,
21
+ normalize_review_requested_pull_requests,
22
+ parse_github_item_url,
23
+ )
24
+ from .included_items import IncludedItemsStore
25
+ from .models import WorkItem, WorkItemType
26
+ from .repo_resolver import resolve_repositories
27
+
28
+ SuggestionMarkers = dict[tuple[WorkItemType, str, int], str]
29
+ ItemIdentity = tuple[WorkItemType, str, int]
30
+
31
+
32
+ @dataclass(frozen=True, slots=True)
33
+ class IncludeResult:
34
+ """Outcome of including a URL into the dashboard.
35
+
36
+ Exactly one of ``invalid``, ``transient_failure``, ``duplicate_identity``,
37
+ or ``fetched_item`` is truthy.
38
+ """
39
+
40
+ invalid: bool = False
41
+ transient_failure: bool = False
42
+ duplicate_identity: ItemIdentity | None = None
43
+ fetched_item: WorkItem | None = None
44
+
45
+
46
+ _SUGGESTION_MARKER = "*"
47
+ _DEFAULT_CACHE_ROOT = Path.home() / ".config" / "workdash" / "cache"
48
+ _DEFAULT_INCLUDED_STORE_PATH = Path.home() / ".config" / "workdash" / "included.json"
49
+
50
+
51
+ def _suggestion_sort_key(item: WorkItem) -> tuple[object, int, str, int]:
52
+ return (
53
+ item.created_at,
54
+ 0 if item.item_type == WorkItemType.PR else 1,
55
+ item.repo,
56
+ item.number,
57
+ )
58
+
59
+
60
+ def compute_suggestion_markers(work_items: list[WorkItem]) -> SuggestionMarkers:
61
+ """Return a single suggestion marker using the v1 ranking heuristic."""
62
+
63
+ if not work_items:
64
+ return {}
65
+ suggested_item = min(work_items, key=_suggestion_sort_key)
66
+ return {
67
+ (suggested_item.item_type, suggested_item.repo, suggested_item.number): _SUGGESTION_MARKER
68
+ }
69
+
70
+
71
+ class WorkdashBackend:
72
+ """Backend service coordinating repository resolution, retrieval, and cache use."""
73
+
74
+ def __init__(
75
+ self,
76
+ *,
77
+ cache_root: Path = _DEFAULT_CACHE_ROOT,
78
+ github_client: GitHubClient | None = None,
79
+ analysis_cache: AnalysisCache | None = None,
80
+ analyzer: Analyzer | None = None,
81
+ config: WorkdashConfig | None = None,
82
+ included_items_store: IncludedItemsStore | None = None,
83
+ ) -> None:
84
+ self.github_client = github_client if github_client is not None else GitHubClient()
85
+ self.analysis_cache = (
86
+ analysis_cache if analysis_cache is not None else AnalysisCache(cache_root)
87
+ )
88
+ self.analyzer = analyzer if analyzer is not None else Analyzer()
89
+ self.config = config if config is not None else WorkdashConfig()
90
+ self.included_items_store = (
91
+ included_items_store
92
+ if included_items_store is not None
93
+ else IncludedItemsStore(_DEFAULT_INCLUDED_STORE_PATH)
94
+ )
95
+
96
+ def load_items(
97
+ self, progress_callback: Callable[[str], None] | None = None
98
+ ) -> tuple[list[WorkItem], SuggestionMarkers]:
99
+ """Load work items from GitHub sources and attach cached analysis state."""
100
+
101
+ report_progress = (
102
+ progress_callback if progress_callback is not None else _noop_progress_callback
103
+ )
104
+ repositories = resolve_repositories(list(self.config.repositories))
105
+ report_progress(f"Resolved {len(repositories)} repository target(s):")
106
+ for repository in repositories:
107
+ report_progress(f" - {repository}")
108
+ github_username = self.config.github_username
109
+ report_progress("Fetching open authored pull requests...")
110
+ authored_pull_requests = self.github_client.list_open_authored_prs(github_username)
111
+ report_progress(f"Fetched {len(authored_pull_requests)} open authored pull request(s).")
112
+ report_progress("Fetching open review-requested pull requests...")
113
+ review_requested_pull_requests = self.github_client.list_open_review_requested_prs(
114
+ github_username,
115
+ progress_callback=report_progress,
116
+ )
117
+ report_progress(
118
+ f"Fetched {len(review_requested_pull_requests)} open review-requested pull request(s)."
119
+ )
120
+ report_progress("Fetching open reviewed pull requests...")
121
+ reviewed_pull_requests = self.github_client.list_open_reviewed_prs(github_username)
122
+ report_progress(f"Fetched {len(reviewed_pull_requests)} open reviewed pull request(s).")
123
+ report_progress("Fetching open assigned issues...")
124
+ assigned_issues = self.github_client.list_open_assigned_issues(github_username)
125
+ report_progress(f"Fetched {len(assigned_issues)} open assigned issue(s).")
126
+ report_progress("Fetching tracked issues and pull requests...")
127
+ recent_tracked_items = self.github_client.list_recent_tracked_items(
128
+ repositories,
129
+ progress_callback=report_progress,
130
+ )
131
+ merged_review_items = merge_normalized_work_items(
132
+ normalize_review_requested_pull_requests(review_requested_pull_requests),
133
+ normalize_review_requested_pull_requests(reviewed_pull_requests),
134
+ )
135
+ merged_items = merge_normalized_work_items(
136
+ normalize_authored_pull_requests(authored_pull_requests),
137
+ merged_review_items,
138
+ )
139
+ merged_items = merge_normalized_work_items(
140
+ merged_items,
141
+ normalize_assigned_issues(assigned_issues),
142
+ )
143
+ merged_items = merge_normalized_work_items(
144
+ merged_items,
145
+ normalize_recent_tracked_items(recent_tracked_items),
146
+ )
147
+ included_work_items = self._load_included_items(report_progress)
148
+ if included_work_items:
149
+ merged_items = merge_normalized_work_items(merged_items, included_work_items)
150
+ report_progress(
151
+ f"Merged {len(merged_items)} unique work item(s); loading cached analyses..."
152
+ )
153
+ for item in merged_items:
154
+ item.analysis = self.analysis_cache.load_analysis(item)
155
+ item.analyzed_at = self.analysis_cache.load_analysis_date(item)
156
+ report_progress("Done loading work items.")
157
+ return merged_items, compute_suggestion_markers(merged_items)
158
+
159
+ def _load_included_items(self, report_progress: Callable[[str], None]) -> list[WorkItem]:
160
+ """Fetch each persisted included URL, pruning gone or invalid entries.
161
+
162
+ Transient failures keep the URL in the store so the next refresh
163
+ can retry. Only permanent drops (state != OPEN, 404-style errors)
164
+ remove the URL.
165
+ """
166
+
167
+ stored_urls = self.included_items_store.load()
168
+ if not stored_urls:
169
+ return []
170
+ report_progress(f"Fetching {len(stored_urls)} included item(s)...")
171
+ survivors: list[str] = []
172
+ fetched: list[WorkItem] = []
173
+ for url in stored_urls:
174
+ parsed = parse_github_item_url(url)
175
+ if parsed is None:
176
+ continue
177
+ try:
178
+ item = self.github_client.fetch_item_by_url(parsed)
179
+ except TransientFetchError:
180
+ survivors.append(parsed.canonical_url)
181
+ continue
182
+ if item is None:
183
+ continue
184
+ survivors.append(parsed.canonical_url)
185
+ fetched.append(item)
186
+ if survivors != stored_urls:
187
+ self.included_items_store.save(survivors)
188
+ return fetched
189
+
190
+ def include_item_by_url(
191
+ self, url: str, existing_identities: set[ItemIdentity]
192
+ ) -> IncludeResult:
193
+ """Resolve a pasted URL to an ``IncludeResult`` for the TUI.
194
+
195
+ The backend owns URL parsing, duplicate detection, fetching, and
196
+ persistence so the TUI only has to consume the result. ``url`` is
197
+ parsed; a known identity short-circuits with ``duplicate_identity``
198
+ after idempotently persisting the canonical URL; an unknown
199
+ identity is fetched and persisted on success. Transient fetch
200
+ failures surface via ``transient_failure`` and do NOT persist so
201
+ the URL is not retained for a URL that may never resolve.
202
+ """
203
+
204
+ parsed = parse_github_item_url(url)
205
+ if parsed is None:
206
+ return IncludeResult(invalid=True)
207
+ identity: ItemIdentity = (parsed.item_type, parsed.repo, parsed.number)
208
+ if identity in existing_identities:
209
+ # Persist canonical URL idempotently so a URL pasted in a
210
+ # non-canonical form (e.g. ``/pull/7/files``) is still saved
211
+ # under its canonical shape for future sessions.
212
+ self.included_items_store.add(parsed.canonical_url)
213
+ return IncludeResult(duplicate_identity=identity)
214
+ try:
215
+ item = self.github_client.fetch_item_by_url(parsed)
216
+ except TransientFetchError:
217
+ return IncludeResult(transient_failure=True)
218
+ if item is None:
219
+ return IncludeResult(invalid=True)
220
+ self.included_items_store.add(parsed.canonical_url)
221
+ return IncludeResult(fetched_item=item)
222
+
223
+ def _resolve_command_tokens(self, tool: str) -> list[str]:
224
+ if tool == "claude":
225
+ return shlex.split(self.config.claude.analyze)
226
+ return shlex.split(self.config.codex.analyze)
227
+
228
+ def analyze_item(self, item: WorkItem, tool: str = "codex") -> str | None:
229
+ """Generate or retrieve analysis, returning the markdown file path.
230
+
231
+ :param str tool: ``"cached"`` to return existing analysis,
232
+ ``"claude"`` or ``"codex"`` to force a fresh run with that backend.
233
+ """
234
+
235
+ if tool == "cached":
236
+ cached_analysis = self.analysis_cache.load_analysis(item)
237
+ if cached_analysis is not None:
238
+ item.analysis = cached_analysis
239
+ return str(self.analysis_cache.build_analysis_path(item))
240
+ return None
241
+ command_tokens = self._resolve_command_tokens(tool)
242
+ analysis_content = self.analyzer.analyze(item, command_tokens=command_tokens)
243
+ if analysis_content is None:
244
+ return None
245
+ self.analysis_cache.save(item, analysis_content)
246
+ item.analysis = analysis_content
247
+ item.analyzed_at = self.analysis_cache.load_analysis_date(item)
248
+ return str(self.analysis_cache.build_analysis_path(item))