socialcli 0.3.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.

Potentially problematic release.


This version of socialcli might be problematic. Click here for more details.

Files changed (224) hide show
  1. socialcli-0.3.0.dist-info/METADATA +168 -0
  2. socialcli-0.3.0.dist-info/RECORD +224 -0
  3. socialcli-0.3.0.dist-info/WHEEL +4 -0
  4. socialcli-0.3.0.dist-info/entry_points.txt +3 -0
  5. socialcli-0.3.0.dist-info/licenses/LICENSE +21 -0
  6. socialctl/__init__.py +0 -0
  7. socialctl/__main__.py +6 -0
  8. socialctl/adapters/__init__.py +6 -0
  9. socialctl/adapters/base.py +68 -0
  10. socialctl/adapters/errores.py +56 -0
  11. socialctl/adapters/facebook.py +180 -0
  12. socialctl/adapters/instagram.py +442 -0
  13. socialctl/adapters/tiktok.py +535 -0
  14. socialctl/adapters/youtube.py +331 -0
  15. socialctl/agent_errors.py +176 -0
  16. socialctl/agent_guide.py +23 -0
  17. socialctl/approval_cli.py +27 -0
  18. socialctl/auth.py +139 -0
  19. socialctl/authflow.py +344 -0
  20. socialctl/brands.py +194 -0
  21. socialctl/capabilities.py +57 -0
  22. socialctl/capabilities.yml +5945 -0
  23. socialctl/cli.py +1766 -0
  24. socialctl/connection_service/__init__.py +0 -0
  25. socialctl/connection_service/__main__.py +33 -0
  26. socialctl/connection_service/app.py +496 -0
  27. socialctl/connection_service/assets/PLATFORM-LOGOS-LICENSE.txt +50 -0
  28. socialctl/connection_service/assets/connection.css +75 -0
  29. socialctl/connection_service/assets/facebook.webp +0 -0
  30. socialctl/connection_service/assets/instagram.svg +194 -0
  31. socialctl/connection_service/assets/socialcli-logo.png +0 -0
  32. socialctl/connection_service/assets/tiktok.png +0 -0
  33. socialctl/connection_service/assets/youtube.svg +1 -0
  34. socialctl/connection_service/landing.py +146 -0
  35. socialctl/connection_service/legacy.py +48 -0
  36. socialctl/connection_service/peer.py +13 -0
  37. socialctl/connection_service/providers.py +324 -0
  38. socialctl/connection_service/settings.py +76 -0
  39. socialctl/connection_service/store.py +124 -0
  40. socialctl/connections/__init__.py +0 -0
  41. socialctl/connections/account_cli.py +438 -0
  42. socialctl/connections/cli.py +379 -0
  43. socialctl/connections/client.py +126 -0
  44. socialctl/connections/credential_cli.py +224 -0
  45. socialctl/connections/credential_store.py +49 -0
  46. socialctl/connections/file_store.py +193 -0
  47. socialctl/connections/keychain.py +78 -0
  48. socialctl/connections/meta_user.py +81 -0
  49. socialctl/connections/rotation_cli.py +116 -0
  50. socialctl/connections/saas_client.py +91 -0
  51. socialctl/connections/temporary_media.py +62 -0
  52. socialctl/delivery_options.py +70 -0
  53. socialctl/engagement.py +200 -0
  54. socialctl/engagement_cli.py +50 -0
  55. socialctl/executor.py +135 -0
  56. socialctl/formatter.py +291 -0
  57. socialctl/hosted_media.py +152 -0
  58. socialctl/identity.py +200 -0
  59. socialctl/inbox.py +298 -0
  60. socialctl/inbox_cli.py +46 -0
  61. socialctl/inventory.py +155 -0
  62. socialctl/inventory_cli.py +171 -0
  63. socialctl/inventory_sources.py +101 -0
  64. socialctl/management/__init__.py +1 -0
  65. socialctl/management/batch_cli.py +115 -0
  66. socialctl/management/batches.py +325 -0
  67. socialctl/management/changes.py +485 -0
  68. socialctl/management/cli.py +227 -0
  69. socialctl/management/comments_cli.py +352 -0
  70. socialctl/management/community_batch_cli.py +63 -0
  71. socialctl/management/community_batches.py +294 -0
  72. socialctl/management/community_changes.py +370 -0
  73. socialctl/management/community_cli.py +142 -0
  74. socialctl/management/community_schema.py +119 -0
  75. socialctl/management/facebook_groups.py +1118 -0
  76. socialctl/management/groups_cli.py +274 -0
  77. socialctl/management/inbox_readers.py +87 -0
  78. socialctl/management/meta_changes.py +197 -0
  79. socialctl/management/meta_cli.py +342 -0
  80. socialctl/management/meta_client.py +631 -0
  81. socialctl/management/meta_comment_inbox.py +565 -0
  82. socialctl/management/meta_comments.py +587 -0
  83. socialctl/management/meta_errors.py +59 -0
  84. socialctl/management/meta_pagination.py +52 -0
  85. socialctl/management/meta_schema.py +128 -0
  86. socialctl/management/meta_webhooks.py +147 -0
  87. socialctl/management/metadata_parts.py +144 -0
  88. socialctl/management/owned_assets.py +85 -0
  89. socialctl/management/owned_changes.py +470 -0
  90. socialctl/management/owned_cli.py +128 -0
  91. socialctl/management/owned_reorder.py +62 -0
  92. socialctl/management/owned_schema.py +368 -0
  93. socialctl/management/reply_context.py +24 -0
  94. socialctl/management/reply_evidence.py +80 -0
  95. socialctl/management/resource_changes.py +407 -0
  96. socialctl/management/resource_cli.py +136 -0
  97. socialctl/management/snippet_readback.py +26 -0
  98. socialctl/management/stories.py +713 -0
  99. socialctl/management/stories_cli.py +172 -0
  100. socialctl/management/youtube.py +323 -0
  101. socialctl/management/youtube_community.py +326 -0
  102. socialctl/management/youtube_metadata.py +122 -0
  103. socialctl/management/youtube_owned.py +259 -0
  104. socialctl/management/youtube_resources.py +305 -0
  105. socialctl/media.py +269 -0
  106. socialctl/media_cli.py +183 -0
  107. socialctl/media_ingress.py +211 -0
  108. socialctl/media_preflight.py +114 -0
  109. socialctl/media_registry.py +301 -0
  110. socialctl/media_requirements.py +52 -0
  111. socialctl/metricas/__init__.py +6 -0
  112. socialctl/metricas/almacen.py +133 -0
  113. socialctl/metricas/analytics_changes.py +295 -0
  114. socialctl/metricas/analytics_cli.py +191 -0
  115. socialctl/metricas/analytics_client.py +304 -0
  116. socialctl/metricas/analytics_ingest.py +260 -0
  117. socialctl/metricas/analytics_schema.py +174 -0
  118. socialctl/metricas/base.py +147 -0
  119. socialctl/metricas/facebook.py +418 -0
  120. socialctl/metricas/insights.py +227 -0
  121. socialctl/metricas/instagram.py +133 -0
  122. socialctl/metricas/modelos.py +87 -0
  123. socialctl/metricas/piezas.py +134 -0
  124. socialctl/metricas/reach.py +94 -0
  125. socialctl/metricas/reporting_client.py +112 -0
  126. socialctl/metricas/resumen.py +251 -0
  127. socialctl/metricas/slugs.py +89 -0
  128. socialctl/metricas/tiktok.py +185 -0
  129. socialctl/metricas/youtube.py +403 -0
  130. socialctl/migration_cli.py +60 -0
  131. socialctl/migration_files.py +68 -0
  132. socialctl/models.py +150 -0
  133. socialctl/native_schedule/__init__.py +13 -0
  134. socialctl/native_schedule/api_delivery.py +15 -0
  135. socialctl/native_schedule/api_reconcile.py +40 -0
  136. socialctl/native_schedule/approval.py +160 -0
  137. socialctl/native_schedule/cadence.py +73 -0
  138. socialctl/native_schedule/cli.py +510 -0
  139. socialctl/native_schedule/dispatcher.py +120 -0
  140. socialctl/native_schedule/facebook.py +112 -0
  141. socialctl/native_schedule/facebook_reels.py +140 -0
  142. socialctl/native_schedule/first_comment.py +181 -0
  143. socialctl/native_schedule/handoff.py +193 -0
  144. socialctl/native_schedule/instagram_delivery.py +224 -0
  145. socialctl/native_schedule/instagram_runtime.py +66 -0
  146. socialctl/native_schedule/inventory.py +70 -0
  147. socialctl/native_schedule/migration.py +310 -0
  148. socialctl/native_schedule/models.py +103 -0
  149. socialctl/native_schedule/reconcile.py +83 -0
  150. socialctl/native_schedule/remote_data.py +177 -0
  151. socialctl/native_schedule/report.py +151 -0
  152. socialctl/native_schedule/store.py +560 -0
  153. socialctl/native_schedule/verification.py +32 -0
  154. socialctl/native_schedule/youtube.py +339 -0
  155. socialctl/operation_output.py +87 -0
  156. socialctl/plantillas/accounts.yml +33 -0
  157. socialctl/plantillas/brand.md +95 -0
  158. socialctl/plantillas/estrategia.md +64 -0
  159. socialctl/postfile.py +240 -0
  160. socialctl/preflight.py +73 -0
  161. socialctl/publication_policy.py +34 -0
  162. socialctl/publication_status.py +75 -0
  163. socialctl/publication_steps.py +398 -0
  164. socialctl/publish_output.py +96 -0
  165. socialctl/publisher.py +445 -0
  166. socialctl/queue_migration.py +302 -0
  167. socialctl/read_budget.py +224 -0
  168. socialctl/read_reports.py +91 -0
  169. socialctl/rutas.py +103 -0
  170. socialctl/saas/__init__.py +1 -0
  171. socialctl/saas/access.py +75 -0
  172. socialctl/saas/auth.py +213 -0
  173. socialctl/saas/backup.py +124 -0
  174. socialctl/saas/billing.py +327 -0
  175. socialctl/saas/billing_enrollment.py +1237 -0
  176. socialctl/saas/billing_enrollment_schema.py +519 -0
  177. socialctl/saas/billing_inventory.py +775 -0
  178. socialctl/saas/billing_reconcile.py +127 -0
  179. socialctl/saas/billing_routes.py +27 -0
  180. socialctl/saas/budget.py +66 -0
  181. socialctl/saas/connections.py +374 -0
  182. socialctl/saas/consent.py +52 -0
  183. socialctl/saas/lifecycle.py +341 -0
  184. socialctl/saas/mail.py +89 -0
  185. socialctl/saas/maintenance.py +68 -0
  186. socialctl/saas/meta_user.py +298 -0
  187. socialctl/saas/meta_webhooks.py +358 -0
  188. socialctl/saas/migration.py +107 -0
  189. socialctl/saas/models.py +8 -0
  190. socialctl/saas/operations.py +102 -0
  191. socialctl/saas/pages.py +126 -0
  192. socialctl/saas/pairing.py +158 -0
  193. socialctl/saas/permissions.py +57 -0
  194. socialctl/saas/reminders.py +128 -0
  195. socialctl/saas/renewal.py +74 -0
  196. socialctl/saas/restore_guard.py +229 -0
  197. socialctl/saas/revocation.py +97 -0
  198. socialctl/saas/rotation.py +114 -0
  199. socialctl/saas/routes.py +221 -0
  200. socialctl/saas/settings.py +34 -0
  201. socialctl/saas/store.py +106 -0
  202. socialctl/saas/temporary_media.py +245 -0
  203. socialctl/saas/webhooks.py +76 -0
  204. socialctl/schedule_remote.py +262 -0
  205. socialctl/schedule_sqlite.py +44 -0
  206. socialctl/scheduler.py +581 -0
  207. socialctl/scheduler_launchd.py +319 -0
  208. socialctl/scheduler_systemd.py +167 -0
  209. socialctl/source_links.py +119 -0
  210. socialctl/ui/__init__.py +1 -0
  211. socialctl/ui/assets/agent-manual.md +850 -0
  212. socialctl/ui/assets/agents.md +27 -0
  213. socialctl/ui/assets/components.css +20 -0
  214. socialctl/ui/assets/connection-layout.css +53 -0
  215. socialctl/ui/assets/otp.template.html +10 -0
  216. socialctl/ui/assets/tokens.css +1 -0
  217. socialctl/ui/assets/trial.template.html +11 -0
  218. socialctl/ui/assets/web-layout.css +38 -0
  219. socialctl/ui/email/otp.html +10 -0
  220. socialctl/ui/email/trial.html +11 -0
  221. socialctl/upload_consent.py +13 -0
  222. socialctl/workspace.py +8 -0
  223. socialctl/youtube_data.py +471 -0
  224. socialctl/youtube_data_service.py +225 -0
@@ -0,0 +1,565 @@
1
+ """Incremental Meta comment inbox backed by explicit, approved reply ChangeSets."""
2
+ from __future__ import annotations
3
+
4
+ import fcntl
5
+ import hashlib
6
+ import hmac
7
+ import json
8
+ import os
9
+ import re
10
+ import tempfile
11
+ from contextlib import contextmanager
12
+ from datetime import datetime, timedelta, timezone
13
+ from pathlib import Path
14
+ from typing import Literal
15
+
16
+ from pydantic import BaseModel, ConfigDict, Field, ValidationError
17
+
18
+ from socialctl.management.changes import now_utc
19
+ from socialctl.management.meta_comments import (
20
+ CommentCursorRejected,
21
+ CommentError,
22
+ CommentStore,
23
+ MetaCommentsClient,
24
+ apply_comment,
25
+ prepare_comment,
26
+ reconcile_comment,
27
+ _id,
28
+ )
29
+
30
+
31
+ CommentState = Literal["observado", "draft", "aprobado", "respondido", "incierto", "bloqueado"]
32
+ CommentKind = Literal["pregunta", "elogio", "correccion", "spam", "otro"]
33
+ CURSOR_FALLBACK_WINDOW = timedelta(days=7)
34
+
35
+
36
+ class InboxComment(BaseModel):
37
+ model_config = ConfigDict(extra="forbid")
38
+
39
+ platform: Literal["facebook", "instagram"]
40
+ account_id: str
41
+ media_id: str
42
+ comment_id: str
43
+ author_id: str | None
44
+ author_name: str | None = None
45
+ text: str
46
+ created_time: str | None = None
47
+ parent_id: str | None = None
48
+ original_text: str | None = None
49
+ provider_updated_at: str | None = None
50
+ last_observed_at: str | None = None
51
+ observed_at: str
52
+ updated_at: str
53
+ language: Literal["es", "en", "und"]
54
+ kind: CommentKind
55
+ status: CommentState = "observado"
56
+ draft_text: str | None = None
57
+ change_id: str | None = None
58
+ draft_change_ids: list[str] = Field(default_factory=list)
59
+ fingerprint: str | None = None
60
+ idempotency_key: str | None = None
61
+ response_id: str | None = None
62
+ last_error: str | None = None
63
+ journal: list[dict] = Field(default_factory=list)
64
+ reply_evidence: dict | None = None
65
+
66
+
67
+ class InboxCursor(BaseModel):
68
+ model_config = ConfigDict(extra="forbid")
69
+
70
+ platform: Literal["facebook", "instagram"]
71
+ account_id: str
72
+ media_id: str
73
+ parent_id: str | None = None
74
+ requested_since: str | None = None
75
+ since: str | None = None
76
+ provider_cursor: str | None = None
77
+ last_sync_at: str
78
+ complete: bool
79
+
80
+
81
+ class InboxData(BaseModel):
82
+ model_config = ConfigDict(extra="forbid")
83
+
84
+ version: Literal[1] = 1
85
+ comments: list[InboxComment] = Field(default_factory=list)
86
+ cursors: list[InboxCursor] = Field(default_factory=list)
87
+
88
+
89
+ def _parse_time(value: str, label: str = "fecha") -> datetime:
90
+ try:
91
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
92
+ except (TypeError, ValueError, AttributeError):
93
+ raise CommentError(f"{label} must be RFC3339") from None
94
+ if parsed.tzinfo is None:
95
+ raise CommentError(f"{label} must include a timezone")
96
+ return parsed.astimezone(timezone.utc)
97
+
98
+
99
+ def _canonical_time(value: str) -> str:
100
+ return _parse_time(value).isoformat().replace("+00:00", "Z")
101
+
102
+
103
+ def classify_comment(text: str) -> tuple[Literal["es", "en", "und"], CommentKind]:
104
+ """Small deterministic triage; it never produces reply copy."""
105
+ lowered = f" {text.casefold()} "
106
+ spanish = (" que ", " qué ", " por qué ", " gracias", "historia", "incorrecto", "error", " fue ")
107
+ english = (" what ", " why ", " thanks", " follow ", "history", "wrong", "actually", " was ")
108
+ es_score = sum(token in lowered for token in spanish) + sum(ch in lowered for ch in "¿¡ñáéíóú")
109
+ en_score = sum(token in lowered for token in english)
110
+ language: Literal["es", "en", "und"] = "es" if es_score > en_score else "en" if en_score else "und"
111
+
112
+ urls = len(re.findall(r"(?:https?://|www\.)", lowered))
113
+ if urls >= 2 or any(token in lowered for token in ("sígueme", "follow me", "crypto", "promo code", "gana dinero")):
114
+ kind: CommentKind = "spam"
115
+ elif any(token in lowered for token in (" incorrect", " equivocado", " error", " actually", " wrong", " no fue", " no era")):
116
+ kind = "correccion"
117
+ elif "?" in text or "¿" in text or any(lowered.lstrip().startswith(token) for token in
118
+ ("qué ", "que ", "cómo ", "como ", "cuándo ", "cuando ", "why ", "what ", "how ")):
119
+ kind = "pregunta"
120
+ elif any(token in lowered for token in (" gracias", " excelente", " buen video", " buen vídeo", " me encanta", " thanks", " great", " love this")):
121
+ kind = "elogio"
122
+ else:
123
+ kind = "otro"
124
+ return language, kind
125
+
126
+
127
+ def response_key(account_id: str, comment_id: str, text: str) -> str:
128
+ payload = json.dumps([account_id, comment_id, text], ensure_ascii=False, separators=(",", ":"))
129
+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()
130
+
131
+
132
+ class CommentInboxStore:
133
+ def __init__(self, brand_root: Path):
134
+ self.root = brand_root / ".socialctl" / "comment-inbox"
135
+ self.path = self.root / "state.json"
136
+
137
+ def load(self) -> InboxData:
138
+ if not self.path.exists():
139
+ return InboxData()
140
+ try:
141
+ return InboxData.model_validate_json(self.path.read_text(encoding="utf-8"))
142
+ except (OSError, ValidationError):
143
+ raise CommentError("failed to read durable comment state") from None
144
+
145
+ def save(self, data: InboxData) -> None:
146
+ temporary = None
147
+ try:
148
+ for directory in (self.root.parent, self.root):
149
+ directory.mkdir(parents=True, exist_ok=True)
150
+ parent = os.open(directory.parent, os.O_RDONLY)
151
+ try:
152
+ os.fsync(parent)
153
+ finally:
154
+ os.close(parent)
155
+ fd, temporary = tempfile.mkstemp(prefix="state.", suffix=".tmp", dir=self.root)
156
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
157
+ json.dump(data.model_dump(mode="json"), handle, ensure_ascii=False, indent=2)
158
+ handle.write("\n")
159
+ handle.flush()
160
+ os.fsync(handle.fileno())
161
+ os.replace(temporary, self.path)
162
+ descriptor = os.open(self.root, os.O_RDONLY)
163
+ try:
164
+ os.fsync(descriptor)
165
+ finally:
166
+ os.close(descriptor)
167
+ except OSError:
168
+ if temporary:
169
+ try:
170
+ os.unlink(temporary)
171
+ except OSError:
172
+ pass
173
+ raise CommentError("failed to persist durable comment state") from None
174
+
175
+ @contextmanager
176
+ def lock(self):
177
+ self.root.mkdir(parents=True, exist_ok=True)
178
+ descriptor = os.open(self.root / "state.lock", os.O_RDWR | os.O_CREAT, 0o600)
179
+ try:
180
+ fcntl.flock(descriptor, fcntl.LOCK_EX)
181
+ yield
182
+ finally:
183
+ fcntl.flock(descriptor, fcntl.LOCK_UN)
184
+ os.close(descriptor)
185
+
186
+
187
+ def _cursor(data: InboxData, client: MetaCommentsClient, media_id: str, parent_id=None) -> InboxCursor | None:
188
+ rows = [row for row in data.cursors if (row.platform, row.account_id, row.media_id, row.parent_id) ==
189
+ (client.platform.value, client.account_id, media_id, parent_id)]
190
+ if len(rows) > 1:
191
+ raise CommentError("ambiguous durable state for media cursor")
192
+ return rows[0] if rows else None
193
+
194
+
195
+ def _record(data: InboxData, client: MetaCommentsClient, media_id: str, comment_id: str) -> InboxComment:
196
+ rows = [row for row in data.comments if (row.platform, row.account_id, row.media_id, row.comment_id) ==
197
+ (client.platform.value, client.account_id, media_id, comment_id)]
198
+ if len(rows) != 1:
199
+ raise CommentError("comment was not unambiguously observed in inbox")
200
+ return rows[0]
201
+
202
+
203
+ def grouped_inbox(data: InboxData, *, platform: str | None = None, media_id: str | None = None) -> list[dict]:
204
+ groups: dict[tuple, list[InboxComment]] = {}
205
+ for row in data.comments:
206
+ if row.author_id == row.account_id:
207
+ continue
208
+ if platform and row.platform != platform:
209
+ continue
210
+ if media_id and row.media_id != media_id:
211
+ continue
212
+ # Unknown authors must not be grouped as though they were one person.
213
+ key = (row.platform, row.media_id, row.author_id, row.language, row.kind,
214
+ row.comment_id if row.author_id is None else '')
215
+ groups.setdefault(key, []).append(row)
216
+ result = []
217
+ for key in sorted(groups, key=lambda parts: tuple(part or '' for part in parts)):
218
+ rows = sorted(groups[key], key=lambda row: (row.created_time or "", row.comment_id))
219
+ result.append({"platform": key[0], "media_id": key[1], "author_id": key[2],
220
+ "language": key[3], "kind": key[4], "comments": [row.model_dump(mode="json") for row in rows]})
221
+ return result
222
+
223
+
224
+ def verified_inbox_rows(rows, platform, media_id, parent_id=None):
225
+ """Keep independent valid observations; ambiguous IDs never become parents."""
226
+ remote, rejected, skipped = {}, set(), 0
227
+ field = 'message' if platform.value == 'facebook' else 'text'
228
+ time_field = 'created_time' if platform.value == 'facebook' else 'timestamp'
229
+ for row in rows:
230
+ ident = row.get('id')
231
+ try:
232
+ _id(ident)
233
+ author = row.get('from')
234
+ if (author is not None and (not isinstance(author, dict) or not isinstance(author.get('id'), str) or not author['id'])) or not isinstance(row.get(field), str):
235
+ raise CommentError('unverifiable text or author')
236
+ if platform.value == 'facebook':
237
+ parent = row.get('parent')
238
+ if parent is not None and (not isinstance(parent, dict) or parent.get('id') != (parent_id or media_id)):
239
+ raise CommentError('unverifiable parent')
240
+ elif row.get('parent_id') is not None and row['parent_id'] != parent_id:
241
+ raise CommentError('unverifiable parent')
242
+ if row.get(time_field) is not None:
243
+ _canonical_time(row[time_field])
244
+ if ident in rejected:
245
+ skipped += 1
246
+ continue
247
+ if ident in remote and remote[ident] != row:
248
+ del remote[ident]
249
+ rejected.add(ident)
250
+ skipped += 2
251
+ continue
252
+ remote[ident] = row
253
+ except (CommentError, ValueError, TypeError):
254
+ if isinstance(ident, str) and ident in remote:
255
+ del remote[ident]
256
+ skipped += 1
257
+ if isinstance(ident, str): rejected.add(ident)
258
+ skipped += 1
259
+ return remote, skipped
260
+
261
+
262
+ def sync_inbox(client: MetaCommentsClient, store: CommentInboxStore, *, media_id: str,
263
+ since: str | None = None, max_pages: int = 100, parent_id: str | None = None, resume: bool = False) -> dict:
264
+ if not 1 <= max_pages <= 100:
265
+ raise CommentError("max_pages must be between 1 and 100")
266
+ media_id = str(media_id)
267
+ current = store.load()
268
+ prior_cursor = _cursor(current, client, media_id, parent_id)
269
+ explicit_since = _canonical_time(since) if since is not None else None
270
+ effective_since = explicit_since or (prior_cursor.since if prior_cursor else None)
271
+ # An explicit cut-off starts a fresh traversal. A cursor belongs to the
272
+ # older traversal and must never override the caller's requested boundary.
273
+ resume_cursor = (prior_cursor.provider_cursor if prior_cursor and not prior_cursor.complete
274
+ and (since is None or (resume and explicit_since == prior_cursor.requested_since)) else None)
275
+ cursor_recovered = False
276
+ try:
277
+ listing = client.list_comments(media_id, max_pages=max_pages, after=resume_cursor,
278
+ **({"parent_id":parent_id} if parent_id else {}))
279
+ except CommentCursorRejected:
280
+ if resume_cursor is None:
281
+ raise
282
+ # Graph cursors are opaque and may expire. Restart the bounded traversal
283
+ # without `after`, retaining the completed cut-off or a conservative
284
+ # overlap window anchored to the sync that saved the rejected cursor.
285
+ if effective_since is None:
286
+ anchor = _parse_time(prior_cursor.last_sync_at, "cursor timestamp")
287
+ effective_since = (anchor - CURSOR_FALLBACK_WINDOW).isoformat().replace(
288
+ "+00:00", "Z")
289
+ listing = client.list_comments(media_id, max_pages=max_pages, after=None,
290
+ **({"parent_id":parent_id} if parent_id else {}))
291
+ cursor_recovered = True
292
+ now = now_utc().isoformat()
293
+ remote, skipped_unverifiable = verified_inbox_rows(listing['data'], client.platform, media_id, parent_id)
294
+ if skipped_unverifiable:
295
+ listing = {**listing, 'complete':False, 'next_cursor':None,
296
+ 'error': ((listing.get('error') + '; ') if listing.get('error') else '') +
297
+ 'Some Meta comments lack verifiable identity, text, author, parent or time; valid observations retained'}
298
+ time_field = 'created_time' if client.platform.value == 'facebook' else 'timestamp'
299
+ unknown_creation_time = sum(row.get(time_field) is None for row in remote.values())
300
+ if unknown_creation_time:
301
+ listing = {**listing, 'complete':False, 'next_cursor':None,
302
+ 'error': ((listing.get('error') + '; ') if listing.get('error') else '') +
303
+ 'Some Meta comments lack creation time; interval membership unknown; observations retained'}
304
+
305
+ from socialctl.management.reply_evidence import meta_reply_evidence, retain_positive, reply_evidence
306
+ evidence = meta_reply_evidence(client, media_id, parent_id, listing,
307
+ from_start=resume_cursor is None or cursor_recovered) if parent_id else None
308
+
309
+ added = updated = unchanged = skipped_own = skipped_before_since = unknown_author = 0
310
+ with store.lock():
311
+ data = store.load()
312
+ existing = {(row.platform, row.account_id, row.comment_id): row for row in data.comments}
313
+ observed_times = []
314
+ for ident, raw in remote.items():
315
+ author = raw.get("from") or {}
316
+ author_id = author.get("id") if isinstance(author, dict) else None
317
+ key = (client.platform.value, client.account_id, ident)
318
+ previous = existing.get(key)
319
+ if previous:
320
+ if (previous.media_id, previous.parent_id) != (media_id, parent_id):
321
+ raise CommentError("remote ID already belongs to another inbox item")
322
+ if previous.author_id != author_id:
323
+ previous.journal.append({'at': now, 'event': 'author_identity_observed',
324
+ 'before': previous.author_id, 'after': author_id})
325
+ previous.author_id = author_id
326
+ name = author.get('name') or author.get('username')
327
+ previous.author_name = name if isinstance(name, str) else None
328
+ previous.last_observed_at = now
329
+ if parent_id is None:
330
+ previous.reply_evidence = retain_positive(previous.reply_evidence,
331
+ reply_evidence(client.platform.value, client.account_id, media_id, ident))
332
+ if author_id == client.account_id:
333
+ skipped_own += 1
334
+ continue
335
+ field = "message" if client.platform.value == "facebook" else "text"
336
+ text = raw.get(field)
337
+ if not isinstance(text, str):
338
+ raise CommentError("Meta returned unverifiable text or author")
339
+ created = raw.get("created_time") if client.platform.value == "facebook" else raw.get("timestamp")
340
+ if created is not None:
341
+ created = _canonical_time(created)
342
+ if (effective_since and previous is None and
343
+ _parse_time(created) < _parse_time(effective_since)):
344
+ skipped_before_since += 1
345
+ continue
346
+ observed_times.append(created)
347
+ if author_id is None:
348
+ unknown_author += 1
349
+ language, kind = classify_comment(text)
350
+ if previous:
351
+ previous.provider_updated_at = raw.get('updated_time')
352
+ if previous.original_text is None: previous.original_text = previous.text
353
+ if previous.text != text:
354
+ previous.text, previous.language, previous.kind = text, language, kind
355
+ previous.updated_at = now
356
+ previous.journal.append({"at": now, "event": "remote_text_changed", "text":text})
357
+ updated += 1
358
+ else:
359
+ unchanged += 1
360
+ continue
361
+ name = author.get("name") or author.get("username")
362
+ record = InboxComment(platform=client.platform.value, account_id=client.account_id,
363
+ media_id=media_id, parent_id=parent_id, comment_id=ident, author_id=author_id,
364
+ author_name=name if isinstance(name, str) else None, text=text,
365
+ created_time=created, original_text=text, last_observed_at=now,
366
+ provider_updated_at=raw.get('updated_time'), observed_at=now, updated_at=now,
367
+ language=language, kind=kind,
368
+ journal=[{"at": now, "event": "observed_by_incremental_get"}])
369
+ data.comments.append(record)
370
+ existing[key] = record
371
+ added += 1
372
+ if evidence:
373
+ parent_record = existing.get((client.platform.value, client.account_id, parent_id))
374
+ if parent_record and parent_record.media_id == media_id and parent_record.parent_id is None:
375
+ parent_record.reply_evidence = retain_positive(parent_record.reply_evidence, evidence)
376
+ cursor = _cursor(data, client, media_id, parent_id)
377
+ all_times = [row.created_time for row in data.comments
378
+ if (row.platform, row.account_id, row.media_id, row.parent_id) ==
379
+ (client.platform.value, client.account_id, media_id, parent_id) and row.created_time]
380
+ completed_cutoffs = [*all_times, *observed_times]
381
+ if effective_since is not None:
382
+ completed_cutoffs.append(effective_since)
383
+ next_since = max(completed_cutoffs) if listing["complete"] and completed_cutoffs else effective_since
384
+ new_cursor = InboxCursor(platform=client.platform.value, account_id=client.account_id,
385
+ media_id=media_id, parent_id=parent_id, requested_since=explicit_since, since=next_since, provider_cursor=listing.get("next_cursor"),
386
+ last_sync_at=now, complete=listing["complete"])
387
+ if cursor:
388
+ data.cursors[data.cursors.index(cursor)] = new_cursor
389
+ else:
390
+ data.cursors.append(new_cursor)
391
+ store.save(data)
392
+ return {"platform": client.platform.value, "account_id": client.account_id,
393
+ "media_id": media_id, "reply_parent_id": parent_id, "observed_at": now, "since_used": effective_since, "next_since": next_since,
394
+ "provider_cursor": listing.get("next_cursor"), "complete": listing["complete"],
395
+ "cursor_recovered": cursor_recovered, "interrupted":listing.get("interrupted",False), "parent_ids": list(remote), "error": listing.get("error"),
396
+ **({"error_detail": listing["error_detail"]} if "error_detail" in listing else {}),
397
+ "new": added, "updated": updated,
398
+ "deduplicated": unchanged + max(0, len(listing["data"]) - len(remote) - skipped_unverifiable),
399
+ "skipped_own": skipped_own, "skipped_before_since": skipped_before_since,
400
+ "skipped_unverifiable": skipped_unverifiable,
401
+ "unknown_creation_time": unknown_creation_time,
402
+ "unknown_author": unknown_author,
403
+ "groups": grouped_inbox(data, platform=client.platform.value, media_id=media_id)}
404
+
405
+
406
+ def prepare_inbox_draft(client: MetaCommentsClient, comment_store: CommentStore,
407
+ inbox_store: CommentInboxStore, *, media_id: str,
408
+ comment_id: str, text: str, on_prepared=None, reply_context=None):
409
+ if not isinstance(text, str) or not text.strip():
410
+ raise CommentError("draft must contain explicit nonempty text")
411
+ with inbox_store.lock():
412
+ data = inbox_store.load()
413
+ record = _record(data, client, media_id, comment_id)
414
+ if record.author_id == record.account_id or (not record.author_id and client.platform.value != 'facebook'):
415
+ raise CommentError('target must have a verified external author')
416
+ if record.reply_evidence and record.reply_evidence.get('state') == 'owner_reply_found':
417
+ raise CommentError('Verified owner reply exists; inspect before preparing an additional reply')
418
+ key = response_key(client.account_id, comment_id, text)
419
+ if record.status in {"aprobado", "respondido", "incierto"}:
420
+ raise CommentError("comment already has an approved or uncertain reply; no additional POST created")
421
+ from socialctl.management.reply_evidence import check_reply_coverage
422
+ check_reply_coverage(client, record.model_dump())
423
+ if record.idempotency_key == key and record.change_id:
424
+ prior = comment_store.load(record.change_id)
425
+ if prior.before.get('reply_context') != reply_context:
426
+ raise CommentError('existing draft has different reply context; inspect before preparing another draft')
427
+ return prior, record
428
+ if any(row is not record and row.idempotency_key == key and
429
+ row.status in {"draft", "aprobado", "respondido", "incierto"} for row in data.comments):
430
+ raise CommentError("duplicate reply for the same account, comment and text")
431
+ change = prepare_comment(client, comment_store, media_id=media_id, action="reply",
432
+ parent_id=comment_id, text=text, reply_context=reply_context, inbox_binding={
433
+ "platform": client.platform.value, "account_id": client.account_id,
434
+ "media_id": media_id, "comment_id": comment_id,
435
+ "idempotency_key": key})
436
+ # The immutable child already exists even if the inbox save below fails.
437
+ # Observation must not change draft persistence or authorize any write.
438
+ if on_prepared is not None:
439
+ try:
440
+ on_prepared(change)
441
+ except Exception:
442
+ pass
443
+ now = now_utc().isoformat()
444
+ record.status = "draft"
445
+ record.draft_text = text
446
+ record.change_id = change.id
447
+ record.draft_change_ids.append(change.id)
448
+ record.fingerprint = change.fingerprint
449
+ record.idempotency_key = key
450
+ record.response_id = None
451
+ record.last_error = None
452
+ record.updated_at = now
453
+ record.journal.append({"at": now, "event": "explicit_draft_prepared", "change_id": change.id})
454
+ inbox_store.save(data)
455
+ return change, record
456
+
457
+
458
+ def _recent_attempts(data: InboxData, *, account_id: str, window_seconds: int, at: datetime) -> int:
459
+ cutoff = at - timedelta(seconds=window_seconds)
460
+ count = 0
461
+ for row in data.comments:
462
+ if row.account_id != account_id:
463
+ continue
464
+ for event in row.journal:
465
+ if event.get("event") != "reply_write_intent":
466
+ continue
467
+ try:
468
+ if _parse_time(event["at"], "journal timestamp") >= cutoff:
469
+ count += 1
470
+ except (CommentError, KeyError):
471
+ raise CommentError("invalid frequency journal") from None
472
+ return count
473
+
474
+
475
+ def apply_inbox_draft(client: MetaCommentsClient, comment_store: CommentStore,
476
+ inbox_store: CommentInboxStore, *, media_id: str, comment_id: str,
477
+ approval_digest: str, max_replies: int = 10, window_seconds: int = 3600):
478
+ if max_replies < 1 or window_seconds < 1:
479
+ raise CommentError("frequency limits must be positive integers")
480
+ with inbox_store.lock():
481
+ data = inbox_store.load()
482
+ record = _record(data, client, media_id, comment_id)
483
+ if not record.fingerprint or not hmac.compare_digest(approval_digest, record.fingerprint):
484
+ raise CommentError("approval does not match exact fingerprint")
485
+ if record.status == "respondido":
486
+ return record
487
+ if record.status == "incierto":
488
+ raise CommentError("uncertain outcome blocked; run reconcile-draft before another attempt")
489
+ if record.status not in {"draft", "aprobado", "bloqueado"} or not record.change_id:
490
+ raise CommentError("comment has no applicable draft")
491
+ now = now_utc()
492
+ attempts = _recent_attempts(data, account_id=client.account_id,
493
+ window_seconds=window_seconds, at=now)
494
+ if record.status != "aprobado" and attempts >= max_replies:
495
+ record.status = "bloqueado"
496
+ record.last_error = "frequency_limit"
497
+ record.updated_at = now.isoformat()
498
+ record.journal.append({"at": now.isoformat(), "event": "frequency_limit_blocked",
499
+ "max_replies": max_replies, "window_seconds": window_seconds, "observed_attempts": attempts})
500
+ inbox_store.save(data)
501
+ raise CommentError("frequency limit reached; no POST was sent")
502
+ if record.status != "aprobado":
503
+ record.status = "aprobado"
504
+ record.last_error = None
505
+ record.updated_at = now.isoformat()
506
+ record.journal.append({"at": now.isoformat(), "event": "reply_write_intent",
507
+ "max_replies": max_replies, "window_seconds": window_seconds,
508
+ "observed_attempts": attempts})
509
+ inbox_store.save(data)
510
+
511
+ try:
512
+ change = apply_comment(client, comment_store, record.change_id, approval_digest)
513
+ except CommentError as exc:
514
+ # Once the underlying durable intent left `proposed`, a persistence or
515
+ # transport failure may have happened after Meta accepted the POST.
516
+ # Fail closed even when the ChangeSet can no longer be read.
517
+ uncertain = True
518
+ try:
519
+ uncertain = comment_store.load(record.change_id).status != "proposed"
520
+ except CommentError:
521
+ pass
522
+ with inbox_store.lock():
523
+ data = inbox_store.load()
524
+ current = _record(data, client, media_id, comment_id)
525
+ current.status = "incierto" if uncertain else "bloqueado"
526
+ current.last_error = str(exc)
527
+ current.updated_at = now_utc().isoformat()
528
+ current.journal.append({"at": current.updated_at, "event": "sanitized_apply_error"})
529
+ inbox_store.save(data)
530
+ raise
531
+ with inbox_store.lock():
532
+ data = inbox_store.load()
533
+ current = _record(data, client, media_id, comment_id)
534
+ current.response_id = change.remote_id
535
+ current.status = "respondido" if change.status == "verified" else (
536
+ "incierto" if change.status in {"applying", "uncertain", "applied_unverified"} else "bloqueado")
537
+ current.last_error = None if current.status == "respondido" else f"changeset:{change.status}"
538
+ current.updated_at = now_utc().isoformat()
539
+ current.journal.append({"at": current.updated_at, "event": "reply_result",
540
+ "changeset_status": change.status, "response_id": change.remote_id})
541
+ inbox_store.save(data)
542
+ return current
543
+
544
+
545
+ def reconcile_inbox_draft(client: MetaCommentsClient, comment_store: CommentStore,
546
+ inbox_store: CommentInboxStore, *, media_id: str, comment_id: str):
547
+ with inbox_store.lock():
548
+ data = inbox_store.load()
549
+ record = _record(data, client, media_id, comment_id)
550
+ if not record.change_id:
551
+ raise CommentError("comment has no ChangeSet to reconcile")
552
+ change_id = record.change_id
553
+ change = reconcile_comment(client, comment_store, change_id)
554
+ with inbox_store.lock():
555
+ data = inbox_store.load()
556
+ current = _record(data, client, media_id, comment_id)
557
+ current.response_id = change.remote_id
558
+ current.status = "respondido" if change.status == "verified" else (
559
+ "incierto" if change.status in {"applying", "uncertain", "applied_unverified"} else "bloqueado")
560
+ current.last_error = None if current.status == "respondido" else f"changeset:{change.status}"
561
+ current.updated_at = now_utc().isoformat()
562
+ current.journal.append({"at": current.updated_at, "event": "read_only_reconciliation",
563
+ "changeset_status": change.status})
564
+ inbox_store.save(data)
565
+ return current