continuum-task-server-bundle 1.0.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.
Files changed (90) hide show
  1. continuum_task_server_bundle/__init__.py +1 -0
  2. continuum_task_server_bundle/daytona/__init__.py +4 -0
  3. continuum_task_server_bundle/daytona/common.py +534 -0
  4. continuum_task_server_bundle/daytona/create_sandbox.py +166 -0
  5. continuum_task_server_bundle/daytona/dispatch.py +125 -0
  6. continuum_task_server_bundle/daytona/execute_sandbox.py +243 -0
  7. continuum_task_server_bundle/daytona/filesystem.py +330 -0
  8. continuum_task_server_bundle/daytona/fs_edit.py +127 -0
  9. continuum_task_server_bundle/daytona/git_ops.py +585 -0
  10. continuum_task_server_bundle/daytona/github_app.py +207 -0
  11. continuum_task_server_bundle/daytona/manage_sandbox.py +104 -0
  12. continuum_task_server_bundle/daytona/plugin.py +18 -0
  13. continuum_task_server_bundle/daytona/s3_transfer.py +207 -0
  14. continuum_task_server_bundle/discord/__init__.py +4 -0
  15. continuum_task_server_bundle/discord/attachment_registry_db.py +127 -0
  16. continuum_task_server_bundle/discord/attachment_resolve.py +213 -0
  17. continuum_task_server_bundle/discord/await_cleanup.py +105 -0
  18. continuum_task_server_bundle/discord/discord_ready.py +39 -0
  19. continuum_task_server_bundle/discord/message_await_apply.py +143 -0
  20. continuum_task_server_bundle/discord/message_await_db.py +197 -0
  21. continuum_task_server_bundle/discord/message_await_inbound.py +54 -0
  22. continuum_task_server_bundle/discord/message_await_logic.py +133 -0
  23. continuum_task_server_bundle/discord/message_await_poller.py +122 -0
  24. continuum_task_server_bundle/discord/message_chunking.py +45 -0
  25. continuum_task_server_bundle/discord/methods.py +408 -0
  26. continuum_task_server_bundle/discord/plugin.py +105 -0
  27. continuum_task_server_bundle/discord/reaction_await_apply.py +238 -0
  28. continuum_task_server_bundle/discord/reaction_await_db.py +174 -0
  29. continuum_task_server_bundle/discord/reaction_await_inbound.py +47 -0
  30. continuum_task_server_bundle/discord/reaction_await_logic.py +118 -0
  31. continuum_task_server_bundle/discord/reaction_await_poller.py +131 -0
  32. continuum_task_server_bundle/discord/s3_attachment_config.py +25 -0
  33. continuum_task_server_bundle/discord/s3_message_attachments.py +139 -0
  34. continuum_task_server_bundle/discord/sql/001_message_awaits.sql +112 -0
  35. continuum_task_server_bundle/discord/sql/002_reaction_awaits.sql +61 -0
  36. continuum_task_server_bundle/github/__init__.py +4 -0
  37. continuum_task_server_bundle/github/awaits/__init__.py +1 -0
  38. continuum_task_server_bundle/github/awaits/apply.py +92 -0
  39. continuum_task_server_bundle/github/awaits/cleanup.py +94 -0
  40. continuum_task_server_bundle/github/awaits/db.py +220 -0
  41. continuum_task_server_bundle/github/awaits/evaluators.py +325 -0
  42. continuum_task_server_bundle/github/awaits/fetch.py +192 -0
  43. continuum_task_server_bundle/github/awaits/poller.py +82 -0
  44. continuum_task_server_bundle/github/awaits/register.py +37 -0
  45. continuum_task_server_bundle/github/ci_status.py +70 -0
  46. continuum_task_server_bundle/github/comment_normalize.py +76 -0
  47. continuum_task_server_bundle/github/errors.py +52 -0
  48. continuum_task_server_bundle/github/github_app.py +291 -0
  49. continuum_task_server_bundle/github/github_http.py +377 -0
  50. continuum_task_server_bundle/github/methods/__init__.py +90 -0
  51. continuum_task_server_bundle/github/methods/_common.py +183 -0
  52. continuum_task_server_bundle/github/methods/awaits.py +107 -0
  53. continuum_task_server_bundle/github/methods/ci.py +158 -0
  54. continuum_task_server_bundle/github/methods/comments.py +214 -0
  55. continuum_task_server_bundle/github/methods/credentials.py +59 -0
  56. continuum_task_server_bundle/github/methods/issues.py +131 -0
  57. continuum_task_server_bundle/github/methods/pulls.py +329 -0
  58. continuum_task_server_bundle/github/methods/repos.py +424 -0
  59. continuum_task_server_bundle/github/methods/search.py +109 -0
  60. continuum_task_server_bundle/github/plugin.py +91 -0
  61. continuum_task_server_bundle/github/sql/001_github_awaits.sql +65 -0
  62. continuum_task_server_bundle/github/webhook_server.py +126 -0
  63. continuum_task_server_bundle/jira/__init__.py +4 -0
  64. continuum_task_server_bundle/jira/await_poller.py +236 -0
  65. continuum_task_server_bundle/jira/await_store.py +271 -0
  66. continuum_task_server_bundle/jira/config.py +68 -0
  67. continuum_task_server_bundle/jira/jira_client.py +382 -0
  68. continuum_task_server_bundle/jira/methods.py +246 -0
  69. continuum_task_server_bundle/jira/plugin.py +86 -0
  70. continuum_task_server_bundle/jira/sql/001_jira_issue_comment_waits.sql +19 -0
  71. continuum_task_server_bundle/jira/webhook.py +70 -0
  72. continuum_task_server_bundle/openrouter/__init__.py +4 -0
  73. continuum_task_server_bundle/openrouter/chat_service.py +1037 -0
  74. continuum_task_server_bundle/openrouter/chat_store.py +849 -0
  75. continuum_task_server_bundle/openrouter/environment.py +29 -0
  76. continuum_task_server_bundle/openrouter/handler.py +59 -0
  77. continuum_task_server_bundle/openrouter/image_context.py +207 -0
  78. continuum_task_server_bundle/openrouter/openrouter_client.py +324 -0
  79. continuum_task_server_bundle/openrouter/plugin.py +37 -0
  80. continuum_task_server_bundle/openrouter/prompt_projection.py +417 -0
  81. continuum_task_server_bundle/openrouter/sql/chat.sql +50 -0
  82. continuum_task_server_bundle/openrouter/sql/migrate_prune_then_chunk_v1.sql +11 -0
  83. continuum_task_server_bundle/roblox/__init__.py +4 -0
  84. continuum_task_server_bundle/roblox/open_cloud.py +335 -0
  85. continuum_task_server_bundle/roblox/plugin.py +30 -0
  86. continuum_task_server_bundle/roblox/storage_s3.py +55 -0
  87. continuum_task_server_bundle-1.0.0.dist-info/METADATA +109 -0
  88. continuum_task_server_bundle-1.0.0.dist-info/RECORD +90 -0
  89. continuum_task_server_bundle-1.0.0.dist-info/WHEEL +5 -0
  90. continuum_task_server_bundle-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,220 @@
1
+ """PostgreSQL persistence for durable GitHub awaits.
2
+
3
+ Concurrency (multiple worker processes against one database):
4
+
5
+ - ``claim_due`` uses ``FOR UPDATE SKIP LOCKED`` so only one poller claims a
6
+ given row per due time; others skip locked rows and pick different work.
7
+ - ``apply`` (see ``awaits.apply``) loads the row with ``SELECT ... FOR UPDATE``
8
+ in one transaction, then updates or completes with ``WHERE status = 'active'``.
9
+ - ``insert_github_await`` is a single ``INSERT ... ON CONFLICT DO NOTHING``.
10
+ - ``mark_failed`` uses ``UPDATE ... WHERE status = 'active'`` so only one writer
11
+ wins the terminal transition.
12
+
13
+ Webhooks only set ``next_poll_at = now()``; they never complete a row.
14
+ Continuum HTTP calls (heartbeat, complete, fail) run after the DB transaction commits.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ from datetime import datetime, timedelta, timezone
21
+ from os import getenv
22
+ from typing import Any
23
+ from uuid import UUID
24
+
25
+ import psycopg
26
+ from psycopg.rows import dict_row
27
+ from psycopg.types.json import Json
28
+
29
+
30
+ def database_url() -> str | None:
31
+ url = getenv("DATABASE_URL")
32
+ return url if url else None
33
+
34
+
35
+ def connect():
36
+ url = database_url()
37
+ if not url:
38
+ raise RuntimeError("DATABASE_URL is not set")
39
+ return psycopg.connect(url, row_factory=dict_row)
40
+
41
+
42
+ def insert_github_await(
43
+ *,
44
+ queue_item_id: UUID,
45
+ kind: str,
46
+ repo_full_name: str,
47
+ number: int | None,
48
+ head_sha: str | None,
49
+ params: dict[str, Any],
50
+ timeout_seconds: float,
51
+ poll_interval_seconds: float,
52
+ ) -> bool:
53
+ """Insert a new await row. Returns True if inserted, False if queue_item_id exists."""
54
+ deadline = timedelta(seconds=timeout_seconds)
55
+ with connect() as conn:
56
+ with conn.transaction():
57
+ with conn.cursor() as cur:
58
+ cur.execute(
59
+ """
60
+ INSERT INTO github_awaits (
61
+ queue_item_id,
62
+ kind,
63
+ repo_full_name,
64
+ number,
65
+ head_sha,
66
+ params_json,
67
+ timeout_seconds,
68
+ poll_interval_seconds,
69
+ deadline_at,
70
+ next_poll_at
71
+ )
72
+ VALUES (
73
+ %s, %s, %s, %s, %s, %s, %s, %s,
74
+ now() + %s::interval,
75
+ now()
76
+ )
77
+ ON CONFLICT (queue_item_id) DO NOTHING
78
+ RETURNING id
79
+ """,
80
+ (
81
+ str(queue_item_id),
82
+ kind,
83
+ repo_full_name,
84
+ number,
85
+ head_sha,
86
+ Json(params),
87
+ timeout_seconds,
88
+ poll_interval_seconds,
89
+ deadline,
90
+ ),
91
+ )
92
+ row = cur.fetchone()
93
+ return row is not None
94
+
95
+
96
+ def claim_due(*, limit: int = 10) -> list[dict[str, Any]]:
97
+ """Atomically schedule next_poll_at and return rows due for a GitHub poll."""
98
+ with connect() as conn:
99
+ with conn.transaction():
100
+ with conn.cursor() as cur:
101
+ cur.execute(
102
+ """
103
+ WITH picked AS (
104
+ SELECT id
105
+ FROM github_awaits
106
+ WHERE status = 'active' AND next_poll_at <= now()
107
+ ORDER BY next_poll_at
108
+ FOR UPDATE SKIP LOCKED
109
+ LIMIT %(lim)s
110
+ )
111
+ UPDATE github_awaits g
112
+ SET next_poll_at = now() + (g.poll_interval_seconds * INTERVAL '1 second')
113
+ FROM picked p
114
+ WHERE g.id = p.id AND g.status = 'active'
115
+ RETURNING g.*
116
+ """,
117
+ {"lim": limit},
118
+ )
119
+ return list(cur.fetchall())
120
+
121
+
122
+ def delete_by_queue_item_id(queue_item_id: UUID) -> int:
123
+ """Delete the await row for this queue item. Returns rows deleted (0 or 1)."""
124
+ with connect() as conn:
125
+ with conn.transaction():
126
+ with conn.cursor() as cur:
127
+ cur.execute(
128
+ """
129
+ DELETE FROM github_awaits
130
+ WHERE queue_item_id = %s
131
+ """,
132
+ (str(queue_item_id),),
133
+ )
134
+ return int(cur.rowcount or 0)
135
+
136
+
137
+ def mark_failed(*, row_id: UUID, error: dict[str, Any]) -> UUID | None:
138
+ """Set status failed if still active. Returns queue_item_id if updated."""
139
+ with connect() as conn:
140
+ with conn.transaction():
141
+ with conn.cursor() as cur:
142
+ cur.execute(
143
+ """
144
+ UPDATE github_awaits
145
+ SET status = 'failed',
146
+ completed_at = now(),
147
+ error_json = %s
148
+ WHERE id = %s AND status = 'active'
149
+ RETURNING queue_item_id
150
+ """,
151
+ (Json(error), str(row_id)),
152
+ )
153
+ one = cur.fetchone()
154
+ if not one:
155
+ return None
156
+ return UUID(str(one["queue_item_id"]))
157
+
158
+
159
+ def bump_matching(
160
+ *,
161
+ repo_full_name: str,
162
+ number: int | None = None,
163
+ head_sha: str | None = None,
164
+ ) -> int:
165
+ """Set next_poll_at = now() for active rows matching the repo and number and/or sha.
166
+
167
+ A webhook calls this so the poller re-checks immediately. Rows are matched
168
+ when the number matches or the head sha matches (either is enough).
169
+ """
170
+ if number is None and not head_sha:
171
+ return 0
172
+ clauses: list[str] = []
173
+ params: dict[str, Any] = {"repo": repo_full_name.strip().lower()}
174
+ if number is not None:
175
+ clauses.append("number = %(number)s")
176
+ params["number"] = int(number)
177
+ if head_sha:
178
+ clauses.append("head_sha = %(sha)s")
179
+ params["sha"] = head_sha
180
+ where_or = " OR ".join(clauses)
181
+ with connect() as conn:
182
+ with conn.transaction():
183
+ with conn.cursor() as cur:
184
+ cur.execute(
185
+ f"""
186
+ UPDATE github_awaits
187
+ SET next_poll_at = now()
188
+ WHERE status = 'active'
189
+ AND repo_full_name = %(repo)s
190
+ AND ({where_or})
191
+ """,
192
+ params,
193
+ )
194
+ return int(cur.rowcount or 0)
195
+
196
+
197
+ def utcnow() -> datetime:
198
+ return datetime.now(timezone.utc)
199
+
200
+
201
+ def parse_json_object(raw: Any) -> dict[str, Any]:
202
+ if raw is None:
203
+ return {}
204
+ if isinstance(raw, dict):
205
+ return dict(raw)
206
+ if isinstance(raw, str):
207
+ loaded = json.loads(raw)
208
+ return dict(loaded) if isinstance(loaded, dict) else {}
209
+ return {}
210
+
211
+
212
+ def parse_json_list(raw: Any) -> list[Any]:
213
+ if raw is None:
214
+ return []
215
+ if isinstance(raw, list):
216
+ return list(raw)
217
+ if isinstance(raw, str):
218
+ loaded = json.loads(raw)
219
+ return list(loaded) if isinstance(loaded, list) else []
220
+ return []
@@ -0,0 +1,325 @@
1
+ """Pure completion rules for GitHub awaits.
2
+
3
+ ``evaluate(row, fetched, now)`` does not perform I/O. The poller fetches GitHub
4
+ state, then this module decides whether the queue item is done.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass
10
+ from datetime import datetime, timedelta, timezone
11
+ from typing import Any
12
+
13
+ from continuum_task_server_bundle.github.ci_status import any_failed, summarize_checks
14
+ from continuum_task_server_bundle.github.comment_normalize import comment_key
15
+
16
+ _PR_UNTIL = {"merged", "closed", "approved", "changes_requested", "mergeable"}
17
+
18
+
19
+ @dataclass
20
+ class EvalResult:
21
+ complete: bool
22
+ output: dict[str, Any] | None
23
+ state: dict[str, Any]
24
+ next_poll_seconds: float | None = None
25
+
26
+
27
+ def evaluate(row: dict[str, Any], fetched: dict[str, Any], *, now: datetime) -> EvalResult:
28
+ kind = row.get("kind")
29
+ if kind == "await_ci":
30
+ return evaluate_ci(row, fetched, now=now)
31
+ if kind == "await_comments":
32
+ return evaluate_comments(row, fetched, now=now)
33
+ if kind == "await_pull_request":
34
+ return evaluate_pull_request(row, fetched, now=now)
35
+ if kind == "repo_ready":
36
+ return evaluate_repo_ready(row, fetched, now=now)
37
+ return EvalResult(
38
+ complete=True,
39
+ output={"success": False, "error": f"unknown await kind {kind!r}"},
40
+ state={},
41
+ )
42
+
43
+
44
+ def evaluate_ci(row: dict[str, Any], fetched: dict[str, Any], *, now: datetime) -> EvalResult:
45
+ params = _params(row)
46
+ checks = list(fetched.get("checks") or [])
47
+ required = params.get("required_checks")
48
+ if isinstance(required, str):
49
+ required = [required]
50
+ if required is not None and not isinstance(required, list):
51
+ required = None
52
+
53
+ grace = float(params.get("checks_grace_seconds", 180))
54
+ registered = _dt(row.get("registered_at")) or now
55
+ past_grace = now >= registered + timedelta(seconds=grace)
56
+ expired = _expired(row, now)
57
+
58
+ if required:
59
+ wanted = {str(name) for name in required}
60
+ present = [check for check in checks if check.get("name") in wanted]
61
+ missing = sorted(wanted - {check.get("name") for check in present})
62
+ else:
63
+ present = list(checks)
64
+ missing = []
65
+
66
+ new_state = {
67
+ "checks": checks,
68
+ "check_runs": list(fetched.get("check_runs") or []),
69
+ "statuses": list(fetched.get("statuses") or []),
70
+ }
71
+ unfinished = [check for check in present if check.get("status") != "completed"]
72
+
73
+ def payload(state: str, timed_out: bool) -> dict[str, Any]:
74
+ return {
75
+ "success": True,
76
+ "state": state,
77
+ "head_sha": row.get("head_sha"),
78
+ "checks": present,
79
+ "missing_checks": missing,
80
+ "timed_out": timed_out,
81
+ }
82
+
83
+ if not present:
84
+ if not past_grace and not expired:
85
+ return EvalResult(False, None, new_state)
86
+ return EvalResult(True, payload("no_checks", expired), new_state)
87
+
88
+ if unfinished or missing:
89
+ if not expired:
90
+ return EvalResult(False, None, new_state)
91
+ state = "failure" if any_failed(present) else "pending"
92
+ return EvalResult(True, payload(state, True), new_state)
93
+
94
+ return EvalResult(True, payload(summarize_checks(present), False), new_state)
95
+
96
+
97
+ def evaluate_comments(row: dict[str, Any], fetched: dict[str, Any], *, now: datetime) -> EvalResult:
98
+ params = _params(row)
99
+ include = params.get("include") or ["issue_comment", "review_comment", "review"]
100
+ include_set = {str(kind) for kind in include}
101
+ limit = max(1, int(params.get("limit", 50)))
102
+ quiet = float(params.get("quiet_period_seconds", 0))
103
+ ignore_own = bool(params.get("ignore_own_app", True))
104
+ app_slug = params.get("app_slug")
105
+ authors = params.get("author_logins")
106
+ author_set = {str(login).lower() for login in authors} if authors else None
107
+ since = _dt(params.get("since")) if params.get("since") else None
108
+ after_id = params.get("after_id")
109
+ if since is None and after_id is None:
110
+ since = _dt(row.get("registered_at"))
111
+
112
+ existing = list((_state(row).get("comments") or []))
113
+ incoming = list(fetched.get("comments") or [])
114
+ filtered = [
115
+ comment
116
+ for comment in incoming
117
+ if _comment_allowed(
118
+ comment,
119
+ include=include_set,
120
+ since=since,
121
+ after_id=after_id,
122
+ ignore_own=ignore_own,
123
+ app_slug=str(app_slug) if app_slug else None,
124
+ authors=author_set,
125
+ )
126
+ ]
127
+ merged = _merge_comments(existing, filtered, limit=limit)
128
+ new_state = {"comments": merged}
129
+ expired = _expired(row, now)
130
+ last_at = _last_comment_time(merged)
131
+ quiet_ok = bool(merged) and last_at is not None and now >= last_at + timedelta(seconds=quiet)
132
+
133
+ if expired or quiet_ok:
134
+ return EvalResult(
135
+ True,
136
+ {
137
+ "success": True,
138
+ "comments": merged,
139
+ "timed_out": expired,
140
+ },
141
+ new_state,
142
+ )
143
+
144
+ next_poll = quiet if merged and quiet > 0 else None
145
+ return EvalResult(False, None, new_state, next_poll_seconds=next_poll)
146
+
147
+
148
+ def evaluate_pull_request(row: dict[str, Any], fetched: dict[str, Any], *, now: datetime) -> EvalResult:
149
+ params = _params(row)
150
+ until = params.get("until") or ["merged"]
151
+ if isinstance(until, str):
152
+ until = [until]
153
+ pull = dict(fetched.get("pull") or {})
154
+ new_state = {"pull": pull}
155
+ matched = _match_pull(until, pull)
156
+ expired = _expired(row, now)
157
+ if matched is not None:
158
+ return EvalResult(
159
+ True,
160
+ {
161
+ "success": True,
162
+ "matched": matched,
163
+ "timed_out": False,
164
+ "pull_request": pull,
165
+ },
166
+ new_state,
167
+ )
168
+ if expired:
169
+ return EvalResult(
170
+ True,
171
+ {
172
+ "success": True,
173
+ "matched": None,
174
+ "timed_out": True,
175
+ "pull_request": pull,
176
+ },
177
+ new_state,
178
+ )
179
+ return EvalResult(False, None, new_state)
180
+
181
+
182
+ def evaluate_repo_ready(row: dict[str, Any], fetched: dict[str, Any], *, now: datetime) -> EvalResult:
183
+ params = _params(row)
184
+ exists = bool(fetched.get("exists"))
185
+ default_branch = fetched.get("default_branch")
186
+ new_state = {
187
+ "exists": exists,
188
+ "default_branch": default_branch,
189
+ "full_name": fetched.get("full_name") or params.get("full_name"),
190
+ "html_url": fetched.get("html_url") or params.get("html_url"),
191
+ }
192
+ ready = exists and bool(default_branch)
193
+ expired = _expired(row, now)
194
+ if ready or expired:
195
+ full_name = new_state.get("full_name") or row.get("repo_full_name")
196
+ return EvalResult(
197
+ True,
198
+ {
199
+ "success": True,
200
+ "ready": ready,
201
+ "timed_out": expired and not ready,
202
+ "repo": full_name,
203
+ "full_name": full_name,
204
+ "default_branch": default_branch,
205
+ "html_url": new_state.get("html_url"),
206
+ "clone_url": fetched.get("clone_url") or params.get("clone_url"),
207
+ },
208
+ new_state,
209
+ )
210
+ return EvalResult(False, None, new_state)
211
+
212
+
213
+ def _match_pull(until: list[Any], pull: dict[str, Any]) -> str | None:
214
+ for raw in until:
215
+ cond = str(raw)
216
+ if cond not in _PR_UNTIL:
217
+ continue
218
+ if cond == "merged" and pull.get("merged") is True:
219
+ return cond
220
+ if cond == "closed" and pull.get("state") == "closed":
221
+ return cond
222
+ if cond == "approved" and pull.get("review_decision") == "APPROVED":
223
+ return cond
224
+ if cond == "changes_requested" and pull.get("review_decision") == "CHANGES_REQUESTED":
225
+ return cond
226
+ if cond == "mergeable" and pull.get("mergeable") is True:
227
+ return cond
228
+ return None
229
+
230
+
231
+ def _comment_allowed(
232
+ comment: dict[str, Any],
233
+ *,
234
+ include: set[str],
235
+ since: datetime | None,
236
+ after_id: Any,
237
+ ignore_own: bool,
238
+ app_slug: str | None,
239
+ authors: set[str] | None,
240
+ ) -> bool:
241
+ if comment.get("kind") not in include:
242
+ return False
243
+ login = str(comment.get("user_login") or "")
244
+ if ignore_own and app_slug and login.lower() == f"{app_slug}[bot]".lower():
245
+ return False
246
+ if authors is not None and login.lower() not in authors:
247
+ return False
248
+ created = _dt(comment.get("created_at"))
249
+ if since is not None and (created is None or created <= since):
250
+ return False
251
+ if after_id is not None and _id_leq(comment.get("id"), after_id):
252
+ return False
253
+ return True
254
+
255
+
256
+ def _id_leq(comment_id: Any, after_id: Any) -> bool:
257
+ try:
258
+ return int(str(comment_id)) <= int(str(after_id))
259
+ except (TypeError, ValueError):
260
+ return str(comment_id) <= str(after_id)
261
+
262
+
263
+ def _merge_comments(
264
+ existing: list[dict[str, Any]],
265
+ incoming: list[dict[str, Any]],
266
+ *,
267
+ limit: int,
268
+ ) -> list[dict[str, Any]]:
269
+ by_key: dict[str, dict[str, Any]] = {}
270
+ for comment in existing:
271
+ by_key[comment_key(comment)] = comment
272
+ for comment in incoming:
273
+ by_key[comment_key(comment)] = comment
274
+ merged = sorted(by_key.values(), key=_comment_sort_key)
275
+ return merged[:limit]
276
+
277
+
278
+ def _comment_sort_key(comment: dict[str, Any]) -> tuple:
279
+ created = comment.get("created_at") or ""
280
+ return (str(created), str(comment.get("kind")), str(comment.get("id")))
281
+
282
+
283
+ def _last_comment_time(comments: list[dict[str, Any]]) -> datetime | None:
284
+ times = [parsed for comment in comments if (parsed := _dt(comment.get("created_at"))) is not None]
285
+ if not times:
286
+ return None
287
+ return max(times)
288
+
289
+
290
+ def _params(row: dict[str, Any]) -> dict[str, Any]:
291
+ raw = row.get("params_json")
292
+ if isinstance(raw, dict):
293
+ return raw
294
+ return {}
295
+
296
+
297
+ def _state(row: dict[str, Any]) -> dict[str, Any]:
298
+ raw = row.get("state_json")
299
+ if isinstance(raw, dict):
300
+ return raw
301
+ return {}
302
+
303
+
304
+ def _dt(value: Any) -> datetime | None:
305
+ if value is None:
306
+ return None
307
+ if isinstance(value, datetime):
308
+ if value.tzinfo is None:
309
+ return value.replace(tzinfo=timezone.utc)
310
+ return value.astimezone(timezone.utc)
311
+ text = str(value).replace("Z", "+00:00")
312
+ try:
313
+ parsed = datetime.fromisoformat(text)
314
+ except ValueError:
315
+ return None
316
+ if parsed.tzinfo is None:
317
+ parsed = parsed.replace(tzinfo=timezone.utc)
318
+ return parsed.astimezone(timezone.utc)
319
+
320
+
321
+ def _expired(row: dict[str, Any], now: datetime) -> bool:
322
+ deadline = _dt(row.get("deadline_at"))
323
+ if deadline is None:
324
+ return False
325
+ return now >= deadline