feed-the-machine 1.1.0 → 1.3.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 (92) hide show
  1. package/bin/generate-manifest.mjs +253 -0
  2. package/bin/install.mjs +372 -26
  3. package/docs/INBOX.md +233 -0
  4. package/ftm/SKILL.md +34 -0
  5. package/ftm-audit/SKILL.md +69 -0
  6. package/ftm-brainstorm/SKILL.md +51 -0
  7. package/ftm-browse/SKILL.md +39 -0
  8. package/ftm-capture/SKILL.md +370 -0
  9. package/ftm-capture.yml +4 -0
  10. package/ftm-codex-gate/SKILL.md +59 -0
  11. package/ftm-config/SKILL.md +35 -0
  12. package/ftm-council/SKILL.md +56 -0
  13. package/ftm-dashboard/SKILL.md +34 -0
  14. package/ftm-debug/SKILL.md +84 -0
  15. package/ftm-diagram/SKILL.md +44 -0
  16. package/ftm-executor/SKILL.md +97 -0
  17. package/ftm-git/SKILL.md +60 -0
  18. package/ftm-inbox/backend/__init__.py +0 -0
  19. package/ftm-inbox/backend/adapters/__init__.py +0 -0
  20. package/ftm-inbox/backend/adapters/_retry.py +64 -0
  21. package/ftm-inbox/backend/adapters/base.py +230 -0
  22. package/ftm-inbox/backend/adapters/freshservice.py +104 -0
  23. package/ftm-inbox/backend/adapters/gmail.py +125 -0
  24. package/ftm-inbox/backend/adapters/jira.py +136 -0
  25. package/ftm-inbox/backend/adapters/registry.py +192 -0
  26. package/ftm-inbox/backend/adapters/slack.py +110 -0
  27. package/ftm-inbox/backend/db/__init__.py +0 -0
  28. package/ftm-inbox/backend/db/connection.py +54 -0
  29. package/ftm-inbox/backend/db/schema.py +78 -0
  30. package/ftm-inbox/backend/executor/__init__.py +7 -0
  31. package/ftm-inbox/backend/executor/engine.py +149 -0
  32. package/ftm-inbox/backend/executor/step_runner.py +98 -0
  33. package/ftm-inbox/backend/main.py +103 -0
  34. package/ftm-inbox/backend/models/__init__.py +1 -0
  35. package/ftm-inbox/backend/models/unified_task.py +36 -0
  36. package/ftm-inbox/backend/planner/__init__.py +6 -0
  37. package/ftm-inbox/backend/planner/generator.py +127 -0
  38. package/ftm-inbox/backend/planner/schema.py +34 -0
  39. package/ftm-inbox/backend/requirements.txt +5 -0
  40. package/ftm-inbox/backend/routes/__init__.py +0 -0
  41. package/ftm-inbox/backend/routes/execute.py +186 -0
  42. package/ftm-inbox/backend/routes/health.py +52 -0
  43. package/ftm-inbox/backend/routes/inbox.py +68 -0
  44. package/ftm-inbox/backend/routes/plan.py +271 -0
  45. package/ftm-inbox/bin/launchagent.mjs +91 -0
  46. package/ftm-inbox/bin/setup.mjs +188 -0
  47. package/ftm-inbox/bin/start.sh +10 -0
  48. package/ftm-inbox/bin/status.sh +17 -0
  49. package/ftm-inbox/bin/stop.sh +8 -0
  50. package/ftm-inbox/config.example.yml +55 -0
  51. package/ftm-inbox/package-lock.json +2898 -0
  52. package/ftm-inbox/package.json +26 -0
  53. package/ftm-inbox/postcss.config.js +6 -0
  54. package/ftm-inbox/src/app.css +199 -0
  55. package/ftm-inbox/src/app.html +18 -0
  56. package/ftm-inbox/src/lib/api.ts +166 -0
  57. package/ftm-inbox/src/lib/components/ExecutionLog.svelte +81 -0
  58. package/ftm-inbox/src/lib/components/InboxFeed.svelte +143 -0
  59. package/ftm-inbox/src/lib/components/PlanStep.svelte +271 -0
  60. package/ftm-inbox/src/lib/components/PlanView.svelte +206 -0
  61. package/ftm-inbox/src/lib/components/StreamPanel.svelte +99 -0
  62. package/ftm-inbox/src/lib/components/TaskCard.svelte +190 -0
  63. package/ftm-inbox/src/lib/components/ui/EmptyState.svelte +63 -0
  64. package/ftm-inbox/src/lib/components/ui/KawaiiCard.svelte +86 -0
  65. package/ftm-inbox/src/lib/components/ui/PillButton.svelte +106 -0
  66. package/ftm-inbox/src/lib/components/ui/StatusBadge.svelte +67 -0
  67. package/ftm-inbox/src/lib/components/ui/StreamDrawer.svelte +149 -0
  68. package/ftm-inbox/src/lib/components/ui/ThemeToggle.svelte +80 -0
  69. package/ftm-inbox/src/lib/theme.ts +47 -0
  70. package/ftm-inbox/src/routes/+layout.svelte +76 -0
  71. package/ftm-inbox/src/routes/+page.svelte +401 -0
  72. package/ftm-inbox/static/favicon.png +0 -0
  73. package/ftm-inbox/svelte.config.js +12 -0
  74. package/ftm-inbox/tailwind.config.ts +63 -0
  75. package/ftm-inbox/tsconfig.json +13 -0
  76. package/ftm-inbox/vite.config.ts +6 -0
  77. package/ftm-intent/SKILL.md +44 -0
  78. package/ftm-manifest.json +3794 -0
  79. package/ftm-map/SKILL.md +50 -0
  80. package/ftm-mind/SKILL.md +173 -66
  81. package/ftm-pause/SKILL.md +43 -0
  82. package/ftm-researcher/SKILL.md +55 -0
  83. package/ftm-resume/SKILL.md +47 -0
  84. package/ftm-retro/SKILL.md +54 -0
  85. package/ftm-routine/SKILL.md +36 -0
  86. package/ftm-state/blackboard/capabilities.json +5 -0
  87. package/ftm-state/blackboard/capabilities.schema.json +27 -0
  88. package/ftm-upgrade/SKILL.md +41 -0
  89. package/hooks/ftm-blackboard-enforcer.sh +28 -27
  90. package/hooks/ftm-plan-gate.sh +21 -25
  91. package/install.sh +238 -111
  92. package/package.json +6 -2
@@ -0,0 +1,230 @@
1
+ """
2
+ BaseAdapter — abstract interface all poller adapters must implement.
3
+
4
+ Every adapter handles one external system (Jira, Freshservice, Slack, etc.)
5
+ and is responsible for fetching, normalizing, deduplicating, and storing
6
+ items into the ftm-inbox database.
7
+
8
+ Deduplication uses a SHA-256 hash of (source + source_id) so the same
9
+ external item is never stored twice regardless of content changes.
10
+ To track updates, adapters should update the existing row rather than
11
+ insert a duplicate.
12
+ """
13
+
14
+ import hashlib
15
+ import json
16
+ from abc import ABC, abstractmethod
17
+ from datetime import datetime, timezone
18
+ from typing import Any
19
+
20
+
21
+ class NormalizedItem:
22
+ """Canonical representation of an inbox item before storage."""
23
+
24
+ __slots__ = (
25
+ "source",
26
+ "source_id",
27
+ "title",
28
+ "body",
29
+ "status",
30
+ "priority",
31
+ "assignee",
32
+ "requester",
33
+ "created_at",
34
+ "updated_at",
35
+ "tags",
36
+ "custom_fields",
37
+ "raw_payload",
38
+ "source_url",
39
+ "content_hash",
40
+ )
41
+
42
+ def __init__(
43
+ self,
44
+ source: str,
45
+ source_id: str,
46
+ title: str,
47
+ body: str = "",
48
+ status: str = "open",
49
+ priority: str = "medium",
50
+ assignee: str | None = None,
51
+ requester: str | None = None,
52
+ created_at: str | None = None,
53
+ updated_at: str | None = None,
54
+ tags: list[str] | None = None,
55
+ custom_fields: dict[str, Any] | None = None,
56
+ raw_payload: dict[str, Any] | None = None,
57
+ source_url: str | None = None,
58
+ ) -> None:
59
+ self.source = source
60
+ self.source_id = source_id
61
+ self.title = title
62
+ self.body = body
63
+ self.status = status
64
+ self.priority = priority
65
+ self.assignee = assignee
66
+ self.requester = requester
67
+ self.created_at = created_at
68
+ self.updated_at = updated_at
69
+ self.tags = tags or []
70
+ self.custom_fields = custom_fields or {}
71
+ self.raw_payload = raw_payload or {}
72
+ self.source_url = source_url
73
+ self.content_hash = _compute_hash(source, source_id)
74
+
75
+ def to_dict(self) -> dict[str, Any]:
76
+ return {
77
+ "source": self.source,
78
+ "source_id": self.source_id,
79
+ "title": self.title,
80
+ "body": self.body,
81
+ "status": self.status,
82
+ "priority": self.priority,
83
+ "assignee": self.assignee,
84
+ "requester": self.requester,
85
+ "created_at": self.created_at,
86
+ "updated_at": self.updated_at,
87
+ "tags": json.dumps(self.tags),
88
+ "custom_fields": json.dumps(self.custom_fields),
89
+ "raw_payload": json.dumps(self.raw_payload),
90
+ "source_url": self.source_url,
91
+ "content_hash": self.content_hash,
92
+ }
93
+
94
+
95
+ def _compute_hash(source: str, source_id: str) -> str:
96
+ """SHA-256 of 'source:source_id' — stable dedup key."""
97
+ raw = f"{source}:{source_id}".encode("utf-8")
98
+ return hashlib.sha256(raw).hexdigest()
99
+
100
+
101
+ class BaseAdapter(ABC):
102
+ """
103
+ Abstract base class for all ftm-inbox poller adapters.
104
+
105
+ Subclasses must implement poll(), normalize(), and optionally override
106
+ deduplicate() and store() if the defaults don't suit the source.
107
+
108
+ Lifecycle per poll cycle:
109
+ raw_items = self.poll()
110
+ normalized = [self.normalize(item) for item in raw_items]
111
+ new_items = self.deduplicate(normalized, conn)
112
+ self.store(new_items, conn)
113
+ """
114
+
115
+ #: Unique identifier for this adapter, e.g. "jira", "freshservice"
116
+ source_name: str = ""
117
+
118
+ def __init__(self, credentials: dict[str, Any], config: dict[str, Any]) -> None:
119
+ """
120
+ Args:
121
+ credentials: Secrets from config.yml (API keys, tokens, etc.)
122
+ config: Non-secret settings (base_url, project_key, etc.)
123
+ """
124
+ self.credentials = credentials
125
+ self.config = config
126
+
127
+ @abstractmethod
128
+ def poll(self) -> list[dict[str, Any]]:
129
+ """
130
+ Fetch raw items from the external system.
131
+
132
+ Returns:
133
+ List of raw dicts as returned by the source API.
134
+ """
135
+ ...
136
+
137
+ @abstractmethod
138
+ def normalize(self, raw_item: dict[str, Any]) -> NormalizedItem:
139
+ """
140
+ Convert a raw API item into a NormalizedItem.
141
+
142
+ Args:
143
+ raw_item: One element from the list returned by poll().
144
+
145
+ Returns:
146
+ NormalizedItem ready for deduplication and storage.
147
+ """
148
+ ...
149
+
150
+ def deduplicate(
151
+ self, items: list[NormalizedItem], conn
152
+ ) -> list[NormalizedItem]:
153
+ """
154
+ Filter out items already present in the database by content_hash.
155
+
156
+ Uses the UNIQUE constraint on inbox.content_hash. Returns only
157
+ items that do not yet exist.
158
+
159
+ Args:
160
+ items: Normalized items from this poll cycle.
161
+ conn: Active sqlite3 connection.
162
+
163
+ Returns:
164
+ Subset of items not yet in the database.
165
+ """
166
+ if not items:
167
+ return []
168
+
169
+ hashes = [item.content_hash for item in items]
170
+ placeholders = ",".join("?" * len(hashes))
171
+ rows = conn.execute(
172
+ f"SELECT content_hash FROM inbox WHERE content_hash IN ({placeholders})",
173
+ hashes,
174
+ ).fetchall()
175
+ existing = {row["content_hash"] for row in rows}
176
+ return [item for item in items if item.content_hash not in existing]
177
+
178
+ def store(self, items: list[NormalizedItem], conn) -> int:
179
+ """
180
+ Insert new items into the inbox table.
181
+
182
+ Skips items that already exist (content_hash collision) rather than
183
+ raising — adapters that want upsert behavior should override this.
184
+
185
+ Args:
186
+ items: Deduplicated NormalizedItems to insert.
187
+ conn: Active sqlite3 connection.
188
+
189
+ Returns:
190
+ Number of rows actually inserted.
191
+ """
192
+ if not items:
193
+ return 0
194
+
195
+ inserted = 0
196
+ for item in items:
197
+ data = item.to_dict()
198
+ try:
199
+ conn.execute(
200
+ """
201
+ INSERT INTO inbox
202
+ (source, source_id, title, body, status, priority,
203
+ assignee, requester, created_at, updated_at,
204
+ tags, custom_fields, raw_payload, source_url, content_hash)
205
+ VALUES
206
+ (:source, :source_id, :title, :body, :status, :priority,
207
+ :assignee, :requester, :created_at, :updated_at,
208
+ :tags, :custom_fields, :raw_payload, :source_url, :content_hash)
209
+ """,
210
+ data,
211
+ )
212
+ inserted += 1
213
+ except Exception:
214
+ # Swallow duplicate key errors; log others in production
215
+ pass
216
+
217
+ conn.commit()
218
+ return inserted
219
+
220
+ def run_cycle(self, conn) -> int:
221
+ """
222
+ Execute a full poll-normalize-deduplicate-store cycle.
223
+
224
+ Returns:
225
+ Number of new items stored.
226
+ """
227
+ raw_items = self.poll()
228
+ normalized = [self.normalize(item) for item in raw_items]
229
+ new_items = self.deduplicate(normalized, conn)
230
+ return self.store(new_items, conn)
@@ -0,0 +1,104 @@
1
+ """
2
+ FreshserviceAdapter — polls Freshservice tickets via the REST API v2.
3
+
4
+ Required credentials:
5
+ api_key Freshservice API key (Settings > API in Freshservice admin)
6
+
7
+ Config keys:
8
+ domain e.g. "yourorg.freshservice.com"
9
+ per_page Number of tickets per page, default 100
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import logging
15
+ from typing import Any
16
+
17
+ import requests
18
+ from requests.auth import HTTPBasicAuth
19
+
20
+ from backend.adapters._retry import retry
21
+ from backend.adapters.base import BaseAdapter, NormalizedItem
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+ _STATUS_MAP = {2: "open", 3: "pending", 4: "resolved", 5: "closed"}
26
+ _PRIORITY_MAP = {1: "low", 2: "medium", 3: "high", 4: "urgent"}
27
+
28
+
29
+ class FreshserviceAdapter(BaseAdapter):
30
+ """Polls Freshservice tickets via REST API v2."""
31
+
32
+ source_name = "freshservice"
33
+ required_credentials = ["api_key"]
34
+
35
+ def __init__(self, credentials: dict, config: dict) -> None:
36
+ super().__init__(credentials, config)
37
+ self._domain = config.get("domain", "")
38
+ if not self._domain:
39
+ raise ValueError("FreshserviceAdapter requires config['domain']")
40
+ self._auth = HTTPBasicAuth(credentials["api_key"], "X")
41
+ self._per_page = int(config.get("per_page", 100))
42
+
43
+ @retry(max_attempts=3, base_delay=1.0, exceptions=(requests.RequestException,))
44
+ def poll(self) -> list[dict]:
45
+ """Fetch tickets from Freshservice with pagination."""
46
+ url = f"https://{self._domain}/api/v2/tickets"
47
+ params: dict[str, Any] = {
48
+ "per_page": self._per_page,
49
+ "order_by": "updated_at",
50
+ "order_type": "desc",
51
+ }
52
+ response = requests.get(url, auth=self._auth, params=params, timeout=30)
53
+ response.raise_for_status()
54
+ data = response.json()
55
+ return data.get("tickets", [])
56
+
57
+ def normalize(self, raw_item: dict) -> NormalizedItem:
58
+ """Map a Freshservice ticket dict to NormalizedItem."""
59
+ ticket_id = str(raw_item.get("id", ""))
60
+
61
+ title = raw_item.get("subject") or "(no subject)"
62
+ body = raw_item.get("description_text") or raw_item.get("description") or ""
63
+
64
+ status_int = raw_item.get("status", 2)
65
+ status = _STATUS_MAP.get(status_int, "open")
66
+
67
+ priority_int = raw_item.get("priority", 2)
68
+ priority = _PRIORITY_MAP.get(priority_int, "medium")
69
+
70
+ requester_id = raw_item.get("requester_id")
71
+ requester = str(requester_id) if requester_id else None
72
+
73
+ responder_id = raw_item.get("responder_id")
74
+ assignee = str(responder_id) if responder_id else None
75
+
76
+ created_at = raw_item.get("created_at")
77
+ updated_at = raw_item.get("updated_at")
78
+
79
+ tags: list[str] = raw_item.get("tags") or []
80
+
81
+ custom_fields: dict[str, Any] = {}
82
+ raw_cf = raw_item.get("custom_fields") or {}
83
+ for key, value in raw_cf.items():
84
+ if value is not None:
85
+ custom_fields[key] = value
86
+
87
+ source_url = f"https://{self._domain}/a/tickets/{ticket_id}"
88
+
89
+ return NormalizedItem(
90
+ source=self.source_name,
91
+ source_id=ticket_id,
92
+ title=title,
93
+ body=body,
94
+ status=status,
95
+ priority=priority,
96
+ assignee=assignee,
97
+ requester=requester,
98
+ created_at=created_at,
99
+ updated_at=updated_at,
100
+ tags=tags,
101
+ custom_fields=custom_fields,
102
+ raw_payload=raw_item,
103
+ source_url=source_url,
104
+ )
@@ -0,0 +1,125 @@
1
+ """
2
+ GmailAdapter — polls Gmail for recent emails matching a label filter.
3
+
4
+ Required credentials:
5
+ credentials_json_path Path to Google OAuth credentials JSON
6
+ token_path Path to stored OAuth token
7
+
8
+ Config keys:
9
+ label_filter Gmail label to filter by, default "INBOX"
10
+ max_results Max emails per poll cycle, default 50
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import logging
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ import requests
21
+
22
+ from backend.adapters._retry import retry
23
+ from backend.adapters.base import BaseAdapter, NormalizedItem
24
+
25
+ logger = logging.getLogger(__name__)
26
+
27
+
28
+ class GmailAdapter(BaseAdapter):
29
+ """Polls Gmail for recent emails using the Gmail REST API."""
30
+
31
+ source_name = "gmail"
32
+ required_credentials = ["credentials_json_path"]
33
+
34
+ def __init__(self, credentials: dict, config: dict) -> None:
35
+ super().__init__(credentials, config)
36
+ self._credentials_path = Path(
37
+ credentials.get("credentials_json_path", "")
38
+ ).expanduser()
39
+ self._token_path = Path(
40
+ credentials.get("token_path", "~/.config/ftm-inbox/gmail-token.json")
41
+ ).expanduser()
42
+ self._label_filter = config.get("label_filter", "INBOX")
43
+ self._max_results = int(config.get("max_results", 50))
44
+ self._access_token: str | None = None
45
+
46
+ def _get_access_token(self) -> str:
47
+ """Load OAuth access token from token file."""
48
+ if self._access_token:
49
+ return self._access_token
50
+
51
+ if not self._token_path.exists():
52
+ raise RuntimeError(
53
+ f"Gmail token file not found at {self._token_path}. "
54
+ "Run the setup wizard first."
55
+ )
56
+
57
+ token_data = json.loads(self._token_path.read_text())
58
+ self._access_token = token_data.get("access_token", "")
59
+ if not self._access_token:
60
+ raise RuntimeError("Gmail token file has no access_token field.")
61
+ return self._access_token
62
+
63
+ @retry(max_attempts=3, base_delay=1.0, exceptions=(requests.RequestException,))
64
+ def poll(self) -> list[dict]:
65
+ """Fetch recent emails from Gmail matching the label filter."""
66
+ token = self._get_access_token()
67
+ headers = {"Authorization": f"Bearer {token}"}
68
+
69
+ url = "https://gmail.googleapis.com/gmail/v1/users/me/messages"
70
+ params: dict[str, Any] = {
71
+ "maxResults": self._max_results,
72
+ "labelIds": self._label_filter,
73
+ }
74
+ response = requests.get(url, headers=headers, params=params, timeout=30)
75
+ response.raise_for_status()
76
+ data = response.json()
77
+ message_ids = [m["id"] for m in data.get("messages", [])]
78
+
79
+ messages: list[dict] = []
80
+ for msg_id in message_ids:
81
+ msg_url = f"{url}/{msg_id}"
82
+ msg_params = {"format": "metadata", "metadataHeaders": "Subject,From,Date"}
83
+ msg_response = requests.get(
84
+ msg_url, headers=headers, params=msg_params, timeout=30
85
+ )
86
+ if msg_response.ok:
87
+ messages.append(msg_response.json())
88
+
89
+ return messages
90
+
91
+ def normalize(self, raw_item: dict) -> NormalizedItem:
92
+ """Map a Gmail message dict to NormalizedItem."""
93
+ msg_id = raw_item.get("id", "")
94
+ headers = raw_item.get("payload", {}).get("headers", [])
95
+
96
+ header_map: dict[str, str] = {}
97
+ for h in headers:
98
+ header_map[h.get("name", "").lower()] = h.get("value", "")
99
+
100
+ title = header_map.get("subject") or "(no subject)"
101
+ requester = header_map.get("from")
102
+ created_at = header_map.get("date")
103
+
104
+ snippet = raw_item.get("snippet", "")
105
+
106
+ source_url = f"https://mail.google.com/mail/u/0/#inbox/{msg_id}"
107
+
108
+ label_ids: list[str] = raw_item.get("labelIds", [])
109
+
110
+ return NormalizedItem(
111
+ source=self.source_name,
112
+ source_id=msg_id,
113
+ title=title,
114
+ body=snippet,
115
+ status="open",
116
+ priority="medium",
117
+ assignee=None,
118
+ requester=requester,
119
+ created_at=created_at,
120
+ updated_at=None,
121
+ tags=label_ids,
122
+ custom_fields={},
123
+ raw_payload=raw_item,
124
+ source_url=source_url,
125
+ )
@@ -0,0 +1,136 @@
1
+ """
2
+ JiraAdapter — polls a Jira project via the REST API v3 and normalizes issues.
3
+
4
+ Required credentials:
5
+ api_token Jira API token (generated at id.atlassian.net)
6
+ email Atlassian account email associated with the token
7
+
8
+ Config keys:
9
+ base_url e.g. "https://myorg.atlassian.net"
10
+ jql JQL filter string, default "assignee = currentUser() ORDER BY updated DESC"
11
+ max_results Number of issues to fetch per poll cycle, default 50
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import logging
17
+ from typing import Any
18
+
19
+ import requests
20
+ from requests.auth import HTTPBasicAuth
21
+
22
+ from backend.adapters._retry import retry
23
+ from backend.adapters.base import BaseAdapter, NormalizedItem
24
+
25
+ logger = logging.getLogger(__name__)
26
+
27
+ _DEFAULT_JQL = "assignee = currentUser() ORDER BY updated DESC"
28
+ _DEFAULT_MAX_RESULTS = 50
29
+
30
+
31
+ class JiraAdapter(BaseAdapter):
32
+ """Polls Jira issues using the REST API v3."""
33
+
34
+ source_name = "jira"
35
+ required_credentials = ["api_token", "email"]
36
+
37
+ def __init__(self, credentials: dict, config: dict) -> None:
38
+ super().__init__(credentials, config)
39
+ self._base_url = config.get("base_url", "").rstrip("/")
40
+ if not self._base_url:
41
+ raise ValueError("JiraAdapter requires config['base_url']")
42
+ self._auth = HTTPBasicAuth(
43
+ credentials["email"], credentials["api_token"]
44
+ )
45
+ self._jql = config.get("jql", _DEFAULT_JQL)
46
+ self._max_results = int(config.get("max_results", _DEFAULT_MAX_RESULTS))
47
+
48
+ @retry(max_attempts=3, base_delay=1.0, exceptions=(requests.RequestException,))
49
+ def poll(self) -> list[dict]:
50
+ """Fetch Jira issues matching the configured JQL query."""
51
+ url = f"{self._base_url}/rest/api/3/search"
52
+ params: dict[str, Any] = {
53
+ "jql": self._jql,
54
+ "maxResults": self._max_results,
55
+ "fields": (
56
+ "summary,description,status,priority,"
57
+ "assignee,reporter,created,updated,labels,issuetype"
58
+ ),
59
+ }
60
+ response = requests.get(url, auth=self._auth, params=params, timeout=30)
61
+ response.raise_for_status()
62
+ data = response.json()
63
+ return data.get("issues", [])
64
+
65
+ def normalize(self, raw_item: dict) -> NormalizedItem:
66
+ """Map a Jira issue dict to NormalizedItem."""
67
+ fields = raw_item.get("fields") or {}
68
+ key = raw_item.get("key", "")
69
+ issue_id = raw_item.get("id", key)
70
+
71
+ title = fields.get("summary") or key or "(no summary)"
72
+ body = _extract_jira_text(fields.get("description"))
73
+
74
+ status_obj = fields.get("status") or {}
75
+ status = (status_obj.get("name") or "open").lower()
76
+
77
+ priority_obj = fields.get("priority") or {}
78
+ priority = (priority_obj.get("name") or "medium").lower()
79
+
80
+ assignee_obj = fields.get("assignee") or {}
81
+ assignee = assignee_obj.get("displayName") or assignee_obj.get("emailAddress")
82
+
83
+ reporter_obj = fields.get("reporter") or {}
84
+ requester = reporter_obj.get("displayName") or reporter_obj.get("emailAddress")
85
+
86
+ created_at = fields.get("created")
87
+ updated_at = fields.get("updated")
88
+
89
+ tags: list[str] = fields.get("labels") or []
90
+
91
+ issuetype_obj = fields.get("issuetype") or {}
92
+ custom_fields: dict[str, Any] = {}
93
+ if issuetype_obj.get("name"):
94
+ custom_fields["issue_type"] = issuetype_obj["name"]
95
+
96
+ source_url = f"{self._base_url}/browse/{key}" if key else None
97
+
98
+ return NormalizedItem(
99
+ source=self.source_name,
100
+ source_id=str(issue_id),
101
+ title=title,
102
+ body=body,
103
+ status=status,
104
+ priority=priority,
105
+ assignee=assignee,
106
+ requester=requester,
107
+ created_at=created_at,
108
+ updated_at=updated_at,
109
+ tags=tags,
110
+ custom_fields=custom_fields,
111
+ raw_payload=raw_item,
112
+ source_url=source_url,
113
+ )
114
+
115
+
116
+ def _extract_jira_text(adf: Any) -> str:
117
+ """Recursively pull plain text from an Atlassian Document Format node."""
118
+ if adf is None:
119
+ return ""
120
+ if isinstance(adf, str):
121
+ return adf
122
+ if not isinstance(adf, dict):
123
+ return ""
124
+
125
+ node_type = adf.get("type", "")
126
+ if node_type == "text":
127
+ return adf.get("text", "")
128
+
129
+ parts: list[str] = []
130
+ for child in adf.get("content") or []:
131
+ part = _extract_jira_text(child)
132
+ if part:
133
+ parts.append(part)
134
+
135
+ separator = "\n" if node_type in ("paragraph", "heading", "bulletList", "orderedList") else " "
136
+ return separator.join(parts).strip()