linkedin-studio/hooks/scripts/slots.mjs
Kjell Tore Guttormsen 677eab9294 feat(linkedin-studio): N13 — publiserings-slots + vacancy-varsel + WIP-roll-up + slot-default [skip-docs]
A1-10 + D-5. The queue answers "what is scheduled"; nothing answered "is the week
covered, and what is still being written". N13 makes both readable at session start.

- Publishing slots are operator config: profile/publishing-slots.json in the per-user
  data dir, schema + OPT-IN template in config/publishing-slots.template.json. The
  plugin ships no publishing times and writes the grid for nobody; absent config means
  every slot surface stays silent (same never-nag discipline as the trend/brain nudges).
  Data dir rather than the state file, which is machine-written and whose frontmatter
  reader does not parse lists.
- hooks/scripts/slots.mjs (new): one implementation behind four surfaces. Zero-dep (a
  SessionStart hook must not spawn tsx), pure core (dates in as strings, no clock),
  imported by the commands exactly as queue-manager.mjs already is — so session-start's
  vacancy warning and Step 10's slot default cannot drift apart.
- Coverage counts the short-form queue (scheduled/published; cancelled frees the slot)
  AND editions-register rows claiming that date, counted per date, so long-form and
  short-form cannot be double-booked and a two-slot day needs two posts.
- Session start gains "## Editions in Flight" (series, phase, next action, claimed slot,
  days in flight) and "## Publishing Slots" (next open slot, open count in 14 days, and
  how to fill it when the gap is <=3 days). The existing discovery nudge is untouched.
- /linkedin router + /linkedin:calendar surface the same roll-up; calendar documents the
  opt-in copy. /linkedin:newsletter Step 10 defaults to the next open slot (one
  confirmation, not an interview) and writes --slot onto the register row.
- D-5: references/scheduling-strategy.md marked "confidence: low / directional" per the
  algorithm reference's own standard, deferring to the operator's grid and their own
  analytics. Neutral example time replaces the operator-specific one in the N12 docs.

TDD: red proven first (module absent; 5 session-start behaviours failing).
hooks 140 -> 174 · test-runner 184 -> 197 (Section 16t: 13 unconditional greps incl. a
de-niche check that no publishing time is hardcoded in the slot path and no operator grid
is committed, + non-vacuity self-test; anti-erosion floor 166 -> 179).
Suites green: trends 300/0 · brain 134/0 · editions 72/0 · specifics-bank 45/0 ·
tests 35/0 · render 60/0.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QxvWAjte7vPcF79QeSRvRJ
2026-07-25 07:28:48 +02:00

211 lines
8.1 KiB
JavaScript

#!/usr/bin/env node
// Publishing slots + work-in-progress view (N13 — A1-10).
//
// The week's production grid in one place: the slots the operator publishes in,
// what already covers them (the short-form queue + the editions register), and
// which long-form editions are still in flight. Session start reads it so the
// week is visible without opening a file; the commands read the SAME functions
// through `node --input-type=module -e` (the queue-manager.mjs pattern), so the
// vacancy the hook reports and the slot `/linkedin:newsletter` defaults to can
// never disagree.
//
// Zero-dep on purpose: this runs inside a SessionStart hook, which must not
// spawn tsx or touch node_modules (same discipline as session-start.mjs's direct
// trend-store read).
//
// DOMAIN-NEUTRAL: the plugin ships no publishing times. The grid lives in the
// per-user data dir (`profile/publishing-slots.json`); an absent config means
// silence, never a default schedule imposed on the user.
//
// The core is pure — dates in as `YYYY-MM-DD` strings, no clock — so vacancy is
// testable without freezing time. Only the thin readers below touch the disk.
import { readFileSync, existsSync } from 'node:fs';
import { join } from 'node:path';
import { getDataRoot } from './data-root.mjs';
export const SLOTS_SCHEMA_VERSION = 1;
const MS_PER_DAY = 86400000;
// Canonical day keys (ISO-ish 3-letter, lowercase) → JS getUTCDay index.
const DAY_INDEX = { sun: 0, mon: 1, tue: 2, wed: 3, thu: 4, fri: 5, sat: 6 };
const DAY_LABEL = { sun: 'Sun', mon: 'Mon', tue: 'Tue', wed: 'Wed', thu: 'Thu', fri: 'Fri', sat: 'Sat' };
// A queue entry counts as covering its date when it is still going out or has
// already gone out. A cancelled entry does NOT — that slot fell vacant again.
const COVERING_QUEUE_STATUS = new Set(['scheduled', 'published']);
const TIME_RE = /^([01]\d|2[0-3]):[0-5]\d$/;
/** `${DATA}/profile/publishing-slots.json` — user config, survives reinstalls (M0). */
export function defaultSlotsPath() {
return join(getDataRoot('profile'), 'publishing-slots.json');
}
/** `${DATA}/editions/register.json` — twin of scripts/editions/src/register.ts:defaultRegisterPath. */
export function defaultRegisterPath() {
return join(getDataRoot('editions'), 'register.json');
}
/** `${DATA}/drafts/queue.json` — read directly (never via queue-manager's ensureQueue: a read-only check must not create files). */
function queuePath() {
return join(getDataRoot('drafts'), 'queue.json');
}
function readJson(path) {
if (!existsSync(path)) return null;
try {
return JSON.parse(readFileSync(path, 'utf-8'));
} catch {
return null;
}
}
/**
* Normalize a raw config into the grid the rest of the module speaks.
* Forgiving by design: an unusable row is dropped, never thrown — a typo in a
* config file must not take down session start.
*/
export function normalizeSlots(raw) {
const timezone = typeof raw?.timezone === 'string' ? raw.timezone : '';
const rows = Array.isArray(raw?.slots) ? raw.slots : [];
const slots = [];
for (const r of rows) {
const day = String(r?.day ?? '').trim().toLowerCase().slice(0, 3);
const time = String(r?.time ?? '').trim();
if (!(day in DAY_INDEX) || !TIME_RE.test(time)) continue;
slots.push({ day, time, label: typeof r?.label === 'string' ? r.label : '' });
}
return { timezone, slots };
}
/** Read the per-user grid. Absent/malformed ⇒ empty grid (silence, not a nag). */
export function readSlots(path = defaultSlotsPath()) {
return normalizeSlots(readJson(path));
}
function addDays(dateStr, n) {
// Noon UTC anchor — the codebase idiom (state-updater.mjs) that keeps date
// arithmetic clear of DST edges.
const d = new Date(`${dateStr}T12:00:00Z`);
d.setUTCDate(d.getUTCDate() + n);
return d.toISOString().slice(0, 10);
}
function weekdayKey(dateStr) {
const idx = new Date(`${dateStr}T12:00:00Z`).getUTCDay();
return Object.keys(DAY_INDEX).find((k) => DAY_INDEX[k] === idx) ?? '';
}
/**
* Expand the weekly grid into concrete occurrences across `days` calendar days
* starting at (and including) `from` — a slot today is still actionable.
*/
export function slotOccurrences(slots, from, days) {
const out = [];
for (let i = 0; i < days; i += 1) {
const date = addDays(from, i);
const key = weekdayKey(date);
for (const s of slots) {
if (s.day === key) out.push({ date, day: s.day, dayLabel: DAY_LABEL[s.day], time: s.time, label: s.label });
}
}
return out.sort((a, b) => `${a.date} ${a.time}`.localeCompare(`${b.date} ${b.time}`));
}
/**
* How many published/scheduled things land on each date — counted, not merely
* flagged, so a day carrying two slots needs two posts to be full.
*/
export function coverageByDate(queueEntries, editionRows) {
const counts = new Map();
const bump = (date) => {
if (!date) return;
counts.set(date, (counts.get(date) ?? 0) + 1);
};
for (const e of queueEntries ?? []) {
if (COVERING_QUEUE_STATUS.has(e?.status)) bump(e?.scheduled_date);
}
// Register rows carry `slot` as "YYYY-MM-DD HH:MM". Completed rows count too:
// an edition that reached Step 10 IS the thing occupying that slot.
for (const r of editionRows ?? []) {
if (typeof r?.slot === 'string' && r.slot.length >= 10) bump(r.slot.slice(0, 10));
}
return counts;
}
/** The occurrences nothing covers, chronological. Per date, the earliest slots are considered filled first. */
export function vacantSlots(occurrences, coverage) {
const remaining = new Map(coverage);
const vacant = [];
for (const occ of occurrences) {
const left = remaining.get(occ.date) ?? 0;
if (left > 0) remaining.set(occ.date, left - 1);
else vacant.push(occ);
}
return vacant;
}
/** All register rows, whatever their status (coverage cares about completed ones too). */
export function readRegisterRows(path = defaultRegisterPath()) {
const parsed = readJson(path);
return Array.isArray(parsed?.editions) ? parsed.editions : [];
}
function readQueueEntries() {
const parsed = readJson(queuePath());
return Array.isArray(parsed?.queue) ? parsed.queue : [];
}
function todayISO() {
return new Date().toISOString().slice(0, 10);
}
/** Every uncovered slot in the horizon — the vacancy warning's raw material. */
export function slotVacancies({ from = todayISO(), days = 14 } = {}) {
const { slots } = readSlots();
if (slots.length === 0) return [];
const occurrences = slotOccurrences(slots, from, days);
return vacantSlots(occurrences, coverageByDate(readQueueEntries(), readRegisterRows()));
}
/** The slot `/linkedin:newsletter` Step 10 defaults to; null when nothing is configured or everything is covered. */
export function nextFreeSlot(options = {}) {
return slotVacancies(options)[0] ?? null;
}
/**
* Editions in production right now, with whole days in flight (the `daysSince`
* idiom the hook already reports elapsed time with). Deterministic order —
* series, then edition id — mirroring listEditions in scripts/editions.
*/
export function activeEditions({ now = new Date().toISOString() } = {}) {
const nowMs = Date.parse(now);
return readRegisterRows()
.filter((r) => r?.status === 'active')
.sort((a, b) => String(a.series).localeCompare(String(b.series)) || String(a.editionId).localeCompare(String(b.editionId)))
.map((r) => {
const started = Date.parse(r?.startedAt ?? '');
const daysInFlight =
Number.isNaN(started) || Number.isNaN(nowMs) ? null : Math.floor((nowMs - started) / MS_PER_DAY);
return { ...r, daysInFlight };
});
}
/** "today" / "tomorrow" / "in N days" — how far off a slot is, in words. */
export function daysUntil(from, date) {
const a = Date.parse(`${from}T12:00:00Z`);
const b = Date.parse(`${date}T12:00:00Z`);
if (Number.isNaN(a) || Number.isNaN(b)) return null;
return Math.round((b - a) / MS_PER_DAY);
}
/** One slot rendered for a human: "Thu 2026-07-30 12:00 (in 3 days)". */
export function formatSlot(slot, from = todayISO()) {
const n = daysUntil(from, slot.date);
const when = n === null ? '' : n === 0 ? ' (today)' : n === 1 ? ' (tomorrow)' : ` (in ${n} days)`;
const label = slot.label ? `${slot.label}` : '';
return `${slot.dayLabel} ${slot.date} ${slot.time}${when}${label}`;
}