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,227 @@
1
+ """Bounded CLI commands for inspection and metadata ChangeSets."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import difflib
6
+ import json
7
+ from pathlib import Path
8
+
9
+ import httpx
10
+ import typer
11
+
12
+ from socialctl.approval_cli import read_approval
13
+
14
+ from socialctl.brands import (
15
+ AccountsInvalido,
16
+ Brand,
17
+ BrandNoEncontrada,
18
+ NombreDeMarcaInvalido,
19
+ cargar_brand,
20
+ )
21
+ from socialctl.management.changes import (
22
+ ChangeError,
23
+ ChangeSet,
24
+ ChangeStore,
25
+ apply_youtube_change,
26
+ load_edit_file,
27
+ prepare_youtube_change,
28
+ )
29
+ from socialctl.management.youtube import YouTubeManagementClient, YouTubeManagementError
30
+ from socialctl.management.batches import BatchStore
31
+ from socialctl.management.batch_cli import apply_selected, register
32
+
33
+ from socialctl.workspace import default_root
34
+
35
+ DEFAULT_ROOT = default_root()
36
+
37
+ content_app = typer.Typer(help="Inspect and prepare changes to existing content.")
38
+ changes_app = typer.Typer(help="Inspect and apply previously prepared ChangeSets.")
39
+
40
+
41
+ def make_http_client() -> httpx.Client:
42
+ """Small construction hook for testing CLI without live network."""
43
+ return httpx.Client(timeout=30.0)
44
+
45
+
46
+ def _fail(message: str) -> None:
47
+ typer.echo(message)
48
+ raise typer.Exit(1)
49
+
50
+
51
+ def _brand(root: Path, name: str) -> Brand:
52
+ try:
53
+ return cargar_brand(root, name)
54
+ except (BrandNoEncontrada, NombreDeMarcaInvalido, AccountsInvalido) as exc:
55
+ _fail(str(exc))
56
+
57
+
58
+ def _json(data: object) -> str:
59
+ return json.dumps(data, indent=2, ensure_ascii=False, sort_keys=True)
60
+
61
+
62
+ def render_change_preview(change: ChangeSet) -> str:
63
+ """Display complete final snippet and exact diff before approval."""
64
+ before = _json(change.before).splitlines()
65
+ after = _json(change.after).splitlines()
66
+ diff = "\n".join(
67
+ difflib.unified_diff(
68
+ before,
69
+ after,
70
+ fromfile="current snippet",
71
+ tofile="proposed snippet",
72
+ lineterm="",
73
+ )
74
+ ) or "(no differences)"
75
+ return (
76
+ f"ChangeSet: {change.id}\n"
77
+ f"Target brand/channel: {change.target_account}\n"
78
+ f"Video: {change.video_id}\n"
79
+ f"Exact fingerprint for approval: {change.fingerprint}\n\n"
80
+ f"Complete proposed snippet:\n{_json(change.after)}\n\n"
81
+ f"Diff:\n{diff}\n\n"
82
+ "V1 limitations: one video, snippet only. Batches and other parts use content edit-batch. "
83
+ "Restoration proposes a new change with changes restore --dry-run."
84
+ )
85
+
86
+
87
+ @content_app.command("show")
88
+ def content_show(
89
+ video_id: str = typer.Argument(..., help="Remote YouTube video ID."),
90
+ brand: str = typer.Option(
91
+ ..., "--brand", help="Owning brand; never inferred."
92
+ ),
93
+ root: Path = typer.Option(DEFAULT_ROOT, "--root", help="Social project root."),
94
+ ) -> None:
95
+ """Display remote snippet after verifying authenticated channel and ownership."""
96
+ selected = _brand(root, brand)
97
+ try:
98
+ with make_http_client() as client:
99
+ inspected = YouTubeManagementClient(selected, client).inspect(video_id)
100
+ except (YouTubeManagementError, OSError) as exc:
101
+ _fail(str(exc))
102
+ typer.echo(
103
+ _json(
104
+ {
105
+ "platform": "youtube",
106
+ "video_id": inspected.video_id,
107
+ "channel_id": inspected.channel_id,
108
+ "etag": inspected.etag,
109
+ "snippet": inspected.snippet,
110
+ }
111
+ )
112
+ )
113
+
114
+
115
+ @content_app.command("edit")
116
+ def content_edit(
117
+ file: Path = typer.Option(
118
+ ..., "--file", help="Version 1 YAML with video_id and patch."
119
+ ),
120
+ brand: str = typer.Option(
121
+ ..., "--brand", help="Owning brand; never inferred."
122
+ ),
123
+ root: Path = typer.Option(DEFAULT_ROOT, "--root", help="Social project root."),
124
+ dry_run: bool = typer.Option(
125
+ False, "--dry-run", help="Display proposal; never write to YouTube."
126
+ ),
127
+ ) -> None:
128
+ """Prepare immutable local proposal for exactly one video."""
129
+ selected = _brand(root, brand)
130
+ try:
131
+ edit = load_edit_file(file)
132
+ with make_http_client() as client:
133
+ change = prepare_youtube_change(
134
+ YouTubeManagementClient(selected, client), ChangeStore(selected.raiz), edit
135
+ )
136
+ except (ChangeError, YouTubeManagementError, OSError) as exc:
137
+ _fail(str(exc))
138
+ if dry_run:
139
+ typer.echo("Remote DRY-RUN: no YouTube writes performed.")
140
+ else:
141
+ typer.echo("Proposal prepared: this command does not write to YouTube.")
142
+ typer.echo(render_change_preview(change))
143
+
144
+
145
+ @changes_app.command("status")
146
+ def changes_status(
147
+ change_id: str = typer.Argument(..., help="ChangeSet UUID."),
148
+ brand: str = typer.Option(
149
+ ..., "--brand", help="Owning brand; never inferred."
150
+ ),
151
+ root: Path = typer.Option(DEFAULT_ROOT, "--root", help="Social project root."),
152
+ ) -> None:
153
+ """Display complete local proposal, state and journal."""
154
+ selected = _brand(root, brand)
155
+ try:
156
+ batch_store = BatchStore(selected.raiz)
157
+ store = batch_store if batch_store.path_for(change_id).exists() else ChangeStore(selected.raiz)
158
+ change = store.load(change_id)
159
+ except ChangeError as exc:
160
+ _fail(str(exc))
161
+ typer.echo(_json(change.model_dump(mode="json")))
162
+
163
+
164
+ @changes_app.command("apply")
165
+ def changes_apply(
166
+ change_id: str = typer.Argument(..., help="ChangeSet UUID."),
167
+ brand: str = typer.Option(
168
+ ..., "--brand", help="Owning brand; never inferred."
169
+ ),
170
+ root: Path = typer.Option(DEFAULT_ROOT, "--root", help="Social project root."),
171
+ yes: bool = typer.Option(
172
+ False, "--yes", help="Does not replace exact fingerprint approval."
173
+ ),
174
+ approval_fingerprint: str | None = typer.Option(None, "--approval-fingerprint", "--approval", "--approval-digest", help="Exact fingerprint from the approved complete preview."),
175
+ approval_stdin: bool = typer.Option(False, "--approval-stdin", help="Explicitly read one approval line from stdin."),
176
+ ) -> None:
177
+ """Apply snippet after entering exact displayed fingerprint."""
178
+ selected = _brand(root, brand)
179
+ store = ChangeStore(selected.raiz)
180
+ try:
181
+ if BatchStore(selected.raiz).path_for(change_id).exists():
182
+ apply_selected(selected, change_id, yes, approval_fingerprint, approval_stdin=approval_stdin)
183
+ return
184
+ change = store.load(change_id)
185
+ except (ChangeError, YouTubeManagementError, OSError) as exc:
186
+ _fail(str(exc))
187
+ typer.echo(render_change_preview(change))
188
+ if yes:
189
+ typer.echo("NOTICE: --yes does not replace exact approval of this ChangeSet.")
190
+ try:
191
+ approval = read_approval(approval_fingerprint, approval_stdin=approval_stdin)
192
+ except ValueError as exc:
193
+ _fail(str(exc))
194
+ except (EOFError, KeyboardInterrupt):
195
+ _fail("Application cancelled: exact approval was not received.")
196
+ if approval != change.fingerprint:
197
+ _fail("Application cancelled: approval does not match exact fingerprint.")
198
+
199
+ try:
200
+ with make_http_client() as client:
201
+ result = apply_youtube_change(
202
+ YouTubeManagementClient(selected, client), store, change_id, approval
203
+ )
204
+ except (ChangeError, YouTubeManagementError, OSError) as exc:
205
+ _fail(str(exc))
206
+ typer.echo(
207
+ f"ChangeSet {result.id} applied and verified by reread. Status: {result.status}."
208
+ )
209
+
210
+
211
+ register(content_app, changes_app, DEFAULT_ROOT)
212
+
213
+ from socialctl.management.resource_cli import register as register_resources
214
+
215
+ register_resources(content_app, DEFAULT_ROOT)
216
+
217
+ from socialctl.management.owned_cli import register as register_owned
218
+
219
+ register_owned(content_app, DEFAULT_ROOT)
220
+
221
+ from socialctl.management.community_cli import register as register_community
222
+
223
+ register_community(content_app, DEFAULT_ROOT)
224
+
225
+ from socialctl.metricas.analytics_cli import register as register_analytics
226
+
227
+ register_analytics(content_app, DEFAULT_ROOT)
@@ -0,0 +1,352 @@
1
+ """Bounded Meta comments commands: owned media, complete previews, exact approval."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ from pathlib import Path
6
+
7
+ import httpx
8
+ import typer
9
+
10
+ from socialctl.approval_cli import read_approval
11
+
12
+ from socialctl.read_budget import active_read_budget, bounded_read, read_client
13
+
14
+ from socialctl.management.cli import DEFAULT_ROOT, _brand, _fail
15
+ from socialctl.management.changes import ChangeError
16
+ from socialctl.management.meta_comments import (
17
+ CommentStore, MetaCommentsClient, apply_comment, prepare_comment, reconcile_comment,
18
+ )
19
+ from socialctl.management.meta_comment_inbox import (
20
+ CommentInboxStore,
21
+ apply_inbox_draft,
22
+ grouped_inbox,
23
+ prepare_inbox_draft,
24
+ reconcile_inbox_draft,
25
+ sync_inbox,
26
+ )
27
+ from socialctl.models import Platform
28
+ from socialctl.publication_steps import PublicationStore, retry_first_comment
29
+ from socialctl.operation_output import OperationOutput
30
+
31
+ comments_app = typer.Typer(help="Durable Facebook/Instagram comments on owned media; Instagram does not allow text editing.")
32
+
33
+
34
+ def make_http_client():
35
+ budget = active_read_budget.get()
36
+ if budget is not None:
37
+ return read_client(budget, progress=lambda: typer.echo('Reading provider data...', err=True))
38
+ from socialctl.read_budget import ReadBudget
39
+ return read_client(ReadBudget(120))
40
+
41
+
42
+ def _json(value):
43
+ return json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True)
44
+
45
+
46
+ def render_comment_preview(change):
47
+ return ("COMPLETE PREVIEW — standalone comment\n" + _json(change.model_dump(mode="json")) +
48
+ "\nMedia is not modified. Creation does not prove the link is clickable or the comment is pinned."
49
+ "\nDelete explicitly removes owned comment; an empty read does not prove absence."
50
+ f"\nExact fingerprint for approval: {change.fingerprint}")
51
+
52
+
53
+ def _inbox_record(selected, platform: Platform, media_id: str, comment_id: str):
54
+ if platform not in {Platform.FACEBOOK, Platform.INSTAGRAM}:
55
+ raise ChangeError("inbox supports only Facebook and Instagram")
56
+ account_key = "page_id" if platform is Platform.FACEBOOK else "ig_user_id"
57
+ account_id = (selected.cuentas.get(platform.value) or {}).get(account_key)
58
+ rows = [row for row in CommentInboxStore(selected.raiz).load().comments
59
+ if (row.platform, row.account_id, row.media_id, row.comment_id) ==
60
+ (platform.value, account_id, media_id, comment_id)]
61
+ if len(rows) != 1:
62
+ raise ChangeError("comment was not unambiguously observed in inbox")
63
+ return rows[0]
64
+
65
+
66
+ def _inbox_record_for_change(selected, change):
67
+ data = CommentInboxStore(selected.raiz).load()
68
+ binding = change.inbox_binding
69
+ if binding:
70
+ rows = [row for row in data.comments
71
+ if (row.platform, row.account_id, row.media_id, row.comment_id) ==
72
+ (binding.get("platform"), binding.get("account_id"),
73
+ binding.get("media_id"), binding.get("comment_id"))]
74
+ if len(rows) != 1:
75
+ raise ChangeError("durable ChangeSet link to inbox mismatch")
76
+ if rows[0].change_id != change.id:
77
+ raise ChangeError(
78
+ "this inbox draft was replaced by another ChangeSet; cannot be applied")
79
+ if rows[0].idempotency_key != binding.get("idempotency_key"):
80
+ raise ChangeError("durable ChangeSet link to inbox mismatch")
81
+ return rows[0]
82
+ # Compatibility for inbox drafts created before the binding was embedded in
83
+ # the ChangeSet: both the current pointer and immutable preparation events
84
+ # keep superseded drafts out of the legacy apply/reconcile path.
85
+ rows = [row for row in data.comments if row.change_id == change.id or
86
+ change.id in row.draft_change_ids or any(
87
+ event.get("event") == "explicit_draft_prepared" and
88
+ event.get("change_id") == change.id for event in row.journal)]
89
+ if len(rows) > 1:
90
+ raise ChangeError("ChangeSet duplicated in inbox")
91
+ return rows[0] if rows else None
92
+
93
+
94
+ def render_draft_preview(record, change):
95
+ return ("COMPLETE PREVIEW — reply to an observed comment\n"
96
+ + _json({"source_comment": record.model_dump(mode="json"),
97
+ "changeset": change.model_dump(mode="json")})
98
+ + "\nNo reply without exact approval. An uncertain outcome blocks another POST."
99
+ + f"\nExact fingerprint for approval: {change.fingerprint}")
100
+
101
+
102
+ @comments_app.command("list")
103
+ def list_comments(media_id: str, platform: Platform = typer.Option(..., "--platform"),
104
+ brand: str = typer.Option(..., "--brand"), root: Path = typer.Option(DEFAULT_ROOT, "--root"),
105
+ parent_id: str | None = typer.Option(None, "--parent-id"),
106
+ include_moderation: bool = typer.Option(False, "--include-moderation", help="Include hidden status when exposed by provider."), timeout: float = typer.Option(120, "--timeout"), json_output: bool = typer.Option(False, "--json", help="Explicit JSON mode (already the default).")):
107
+ """Read paginated comments with account and ownership checks; does not prove absence."""
108
+ from socialctl.read_reports import load_read_brand, annotate_partial_read
109
+ selected = load_read_brand(root, brand) if json_output else _brand(root, brand)
110
+ try:
111
+ with bounded_read(timeout), make_http_client() as http:
112
+ result = MetaCommentsClient(selected, platform, http).list_comments(
113
+ media_id, parent_id=parent_id, include_moderation=include_moderation)
114
+ except (ChangeError, OSError, ValueError, httpx.HTTPError) as exc:
115
+ from socialctl.read_reports import fail_read
116
+ fail_read(exc, json_output=json_output)
117
+ typer.echo(_json(annotate_partial_read(result)))
118
+ if json_output and result.get("complete") is False:
119
+ raise typer.Exit(1)
120
+
121
+
122
+ @comments_app.command("show")
123
+ def show_comment(media_id: str, comment_id: str, platform: Platform = typer.Option(..., "--platform"),
124
+ brand: str = typer.Option(..., "--brand"), root: Path = typer.Option(DEFAULT_ROOT, "--root"),
125
+ parent_id: str | None = typer.Option(None, "--parent-id"), timeout: float = typer.Option(120, "--timeout"), json_output: bool = typer.Option(False, "--json", help="Explicit JSON mode (already the default).")):
126
+ """Verify comment ID and membership in owned media or parent."""
127
+ from socialctl.read_reports import load_read_brand, annotate_partial_read
128
+ selected = load_read_brand(root, brand) if json_output else _brand(root, brand)
129
+ try:
130
+ with bounded_read(timeout), make_http_client() as http:
131
+ result = MetaCommentsClient(selected, platform, http).find_comment(media_id, comment_id, parent_id=parent_id)
132
+ except (ChangeError, OSError, ValueError, httpx.HTTPError) as exc:
133
+ from socialctl.read_reports import fail_read
134
+ fail_read(exc, json_output=json_output)
135
+ typer.echo(_json(annotate_partial_read(result)))
136
+ if json_output and result.get("complete") is False:
137
+ raise typer.Exit(1)
138
+
139
+
140
+ @comments_app.command("sync")
141
+ def sync(media_id: str, platform: Platform = typer.Option(..., "--platform"),
142
+ brand: str = typer.Option(..., "--brand"), root: Path = typer.Option(DEFAULT_ROOT, "--root"),
143
+ since: str | None = typer.Option(None, "--since", help="Initial RFC3339 timestamp; subsequent reads reuse durable time cursor."),
144
+ max_pages: int = typer.Option(100, "--max-pages", min=1, max=100), timeout: float = typer.Option(120, "--timeout"), json_output: bool = typer.Option(False, "--json", help="Explicit JSON mode (already the default).")):
145
+ """Read new comments, deduplicate IDs and update inbox without replying."""
146
+ from socialctl.read_reports import load_read_brand, annotate_partial_read
147
+ selected = load_read_brand(root, brand) if json_output else _brand(root, brand)
148
+ try:
149
+ with bounded_read(timeout), make_http_client() as http:
150
+ result = sync_inbox(MetaCommentsClient(selected, platform, http),
151
+ CommentInboxStore(selected.raiz), media_id=media_id, since=since,
152
+ max_pages=max_pages)
153
+ except (ChangeError, OSError, ValueError, httpx.HTTPError) as exc:
154
+ from socialctl.read_reports import fail_read
155
+ fail_read(exc, json_output=json_output)
156
+ typer.echo(_json(annotate_partial_read(result)))
157
+ if json_output and result.get("complete") is False:
158
+ raise typer.Exit(1)
159
+
160
+
161
+ @comments_app.command("inbox")
162
+ def inbox(brand: str = typer.Option(..., "--brand"), root: Path = typer.Option(DEFAULT_ROOT, "--root"),
163
+ platform: Platform | None = typer.Option(None, "--platform"),
164
+ media_id: str | None = typer.Option(None, "--media-id"), json_output: bool = typer.Option(False, "--json", help="Explicit JSON mode (already the default).")):
165
+ """Display inbox grouped by item, author, language and type without accessing Meta."""
166
+ from socialctl.read_reports import load_read_brand, fail_read, ReadReport, emit_report
167
+ selected = load_read_brand(root, brand) if json_output else _brand(root, brand)
168
+ if platform not in {None, Platform.FACEBOOK, Platform.INSTAGRAM}:
169
+ if json_output:
170
+ emit_report(ReadReport(status='error', errors=[{'code':'unsupported_operation'}]))
171
+ raise typer.Exit(1)
172
+ _fail("inbox supports only Facebook and Instagram")
173
+ try:
174
+ data = CommentInboxStore(selected.raiz).load()
175
+ except (ChangeError, OSError, ValueError) as exc:
176
+ fail_read(exc, json_output=json_output)
177
+ typer.echo(_json({"version": data.version,
178
+ "groups": grouped_inbox(data, platform=platform.value if platform else None, media_id=media_id),
179
+ "cursors": [row.model_dump(mode="json") for row in data.cursors
180
+ if (not platform or row.platform == platform.value) and
181
+ (not media_id or row.media_id == media_id)]}))
182
+
183
+
184
+ @comments_app.command("draft")
185
+ def draft(media_id: str, comment_id: str, platform: Platform = typer.Option(..., "--platform"),
186
+ text: str = typer.Option(..., "--text", help="Supplied literal reply; not AI-generated."),
187
+ brand: str = typer.Option(..., "--brand"), root: Path = typer.Option(DEFAULT_ROOT, "--root"),
188
+ dry_run: bool = typer.Option(False, "--dry-run", help="Compatibility: preparation is always local only.")):
189
+ """Prepare explicit draft and ChangeSet without POSTs."""
190
+ selected = _brand(root, brand)
191
+ try:
192
+ with make_http_client() as http:
193
+ change, record = prepare_inbox_draft(MetaCommentsClient(selected, platform, http),
194
+ CommentStore(selected.raiz), CommentInboxStore(selected.raiz),
195
+ media_id=media_id, comment_id=comment_id, text=text)
196
+ except (ChangeError, OSError, ValueError) as exc:
197
+ _fail(str(exc))
198
+ typer.echo("Remote DRY-RUN: local draft and ChangeSet; no Meta writes.")
199
+ typer.echo(render_draft_preview(record, change))
200
+
201
+
202
+ @comments_app.command("apply-draft")
203
+ def apply_draft(media_id: str, comment_id: str,
204
+ platform: Platform = typer.Option(..., "--platform"),
205
+ brand: str = typer.Option(..., "--brand"), root: Path = typer.Option(DEFAULT_ROOT, "--root"),
206
+ max_replies: int = typer.Option(10, "--max-replies", min=1,
207
+ help="Maximum reply intentions within window and account."),
208
+ window_seconds: int = typer.Option(3600, "--window-seconds", min=1),
209
+ json_output: bool = typer.Option(False, "--json", help="JSON result; full preview and exact approval prompt on stderr."),
210
+ approval_fingerprint: str | None = typer.Option(None, "--approval-fingerprint", "--approval", "--approval-digest", help="Exact fingerprint from the approved complete preview."),
211
+ approval_stdin: bool = typer.Option(False, "--approval-stdin", help="Explicitly read one approval line from stdin.")):
212
+ """Display preview and apply only after entering exact fingerprint."""
213
+ with OperationOutput(json_output) as output:
214
+ selected = output.brand(root, brand)
215
+ record = _inbox_record(selected, platform, media_id, comment_id)
216
+ if not record.change_id:
217
+ raise ChangeError("comment has no draft")
218
+ change = CommentStore(selected.raiz).load(record.change_id)
219
+ digest = output.approve(change, render_draft_preview(record, change), approval_fingerprint, approval_stdin=approval_stdin)
220
+ with make_http_client() as http:
221
+ client = MetaCommentsClient(selected, platform, http)
222
+ output.begin_write()
223
+ result = apply_inbox_draft(client,
224
+ CommentStore(selected.raiz), CommentInboxStore(selected.raiz),
225
+ media_id=media_id, comment_id=comment_id, approval_digest=digest,
226
+ max_replies=max_replies, window_seconds=window_seconds)
227
+ output.emit(result)
228
+ if result.status != "respondido":
229
+ raise typer.Exit(1)
230
+
231
+
232
+ @comments_app.command("reconcile-draft")
233
+ def reconcile_draft(media_id: str, comment_id: str,
234
+ platform: Platform = typer.Option(..., "--platform"),
235
+ brand: str = typer.Option(..., "--brand"),
236
+ root: Path = typer.Option(DEFAULT_ROOT, "--root"),
237
+ json_output: bool = typer.Option(False, "--json", help="JSON result with recovery action; no remote writes.")):
238
+ """GET only: reconcile uncertain outcome and never repeat POST."""
239
+ with OperationOutput(json_output, read_only=True) as output:
240
+ selected = output.brand(root, brand)
241
+ record = _inbox_record(selected, platform, media_id, comment_id)
242
+ output.change_id = record.change_id
243
+ with make_http_client() as http:
244
+ result = reconcile_inbox_draft(MetaCommentsClient(selected, platform, http),
245
+ CommentStore(selected.raiz), CommentInboxStore(selected.raiz),
246
+ media_id=media_id, comment_id=comment_id)
247
+ output.emit(result)
248
+ if result.status != "respondido":
249
+ raise typer.Exit(1)
250
+
251
+
252
+ @comments_app.command("prepare")
253
+ def prepare(media_id: str, platform: Platform = typer.Option(..., "--platform"),
254
+ brand: str = typer.Option(..., "--brand"), root: Path = typer.Option(DEFAULT_ROOT, "--root"),
255
+ action: str = typer.Option("add", "--action", help="add, reply, edit (Facebook only) or delete (own author)."),
256
+ text: str | None = typer.Option(None, "--text", help="Exact user-supplied text; no copy generated."),
257
+ parent_id: str | None = typer.Option(None, "--parent-id"),
258
+ comment_id: str | None = typer.Option(None, "--comment-id"),
259
+ dry_run: bool = typer.Option(False, "--dry-run", help="Only prepare and display ChangeSet; no Meta writes.")):
260
+ """Prepare add/reply/edit/delete without remote writes and display full proposal."""
261
+ selected = _brand(root, brand)
262
+ try:
263
+ with make_http_client() as http:
264
+ change = prepare_comment(MetaCommentsClient(selected, platform, http), CommentStore(selected.raiz),
265
+ media_id=media_id, text=text, action=action, parent_id=parent_id, comment_id=comment_id)
266
+ except (ChangeError, OSError, ValueError) as exc:
267
+ _fail(str(exc))
268
+ typer.echo("Remote DRY-RUN: local proposal; no Meta writes.")
269
+ typer.echo(render_comment_preview(change))
270
+
271
+
272
+ @comments_app.command("status")
273
+ def status(change_id: str, brand: str = typer.Option(..., "--brand"),
274
+ root: Path = typer.Option(DEFAULT_ROOT, "--root"), json_output: bool = typer.Option(False, "--json", help="Explicit JSON mode (already the default).")):
275
+ """Display complete ChangeSet and journal without accessing Meta."""
276
+ with OperationOutput(json_output, read_only=True) as output:
277
+ selected = output.brand(root, brand)
278
+ change = CommentStore(selected.raiz).load(change_id)
279
+ output.emit(change)
280
+
281
+
282
+ @comments_app.command("apply")
283
+ def apply(change_id: str, brand: str = typer.Option(..., "--brand"),
284
+ root: Path = typer.Option(DEFAULT_ROOT, "--root"),
285
+ json_output: bool = typer.Option(False, "--json", help="JSON result; full preview and exact approval prompt on stderr."),
286
+ approval_fingerprint: str | None = typer.Option(None, "--approval-fingerprint", "--approval", "--approval-digest", help="Exact fingerprint from the approved complete preview."),
287
+ approval_stdin: bool = typer.Option(False, "--approval-stdin", help="Explicitly read one approval line from stdin.")):
288
+ """Display full preview and require exact fingerprint entry; uncertain POST is never repeated."""
289
+ with OperationOutput(json_output) as output:
290
+ selected = output.brand(root, brand)
291
+ store = CommentStore(selected.raiz)
292
+ change = store.load(change_id)
293
+ output.change_id = change.id
294
+ if _inbox_record_for_change(selected, change):
295
+ raise ChangeError("this ChangeSet belongs to inbox; use comments apply-draft to preserve state and frequency")
296
+ digest = output.approve(change, render_comment_preview(change), approval_fingerprint, approval_stdin=approval_stdin)
297
+ with make_http_client() as http:
298
+ client = MetaCommentsClient(selected, Platform(change.platform), http)
299
+ output.begin_write()
300
+ result = apply_comment(client, store, change_id, digest)
301
+ output.emit(result)
302
+ if result.status != "verified":
303
+ raise typer.Exit(1)
304
+
305
+
306
+ @comments_app.command("reconcile")
307
+ def reconcile(change_id: str, brand: str = typer.Option(..., "--brand"),
308
+ root: Path = typer.Option(DEFAULT_ROOT, "--root"),
309
+ json_output: bool = typer.Option(False, "--json", help="JSON result with recovery action; no remote writes.")):
310
+ """Remote GET only: identical candidates do not prove creation; never POST."""
311
+ with OperationOutput(json_output, read_only=True) as output:
312
+ selected = output.brand(root, brand)
313
+ store = CommentStore(selected.raiz)
314
+ change = store.load(change_id)
315
+ output.change_id = change.id
316
+ if _inbox_record_for_change(selected, change):
317
+ raise ChangeError("this ChangeSet belongs to inbox; use comments reconcile-draft")
318
+ with make_http_client() as http:
319
+ result = reconcile_comment(MetaCommentsClient(selected, Platform(change.platform), http), store, change_id)
320
+ output.emit(result)
321
+
322
+
323
+ @comments_app.command("publication-status")
324
+ def publication_status(publication_id: str, brand: str = typer.Option(..., "--brand"),
325
+ root: Path = typer.Option(DEFAULT_ROOT, "--root"), json_output: bool = typer.Option(False, "--json", help="Explicit JSON mode (already the default).")):
326
+ """Read durable attempt containing confirmed media, approved text and comment ChangeSet."""
327
+ selected = _brand(root, brand)
328
+ try:
329
+ result = PublicationStore(selected.raiz).load(publication_id)
330
+ except ChangeError as exc:
331
+ _fail(str(exc))
332
+ typer.echo(_json(result))
333
+
334
+
335
+ @comments_app.command("retry-first")
336
+ def retry_first(publication_id: str, brand: str = typer.Option(..., "--brand"),
337
+ root: Path = typer.Option(DEFAULT_ROOT, "--root"),
338
+ dry_run: bool = typer.Option(False, "--dry-run")):
339
+ """Resume only originally approved comment; never upload media or repeat uncertain POSTs."""
340
+ selected = _brand(root, brand)
341
+ try:
342
+ data = PublicationStore(selected.raiz).load(publication_id)
343
+ typer.echo("First comment: approval inherited from complete original attempt:\n" + _json(data))
344
+ if dry_run:
345
+ return
346
+ with make_http_client() as http:
347
+ result = retry_first_comment(selected, http, publication_id)
348
+ except (ChangeError, OSError, ValueError) as exc:
349
+ _fail(str(exc))
350
+ typer.echo(_json(result.model_dump(mode="json")))
351
+ if result.first_comment_status not in {None, "verified"}:
352
+ raise typer.Exit(1)
@@ -0,0 +1,63 @@
1
+ """One exact digest approves only the displayed immutable community batch."""
2
+ from pathlib import Path
3
+ import json
4
+ import typer
5
+ import yaml
6
+ from socialctl.management.changes import ChangeError
7
+ from socialctl.operation_output import OperationOutput
8
+ from socialctl.management.community_batches import (prepare_community_batch,apply_community_batch,
9
+ reconcile_community_batch,CommunityBatchStore,validate_batch,batch_document)
10
+
11
+
12
+ def progress(event):
13
+ typer.echo(f"Batch child {event['child_index']}/{event['total']} {event['platform']} {event['change_id']}: {event['status']}", err=True)
14
+
15
+
16
+ def emit(batch,brand=None):
17
+ typer.echo(json.dumps(batch_document(batch,brand=brand), ensure_ascii=False, indent=2, sort_keys=True))
18
+
19
+
20
+ def preview(batch):
21
+ return 'DRY-RUN — FULL COMMUNITY BATCH PREVIEW\n'+batch.model_dump_json(indent=2)+'\nEvery displayed child effect requires exact approval. No rollback is promised.\nExact batch fingerprint: '+batch.fingerprint
22
+
23
+
24
+ def register(changes_app,default_root):
25
+ @changes_app.command('prepare-batch')
26
+ def prepare(file:Path=typer.Option(...,'--file'),brand:str=typer.Option(...,'--brand'),root:Path=typer.Option(default_root,'--root'),dry_run:bool=typer.Option(False,'--dry-run'),json_output:bool=typer.Option(False,'--json')):
27
+ with OperationOutput(json_output) as output:
28
+ selected=output.brand(root,brand)
29
+ raw=yaml.safe_load(file.read_text())
30
+ if not isinstance(raw,dict) or set(raw)!={'version','children'} or type(raw['version']) is not int or raw['version']!=1:
31
+ raise ChangeError('expected version 1 and explicit children')
32
+ batch=prepare_community_batch(selected,raw['children'])
33
+ typer.echo(preview(batch),err=json_output)
34
+ if json_output:emit(batch,selected)
35
+
36
+ @changes_app.command('apply-batch')
37
+ def apply(batch_id:str,approval:str|None=typer.Option(None,'--approval-fingerprint','--approval','--approval-digest'),approval_stdin:bool=typer.Option(False,'--approval-stdin'),brand:str=typer.Option(...,'--brand'),root:Path=typer.Option(default_root,'--root'),json_output:bool=typer.Option(False,'--json')):
38
+ with OperationOutput(json_output) as output:
39
+ selected=output.brand(root,brand)
40
+ batch=CommunityBatchStore(selected.raiz).load(batch_id)
41
+ validate_batch(selected,batch)
42
+ approved=output.approve(batch,preview(batch),approval,approval_stdin=approval_stdin)
43
+ output.begin_write()
44
+ result=apply_community_batch(selected,batch_id,approved,progress=progress)
45
+ emit(result,selected)
46
+ if result.status!='verified':raise typer.Exit(1)
47
+
48
+ @changes_app.command('reconcile-batch')
49
+ def reconcile(batch_id:str,brand:str=typer.Option(...,'--brand'),root:Path=typer.Option(default_root,'--root'),json_output:bool=typer.Option(False,'--json')):
50
+ with OperationOutput(json_output,read_only=True) as output:
51
+ selected=output.brand(root,brand)
52
+ output.change_id=CommunityBatchStore(selected.raiz).load(batch_id).id
53
+ result=reconcile_community_batch(selected,batch_id,progress=progress)
54
+ emit(result,selected)
55
+ if result.status!='verified':raise typer.Exit(1)
56
+
57
+ @changes_app.command('status-batch')
58
+ def status(batch_id:str,brand:str=typer.Option(...,'--brand'),root:Path=typer.Option(default_root,'--root'),json_output:bool=typer.Option(False,'--json')):
59
+ with OperationOutput(json_output,read_only=True) as output:
60
+ selected=output.brand(root,brand)
61
+ result=CommunityBatchStore(selected.raiz).load(batch_id)
62
+ validate_batch(selected,result)
63
+ emit(result,selected)