src/queue.js
// Content hashing, idempotency keys and the approval-queue scheduler for social-publisher.
import { createHash } from "node:crypto";
import { ToolError } from "./errors.js";
import { RULES, measure } from "./text.js";
import { isValidTimeZone, zonedToUtc, fromDayNum, weekday, parseYmd, isoUtc, isoLocal, parseInstant, utcToZoned, dayNum } from "./tz.js";
const WD = { SU: 0, MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6 };
const sha256 = (s) => createHash("sha256").update(s).digest("hex");
const norm = (s) => String(s ?? "").normalize("NFC").replace(/\s+/g, " ").trim();
/** Hash of what a reader sees: platform, text, title and link (whitespace-insensitive). */
export function contentHash(item) {
return sha256(JSON.stringify([item.platform, norm(item.text), norm(item.title), norm(item.link)]));
}
/** Deterministic per platform + account + content, so retries and re-runs map to the same key. */
export function idempotencyKey(platform, account, hash) {
return sha256(JSON.stringify(["agentrove.social-publisher/1", platform, norm(account).toLowerCase(), hash])).slice(0, 32);
}
export function requireTz(tz) {
if (!isValidTimeZone(tz)) throw new ToolError("invalid_input", `timezone: unknown IANA time zone "${String(tz).slice(0, 64)}"`);
return tz;
}
/**
* Key for the cross-account check: what readers see (text and title, case- and whitespace-insensitive).
* The link field is left out because it is metadata; on X the link is already part of the text.
*/
const visibleKey = (item) => `${item.platform}|${sha256(JSON.stringify([norm(item.text).toLowerCase(), norm(item.title).toLowerCase()]))}`;
const localDay = (ms, tz) => {
const z = utcToZoned(ms, tz);
return dayNum(z.y, z.m, z.d);
};
export function scheduleQueue(input, nowMs) {
const tz = requireTz(input.timezone);
const maxPerDay = input.max_per_account_per_day ?? 3;
const gapMs = (input.min_gap_minutes ?? 60) * 60000;
const horizonDays = input.horizon_days ?? 60;
const warnings = [];
const skipped = [];
// State per platform+account: occupied instants and posts per local day.
const accounts = new Map();
const slotState = (platform, account) => {
const k = `${platform}|${norm(account).toLowerCase()}`;
if (!accounts.has(k)) accounts.set(k, { times: [], perDay: new Map() });
return accounts.get(k);
};
const fitsAccount = (st, t) => (st.perDay.get(localDay(t, tz)) ?? 0) < maxPerDay && st.times.every((x) => Math.abs(x - t) >= gapMs);
const occupy = (st, t) => {
st.times.push(t);
const d = localDay(t, tz);
st.perDay.set(d, (st.perDay.get(d) ?? 0) + 1);
};
const dedupe = new Map(); // platform|account|hash -> id
const crossAccount = new Map(); // visibleKey -> first account
const existing = [];
const REQUIRED = ["id", "content_hash", "idempotency_key", "platform", "account", "text", "publish_at", "status"];
for (const [i, it] of (input.existing_queue?.items ?? []).entries()) {
if (!it || REQUIRED.some((k) => typeof it[k] !== "string") || typeof it.approved !== "boolean") {
warnings.push(`existing_queue.items[${i}] is not a complete queue item; it was left out of the returned queue.`);
continue;
}
existing.push(it);
dedupe.set(`${it.platform}|${norm(it.account).toLowerCase()}|${it.content_hash}`, it.id);
if (!crossAccount.has(visibleKey(it))) crossAccount.set(visibleKey(it), norm(it.account).toLowerCase());
const t = parseInstant(it.publish_at);
if (t !== null) occupy(slotState(it.platform, it.account), t);
}
// Pass 1: validate and de-duplicate in input order (the first copy wins).
const accepted = [];
for (const [index, p] of input.posts.entries()) {
const rule = RULES[p.platform];
const len = measure(p.text, rule.method);
if (len > rule.limit) {
skipped.push({ index, reason: `Text is ${len} (${rule.method}) but ${p.platform} allows ${rule.limit}; re-draft it with draft_posts.` });
continue;
}
if (p.platform === "youtube" && !norm(p.title)) {
skipped.push({ index, reason: "YouTube items need a title." });
continue;
}
const hash = contentHash(p);
const acct = norm(p.account).toLowerCase();
const key = `${p.platform}|${acct}|${hash}`;
if (dedupe.has(key)) {
skipped.push({ index, reason: "Duplicate: the same content is already queued for this account.", duplicate_of: dedupe.get(key) });
continue;
}
const firstAcct = crossAccount.get(visibleKey(p));
if (firstAcct !== undefined && firstAcct !== acct) {
if (p.platform === "x") {
skipped.push({ index, reason: "Identical content is already queued for another X account; X's automation rules prohibit posting identical content across multiple accounts." });
continue;
}
warnings.push(`posts[${index}]: identical ${p.platform} content is queued for more than one account; consider account-specific wording.`);
}
const id = `q_${sha256(key).slice(0, 16)}`;
dedupe.set(key, id);
if (firstAcct === undefined) crossAccount.set(visibleKey(p), acct);
accepted.push({ index, p, hash, id });
}
// Pass 2: explicit times.
const placed = [];
const auto = [];
for (const a of accepted) {
if (a.p.publish_at === undefined) {
auto.push(a);
continue;
}
const t = parseInstant(a.p.publish_at, tz);
if (t === null) throw new ToolError("invalid_input", `posts[${a.index}].publish_at must be an ISO date-time with Z/offset or a local YYYY-MM-DDTHH:MM`);
if (t < nowMs) {
skipped.push({ index: a.index, reason: `publish_at ${isoUtc(t)} is in the past.` });
continue;
}
const st = slotState(a.p.platform, a.p.account);
if (!fitsAccount(st, t)) {
skipped.push({ index: a.index, reason: `publish_at would exceed ${maxPerDay} posts per day or the ${gapMs / 60000}-minute gap for this account.` });
continue;
}
occupy(st, t);
placed.push({ ...a, t });
}
// Pass 3: auto-place into local slot times (DST-correct: each day's local time is converted with that day's offset).
if (auto.length) {
if (!input.slots) throw new ToolError("invalid_input", "Posts without publish_at need slots ({start_date, times, days?}).");
const startDay = parseYmd(input.slots.start_date);
if (startDay === null) throw new ToolError("invalid_input", "slots.start_date must be a real calendar date (YYYY-MM-DD)");
const days = new Set((input.slots.days ?? ["MO", "TU", "WE", "TH", "FR", "SA", "SU"]).map((d) => WD[d]));
const times = [...new Set(input.slots.times)].sort().map((t) => t.split(":").map(Number));
const from = Math.max(startDay, localDay(nowMs, tz));
const candidates = [];
for (let day = from; day < from + horizonDays; day++) {
if (!days.has(weekday(day))) continue;
const f = fromDayNum(day);
for (const [hh, mi] of times) {
const t = zonedToUtc(f.y, f.m, f.d, hh, mi, 0, tz);
if (t >= nowMs) candidates.push(t);
}
}
for (const a of auto) {
const st = slotState(a.p.platform, a.p.account);
const t = candidates.find((c) => fitsAccount(st, c));
if (t === undefined) {
skipped.push({ index: a.index, reason: `No free slot for this account within ${horizonDays} days (max ${maxPerDay}/day, ${gapMs / 60000}-minute gap).` });
continue;
}
occupy(st, t);
placed.push({ ...a, t });
}
}
const items = placed.map(({ p, hash, id, t }) => {
const item = {
id,
content_hash: hash,
idempotency_key: idempotencyKey(p.platform, p.account, hash),
platform: p.platform,
account: p.account,
text: p.text,
publish_at: isoUtc(t),
publish_at_local: isoLocal(t, tz),
status: "pending_approval",
approved: false,
};
if (p.title !== undefined) item.title = p.title;
if (p.link !== undefined) item.link = p.link;
return item;
});
const all = [...existing, ...items].sort((a, b) => String(a.publish_at ?? "").localeCompare(String(b.publish_at ?? "")));
skipped.sort((a, b) => a.index - b.index);
if (items.length) warnings.push("New items are pending_approval. Review each one and set approved: true before calling publish; nothing is posted automatically.");
return { items: all, added: items.length, skipped, warnings, tz };
}