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,510 @@
1
+ """Explicit preview/approval and account-gated local publication dispatch."""
2
+ from datetime import datetime, timezone
3
+ import json
4
+ from pathlib import Path
5
+ import re
6
+ from zoneinfo import ZoneInfo
7
+
8
+ import typer
9
+
10
+ from socialctl.brands import cargar_brand, _validar_nombre_de_marca
11
+ from socialctl.schedule_remote import DEFAULT_ROOT, is_remote, send_native
12
+ from .approval import approval_document, hash_value, media_hashes, reject_secrets, validate_payload, verify_approval
13
+ from .cadence import ZONE, ZONE_NAME, plan_slots, reservation_day, exact_time
14
+ from .models import NativeJob, aware
15
+ from .store import NativeStore
16
+ from .report import NativeReport, active_report, bind_store, capture, begin_submission
17
+ from .inventory import validate_inventory, require_coverage
18
+
19
+ native_app = typer.Typer(help='Native scheduling: prepare MANIFEST --dry-run, prepare --persist --approval-digest DIGEST, approve ID --approval-digest DIGEST. See socialcli agent-guide for complete offline input examples.')
20
+ ACCOUNT_KEYS = {'youtube':'channel_id','facebook':'page_id','instagram':'ig_user_id','tiktok':'open_id'}
21
+
22
+
23
+ def component(value):
24
+ if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.-]{0,127}', value):
25
+ raise ValueError('Invalid native manifest/job identifier')
26
+ return value
27
+
28
+
29
+ def calendar_inventory(brand):
30
+ path = (brand.raiz / 'native-calendar.json').resolve()
31
+ if not path.is_relative_to(brand.raiz.resolve()) or not path.is_file():
32
+ raise ValueError('Fresh native-calendar.json required; inventory the official account calendar first')
33
+ inventory = json.loads(path.read_text())
34
+ validate_inventory(inventory,accounts=brand.cuentas,now=datetime.now(timezone.utc))
35
+ return inventory
36
+
37
+
38
+ def proposal(brand, manifest: str, *, inventory=None):
39
+ component(manifest)
40
+ path = (brand.raiz / manifest).resolve()
41
+ if not path.is_relative_to(brand.raiz.resolve()):
42
+ raise ValueError('Manifest must remain in explicit brand root')
43
+ raw = json.loads(path.read_text())
44
+ reject_secrets(raw)
45
+ required = {'id','platform','account_id','publish_at','dispatch_after','route','payload'}
46
+ if not isinstance(raw, dict) or not required <= set(raw) or set(raw) - required - {'schedule'}:
47
+ raise ValueError('Invalid native manifest schema; see socialcli agent-guide')
48
+ component(raw['id'])
49
+ platform = raw['platform']
50
+ if platform not in ACCOUNT_KEYS or raw['account_id'] != (brand.cuentas.get(platform) or {}).get(ACCOUNT_KEYS[platform]):
51
+ raise ValueError('Account does not match explicit brand accounts.yml')
52
+ payload = raw['payload']
53
+ if not isinstance(payload, dict) or not {'calendar','visibility','copy','options','first_comment','media'} <= set(payload):
54
+ raise ValueError('Payload requires calendar, visibility, copy, options, first_comment and media')
55
+ if not all(isinstance(payload[key],str) for key in ('calendar','visibility','copy')) or not isinstance(payload['options'],dict):
56
+ raise ValueError('Invalid payload fields')
57
+ if not payload['calendar'].strip() or not payload['visibility'].strip() or not isinstance(payload['first_comment'],(str,type(None))):
58
+ raise ValueError('Invalid calendar/visibility/comment')
59
+ # Relative paths are frozen against the authoritative brand, never current cwd.
60
+ if not isinstance(payload['media'],list):
61
+ raise ValueError('Media list required')
62
+ for item in payload['media']:
63
+ if not isinstance(item,dict) or not isinstance(item.get('path'),str):
64
+ raise ValueError('Media path and explicit origin required')
65
+ item['path'] = str((brand.raiz / item['path']).resolve())
66
+ if not Path(item['path']).is_relative_to(brand.raiz.resolve()) or '.secrets' in Path(item['path']).parts:
67
+ raise ValueError('Media must remain inside brand root outside .secrets')
68
+ validate_payload(platform, payload)
69
+ schedule = raw.get('schedule')
70
+ mode, zone = 'legacy_daily', ZONE_NAME
71
+ if 'schedule' in raw:
72
+ if (not isinstance(schedule, dict) or set(schedule) != {'mode', 'timezone'}
73
+ or schedule['mode'] != 'exact' or not isinstance(schedule['timezone'],str)):
74
+ raise ValueError('Schedule requires mode=exact and an explicit IANA timezone')
75
+ mode, zone = schedule['mode'], schedule['timezone']
76
+ entered = datetime.fromisoformat(raw['publish_at'].replace('Z','+00:00'))
77
+ requested = exact_time(entered,zone) if mode == 'exact' else aware(entered)
78
+ if mode == 'legacy_daily':
79
+ reservation_day(requested, ZONE_NAME)
80
+ dispatch = aware(datetime.fromisoformat(raw['dispatch_after'].replace('Z','+00:00')))
81
+ store = NativeStore(brand.raiz,brand=brand.nombre)
82
+ inventory = calendar_inventory(brand) if inventory is None else inventory
83
+ now = datetime.now(timezone.utc)
84
+ calendars = validate_inventory(inventory,accounts=brand.cuentas,now=now)
85
+ if (platform,raw['account_id']) not in calendars:
86
+ raise ValueError('Complete account calendar inventory required for destination')
87
+ if mode == 'exact':
88
+ if requested <= now:
89
+ raise ValueError('Exact publication time must be in the future')
90
+ final = requested
91
+ for item in inventory['objects']:
92
+ if (item['platform'] == platform and item['account_id'] == raw['account_id']
93
+ and aware(datetime.fromisoformat(item['publish_at'].replace('Z','+00:00'))) == final):
94
+ raise ValueError('Exact publication time conflicts with external calendar evidence; choose another time')
95
+ else:
96
+ occupied = store.reserved_days(platform,raw['account_id']) | calendars[platform,raw['account_id']]
97
+ final = plan_slots([requested],occupied=occupied)[0]
98
+ require_coverage(inventory,final,zone)
99
+ payload['requested_publish_at'] = requested.isoformat()
100
+ job = NativeJob(id=raw['id'],brand=brand.nombre,platform=platform,account_id=raw['account_id'],
101
+ media_hash=hash_value(media_hashes(payload)),content_hash=hash_value(payload),
102
+ publish_at=final,timezone_name=zone,schedule_mode=mode,dispatch_after=dispatch,
103
+ route=raw['route'],created_at=now,updated_at=now)
104
+ if mode == 'exact':
105
+ store.assert_available(job)
106
+ return job,payload
107
+
108
+
109
+ def run(operation, *, json_output=False, command=None, brand=None):
110
+ if json_output:
111
+ with NativeReport(command, brand):
112
+ operation()
113
+ return
114
+ try:
115
+ operation()
116
+ except typer.Exit:
117
+ raise
118
+ except Exception as exc:
119
+ # Input/Pydantic/OS errors can contain the complete payload or credentials.
120
+ if type(exc) is ValueError:
121
+ message = str(exc)
122
+ try:
123
+ reject_secrets(message)
124
+ except Exception:
125
+ message = 'Invalid or unsafe native scheduling input'
126
+ else:
127
+ message = 'Native scheduling failed safely; check schema, paths, account and slot conflicts'
128
+ typer.echo(message)
129
+ raise typer.Exit(1) from exc
130
+
131
+
132
+ def selected(root, brand, args):
133
+ brand_root = _validar_nombre_de_marca(root,brand)
134
+ if is_remote(brand_root):
135
+ report = active_report.get()
136
+ if report is None:
137
+ send_native(root,brand,args)
138
+ else:
139
+ # The SSH outcome is unknown until a bound envelope is received.
140
+ if args[0] not in {'status', 'handoff', 'migration-prepare'}:
141
+ begin_submission()
142
+ report.remote = send_native(root,brand,[*args,'--json'])
143
+ return None
144
+ chosen = cargar_brand(root,brand)
145
+ bind_store(NativeStore(chosen.raiz,brand=brand))
146
+ return chosen
147
+
148
+
149
+ @native_app.command()
150
+ def prepare(manifest: str, brand: str = typer.Option(...,'--brand'),
151
+ root: Path = typer.Option(DEFAULT_ROOT), dry_run: bool = typer.Option(False,'--dry-run'),
152
+ persist: bool = typer.Option(False,'--persist'), approval_digest: str | None = typer.Option(None,'--approval-digest'), json_output: bool = typer.Option(False, '--json', help='One structured native result; preview on stderr.')):
153
+ def operation():
154
+ component(manifest)
155
+ if dry_run == persist or (dry_run and approval_digest) or (persist and not approval_digest):
156
+ raise ValueError('Use --dry-run OR --persist --approval-digest from the displayed preview')
157
+ args = ['prepare',manifest] + (['--dry-run'] if dry_run else ['--persist','--approval-digest',approval_digest])
158
+ chosen = selected(root,brand,args)
159
+ if chosen is None:
160
+ return
161
+ inventory = calendar_inventory(chosen)
162
+ job,payload = proposal(chosen,manifest,inventory=inventory)
163
+ if persist:
164
+ verify_approval(job,payload,approval_digest)
165
+ NativeStore(chosen.raiz,brand=brand).prepare(job,payload=payload,inventory=inventory)
166
+ typer.echo(f'Prepared: {job.id}; approval is still required')
167
+ return
168
+ document = approval_document(job,payload)
169
+ capture(document)
170
+ typer.echo(json.dumps(document,indent=2,ensure_ascii=False))
171
+ typer.echo(f'Final local: {job.publish_at.astimezone(ZoneInfo(job.timezone_name)).isoformat()} {job.timezone_name}')
172
+ typer.echo(f'Final UTC: {job.publish_at.isoformat()}')
173
+ typer.echo(f'Delivery: {job.dispatch_after.isoformat()}')
174
+ typer.echo(f'Schedule mode: {job.schedule_mode}')
175
+ typer.echo(f'Overflow: requested {payload["requested_publish_at"]}; final {job.publish_at.isoformat()}; item preserved')
176
+ typer.echo(f'Approval digest: {hash_value(document)}')
177
+ run(operation, json_output=json_output, command='prepare', brand=brand)
178
+
179
+
180
+ @native_app.command()
181
+ def approve(job_id: str, approval_digest: str = typer.Option(...,'--approval-digest'),
182
+ brand: str = typer.Option(...,'--brand'),root: Path = typer.Option(DEFAULT_ROOT), json_output: bool = typer.Option(False, '--json', help='One structured native result; preview on stderr.')):
183
+ def operation():
184
+ component(job_id)
185
+ chosen = selected(root,brand,['approve',job_id,'--approval-digest',approval_digest])
186
+ if chosen is None:
187
+ return
188
+ store = NativeStore(chosen.raiz,brand=brand)
189
+ job = store.get(job_id)
190
+ if job is None or job.state != 'prepared':
191
+ raise ValueError('Existing prepared job required')
192
+ verify_approval(job,store.get_payload(job_id),approval_digest)
193
+ if not store.transition(job_id,'prepared','approved',approval_digest=approval_digest):
194
+ raise ValueError('Job changed; show a new preview')
195
+ typer.echo(f'Approved: {job_id}')
196
+ run(operation, json_output=json_output, command='approve', brand=brand)
197
+
198
+
199
+ @native_app.command()
200
+ def status(brand: str = typer.Option(...,'--brand'),root: Path = typer.Option(DEFAULT_ROOT), json_output: bool = typer.Option(False, '--json', help='One structured native result; preview on stderr.')):
201
+ def operation():
202
+ chosen = selected(root,brand,['status'])
203
+ if chosen is None:
204
+ return
205
+ from socialctl.publication_status import describe_native_job
206
+ store=NativeStore(chosen.raiz,brand=brand)
207
+ for job in store.list_jobs():
208
+ from .first_comment import first_comment_status
209
+ payload = store.get_payload(job.id)
210
+ text = f'{job.id} | {job.platform}/{job.account_id} | {describe_native_job(job,payload,comment_status=first_comment_status(chosen,job,payload))}'
211
+ reject_secrets(text)
212
+ typer.echo(text)
213
+ run(operation, json_output=json_output, command='status', brand=brand)
214
+
215
+
216
+
217
+ def artifact(chosen, name):
218
+ component(name)
219
+ path=(chosen.raiz/name).resolve()
220
+ if not path.is_relative_to(chosen.raiz.resolve()):
221
+ raise ValueError('Artifact must remain inside brand root')
222
+ return path
223
+
224
+
225
+ def output(value):
226
+ text=json.dumps(value,indent=2,ensure_ascii=False,default=str)
227
+ reject_secrets(text)
228
+ capture(value)
229
+ typer.echo(text)
230
+
231
+
232
+ def eligibility_artifact(chosen, filename):
233
+ relative = Path(filename)
234
+ if relative.is_absolute() or not relative.parts:
235
+ raise ValueError('Eligibility path must be relative to the brand')
236
+ for part in relative.parts:
237
+ component(part)
238
+ path = (chosen.raiz / relative).resolve()
239
+ if not path.is_relative_to(chosen.raiz.resolve()) or '.secrets' in path.parts:
240
+ raise ValueError('Eligibility artifact must remain inside brand root outside secrets')
241
+ return path
242
+
243
+
244
+ def api_eligibility(chosen, job, filename):
245
+ from .facebook import FacebookEligibility
246
+ from .youtube import YouTubeEligibility
247
+ kind = {'facebook': FacebookEligibility, 'youtube': YouTubeEligibility}.get(job.platform)
248
+ if kind is None:
249
+ raise ValueError('Native API scheduling is not supported for this platform; no upload attempted')
250
+ if filename is None:
251
+ return kind()
252
+ path = eligibility_artifact(chosen, filename)
253
+ if path.stat().st_size > 16384:
254
+ raise ValueError('Invalid eligibility file')
255
+ data = json.loads(path.read_text())
256
+ flags = ({'api_enabled', 'page_pilot_verified'} if job.platform == 'facebook'
257
+ else {'api_enabled', 'project_verified', 'studio_pilot_verified'})
258
+ if (not isinstance(data, dict) or set(data) != flags | {'version', 'platform', 'account_id', 'evidence_ref'}
259
+ or type(data['version']) is not int or data['version'] != 1 or data['platform'] != job.platform
260
+ or data['account_id'] != job.account_id or any(type(data[k]) is not bool for k in flags)):
261
+ raise ValueError('Invalid or mismatched native API eligibility')
262
+ reject_secrets(data)
263
+ evidence = data['evidence_ref']
264
+ if not isinstance(evidence, str) or not artifact(chosen, evidence).is_file() or not artifact(chosen, evidence).stat().st_size:
265
+ raise ValueError('Native API eligibility requires the operator-recorded pilot evidence')
266
+ return kind(**{k: v for k, v in data.items() if k not in {'version', 'platform'}})
267
+
268
+
269
+ @native_app.command('submit-api')
270
+ def submit_api(job_id: str, eligibility: str | None = typer.Option(None, '--eligibility'),
271
+ brand: str = typer.Option(..., '--brand'), root: Path = typer.Option(DEFAULT_ROOT), json_output: bool = typer.Option(False, '--json', help='One structured native result; preview on stderr.')):
272
+ """Submit one approved YouTube/Facebook native schedule with operator pilot evidence."""
273
+ def operation():
274
+ import httpx
275
+ from socialctl.brands import cargar_brand
276
+ component(job_id)
277
+ # Media must stay on the client's executor. No implicit SSH or copying.
278
+ if is_remote(_validar_nombre_de_marca(root, brand)):
279
+ raise ValueError('Native submission requires the local customer workspace; no media transfer to the SaaS server')
280
+ chosen = cargar_brand(root, brand)
281
+ store = NativeStore(chosen.raiz, brand=brand)
282
+ bind_store(store)
283
+ job = store.get(job_id)
284
+ if job is None or not job.approval_digest:
285
+ raise ValueError('Existing job with explicit preview approval required')
286
+ payload = store.get_payload(job_id)
287
+ verify_approval(job, payload)
288
+ proof = api_eligibility(chosen, job, eligibility)
289
+ from .facebook import schedule_facebook
290
+ from .youtube import schedule_youtube
291
+ submit = schedule_facebook if job.platform == 'facebook' else schedule_youtube
292
+ with httpx.Client(timeout=60, follow_redirects=False) as client:
293
+ begin_submission()
294
+ result = submit(job, payload, brand=chosen, store=store, client=client, eligibility=proof)
295
+ from .first_comment import first_comment_status
296
+ output({'job_id': job.id, 'first_comment':first_comment_status(chosen,store.get(job.id),payload), 'state': result.state, 'remote_id': result.remote_id,
297
+ 'calendar_visible': result.calendar_visible, 'reason': result.reason,
298
+ 'server_media_storage': False})
299
+ if result.state != 'pending_verification':
300
+ raise typer.Exit(1)
301
+ run(operation, json_output=json_output, command='submit-api', brand=brand)
302
+
303
+
304
+ def dispatch_local(chosen, store, *, job_id=None, eligibility=None, eligibility_dir=None):
305
+ """Compose the existing native submitters; no new unguarded provider path."""
306
+ import httpx
307
+ from .dispatcher import dispatch_ready
308
+ from .facebook import schedule_facebook, FacebookScheduleResult
309
+ from .youtube import schedule_youtube
310
+ directory = eligibility_artifact(chosen, eligibility_dir) if eligibility_dir else None
311
+ if directory is not None and not directory.is_dir():
312
+ raise ValueError('Eligibility directory is unavailable')
313
+ with httpx.Client(timeout=60, follow_redirects=False) as client:
314
+ def delivery_context(job, payload):
315
+ if job.platform != 'instagram':
316
+ raise ValueError('This at-time API route is not enabled')
317
+ from .instagram_runtime import delivery_context as instagram_context
318
+ filename = str((directory / 'instagram.json').relative_to(chosen.raiz.resolve())) if directory else eligibility
319
+ path = eligibility_artifact(chosen, filename) if filename else None
320
+ return instagram_context(chosen, job, payload, path=path,
321
+ evidence_path=lambda value: eligibility_artifact(chosen, value), client=client,
322
+ clock=lambda: datetime.now(timezone.utc))
323
+ def submit(job, payload):
324
+ if job.platform not in {'facebook', 'youtube'}:
325
+ return FacebookScheduleResult(reason='No supported native API submission for this platform')
326
+ filename = eligibility
327
+ if directory is not None:
328
+ filename = str((directory / f'{job.platform}.json').relative_to(chosen.raiz.resolve()))
329
+ proof = api_eligibility(chosen, job, filename)
330
+ begin_submission()
331
+ handler = schedule_facebook if job.platform == 'facebook' else schedule_youtube
332
+ return handler(job, payload, brand=chosen, store=store, client=client, eligibility=proof)
333
+ delivered = dispatch_ready(datetime.now(timezone.utc), chosen.nombre, store=store,
334
+ job_id=job_id, native_submit=submit, delivery_context=delivery_context)
335
+ from .first_comment import follow_up, first_comment_status
336
+ for job in store.list_jobs():
337
+ if job_id is not None and job.id != job_id:
338
+ continue
339
+ payload = store.get_payload(job.id)
340
+ if (not payload.get('first_comment') or job.route != 'api'
341
+ or job.state not in {'dispatching','verifying','uncertain','native_scheduled','published'}
342
+ or first_comment_status(chosen, job, payload)['status'] == 'verified'):
343
+ continue
344
+ try:
345
+ follow_up(chosen, client, store, job.id, now=datetime.now(timezone.utc))
346
+ except Exception:
347
+ store.notice(job.id, 'First comment pending: exact public media or complete comment readback unavailable; inspect the durable occurrence before recovery')
348
+ return delivered
349
+
350
+
351
+ @native_app.command()
352
+ def dispatch(job_id: str, brand: str = typer.Option(...,'--brand'), root: Path = typer.Option(DEFAULT_ROOT), yes: bool = typer.Option(False,'--yes'), json_output: bool = typer.Option(False, '--json', help='One structured native result; preview on stderr.'), eligibility: str | None = typer.Option(None, '--eligibility')):
353
+ def operation():
354
+ component(job_id)
355
+ chosen=selected(root,brand,['dispatch',job_id] + (['--yes'] if yes else []) + (['--eligibility',eligibility] if eligibility else []))
356
+ if chosen is None: return
357
+ store=NativeStore(chosen.raiz,brand=brand)
358
+ if store.get(job_id) is None or not store.get(job_id).approval_digest: raise ValueError('Explicit approval required; --yes cannot bypass approval')
359
+ verify_approval(store.get(job_id),store.get_payload(job_id))
360
+ dispatch_local(chosen,store,job_id=job_id,eligibility=eligibility)
361
+ from .first_comment import first_comment_status
362
+ comment = first_comment_status(chosen,store.get(job_id),store.get_payload(job_id))
363
+ output({'job_id':job_id,'state':store.get(job_id).state,'notices':store.get_notices(job_id),'first_comment':comment})
364
+ if store.get(job_id).state in {'blocked', 'uncertain'} or comment['status'] in {'uncertain','manual_review','observed_existing','rejected','failed','conflict','applying','partial','accepted_unverifiable'}:
365
+ raise typer.Exit(1)
366
+ run(operation, json_output=json_output, command='dispatch', brand=brand)
367
+
368
+
369
+ @native_app.command()
370
+ def handoff(job_id: str, brand: str = typer.Option(...,'--brand'), root: Path = typer.Option(DEFAULT_ROOT), json_output: bool = typer.Option(False, '--json', help='One structured native result; preview on stderr.')):
371
+ def operation():
372
+ from .handoff import prepare_handoff
373
+ component(job_id)
374
+ chosen=selected(root,brand,['handoff',job_id])
375
+ if chosen is None: return
376
+ store=NativeStore(chosen.raiz,brand=brand)
377
+ job=store.get(job_id)
378
+ if job is None: raise ValueError('Unknown job')
379
+ action=store.get_action(job_id)
380
+ if action and action['status'] != 'confirmed':
381
+ output({'action':action,'upload_allowed':False,'instruction':'Submit marker BEFORE final official UI confirmation; submitted means readback only'})
382
+ else:
383
+ output(prepare_handoff(job,store.get_payload(job_id),store=store))
384
+ run(operation, json_output=json_output, command='handoff', brand=brand)
385
+
386
+
387
+ @native_app.command('submit-marker')
388
+ def submit_marker(job_id: str, brand: str = typer.Option(...,'--brand'), root: Path = typer.Option(DEFAULT_ROOT), json_output: bool = typer.Option(False, '--json', help='One structured native result; preview on stderr.')):
389
+ def operation():
390
+ from .handoff import mark_ui_submit_started
391
+ from .reconcile import mark_action_submit
392
+ component(job_id)
393
+ chosen=selected(root,brand,['submit-marker',job_id])
394
+ if chosen is None: return
395
+ store=NativeStore(chosen.raiz,brand=brand)
396
+ action=store.get_action(job_id)
397
+ if action and action['status'] != 'confirmed': mark_action_submit(job_id,store=store)
398
+ else: mark_ui_submit_started(job_id,store=store)
399
+ typer.echo('Submit boundary persisted. Confirm once in official UI; then import fresh readback. Never retry blindly.')
400
+ run(operation, json_output=json_output, command='submit-marker', brand=brand)
401
+
402
+
403
+ @native_app.command()
404
+ def reconcile(job_id: str, observation: str | None = typer.Option(None,'--observation'), brand: str = typer.Option(...,'--brand'), root: Path = typer.Option(DEFAULT_ROOT), yes: bool = typer.Option(False,'--yes'), json_output: bool = typer.Option(False, '--json', help='One structured native result; preview on stderr.')):
405
+ def operation():
406
+ from .models import NativeObservation
407
+ from .reconcile import reconcile as import_readback
408
+ component(job_id)
409
+ args=['reconcile',job_id]
410
+ if observation: component(observation); args += ['--observation',observation]
411
+ chosen=selected(root,brand,args)
412
+ if chosen is None: return
413
+ store=NativeStore(chosen.raiz,brand=brand)
414
+ job=store.get(job_id)
415
+ if job is None or not job.approval_digest: raise ValueError('Explicit approval required')
416
+ if observation:
417
+ obs=NativeObservation.model_validate_json(artifact(chosen,observation).read_text())
418
+ evidence=Path(obs.evidence_path)
419
+ if not evidence.is_absolute():
420
+ obs=NativeObservation.model_validate(obs.model_dump() | {'evidence_path':str(artifact(chosen,obs.evidence_path))})
421
+ if not Path(obs.evidence_path).resolve().is_relative_to(chosen.raiz.resolve()) or '.secrets' in Path(obs.evidence_path).parts:
422
+ raise ValueError('Evidence must remain inside brand root outside secrets')
423
+ import_readback(job_id,store=store,observation=obs)
424
+ from .first_comment import follow_up, first_comment_status
425
+ if store.get_payload(job_id).get('first_comment') and job.route == 'api':
426
+ import httpx
427
+ try:
428
+ with httpx.Client(timeout=60, follow_redirects=False) as client:
429
+ follow_up(chosen,client,store,job_id,now=datetime.now(timezone.utc),read_only=True)
430
+ except Exception:
431
+ store.notice(job_id,'First comment readback incomplete; pending obligations preserved, no provider mutation attempted')
432
+ output({'job_id':job_id,'first_comment':first_comment_status(chosen,store.get(job_id),store.get_payload(job_id)),'state':store.get(job_id).state,'observations':[o.model_dump(mode='json') for o in store.get_observations(job_id)],'notices':store.get_notices(job_id),'instruction':'Reconciliation is read-only; pending comments are executed by the approved worker after exact public readback'})
433
+ run(operation, json_output=json_output, command='reconcile', brand=brand)
434
+
435
+
436
+ def _register_action(kind):
437
+ def command(job_id: str, yes: bool = typer.Option(False,'--yes'), publish_at: str | None = typer.Option(None,'--publish-at'), dry_run: bool = typer.Option(False,'--dry-run'), approval_digest: str | None = typer.Option(None,'--approval-digest'), brand: str = typer.Option(...,'--brand'), root: Path = typer.Option(DEFAULT_ROOT), json_output: bool = typer.Option(False, '--json', help='One structured native result; preview on stderr.')):
438
+ def operation():
439
+ from .reconcile import action_preview, approve_action
440
+ component(job_id)
441
+ if dry_run == bool(approval_digest): raise ValueError('Use --dry-run OR --approval-digest from complete action preview')
442
+ args=[kind,job_id]
443
+ if publish_at: args += ['--publish-at',publish_at]
444
+ args += ['--dry-run'] if dry_run else ['--approval-digest',approval_digest]
445
+ chosen=selected(root,brand,args)
446
+ if chosen is None: return
447
+ store=NativeStore(chosen.raiz,brand=brand)
448
+ when=datetime.fromisoformat(publish_at.replace('Z','+00:00')) if publish_at else None
449
+ if dry_run: output(action_preview(job_id,kind,store=store,publish_at=when))
450
+ else: output(approve_action(job_id,approval_digest,kind=kind,store=store,publish_at=when))
451
+ run(operation, json_output=json_output, command=kind, brand=brand)
452
+ native_app.command(kind)(command)
453
+
454
+
455
+ for _operation in ('cancel','reschedule'):
456
+ _register_action(_operation)
457
+
458
+
459
+ @native_app.command('migration-prepare')
460
+ def migration_prepare(brand: str = typer.Option(...,'--brand'), root: Path = typer.Option(DEFAULT_ROOT),
461
+ manifest: str = typer.Option('native-migration.json','--manifest'),
462
+ dry_run: bool = typer.Option(False,'--dry-run'), json_output: bool = typer.Option(False, '--json', help='One structured native result; preview on stderr.')):
463
+ def operation():
464
+ from .migration import prepare_migration
465
+ component(manifest)
466
+ if not dry_run: raise ValueError('Migration preparation requires --dry-run')
467
+ chosen=selected(root,brand,['migration-prepare','--manifest',manifest,'--dry-run'])
468
+ if chosen is not None: output(prepare_migration(brand,root=root,manifest=manifest))
469
+ run(operation, json_output=json_output, command='migration-prepare', brand=brand)
470
+
471
+
472
+ @native_app.command('migration-apply')
473
+ def migration_apply(digest: str = typer.Option(...,'--digest'), brand: str = typer.Option(...,'--brand'),
474
+ root: Path = typer.Option(DEFAULT_ROOT), manifest: str = typer.Option('native-migration.json','--manifest'), json_output: bool = typer.Option(False, '--json', help='One structured native result; preview on stderr.')):
475
+ def operation():
476
+ from .migration import apply_migration
477
+ component(manifest)
478
+ chosen=selected(root,brand,['migration-apply','--manifest',manifest,'--digest',digest])
479
+ if chosen is not None: output(apply_migration(digest,brand=brand,root=root,manifest=manifest))
480
+ run(operation, json_output=json_output, command='migration-apply', brand=brand)
481
+
482
+
483
+ @native_app.command('migration-recover')
484
+ def migration_recover(digest: str = typer.Option(...,'--digest'), brand: str = typer.Option(...,'--brand'), root: Path = typer.Option(DEFAULT_ROOT), json_output: bool = typer.Option(False, '--json', help='One structured native result; preview on stderr.')):
485
+ def operation():
486
+ from .migration import recover_migration
487
+ chosen=selected(root,brand,['migration-recover','--digest',digest])
488
+ if chosen is not None: output(recover_migration(digest,brand=brand,root=root))
489
+ run(operation, json_output=json_output, command='migration-recover', brand=brand)
490
+
491
+
492
+ @native_app.command('deliver')
493
+ def deliver(brand: str = typer.Option(...,'--brand'), root: Path = typer.Option(DEFAULT_ROOT), json_output: bool = typer.Option(False, '--json', help='One structured native result; preview on stderr.'), eligibility_dir: str | None = typer.Option(None, '--eligibility-dir')):
494
+ """Periodic worker: approved jobs only; no graphical session on the server."""
495
+ def operation():
496
+ chosen=selected(root,brand,['deliver'] + (['--eligibility-dir',eligibility_dir] if eligibility_dir else []))
497
+ if chosen is None: return
498
+ store=NativeStore(chosen.raiz,brand=brand)
499
+ delivered=dispatch_local(chosen,store,eligibility_dir=eligibility_dir)
500
+ from .first_comment import first_comment_status
501
+ comments = [{'job_id':j.id, **first_comment_status(chosen,j,store.get_payload(j.id))}
502
+ for j in store.list_jobs() if store.get_payload(j.id).get('first_comment')]
503
+ problems=[j.id for j in store.list_jobs() if j.state in {'blocked', 'uncertain'}]
504
+ problems += [c['job_id'] for c in comments if c['status'] in {'uncertain','manual_review','observed_existing','rejected','failed','conflict','applying','partial','accepted_unverifiable'} and c['job_id'] not in problems]
505
+ output({'delivered':delivered,'first_comments':comments,'awaiting_ui':[j.id for j in store.list_jobs() if j.state=='awaiting_ui'],
506
+ 'needs_attention':problems,
507
+ 'instruction':'Official UI handoffs require an authorized operator session; API routes remain closed unless capability is enabled.'})
508
+ if problems:
509
+ raise typer.Exit(1)
510
+ run(operation, json_output=json_output, command='deliver', brand=brand)
@@ -0,0 +1,120 @@
1
+ """Deliver approved native or due API jobs; never invoke the legacy executor."""
2
+ from datetime import datetime, timedelta, timezone
3
+ from socialctl.capabilities import delivery_route
4
+ from .approval import verify_approval
5
+ from .handoff import prepare_handoff
6
+ from .models import aware
7
+ from .store import NativeStore
8
+
9
+
10
+ def dispatch_ready(now: datetime, brand: str, *, store: NativeStore,
11
+ job_id: str | None = None, budget: int = 10,
12
+ adapters: dict | None = None, capabilities: dict | None = None,
13
+ native_submit=None, delivery_context=None) -> list[str]:
14
+ """Budget counts delivery attempts, independently of editorial reservations.
15
+
16
+ API jobs send in a bounded five-minute window from the approved instant.
17
+ Missing capability evidence never selects an adapter or a UI fallback.
18
+ """
19
+ now = aware(now)
20
+ if brand != store.brand or budget < 0:
21
+ raise ValueError('Explicit brand and nonnegative delivery budget required')
22
+ delivered = []
23
+ for job in store.list_jobs():
24
+ if job_id is not None and job.id != job_id:
25
+ continue
26
+ if job.state not in {'approved', 'waiting_window', 'ready'}:
27
+ continue
28
+ payload = store.get_payload(job.id)
29
+ try:
30
+ verify_approval(job, payload)
31
+ except ValueError:
32
+ store.notice(job.id,'Approval or media changed; new preview required',now=now)
33
+ continue
34
+ delivery_mode = payload.get('delivery_mode', 'native_schedule')
35
+ if delivery_mode not in {'native_schedule', 'at_time'}:
36
+ store.notice(job.id,'Unknown delivery mode; new preview required',now=now)
37
+ continue
38
+ deadline = job.publish_at + (timedelta(minutes=5)
39
+ if job.route == 'api' and delivery_mode == 'at_time'
40
+ else timedelta())
41
+ if deadline <= now:
42
+ store.transition(job.id,job.state,'blocked',now=now)
43
+ store.notice(job.id,'Delivery window expired; no late publication',now=now)
44
+ continue
45
+ if job.route == 'api' and delivery_mode == 'at_time' and now < job.publish_at:
46
+ continue
47
+ cooldown=store.cooldown_until(job.id)
48
+ if job.dispatch_after > now or (cooldown is not None and cooldown > now):
49
+ if job.state == 'approved':
50
+ store.transition(job.id,job.state,'waiting_window',now=now)
51
+ continue
52
+ if len(delivered) >= budget:
53
+ break
54
+ if job.route == 'api':
55
+ if delivery_mode == 'native_schedule' and native_submit is not None:
56
+ try:
57
+ result = native_submit(job, payload)
58
+ if result.state == 'pending_verification':
59
+ delivered.append(job.id)
60
+ elif result.state == 'ui_required':
61
+ store.transition(job.id, job.state, 'blocked', now=now)
62
+ store.notice(job.id, result.reason, now=now)
63
+ else:
64
+ store.notice(job.id, 'Native API result requires reconciliation; no automatic resend', now=now)
65
+ except Exception:
66
+ current = store.get(job.id)
67
+ # Native submitters own their durable claim and uncertainty
68
+ # handling. A competing worker may have claimed this job;
69
+ # this outer worker must never alter that attempt's state.
70
+ if current.state == job.state and current.state in {'approved', 'waiting_window', 'ready'}:
71
+ store.transition(job.id, current.state, 'blocked', now=now)
72
+ store.notice(job.id, 'Native API submission unavailable; inspect eligibility and existing attempts before another approval', now=now)
73
+ continue
74
+ capability = (capabilities or {}).get(job.platform, {})
75
+ adapter = (adapters or {}).get(job.platform)
76
+ if delivery_mode == 'at_time' and delivery_context is not None:
77
+ try:
78
+ adapter, capability = delivery_context(job, payload)
79
+ except Exception:
80
+ store.transition(job.id, job.state, 'blocked', now=now)
81
+ reason = ('Unsupported Instagram first-comment combination or eligibility; no publication attempted'
82
+ if job.platform == 'instagram' and payload.get('first_comment') else
83
+ 'API delivery eligibility or account check failed; no publication attempted')
84
+ store.notice(job.id, reason, now=now)
85
+ continue
86
+ native_unverified = (delivery_mode == 'native_schedule'
87
+ and capability.get('verified_delivery_mode') != 'native_schedule')
88
+ if native_unverified or delivery_route(job, capability, payload.get('options', {}).get('format')) != 'api' or adapter is None:
89
+ store.transition(job.id,job.state,'blocked',now=now)
90
+ store.notice(job.id,'API capability/account unverified or adapter absent; new approval required',now=now)
91
+ continue
92
+ claimed = store.claim(job.id,job.state,now=now)
93
+ if claimed is None:
94
+ continue
95
+ def checkpoint(value, *, claimed=claimed):
96
+ store.checkpoint(claimed.id,claimed.attempt_id,value,now=now)
97
+ try:
98
+ remote_id = adapter.deliver(claimed,payload,checkpoint)
99
+ store.mark_api_submitted(claimed.id,claimed.attempt_id,remote_id,now=now)
100
+ delivered.append(claimed.id)
101
+ except Exception:
102
+ # The adapter may have sent bytes even if its response failed.
103
+ # Preserve the claim and every checkpoint for reconciliation.
104
+ current = store.get(claimed.id)
105
+ if current and current.state == 'dispatching':
106
+ store.transition(claimed.id,'dispatching','uncertain',now=now)
107
+ store.notice(claimed.id,'API result uncertain; reconcile before another send',now=now)
108
+ continue
109
+ if job.route != 'ui':
110
+ store.transition(job.id,job.state,'blocked',now=now)
111
+ store.notice(job.id,'API capability closed; prepare and approve a new UI intent; route unchanged',now=now)
112
+ continue
113
+ try:
114
+ prepare_handoff(job,payload,store=store,now=now,require_new=True)
115
+ delivered.append(job.id)
116
+ except Exception:
117
+ # A competing worker may own the claim. Never alter its state.
118
+ # An interrupted claim remains dispatching until explicit recovery.
119
+ store.notice(job.id,'Delivery requires operator review; inspect existing attempt before retry',now=now)
120
+ return delivered