handsomeng/Hskill-chatcut / skills/publish-video-three-platforms
publish-video-three-platforms
VerifiedPrepare and upload an approved local video to Xiaohongshu, Douyin, and WeChat Channels through the user's logged-in browser. Analyze the actual video or transcript with AI, generate platform-specific titles, descriptions, and hashtags from the content, validate official topic selection, apply scheduling and original-content options when available, and stop before the final publish button unless the user explicitly authorizes publishing. Trigger when a user asks to publish or prepare one video for these three Chinese creator platforms.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 11.6 KB |
| references/content-generation.md | markdown | 2.3 KB |
| references/job-and-adapters.md | markdown | 6.3 KB |
| references/platform-interaction-signals.md | markdown | 1.8 KB |
| scripts/job_state.pyexecutable | script | 14.3 KB |
scripts/job_state.py
View on GitHub#!/usr/bin/env python3
"""Validate and atomically update three-platform publish job state."""
from __future__ import annotations
import argparse
import copy
from datetime import datetime
import json
import os
from pathlib import Path
import re
import tempfile
from typing import Any
PLATFORMS = ("xiaohongshu", "douyin", "wechat_channels")
ALLOWED_STATES = {
"pending",
"page_ready",
"upload_started",
"media_ready",
"copy_ready",
"topics_ready",
"options_ready",
"review_ready",
"published",
"blocked",
}
ALLOWED_MODES = {"prepare_only", "scheduled", "publish_now"}
ACTIVE_STATES = {"copy_ready", "topics_ready", "options_ready"}
SENSITIVE_TERMS = {
"cookie",
"cookies",
"credential",
"credentials",
"password",
"secret",
"secrets",
"token",
"tokens",
}
SENSITIVE_COMPANIONS = {
"api",
"access",
"auth",
"bearer",
"blob",
"client",
"hash",
"key",
"private",
"refresh",
"session",
"value",
}
KEY_QUALIFIERS = {"api", "private", "client", "access", "auth"}
class ValidationError(ValueError):
"""Raised when a job state document violates the contract."""
def __init__(self, errors: list[str]):
self.errors = errors
super().__init__("\n".join(errors))
def _normalize_key(key: str) -> tuple[str, list[str]]:
with_boundaries = re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", key)
normalized = re.sub(r"[^a-zA-Z0-9]+", "_", with_boundaries).strip("_").lower()
return normalized, [part for part in normalized.split("_") if part]
def _is_sensitive_key(key: str) -> bool:
normalized, parts = _normalize_key(key)
part_set = set(parts)
if "authorization" in part_set:
return True
if "key" in part_set and part_set & KEY_QUALIFIERS:
return True
if normalized in SENSITIVE_TERMS:
return True
if any(normalized.endswith(f"_{term}") for term in SENSITIVE_TERMS):
return True
return bool(part_set & SENSITIVE_TERMS and part_set & SENSITIVE_COMPANIONS)
def _find_sensitive_keys(value: Any, path: str = "root") -> list[str]:
errors: list[str] = []
if isinstance(value, dict):
for key, child in value.items():
key_path = f"{path}.{key}"
if _is_sensitive_key(key):
errors.append(f"{key_path}: credential fields are forbidden")
errors.extend(_find_sensitive_keys(child, key_path))
elif isinstance(value, list):
for index, child in enumerate(value):
errors.extend(_find_sensitive_keys(child, f"{path}[{index}]"))
return errors
def _parse_iso_datetime(value: Any, path: str) -> list[str]:
if not isinstance(value, str) or not value.strip():
return [f"{path}: expected an ISO 8601 date-time string"]
if "T" not in value:
return [f"{path}: expected an ISO 8601 date-time string"]
candidate = value[:-1] + "+00:00" if value.endswith("Z") else value
try:
datetime.fromisoformat(candidate)
except ValueError:
return [f"{path}: expected an ISO 8601 date-time string"]
return []
def _validate_schedule(schedule: Any, path: str, required: bool) -> list[str]:
if schedule is None:
return [f"{path}: schedule is required in scheduled mode"] if required else []
if not isinstance(schedule, dict):
return [f"{path}: expected an object or null"]
errors = []
errors.extend(_parse_iso_datetime(schedule.get("at"), f"{path}.at"))
if not isinstance(schedule.get("timezone"), str) or not schedule["timezone"].strip():
errors.append(f"{path}.timezone: expected a non-empty string")
return errors
def validate_job(job: Any) -> None:
errors: list[str] = []
if not isinstance(job, dict):
raise ValidationError(["root: expected an object"])
errors.extend(_find_sensitive_keys(job))
publish = job.get("publish")
if not isinstance(publish, dict):
errors.append("publish: expected an object")
publish = {}
mode = publish.get("mode")
if mode not in ALLOWED_MODES:
errors.append(f"publish.mode: expected one of {sorted(ALLOWED_MODES)}")
owner = publish.get("final_action_owner")
authorized = publish.get("final_click_authorized_current_turn")
if owner not in {"user", "agent"}:
errors.append("publish.final_action_owner: expected 'user' or 'agent'")
if not isinstance(authorized, bool):
errors.append("publish.final_click_authorized_current_turn: expected a boolean")
if mode == "publish_now":
if owner != "agent" or authorized is not True:
errors.append(
"publish: publish_now requires final_action_owner='agent' and "
"final_click_authorized_current_turn=true"
)
elif owner != "user" or authorized is not False:
errors.append(
"publish: prepare_only and scheduled require final_action_owner='user' and "
"final_click_authorized_current_turn=false"
)
platforms = job.get("platforms")
if not isinstance(platforms, dict):
errors.append("platforms: expected an object")
platforms = {}
elif set(platforms) != set(PLATFORMS):
errors.append(f"platforms: expected exactly {list(PLATFORMS)}")
if "active_platform" not in job:
errors.append("active_platform: field is required")
active_platform = None
else:
active_platform = job["active_platform"]
if active_platform is not None and active_platform not in PLATFORMS:
errors.append(f"active_platform: expected null or one of {list(PLATFORMS)}")
active_states: list[str] = []
for platform in PLATFORMS:
data = platforms.get(platform)
path = f"platforms.{platform}"
if not isinstance(data, dict):
errors.append(f"{path}: expected an object")
continue
state = data.get("state")
if state not in ALLOWED_STATES:
errors.append(f"{path}.state: expected one of {sorted(ALLOWED_STATES)}")
elif state in ACTIVE_STATES:
active_states.append(platform)
if "schedule" not in data:
errors.append(f"{path}.schedule: field is required")
else:
errors.extend(
_validate_schedule(data["schedule"], f"{path}.schedule", mode == "scheduled")
)
for status_name in ("original_status", "declaration_status"):
status = data.get(status_name)
if not isinstance(status, str) or not status.strip():
errors.append(f"{path}.{status_name}: expected a non-empty string")
if "last_verified_at" not in data:
errors.append(f"{path}.last_verified_at: field is required")
elif data["last_verified_at"] is not None:
errors.extend(
_parse_iso_datetime(data["last_verified_at"], f"{path}.last_verified_at")
)
evidence = data.get("evidence")
if not isinstance(evidence, dict):
errors.append(f"{path}.evidence: expected an object")
evidence = {}
final_button_clicked = evidence.get("final_button_clicked")
if state == "published":
if mode != "publish_now" or owner != "agent" or authorized is not True:
errors.append(f"{path}.state: published requires current-turn publish authorization")
if final_button_clicked is not True:
errors.append(
f"{path}.evidence.final_button_clicked: must be true for published"
)
elif final_button_clicked is not False:
errors.append(f"{path}.evidence.final_button_clicked: must be false before published")
if state not in {"review_ready", "published"}:
continue
if evidence.get("login_ready") is not True:
errors.append(f"{path}.evidence.login_ready: must be true for {state}")
if evidence.get("media_ready") is not True:
errors.append(f"{path}.evidence.media_ready: must be true for {state}")
title = data.get("title")
if not isinstance(title, str) or not title:
errors.append(f"{path}.title: expected a non-empty string for {state}")
elif evidence.get("title_readback") != title:
errors.append(f"{path}.evidence.title_readback: must equal title")
body = data.get("body")
if not isinstance(body, str):
errors.append(f"{path}.body: expected a string for {state}")
elif evidence.get("body_readback") != body:
errors.append(f"{path}.evidence.body_readback: must equal body")
topics = data.get("topics")
if not isinstance(topics, list) or not topics or not all(
isinstance(topic, str) and topic for topic in topics
):
errors.append(f"{path}.topics: expected a non-empty string array for {state}")
elif evidence.get("topic_elements") != topics:
errors.append(f"{path}.evidence.topic_elements: must equal topics")
if mode == "scheduled" and evidence.get("schedule_readback") != data.get("schedule"):
errors.append(f"{path}.evidence.schedule_readback: must equal schedule")
if evidence.get("original_readback") != data.get("original_status"):
errors.append(f"{path}.evidence.original_readback: must equal original_status")
if evidence.get("declaration_readback") != data.get("declaration_status"):
errors.append(f"{path}.evidence.declaration_readback: must equal declaration_status")
if state == "review_ready" and evidence.get("final_button_visible") is not True:
errors.append(f"{path}.evidence.final_button_visible: must be true")
if not isinstance(data.get("last_verified_at"), str) or not data["last_verified_at"].strip():
errors.append(f"{path}.last_verified_at: required for {state}")
if len(active_states) > 1:
errors.append("platforms: at most one platform may be in an active serial state")
elif active_states and active_platform != active_states[0]:
errors.append(f"active_platform: must equal {active_states[0]!r}")
elif not active_states and active_platform is not None:
errors.append("active_platform: must be null when no platform is in an active serial state")
if errors:
raise ValidationError(errors)
def load_job(path: Path) -> dict[str, Any]:
try:
with path.open(encoding="utf-8") as handle:
job = json.load(handle)
except (OSError, json.JSONDecodeError) as exc:
raise ValidationError([f"{path}: {exc}"]) from exc
validate_job(job)
return job
def _merge(target: dict[str, Any], patch: dict[str, Any]) -> None:
for key, value in patch.items():
if isinstance(value, dict) and isinstance(target.get(key), dict):
_merge(target[key], value)
else:
target[key] = copy.deepcopy(value)
def update_platform(path: Path, platform: str, patch: dict[str, Any]) -> None:
if platform not in PLATFORMS:
raise ValidationError([f"platform: expected one of {list(PLATFORMS)}"])
if not isinstance(patch, dict):
raise ValidationError(["patch: expected an object"])
sensitive = _find_sensitive_keys(patch, "patch")
if sensitive:
raise ValidationError(sensitive)
job = load_job(path)
active_platform = job.get("active_platform")
if active_platform is not None and active_platform != platform:
raise ValidationError(
[
f"active_platform={active_platform!r} blocks updates to "
f"platform {platform!r}"
]
)
previous_state = job["platforms"][platform].get("state")
updated = copy.deepcopy(job)
_merge(updated["platforms"][platform], patch)
updated_state = updated["platforms"][platform].get("state")
if (
updated_state == "published"
and previous_state not in {"review_ready", "published"}
):
raise ValidationError(
[
f"platforms.{platform}.state: published transition requires "
"previous state review_ready"
]
)
if updated_state in ACTIVE_STATES:
updated["active_platform"] = platform
elif updated.get("active_platform") == platform:
updated["active_platform"] = None
validate_job(updated)
temporary_path: str | None = None
try:
with tempfile.NamedTemporaryFile(
mode="w",
encoding="utf-8",
dir=path.parent,
prefix=f".{path.name}.",
suffix=".tmp",
delete=False,
) as handle:
temporary_path = handle.name
json.dump(updated, handle, ensure_ascii=False, indent=2)
handle.write("\n")
handle.flush()
os.fsync(handle.fileno())
os.replace(temporary_path, path)
temporary_path = None
finally:
if temporary_path is not None:
try:
os.unlink(temporary_path)
except FileNotFoundError:
pass
def _load_patch(value: str) -> dict[str, Any]:
try:
patch = json.loads(value)
except json.JSONDecodeError as exc:
raise ValidationError([f"patch: {exc}"]) from exc
if not isinstance(patch, dict):
raise ValidationError(["patch: expected an object"])
return patch
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description=__doc__)
subparsers = parser.add_subparsers(dest="command", required=True)
validate_parser = subparsers.add_parser("validate", help="validate one job state file")
validate_parser.add_argument("file", type=Path)
update_parser = subparsers.add_parser("update", help="atomically update one platform")
update_parser.add_argument("file", type=Path)
update_parser.add_argument("platform", choices=PLATFORMS)
update_parser.add_argument("--patch", required=True, help="JSON object merged into one platform")
return parser
def main() -> int:
args = build_parser().parse_args()
try:
if args.command == "validate":
load_job(args.file)
print(f"valid: {args.file}")
else:
update_platform(args.file, args.platform, _load_patch(args.patch))
print(f"updated: {args.platform}")
except ValidationError as exc:
for error in exc.errors:
print(f"error: {error}")
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack." | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |