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,325 @@
1
+ """Ordered immutable proposals with independent, durable per-video outcomes."""
2
+ from __future__ import annotations
3
+
4
+ import copy
5
+ import hashlib
6
+ import hmac
7
+ import json
8
+ import uuid
9
+ from datetime import datetime, timezone
10
+ from pathlib import Path
11
+ from typing import Any, Literal
12
+
13
+ import yaml
14
+ from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator
15
+
16
+ from socialctl.management.changes import ApprovalMismatch, ChangeError, ChangeStore, now_utc
17
+ from socialctl.management.metadata_parts import KINDS, MetadataEdit, editable_parts, propose_parts
18
+ from socialctl.management.youtube import (YouTubeManagementError, YouTubeUpdateConflict,
19
+ YouTubeUpdateRejected)
20
+ from socialctl.management.youtube_metadata import same_metadata_snapshot
21
+ from socialctl.management.snippet_readback import snippet_mismatch_fields
22
+
23
+
24
+ class BatchFile(BaseModel):
25
+ model_config = ConfigDict(extra="forbid", strict=True)
26
+ version: Literal[2]
27
+ platform: Literal["youtube"]
28
+ operations: list[MetadataEdit] = Field(min_length=1)
29
+
30
+ @model_validator(mode="after")
31
+ def unique_videos(self):
32
+ ids = [edit.video_id for edit in self.operations]
33
+ if len(ids) != len(set(ids)):
34
+ raise ChangeError("duplicate video_id: one operation per video and proposal")
35
+ return self
36
+
37
+
38
+ class Operation(BaseModel):
39
+ model_config = ConfigDict(extra="forbid", strict=True)
40
+ id: str
41
+ video_id: str
42
+ kind: str
43
+ patch: dict[str, Any]
44
+ never_published: bool = False
45
+ observed: dict[str, Any]
46
+ before: dict[str, Any]
47
+ after: dict[str, Any]
48
+ resets: list[str] = Field(default_factory=list)
49
+ fingerprint: str = ""
50
+ status: Literal["pending", "applying", "applied", "failed", "conflict", "uncertain", "manual_review"] = "pending"
51
+ journal: list[dict[str, str]] = Field(default_factory=list)
52
+
53
+
54
+ class Batch(BaseModel):
55
+ model_config = ConfigDict(extra="forbid", strict=True)
56
+ id: str
57
+ version: Literal[2] = 2
58
+ platform: Literal["youtube"] = "youtube"
59
+ brand: str
60
+ brand_root: str
61
+ account: str
62
+ account_config: dict[str, Any]
63
+ accounts_digest: str
64
+ source_files: dict[str, str]
65
+ restored_from: str | None = None
66
+ unavailable: list[str] = Field(default_factory=list)
67
+ operations: list[Operation]
68
+ created_at: str
69
+ fingerprint: str = ""
70
+
71
+
72
+ def digest(value: Any) -> str:
73
+ return hashlib.sha256(json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
74
+
75
+
76
+ def operation_fingerprint(op: Operation) -> str:
77
+ return digest(op.model_dump(exclude={"fingerprint", "status", "journal"}))
78
+
79
+
80
+ def batch_fingerprint(batch: Batch) -> str:
81
+ payload = batch.model_dump(exclude={"fingerprint", "operations"})
82
+ payload["operations"] = [op.model_dump(exclude={"status", "journal"}) for op in batch.operations]
83
+ return digest(payload)
84
+
85
+
86
+ class BatchStore(ChangeStore):
87
+ model_type = Batch
88
+ fingerprint_for = staticmethod(batch_fingerprint)
89
+
90
+ def __init__(self, brand_root: Path):
91
+ self.root = brand_root / ".socialctl" / "metadata-batches"
92
+
93
+ def load(self, change_id: str) -> Batch:
94
+ batch = super().load(change_id)
95
+ ids = [op.video_id for op in batch.operations]
96
+ if len(ids) != len(set(ids)) or not ids:
97
+ raise ChangeError("empty or duplicate membership")
98
+ for op in batch.operations:
99
+ self._validate_id(op.id)
100
+ if not hmac.compare_digest(op.fingerprint, operation_fingerprint(op)):
101
+ raise ChangeError("operation was altered")
102
+ _edit(op)
103
+ return batch
104
+
105
+
106
+ def _file_digest(path: Path) -> str:
107
+ try:
108
+ return hashlib.sha256(path.read_bytes()).hexdigest()
109
+ except OSError:
110
+ raise ChangeError("linked file missing or unreadable; approval invalidated") from None
111
+
112
+
113
+ def _edit(op: Operation) -> MetadataEdit:
114
+ try:
115
+ return MetadataEdit(video_id=op.video_id, kind=op.kind, patch=op.patch, never_published=op.never_published)
116
+ except ValidationError as exc:
117
+ raise ChangeError(f"invalid operation: {exc}") from None
118
+
119
+
120
+ def _operation(client, edit, *, resets=None):
121
+ observed = client.inspect(edit.video_id)
122
+ before, after = propose_parts(observed, edit)
123
+ op = Operation(id=str(uuid.uuid4()), video_id=edit.video_id, kind=edit.kind,
124
+ patch=copy.deepcopy(edit.patch), never_published=edit.never_published,
125
+ observed=copy.deepcopy(observed.resource), before=before, after=after, resets=resets or [])
126
+ op.fingerprint = operation_fingerprint(op)
127
+ return op
128
+
129
+
130
+ def _batch(client, operations, source_files, *, restored_from=None, unavailable=None):
131
+ return Batch(id=str(uuid.uuid4()), brand=client.brand.nombre,
132
+ brand_root=str(client.brand.raiz.resolve()), account=client.configured_channel_id,
133
+ account_config=copy.deepcopy(client.brand.cuentas.get("youtube") or {}),
134
+ accounts_digest=_file_digest(client.brand.raiz / "accounts.yml"),
135
+ operations=operations, source_files=source_files, restored_from=restored_from,
136
+ unavailable=unavailable or [], created_at=now_utc().isoformat())
137
+
138
+
139
+ def _save_new(store, batch):
140
+ if not batch.operations:
141
+ raise ChangeError("restoration unavailable: " + "; ".join(batch.unavailable))
142
+ batch.fingerprint = batch_fingerprint(batch)
143
+ store.save(batch)
144
+ return batch
145
+
146
+
147
+ def prepare_batch(client, store: BatchStore, file: Path) -> Batch:
148
+ path = file.resolve()
149
+ fingerprint = _file_digest(path)
150
+ try:
151
+ raw = yaml.safe_load(path.read_text(encoding="utf-8"))
152
+ edits = BatchFile.model_validate(raw)
153
+ except (OSError, yaml.YAMLError, ValidationError) as exc:
154
+ raise ChangeError(f"invalid V2 file: {exc}") from None
155
+ operations = [_operation(client, edit) for edit in edits.operations]
156
+ if _file_digest(path) != fingerprint:
157
+ raise ChangeError("file modified during preview")
158
+ return _save_new(store, _batch(client, operations, {str(path): fingerprint}))
159
+
160
+
161
+ def _bound(client, batch):
162
+ if (batch.brand, batch.brand_root, batch.account, batch.accounts_digest, batch.account_config) != (
163
+ client.brand.nombre, str(client.brand.raiz.resolve()), client.configured_channel_id,
164
+ _file_digest(client.brand.raiz / "accounts.yml"), client.brand.cuentas.get("youtube") or {}):
165
+ raise ChangeError("brand/account/accounts.yml changed; approval invalidated")
166
+ for path, expected in batch.source_files.items():
167
+ if not hmac.compare_digest(_file_digest(Path(path)), expected):
168
+ raise ChangeError("source file changed; approval invalidated")
169
+
170
+
171
+ def _event(op, event, **details):
172
+ op.journal.append({"at": now_utc().isoformat(), "event": event, **details})
173
+
174
+
175
+ def _mismatch_paths(current, expected):
176
+ """Return bounded field names without raw bodies or values."""
177
+ mismatches = []
178
+ parts = editable_parts(current.resource)
179
+ for part, values in expected.items():
180
+ actual, wanted = copy.deepcopy(parts[part]), copy.deepcopy(values)
181
+ if part == "status" and "publishAt" in actual and "publishAt" in wanted:
182
+ # YouTube commonly canonicalizes an offset timestamp such as
183
+ # ``2026-09-21T18:00:00-04:00`` to the equivalent UTC ``Z`` form.
184
+ # Compare the instants, not their spelling, when reconciling a
185
+ # successful native schedule.
186
+ try:
187
+ actual["publishAt"] = datetime.fromisoformat(
188
+ actual["publishAt"].replace("Z", "+00:00")
189
+ ).astimezone(timezone.utc)
190
+ wanted["publishAt"] = datetime.fromisoformat(
191
+ wanted["publishAt"].replace("Z", "+00:00")
192
+ ).astimezone(timezone.utc)
193
+ except (AttributeError, TypeError, ValueError):
194
+ pass
195
+ if part == "snippet":
196
+ mismatches.extend(f"snippet.{field}" for field in snippet_mismatch_fields(actual, wanted))
197
+ continue
198
+ for field in sorted(set(actual) | set(wanted)):
199
+ if field not in actual or field not in wanted or actual[field] != wanted[field]:
200
+ path = f"{part}.{field}" if part in {"snippet", "status"} else part
201
+ if path not in mismatches:
202
+ mismatches.append(path)
203
+ return mismatches[:16]
204
+
205
+
206
+ def _matches(current, expected):
207
+ return not _mismatch_paths(current, expected)
208
+
209
+
210
+ def _apply_operation(client, store, batch, op):
211
+ if op.status not in {"pending", "applying", "uncertain"}:
212
+ return
213
+ try:
214
+ current = client.inspect(op.video_id)
215
+ except (YouTubeManagementError, ChangeError):
216
+ _event(op, "read_failed", error="read/ownership unverifiable; no write performed")
217
+ store.save(batch)
218
+ return
219
+ if op.status in {"applying", "uncertain"}:
220
+ mismatches = _mismatch_paths(current, op.after)
221
+ op.status = "manual_review" if mismatches else "applied"
222
+ _event(op, "reconciled_read_only", mismatch_paths=", ".join(mismatches))
223
+ store.save(batch)
224
+ return
225
+ if not same_metadata_snapshot(op.observed, current.resource, allow_etag_only=True):
226
+ op.status = "conflict"
227
+ _event(op, "observed_state_changed")
228
+ store.save(batch)
229
+ return
230
+ # Revalidate time-sensitive scheduling and the exact outgoing parts.
231
+ try:
232
+ _, after = propose_parts(current, _edit(op))
233
+ except ChangeError:
234
+ op.status = "failed"
235
+ _event(op, "proposal_no_longer_valid", error="operation conditions no longer valid; prepare another preview")
236
+ store.save(batch)
237
+ return
238
+ if after != op.after:
239
+ raise ChangeError("proposed body altered")
240
+ _bound(client, batch)
241
+ op.status = "applying"
242
+ _event(op, "write_intent", approval=batch.fingerprint, if_match=current.etag)
243
+ store.save(batch) # durable intent MUST finish before PUT
244
+ try:
245
+ def record_verified_etag(etag):
246
+ if etag != current.etag:
247
+ _event(op, "write_intent", approval=batch.fingerprint, if_match=etag)
248
+ store.save(batch)
249
+
250
+ client.update_parts(op.video_id, op.after, etag=current.etag,
251
+ expected_resource=current.resource, before_write=record_verified_etag)
252
+ except YouTubeUpdateConflict:
253
+ op.status = "conflict"
254
+ _event(op, "etag_conflict")
255
+ except YouTubeUpdateRejected as exc:
256
+ op.status = "failed"
257
+ # Only transport-produced, bounded classification is persisted. Local
258
+ # validation rejections get a fixed message, never arbitrary exception text.
259
+ diagnostic = exc.diagnostic or {"error": "Metadata validation rejected the update before PUT."}
260
+ _event(op, "write_rejected", **diagnostic)
261
+ except Exception:
262
+ op.status = "uncertain"
263
+ _event(op, "write_uncertain")
264
+ else:
265
+ try:
266
+ verified = client.inspect(op.video_id)
267
+ mismatches = _mismatch_paths(verified, op.after)
268
+ op.status = "uncertain" if mismatches else "applied"
269
+ _event(op, "read_back_" + op.status, mismatch_paths=", ".join(mismatches))
270
+ except Exception:
271
+ op.status = "uncertain"
272
+ _event(op, "read_back_unavailable")
273
+ store.save(batch)
274
+
275
+
276
+ def apply_batch(client, store: BatchStore, batch_id: str, approval_digest: str) -> Batch:
277
+ with store.apply_lock(batch_id):
278
+ batch = store.load(batch_id)
279
+ if not hmac.compare_digest(batch.fingerprint, approval_digest):
280
+ raise ApprovalMismatch("approval does not match exact batch fingerprint")
281
+ _bound(client, batch)
282
+ for op in batch.operations:
283
+ _apply_operation(client, store, batch, op)
284
+ return batch
285
+
286
+
287
+ def prepare_restore(client, store: BatchStore, original_id: str) -> Batch:
288
+ """New proposal, saved edited fields only; unavailable resets stay explicit."""
289
+ source = store.path_for(original_id)
290
+ if source.exists():
291
+ original = store.load(original_id)
292
+ if (original.brand, original.brand_root, original.account) != (
293
+ client.brand.nombre, str(client.brand.raiz.resolve()), client.configured_channel_id):
294
+ raise ChangeError("original brand/account mismatch")
295
+ rows = [(op.video_id, op.kind, op.patch, op.before) for op in original.operations]
296
+ else:
297
+ legacy_store = ChangeStore(client.brand.raiz)
298
+ original = legacy_store.load(original_id)
299
+ if original.target_account != client.configured_channel_id:
300
+ raise ChangeError("original account mismatch")
301
+ source = legacy_store.path_for(original_id)
302
+ rows = [(original.video_id, "snippet", original.patch, {"snippet": original.before})]
303
+ source_hash = _file_digest(source)
304
+ operations, unavailable = [], []
305
+ for video_id, kind, patch, before in rows:
306
+ part = KINDS[kind][0]
307
+ recovered, resets = {}, []
308
+ for field in patch:
309
+ old = before[part].get(field)
310
+ if old is not None:
311
+ if field == "publishAt":
312
+ unavailable.append(f"{video_id}.publishAt: history/date require a new schedule declaration")
313
+ else:
314
+ recovered[field] = copy.deepcopy(old)
315
+ elif part == "snippet" and field in {"tags", "description"}:
316
+ recovered[field] = [] if field == "tags" else ""
317
+ resets.append(f"{field}: {'empty list' if field == 'tags' else 'empty text'} (original absent/null)")
318
+ else:
319
+ unavailable.append(f"{video_id}.{field}: original value missing/null; reset unverified, current value preserved")
320
+ if recovered:
321
+ restored_kind = "snippet" if kind == "chapters" else "privacy" if kind == "schedule" else kind
322
+ edit = MetadataEdit(video_id=video_id, kind=restored_kind, patch=recovered)
323
+ operations.append(_operation(client, edit, resets=resets))
324
+ return _save_new(store, _batch(client, operations, {str(source): source_hash},
325
+ restored_from=original_id, unavailable=unavailable))