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,560 @@
1
+ """SQLite ledger. All writers use BEGIN IMMEDIATE, full sync, and CAS.
2
+
3
+ Constructing or reading a store never creates a directory/database. Recovery is
4
+ explicit: callers must quiesce workers before recover_dispatching; opening another
5
+ connection must not steal a live worker's claim. Uncertain jobs cannot be claimed.
6
+ """
7
+ from contextlib import contextmanager
8
+ from datetime import datetime, timedelta, timezone
9
+ import json
10
+ from pathlib import Path
11
+ import sqlite3
12
+ from uuid import uuid4
13
+
14
+ from .cadence import reservation_key, slot_day, slots_conflict, ZONE
15
+ from .inventory import validate_inventory, date, reschedule_inventory
16
+ from .models import NativeJob, NativeObservation, aware
17
+ from .verification import evidence_matches, verify
18
+
19
+ # Remote outcomes may ONLY be established via evidence, not generic transitions.
20
+ TRANSITIONS = {
21
+ 'prepared': {'approved', 'blocked', 'cancelled'},
22
+ 'approved': {'ready', 'waiting_window', 'awaiting_ui', 'blocked', 'cancelled'},
23
+ 'waiting_window': {'ready', 'awaiting_ui', 'blocked', 'cancelled'},
24
+ 'ready': {'awaiting_ui', 'blocked', 'cancelled'},
25
+ 'dispatching': {'verifying', 'awaiting_ui', 'uncertain'},
26
+ 'awaiting_ui': {'verifying', 'uncertain'},
27
+ 'verifying': {'uncertain'},
28
+ 'native_scheduled': {'uncertain'},
29
+ 'uncertain': {'verifying'},
30
+ 'blocked': {'prepared'},
31
+ }
32
+
33
+
34
+ def _now(value):
35
+ return aware(value or datetime.now(timezone.utc))
36
+
37
+
38
+ def _replace(job, **changes):
39
+ # model_copy(update=...) bypasses validation; deliberately never use it.
40
+ return NativeJob.model_validate(job.model_dump() | changes)
41
+
42
+
43
+ class NativeStore:
44
+ def __init__(self, brand_root: Path, *, brand: str):
45
+ if not brand or not brand.strip():
46
+ raise ValueError('Explicit brand required')
47
+ self.brand = brand
48
+ self.path = Path(brand_root).resolve() / 'native-schedules.sqlite3'
49
+
50
+ @contextmanager
51
+ def _db(self, *, write=False):
52
+ if not write and not self.path.exists():
53
+ yield None
54
+ return
55
+ if write:
56
+ self.path.parent.mkdir(parents=True, exist_ok=True)
57
+ db = sqlite3.connect(str(self.path) if write else self.path.as_uri() + '?mode=ro',
58
+ uri=not write, timeout=30, isolation_level=None)
59
+ db.row_factory = sqlite3.Row
60
+ try:
61
+ if write:
62
+ db.execute('PRAGMA synchronous=FULL')
63
+ db.execute('BEGIN IMMEDIATE')
64
+ version = db.execute('PRAGMA user_version').fetchone()[0]
65
+ if version not in (0, 1, 2, 3):
66
+ raise ValueError('Unsupported native ledger schema')
67
+ if version == 0:
68
+ for statement in (
69
+ 'CREATE TABLE context (brand TEXT NOT NULL)',
70
+ 'CREATE TABLE jobs (id TEXT PRIMARY KEY, legacy_entry_id TEXT, platform TEXT NOT NULL, account_id TEXT NOT NULL, day TEXT NOT NULL, data TEXT NOT NULL, payload TEXT NOT NULL, UNIQUE(legacy_entry_id,platform), UNIQUE(platform,account_id,day))',
71
+ 'CREATE TABLE attempts (id TEXT PRIMARY KEY, job_id TEXT NOT NULL REFERENCES jobs(id), approval_digest TEXT NOT NULL, started_at TEXT NOT NULL, updated_at TEXT NOT NULL, checkpoint TEXT NOT NULL)',
72
+ 'CREATE TABLE observations (id INTEGER PRIMARY KEY, job_id TEXT NOT NULL REFERENCES jobs(id), data TEXT NOT NULL, verified INTEGER NOT NULL)',
73
+ ):
74
+ db.execute(statement)
75
+ db.execute('INSERT INTO context VALUES (?)', (self.brand,))
76
+ db.execute('PRAGMA user_version=1')
77
+ if db.execute('PRAGMA user_version').fetchone()[0] not in (1, 2, 3):
78
+ raise ValueError('Unsupported native ledger schema')
79
+ if db.execute('PRAGMA user_version').fetchone()[0] in (2, 3):
80
+ for table in ('calendar_inventory','external_reservations'):
81
+ if not db.execute('SELECT 1 FROM sqlite_master WHERE type="table" AND name=?',(table,)).fetchone():
82
+ raise ValueError('Calendar reservation ledger missing; keep writers stopped and recover evidence')
83
+ if write:
84
+ db.execute('CREATE TABLE IF NOT EXISTS calendar_inventory (digest TEXT PRIMARY KEY, data TEXT NOT NULL)')
85
+ db.execute('CREATE TABLE IF NOT EXISTS external_reservations (inventory_digest TEXT NOT NULL, platform TEXT NOT NULL, account_id TEXT NOT NULL, remote_ref TEXT NOT NULL, day TEXT NOT NULL, publish_at TEXT NOT NULL, UNIQUE(inventory_digest,platform,account_id,remote_ref,day,publish_at))')
86
+ db.execute('CREATE INDEX IF NOT EXISTS external_slot ON external_reservations(platform,account_id,day)')
87
+ # Old native writers must reject this ledger rather than ignore
88
+ # the external reservations they do not know how to enforce.
89
+ if db.execute('PRAGMA user_version').fetchone()[0] < 2:
90
+ db.execute('PRAGMA user_version=2')
91
+ db.execute('CREATE TABLE IF NOT EXISTS action_events (job_id TEXT NOT NULL, data TEXT NOT NULL)')
92
+ db.execute('CREATE TABLE IF NOT EXISTS actions (job_id TEXT PRIMARY KEY, data TEXT NOT NULL)')
93
+ db.execute('CREATE TABLE IF NOT EXISTS holds (job_id TEXT PRIMARY KEY, platform TEXT NOT NULL, account_id TEXT NOT NULL, day TEXT NOT NULL, UNIQUE(platform,account_id,day))')
94
+ db.execute('CREATE TABLE IF NOT EXISTS cooldowns (job_id TEXT PRIMARY KEY, until_at TEXT NOT NULL, reason TEXT NOT NULL)')
95
+ db.execute('CREATE TABLE IF NOT EXISTS notices (job_id TEXT NOT NULL, created_at TEXT NOT NULL, message TEXT NOT NULL)')
96
+ if db.execute('SELECT brand FROM context').fetchone()[0] != self.brand:
97
+ raise ValueError('Ledger belongs to a different brand')
98
+ yield db
99
+ if write:
100
+ db.commit()
101
+ except BaseException:
102
+ if write:
103
+ db.rollback()
104
+ raise
105
+ finally:
106
+ db.close()
107
+
108
+ @staticmethod
109
+ def _get(db, job_id):
110
+ row = db.execute('SELECT data FROM jobs WHERE id=?', (job_id,)).fetchone()
111
+ return NativeJob.model_validate_json(row[0]) if row else None
112
+
113
+ @staticmethod
114
+ def _save(db, job):
115
+ db.execute('UPDATE jobs SET data=? WHERE id=?', (job.model_dump_json(), job.id))
116
+
117
+ @staticmethod
118
+ def _require_provider_writable(job):
119
+ if (job is not None and job.platform == 'youtube' and job.state == 'blocked'
120
+ and job.route == 'blocked' and job.approval_digest is None
121
+ and job.remote_id is None):
122
+ raise ValueError('YouTube API data was removed; late provider writes are blocked')
123
+
124
+ def get(self, job_id: str) -> NativeJob | None:
125
+ with self._db() as db:
126
+ return self._get(db, job_id) if db else None
127
+
128
+ def list_jobs(self) -> list[NativeJob]:
129
+ with self._db() as db:
130
+ return [NativeJob.model_validate_json(row[0]) for row in
131
+ db.execute('SELECT data FROM jobs ORDER BY day,id')] if db else []
132
+
133
+ @staticmethod
134
+ def _record_inventory(db, inventory):
135
+ from .approval import hash_value
136
+ validate_inventory(inventory) # Recovery retains even stale protection.
137
+ digest = hash_value(inventory)
138
+ db.execute('INSERT OR IGNORE INTO calendar_inventory VALUES (?,?)',
139
+ (digest,json.dumps(inventory,allow_nan=False)))
140
+ for item in inventory['objects']:
141
+ instant = date(item['publish_at'])
142
+ db.execute('INSERT OR IGNORE INTO external_reservations VALUES (?,?,?,?,?,?)',
143
+ (digest,item['platform'],item['account_id'],item['remote_ref'],
144
+ instant.astimezone(ZONE).date().isoformat(),instant.isoformat()))
145
+
146
+ def record_inventory(self, inventory):
147
+ """Append evidence atomically, including known native refs; never release.
148
+
149
+ Changed and absent refs conservatively retain every observed day. There
150
+ is deliberately no automatic reconciliation/removal API.
151
+ """
152
+ validate_inventory(inventory)
153
+ with self._db(write=True) as db:
154
+ self._record_inventory(db,inventory)
155
+
156
+ @staticmethod
157
+ def _external_occupied(db, platform, account_id, key, *, remote_ref=None, publish_at=None):
158
+ if not db.execute("SELECT 1 FROM sqlite_master WHERE name='external_reservations'").fetchone():
159
+ return False
160
+ column, value = ('publish_at', key[3:]) if key.startswith('at:') else ('day', key)
161
+ # Column is selected only from the two constants above.
162
+ rows = db.execute(f'SELECT remote_ref,publish_at FROM external_reservations WHERE platform=? AND account_id=? AND {column}=?',
163
+ (platform, account_id, value))
164
+ return any(not (remote_ref is not None and publish_at is not None
165
+ and row['remote_ref'] == remote_ref and row['publish_at'] == publish_at.isoformat())
166
+ for row in rows)
167
+
168
+ @classmethod
169
+ def _check_external(cls, db, job):
170
+ if cls._external_occupied(db,job.platform,job.account_id,reservation_key(job)):
171
+ raise ValueError('Slot reserved by external calendar evidence; reconcile before delivery')
172
+
173
+ @staticmethod
174
+ def _check_internal(db, job, *, exclude_id=None):
175
+ key = reservation_key(job)
176
+ for row in db.execute('SELECT id,day FROM jobs WHERE platform=? AND account_id=?',
177
+ (job.platform,job.account_id)):
178
+ if row['id'] != exclude_id and slots_conflict(row['day'],key):
179
+ raise sqlite3.IntegrityError('Destination slot occupied by an existing job')
180
+ if db.execute("SELECT 1 FROM sqlite_master WHERE name='holds'").fetchone():
181
+ for row in db.execute('SELECT job_id,day FROM holds WHERE platform=? AND account_id=?',
182
+ (job.platform,job.account_id)):
183
+ if row['job_id'] != exclude_id and slots_conflict(row['day'],key):
184
+ raise ValueError('Slot reserved by pending remote action')
185
+
186
+ def assert_available(self, job):
187
+ """Read-only preview check; admission rechecks atomically when persisted."""
188
+ with self._db() as db:
189
+ if db is not None:
190
+ self._check_external(db,job)
191
+ self._check_internal(db,job)
192
+
193
+ def prepare(self, job: NativeJob, *, payload: dict, now: datetime | None = None, inventory: dict | None = None) -> NativeJob:
194
+ now = _now(now)
195
+ if job.approval_digest is not None:
196
+ raise ValueError('Prepared jobs cannot carry a prefilled approval digest')
197
+ if (job.brand != self.brand or job.state != 'prepared' or job.attempt_id
198
+ or job.remote_id):
199
+ raise ValueError('Only new prepared jobs for this explicit brand may be inserted')
200
+ if job.publish_at <= now:
201
+ raise ValueError('Cannot prepare a past publication')
202
+ day = reservation_key(job)
203
+ serialized_payload = json.dumps(payload, allow_nan=False)
204
+ # Commit learned occupancy first, even if a competing admission rejects
205
+ # this job. The following write transaction rechecks all reservations.
206
+ if inventory is not None:
207
+ self.record_inventory(inventory)
208
+ with self._db(write=True) as db:
209
+ self._check_external(db,job)
210
+ self._check_internal(db,job)
211
+ if job.schedule_mode == 'exact':
212
+ # Older clients must reject these instant keys instead of ignoring them.
213
+ db.execute('PRAGMA user_version=3')
214
+ db.execute('INSERT INTO jobs VALUES (?,?,?,?,?,?,?)',
215
+ (job.id, job.legacy_entry_id, job.platform, job.account_id, day,
216
+ job.model_dump_json(), serialized_payload))
217
+ return job
218
+
219
+ def get_payload(self, job_id: str) -> dict | None:
220
+ with self._db() as db:
221
+ row = db.execute('SELECT payload FROM jobs WHERE id=?', (job_id,)).fetchone() if db else None
222
+ return json.loads(row[0]) if row else None
223
+
224
+ def transition(self, job_id: str, expected_state: str, state: str, *,
225
+ approval_digest: str | None = None, now: datetime | None = None) -> NativeJob | None:
226
+ if state not in TRANSITIONS.get(expected_state, set()):
227
+ raise ValueError('Unsafe state transition; reconcile remote evidence instead')
228
+ with self._db(write=True) as db:
229
+ job = self._get(db, job_id)
230
+ if job is None or job.state != expected_state:
231
+ return None
232
+ changes = dict(state=state, updated_at=_now(now))
233
+ if state == 'uncertain':
234
+ changes['reconcile_after'] = max(filter(None, [
235
+ job.reconcile_after, job.observation_watermark, changes['updated_at']]))
236
+ if approval_digest is not None:
237
+ if (expected_state, state) != ('prepared', 'approved'):
238
+ raise ValueError('Approval can only be bound when approving a prepared job')
239
+ changes['approval_digest'] = approval_digest
240
+ updated = _replace(job, **changes)
241
+ if state == 'approved' and updated.approval_digest is None:
242
+ raise ValueError('Approval digest required')
243
+ self._save(db, updated)
244
+ return updated
245
+
246
+ def claim(self, job_id: str, expected_state: str, *, now: datetime | None = None) -> NativeJob | None:
247
+ if expected_state not in {'approved', 'ready', 'waiting_window'}:
248
+ return None
249
+ now = _now(now)
250
+ with self._db(write=True) as db:
251
+ job = self._get(db, job_id)
252
+ if job is None:
253
+ return None
254
+ payload_row = db.execute('SELECT payload FROM jobs WHERE id=?', (job.id,)).fetchone()
255
+ delivery_mode = json.loads(payload_row[0]).get('delivery_mode', 'native_schedule')
256
+ if delivery_mode not in {'native_schedule', 'at_time'}:
257
+ raise ValueError('Unknown approved delivery mode')
258
+ due = (job.publish_at <= now < job.publish_at + timedelta(minutes=5)
259
+ if job.route == 'api' and delivery_mode == 'at_time'
260
+ else job.dispatch_after <= now < job.publish_at)
261
+ if (job.state != expected_state or job.approval_digest is None
262
+ or job.attempt_id is not None or job.route == 'blocked' or not due):
263
+ return None
264
+ cooldown=db.execute('SELECT until_at FROM cooldowns WHERE job_id=?',(job.id,)).fetchone()
265
+ if cooldown and datetime.fromisoformat(cooldown[0]) > now:
266
+ return None
267
+ self._check_external(db,job)
268
+ attempt_id = str(uuid4())
269
+ updated = _replace(job, state='dispatching', attempt_id=attempt_id, updated_at=now)
270
+ db.execute('INSERT INTO attempts VALUES (?,?,?,?,?,?)',
271
+ (attempt_id, job_id, job.approval_digest, now.isoformat(), now.isoformat(), '{}'))
272
+ self._save(db, updated)
273
+ return updated
274
+
275
+ def resume_attempt(self, job_id: str, attempt_id: str, *, now: datetime | None = None) -> NativeJob | None:
276
+ """Atomically give one worker the existing uncertain attempt, never a new one."""
277
+ with self._db(write=True) as db:
278
+ job = self._get(db, job_id)
279
+ if job is None or job.state != 'uncertain' or job.attempt_id != attempt_id:
280
+ return None
281
+ row = db.execute('SELECT checkpoint FROM attempts WHERE id=? AND job_id=?',
282
+ (attempt_id, job_id)).fetchone()
283
+ if row is None or not json.loads(row[0]).get('session_uri'):
284
+ return None
285
+ updated = _replace(job, state='dispatching', updated_at=_now(now))
286
+ self._save(db, updated)
287
+ return updated
288
+
289
+ def mark_api_submitted(self, job_id: str, attempt_id: str, remote_id: str,
290
+ *, now: datetime | None = None) -> NativeJob:
291
+ """Bind a remote ID to the owning attempt without claiming publication."""
292
+ if not isinstance(remote_id, str) or not remote_id.strip():
293
+ raise ValueError('Nonempty remote ID required')
294
+ with self._db(write=True) as db:
295
+ job = self._get(db, job_id)
296
+ if job is None or job.attempt_id != attempt_id or job.state != 'dispatching':
297
+ raise ValueError('Dispatching attempt does not own this job')
298
+ updated = _replace(job, remote_id=remote_id, state='verifying',
299
+ updated_at=_now(now))
300
+ row = db.execute('SELECT checkpoint FROM attempts WHERE id=? AND job_id=?',
301
+ (attempt_id, job_id)).fetchone()
302
+ if row is None:
303
+ raise ValueError('Attempt missing')
304
+ checkpoint = json.loads(row[0]) | {'remote_id': remote_id, 'phase': 'submitted_id'}
305
+ db.execute('UPDATE attempts SET checkpoint=?,updated_at=? WHERE id=?',
306
+ (json.dumps(checkpoint, allow_nan=False), _now(now).isoformat(), attempt_id))
307
+ self._save(db, updated)
308
+ return updated
309
+
310
+ def checkpoint(self, job_id: str, attempt_id: str, checkpoint: dict, *, now: datetime | None = None):
311
+ """Merge durable upload/session IDs before any next remote write."""
312
+ with self._db(write=True) as db:
313
+ job = self._get(db, job_id)
314
+ if not job or job.attempt_id != attempt_id or job.state not in {'dispatching', 'awaiting_ui', 'verifying', 'uncertain'}:
315
+ raise ValueError('Attempt does not own this job')
316
+ row = db.execute('SELECT checkpoint FROM attempts WHERE id=? AND job_id=?',
317
+ (attempt_id, job_id)).fetchone()
318
+ if not row:
319
+ raise ValueError('Attempt missing')
320
+ if checkpoint.get('ui_submit_started_at'):
321
+ self._check_external(db,job)
322
+ merged = json.loads(row[0]) | checkpoint
323
+ db.execute('UPDATE attempts SET checkpoint=?,updated_at=? WHERE id=?',
324
+ (json.dumps(merged, allow_nan=False), _now(now).isoformat(), attempt_id))
325
+
326
+ def get_attempts(self, job_id: str) -> list[dict]:
327
+ with self._db() as db:
328
+ if db is None:
329
+ return []
330
+ return [dict(row) | {'checkpoint': json.loads(row['checkpoint'])} for row in
331
+ db.execute('SELECT * FROM attempts WHERE job_id=? ORDER BY started_at,id', (job_id,))]
332
+
333
+ def recover_dispatching(self, *, now: datetime | None = None) -> list[str]:
334
+ """Only after workers have stopped: require reconciliation, never resubmit."""
335
+ recovered = []
336
+ with self._db(write=True) as db:
337
+ for row in db.execute('SELECT data FROM jobs').fetchall():
338
+ job = NativeJob.model_validate_json(row[0])
339
+ if job.state == 'dispatching':
340
+ self._save(db, _replace(job, state='uncertain', updated_at=_now(now),
341
+ reconcile_after=max(filter(None, [job.reconcile_after,
342
+ job.observation_watermark, _now(now)]))))
343
+ recovered.append(job.id)
344
+ return recovered
345
+
346
+ def record_observation(self, observation: NativeObservation, *, now: datetime | None = None) -> bool:
347
+ """Append even conflicting observations; only complete evidence confirms a job."""
348
+ now = _now(now)
349
+ with self._db(write=True) as db:
350
+ job = self._get(db, observation.job_id)
351
+ if job is None:
352
+ raise ValueError('Unknown job')
353
+ self._require_provider_writable(job)
354
+ pending=db.execute('SELECT data FROM actions WHERE job_id=?',(job.id,)).fetchone()
355
+ if pending and json.loads(pending[0])['status'] != 'confirmed':
356
+ raise ValueError('Pending action requires action-specific reconciliation')
357
+ historical_valid = verify(job, observation, now=now)
358
+ published = (observation.state == 'published' and observation.public_visible
359
+ and observation.processing_complete and observation.publish_at == job.publish_at
360
+ and evidence_matches(job,observation,now=now)
361
+ and (observation.actual_published_at is None or observation.actual_published_at <= observation.observed_at))
362
+ historical_valid = historical_valid or published
363
+ payload_row = db.execute('SELECT payload FROM jobs WHERE id=?',
364
+ (job.id,)).fetchone()
365
+ payload = json.loads(payload_row[0])
366
+ known_refs = {job.remote_id} if job.remote_id else set()
367
+ payload_target = payload.get('options', {}).get('video_id')
368
+ if payload_target:
369
+ known_refs.add(payload_target)
370
+ for row in db.execute('SELECT checkpoint FROM attempts WHERE job_id=?',
371
+ (job.id,)).fetchall():
372
+ checkpoint_target = json.loads(row[0]).get('video_id')
373
+ if checkpoint_target:
374
+ known_refs.add(checkpoint_target)
375
+ target_matches = not known_refs or known_refs == {observation.remote_ref}
376
+ delivery_started = (job.approval_digest is not None
377
+ and job.attempt_id is not None
378
+ and job.state in {'dispatching', 'awaiting_ui', 'verifying',
379
+ 'uncertain', 'native_scheduled'})
380
+ current = (job.observation_watermark is None
381
+ or observation.observed_at >= job.observation_watermark)
382
+ after_barrier = (job.reconcile_after is None
383
+ or observation.observed_at > job.reconcile_after)
384
+ mutable = job.state not in {'cancelled', 'published'}
385
+ calendar_conflict = self._external_occupied(db,job.platform,job.account_id,
386
+ reservation_key(job),
387
+ remote_ref=observation.remote_ref,publish_at=observation.publish_at)
388
+ valid = (historical_valid and target_matches and not calendar_conflict and delivery_started and current
389
+ and after_barrier and mutable)
390
+ db.execute('INSERT INTO observations(job_id,data,verified) VALUES (?,?,?)',
391
+ (job.id, observation.model_dump_json(), int(valid)))
392
+ if valid:
393
+ self._save(db, _replace(job, state='published' if published else 'native_scheduled',
394
+ remote_id=observation.remote_ref, updated_at=now,
395
+ observation_watermark=observation.observed_at))
396
+ elif (delivery_started and mutable and current
397
+ and (not historical_valid or not target_matches or calendar_conflict)
398
+ and evidence_matches(job, observation, now=now)
399
+ and (observation.state != 'native_scheduled'
400
+ or observation.publish_at != job.publish_at
401
+ or not target_matches or calendar_conflict
402
+ or (job.remote_id is not None and job.remote_id != observation.remote_ref))):
403
+ # Only authentic, bound contradictions advance the barrier; an API
404
+ # scheduled response lacking a calendar is merely incomplete.
405
+ self._save(db, _replace(job, state='uncertain', updated_at=now,
406
+ observation_watermark=observation.observed_at,
407
+ reconcile_after=max(filter(None, [job.reconcile_after, observation.observed_at]))))
408
+ return valid
409
+
410
+ def get_observations(self, job_id: str) -> list[NativeObservation]:
411
+ with self._db() as db:
412
+ return [NativeObservation.model_validate_json(row[0]) for row in
413
+ db.execute('SELECT data FROM observations WHERE job_id=? ORDER BY id', (job_id,))] if db else []
414
+
415
+ def notice(self, job_id, message, *, now=None):
416
+ with self._db(write=True) as db:
417
+ self._require_provider_writable(self._get(db, job_id))
418
+ db.execute('INSERT INTO notices VALUES (?,?,?)',(job_id,_now(now).isoformat(),message))
419
+
420
+ def get_notices(self, job_id):
421
+ with self._db() as db:
422
+ if db is None or not db.execute("SELECT 1 FROM sqlite_master WHERE name='notices'").fetchone():
423
+ return []
424
+ return [dict(row) for row in db.execute('SELECT * FROM notices WHERE job_id=? ORDER BY created_at',(job_id,))]
425
+
426
+ def reserved_days(self, platform, account_id):
427
+ with self._db() as db:
428
+ if db is None:
429
+ return set()
430
+ days = {row[0] for row in db.execute('SELECT day FROM jobs WHERE platform=? AND account_id=?',(platform,account_id))}
431
+ if db.execute("SELECT 1 FROM sqlite_master WHERE name='holds'").fetchone():
432
+ days |= {row[0] for row in db.execute('SELECT day FROM holds WHERE platform=? AND account_id=?',(platform,account_id))}
433
+ if db.execute("SELECT 1 FROM sqlite_master WHERE name='external_reservations'").fetchone():
434
+ days |= {row[0] for row in db.execute('SELECT day FROM external_reservations WHERE platform=? AND account_id=?',(platform,account_id))}
435
+ return {slot_day(key) for key in days}
436
+
437
+ def get_action(self, job_id):
438
+ with self._db() as db:
439
+ if db is None or not db.execute("SELECT 1 FROM sqlite_master WHERE name='actions'").fetchone():
440
+ return None
441
+ row=db.execute('SELECT data FROM actions WHERE job_id=?',(job_id,)).fetchone()
442
+ action=json.loads(row[0]) if row else None
443
+ if action and action.get('data_lifecycle')=='purged':
444
+ raise ValueError('Native action API receipt expired; replay is blocked. Reconcile in the provider interface.')
445
+ return action
446
+
447
+ def save_action(self, job, action, *, now=None):
448
+ action['created_at']=_now(now).isoformat()
449
+ with self._db(write=True) as db:
450
+ if self._get(db,job.id) != job:
451
+ raise ValueError('Job changed; review a new preview')
452
+ prior=db.execute('SELECT data FROM actions WHERE job_id=?',(job.id,)).fetchone()
453
+ if prior and json.loads(prior[0])['status'] != 'confirmed':
454
+ raise ValueError('An action already owns this job; reconcile it')
455
+ if action['kind']=='reschedule':
456
+ target=NativeJob.model_validate_json(action['job'])
457
+ if target.schedule_mode == 'exact':
458
+ self._record_inventory(db,reschedule_inventory(self.path.parent,target,now=_now(now)))
459
+ self._check_external(db,target)
460
+ day=reservation_key(target)
461
+ self._check_internal(db,target,exclude_id=job.id)
462
+ db.execute('INSERT INTO holds VALUES (?,?,?,?)',(job.id,job.platform,job.account_id,day))
463
+ db.execute('INSERT OR REPLACE INTO actions VALUES (?,?)',(job.id,json.dumps(action)))
464
+ db.execute('INSERT INTO action_events VALUES (?,?)',(job.id,json.dumps(action)))
465
+
466
+ def submit_action(self, job_id, *, now=None):
467
+ now=_now(now)
468
+ with self._db(write=True) as db:
469
+ job=self._get(db,job_id)
470
+ row=db.execute('SELECT data FROM actions WHERE job_id=?',(job_id,)).fetchone()
471
+ action=json.loads(row[0]) if row else None
472
+ if not action or action['status'] != 'approved':
473
+ raise ValueError('Approved action required; submitted actions cannot be retried')
474
+ prior_job = NativeJob.model_validate_json(json.dumps(action['preview']['before']))
475
+ if job != prior_job:
476
+ raise ValueError('Job changed since action approval; reconcile before submission')
477
+ if action['kind']=='reschedule' and NativeJob.model_validate_json(action['job']).publish_at <= now:
478
+ raise ValueError('Destination date expired; no remote write authorized')
479
+ if action['kind']=='reschedule':
480
+ target=NativeJob.model_validate_json(action['job'])
481
+ if target.schedule_mode == 'exact':
482
+ self._record_inventory(db,reschedule_inventory(self.path.parent,target,now=now))
483
+ self._check_external(db,target)
484
+ action.update(status='submitted',submitted_at=now.isoformat())
485
+ db.execute('UPDATE actions SET data=? WHERE job_id=?',(json.dumps(action),job_id))
486
+ db.execute('INSERT INTO action_events VALUES (?,?)',(job_id,json.dumps(action)))
487
+ self._save(db,_replace(job,state='uncertain',updated_at=now,reconcile_after=max(filter(None,[now,job.reconcile_after,job.observation_watermark]))))
488
+ return action
489
+
490
+ def confirm_action(self, observation, *, now=None):
491
+ now=_now(now)
492
+ with self._db(write=True) as db:
493
+ job=self._get(db,observation.job_id)
494
+ row=db.execute('SELECT data FROM actions WHERE job_id=?',(job.id,)).fetchone()
495
+ action=json.loads(row[0]) if row else None
496
+ if not action or action['status'] != 'submitted':
497
+ raise ValueError('Submitted action required')
498
+ target=NativeJob.model_validate_json(action['job'])
499
+ # Consensus and audit share the transaction: a conflicting target is
500
+ # invalid evidence, not a reason to discard a newer contradiction.
501
+ known_refs = {job.remote_id} if job.remote_id else set()
502
+ payload = json.loads(db.execute('SELECT payload FROM jobs WHERE id=?',(job.id,)).fetchone()[0])
503
+ payload_target = payload.get('options', {}).get('video_id')
504
+ if payload_target:
505
+ known_refs.add(payload_target)
506
+ for attempt in db.execute('SELECT checkpoint FROM attempts WHERE job_id=?',(job.id,)):
507
+ checkpoint_target = json.loads(attempt[0]).get('video_id')
508
+ if checkpoint_target:
509
+ known_refs.add(checkpoint_target)
510
+ target_matches = known_refs == {observation.remote_ref}
511
+ valid=(evidence_matches(target,observation,now=now)
512
+ and observation.source=='ui'
513
+ and target_matches
514
+ and observation.observed_at > datetime.fromisoformat(action['submitted_at'])
515
+ and (job.observation_watermark is None or observation.observed_at >= job.observation_watermark)
516
+ and (job.reconcile_after is None or observation.observed_at > job.reconcile_after)
517
+ and observation.publish_at==target.publish_at
518
+ and ((action['kind']=='cancel' and observation.state=='cancelled')
519
+ or (action['kind']=='reschedule' and verify(target,observation,now=now))))
520
+ if action['kind']=='reschedule' and self._external_occupied(db,target.platform,target.account_id,reservation_key(target),remote_ref=observation.remote_ref,publish_at=observation.publish_at):
521
+ valid = False
522
+ db.execute('INSERT INTO observations(job_id,data,verified) VALUES (?,?,?)',(job.id,observation.model_dump_json(),int(valid)))
523
+ if not valid:
524
+ if (evidence_matches(target,observation,now=now)
525
+ and observation.observed_at > datetime.fromisoformat(action['submitted_at'])
526
+ and (job.observation_watermark is None or observation.observed_at >= job.observation_watermark)):
527
+ self._save(db,_replace(job,state='uncertain',updated_at=now,observation_watermark=observation.observed_at,
528
+ reconcile_after=max(filter(None,[job.reconcile_after,observation.observed_at]))))
529
+ db.execute('INSERT INTO notices VALUES (?,?,?)',(job.id,now.isoformat(),'Action readback mismatches approved intent; reservations retained'))
530
+ return False
531
+ updated=_replace(target,state='cancelled' if action['kind']=='cancel' else 'native_scheduled',
532
+ remote_id=observation.remote_ref,updated_at=now,observation_watermark=observation.observed_at,reconcile_after=job.reconcile_after)
533
+ if action['kind']=='reschedule':
534
+ db.execute('UPDATE jobs SET day=? WHERE id=?',(reservation_key(target),job.id))
535
+ self._save(db,updated)
536
+ db.execute('DELETE FROM holds WHERE job_id=?',(job.id,))
537
+ action['status']='confirmed'
538
+ db.execute('UPDATE actions SET data=? WHERE job_id=?',(json.dumps(action),job.id))
539
+ db.execute('INSERT INTO action_events VALUES (?,?)',(job.id,json.dumps(action)))
540
+ return True
541
+
542
+ def defer_before_write(self, job_id, until, *, reason, now=None):
543
+ """Backoff only before a delivery claim; cannot clear an uncertain attempt."""
544
+ now=_now(now)
545
+ until=aware(until)
546
+ if reason not in {'rate_limit','upload_budget','session_expired','outside_window'} or until <= now:
547
+ raise ValueError('Explicit pre-write rejection and future cooldown required')
548
+ with self._db(write=True) as db:
549
+ job=self._get(db,job_id)
550
+ if not job or job.attempt_id or job.state not in {'approved','ready','waiting_window'}:
551
+ raise ValueError('Claimed/submitted attempts require reconciliation, not backoff')
552
+ db.execute('INSERT OR REPLACE INTO cooldowns VALUES (?,?,?)',(job_id,until.isoformat(),reason))
553
+ db.execute('INSERT INTO notices VALUES (?,?,?)',(job_id,now.isoformat(),f'Pre-write {reason}; deferred until {until.isoformat()}'))
554
+
555
+ def cooldown_until(self, job_id):
556
+ with self._db() as db:
557
+ if db is None or not db.execute("SELECT 1 FROM sqlite_master WHERE name='cooldowns'").fetchone():
558
+ return None
559
+ row=db.execute('SELECT until_at FROM cooldowns WHERE job_id=?',(job_id,)).fetchone()
560
+ return datetime.fromisoformat(row[0]) if row else None
@@ -0,0 +1,32 @@
1
+ """Verify a trusted operator attestation; does not interpret image contents."""
2
+ from datetime import datetime, timezone
3
+ from hashlib import sha256
4
+ from pathlib import Path
5
+
6
+ from .models import NativeJob, NativeObservation, aware
7
+
8
+
9
+ def evidence_matches(job: NativeJob, observation: NativeObservation, *, now: datetime) -> bool:
10
+ """Artifact and identity validity, independent of the reported remote outcome."""
11
+ now = aware(now)
12
+ if (observation.job_id != job.id or observation.platform != job.platform
13
+ or observation.account_id != job.account_id or observation.content_hash != job.content_hash
14
+ or observation.approval_digest != job.approval_digest
15
+ or observation.observed_at > now or observation.observed_at < job.created_at):
16
+ return False
17
+ try:
18
+ data = Path(observation.evidence_path).read_bytes()
19
+ return bool(data) and sha256(data).hexdigest() == observation.evidence_sha256
20
+ except OSError:
21
+ return False
22
+
23
+
24
+ def verify(job: NativeJob, observation: NativeObservation, *, now: datetime | None = None) -> bool:
25
+ """Historical attestation validity; ledger separately enforces freshness."""
26
+ return (
27
+ evidence_matches(job, observation, now=now or datetime.now(timezone.utc))
28
+ and observation.publish_at == job.publish_at
29
+ and observation.state == 'native_scheduled' and observation.calendar_visible
30
+ and observation.source == 'ui'
31
+ and (job.remote_id is None or job.remote_id == observation.remote_ref)
32
+ )