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
This commit is contained in:
Kjell Tore Guttormsen 2026-07-25 07:28:48 +02:00
commit 677eab9294
14 changed files with 1069 additions and 19 deletions

View file

@ -0,0 +1,181 @@
import { describe, test } from 'node:test';
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { mkdtempSync, rmSync, mkdirSync, writeFileSync, copyFileSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { tmpdir } from 'node:os';
import { fileURLToPath } from 'node:url';
// N13 (A1-10 / A1-11 surfacing): the week's picture — which editions are in
// flight and which publishing slots are still empty — must be readable at
// session start without opening a file. session-start is a procedural hook with
// no exports, so we run it as a subprocess with an isolated HOME +
// LINKEDIN_STUDIO_DATA and inspect the additionalContext. Pattern:
// session-start-trends-staleness.test.mjs subprocess harness.
const here = dirname(fileURLToPath(import.meta.url));
const hookPath = join(here, '..', 'session-start.mjs');
const PLUGIN_ROOT = join(here, '..', '..', '..');
const STATE_TEMPLATE = join(PLUGIN_ROOT, 'config', 'state-file.template.md');
const WIP_HEADER = '## Editions in Flight';
const SLOTS_HEADER = '## Publishing Slots';
const NEXT_OPEN = 'Next open slot:';
const DAY_KEYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
const isoDaysAhead = (n) => new Date(Date.now() + n * 86400000).toISOString().slice(0, 10);
const isoDaysAgo = (n) => new Date(Date.now() - n * 86400000).toISOString().slice(0, 10);
const weekdayOf = (isoDate) => DAY_KEYS[new Date(`${isoDate}T12:00:00Z`).getUTCDay()];
// Seed an isolated data root, run the hook, return the injected context.
function runHook({ slots, queue, editions, trends } = {}) {
const home = mkdtempSync(join(tmpdir(), 'lis-sl-home-'));
const data = mkdtempSync(join(tmpdir(), 'lis-sl-data-'));
try {
// The status/reminders branch only runs when the state file exists; the
// template is the canonical valid state.
mkdirSync(join(home, '.claude'), { recursive: true });
copyFileSync(STATE_TEMPLATE, join(home, '.claude', 'linkedin-studio.local.md'));
if (slots) {
mkdirSync(join(data, 'profile'), { recursive: true });
writeFileSync(
join(data, 'profile', 'publishing-slots.json'),
JSON.stringify({ schemaVersion: 1, slots }),
);
}
if (queue) {
mkdirSync(join(data, 'drafts'), { recursive: true });
writeFileSync(join(data, 'drafts', 'queue.json'), JSON.stringify({ version: 1, queue }));
}
if (editions) {
mkdirSync(join(data, 'editions'), { recursive: true });
writeFileSync(
join(data, 'editions', 'register.json'),
JSON.stringify({ schemaVersion: 1, editions }),
);
}
if (trends) {
mkdirSync(join(data, 'trends'), { recursive: true });
writeFileSync(join(data, 'trends', 'trends.json'), JSON.stringify({ schemaVersion: 1, trends }));
}
const stdout = execFileSync('node', [hookPath], {
input: '',
env: { ...process.env, HOME: home, USERPROFILE: home, LINKEDIN_STUDIO_DATA: data },
encoding: 'utf-8',
});
return JSON.parse(stdout).hookSpecificOutput.additionalContext;
} finally {
rmSync(home, { recursive: true, force: true });
rmSync(data, { recursive: true, force: true });
}
}
const activeRow = (over = {}) => ({
series: 'serien',
editionId: '05',
title: 'En utgave',
path: '/series/serien',
currentPhase: 'draft',
nextAction: 'Step 4 - full draft',
slot: null,
startedAt: new Date(Date.now() - 3 * 86400000).toISOString(),
updatedAt: new Date().toISOString(),
completedAt: null,
status: 'active',
...over,
});
describe('session-start — editions in flight (N13/A1-11)', () => {
test('surfaces active editions with phase, next action and days in flight', () => {
const ctx = runHook({ editions: [activeRow()] });
assert.ok(ctx.includes(WIP_HEADER), 'expected the in-flight roll-up');
assert.ok(ctx.includes('serien #05'), 'expected the edition identity');
assert.ok(ctx.includes('draft'), 'expected the current phase');
assert.ok(ctx.includes('Step 4 - full draft'), 'expected the next action');
assert.ok(/3d in flight/.test(ctx), 'expected measured days in flight');
});
test('completed editions drop out — the view is work in progress, not history', () => {
const ctx = runHook({
editions: [activeRow({ editionId: '04', status: 'complete', completedAt: new Date().toISOString() })],
});
assert.ok(!ctx.includes(WIP_HEADER), 'a register with no active rows must not print the block');
});
test('no register at all is silence, not an error', () => {
const ctx = runHook({});
assert.ok(!ctx.includes(WIP_HEADER), 'an unused register must not print anything');
});
});
describe('session-start — publishing-slot vacancy (N13/A1-10)', () => {
test('names the next open slot when the grid has an uncovered day', () => {
const target = isoDaysAhead(3);
const ctx = runHook({ slots: [{ day: weekdayOf(target), time: '12:00', label: 'long-form' }] });
assert.ok(ctx.includes(SLOTS_HEADER), 'expected the slots block');
assert.ok(ctx.includes(NEXT_OPEN), 'expected the next open slot to be named');
assert.ok(ctx.includes('long-form'), 'expected the operator label to carry through');
});
test('an unconfigured grid says nothing at all — no default schedule is imposed', () => {
const ctx = runHook({ editions: [activeRow()] });
assert.ok(!ctx.includes(SLOTS_HEADER), 'no slots config => no slots block');
});
test('a queue entry on the slot date covers it', () => {
const today = new Date().toISOString().slice(0, 10);
const day = weekdayOf(today);
// A weekly slot has exactly two occurrences in a 14-day window from today.
const ctx = runHook({
slots: [{ day, time: '08:30' }],
queue: [
{ id: 'a', scheduled_date: today, scheduled_time: '08:30', status: 'scheduled' },
{ id: 'b', scheduled_date: isoDaysAhead(7), scheduled_time: '08:30', status: 'scheduled' },
],
});
assert.ok(ctx.includes(SLOTS_HEADER), 'a configured grid still reports');
assert.ok(!ctx.includes(NEXT_OPEN), 'a fully covered horizon has no open slot to name');
assert.ok(/are covered/.test(ctx), 'expected the all-covered confirmation');
});
test('a scheduled long-form edition covers its claimed slot', () => {
const today = new Date().toISOString().slice(0, 10);
const day = weekdayOf(today);
const ctx = runHook({
slots: [{ day, time: '08:30' }],
editions: [
activeRow({ slot: `${today} 08:30` }),
activeRow({ editionId: '06', slot: `${isoDaysAhead(7)} 08:30` }),
],
});
assert.ok(!ctx.includes(NEXT_OPEN), 'register-claimed slots count as covered');
});
test('an imminent empty slot (<=3 days) says how to fill it', () => {
const target = isoDaysAhead(2);
const ctx = runHook({ slots: [{ day: weekdayOf(target), time: '09:00' }] });
assert.ok(/\/linkedin:newsletter/.test(ctx), 'expected the fill-it pointer for an imminent vacancy');
});
});
describe('session-start — N13 leaves the existing nudges intact', () => {
test('the trend-staleness (discovery) nudge still fires alongside the new blocks', () => {
const ctx = runHook({
slots: [{ day: weekdayOf(isoDaysAhead(3)), time: '12:00' }],
editions: [activeRow()],
trends: [
{
id: 't1',
title: 'A trend',
url: 'https://example.com/1',
source: 'tavily',
capturedAt: isoDaysAgo(10),
topics: ['x'],
},
],
});
assert.ok(ctx.includes('Trend signals are'), 'the discovery nudge must survive N13');
assert.ok(ctx.includes(SLOTS_HEADER) && ctx.includes(WIP_HEADER), 'the new blocks render too');
});
});

View file

@ -0,0 +1,313 @@
import { describe, test } from 'node:test';
import assert from 'node:assert/strict';
import { mkdtempSync, rmSync, mkdirSync, writeFileSync, existsSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import {
SLOTS_SCHEMA_VERSION,
normalizeSlots,
readSlots,
slotOccurrences,
coverageByDate,
vacantSlots,
nextFreeSlot,
activeEditions,
defaultSlotsPath,
defaultRegisterPath,
} from '../slots.mjs';
// N13 (A1-10): the week's production grid — configured publishing slots, what
// covers them (queue + editions register) and what is still in flight. The core
// is pure (dates in as strings, no clock) so vacancy is testable without
// freezing time; only the thin readers touch the data dir.
// Run `fn` with an isolated LINKEDIN_STUDIO_DATA root, seeded by `seed(dir)`.
function withDataRoot(seed, fn) {
const data = mkdtempSync(join(tmpdir(), 'lis-slots-'));
const prev = process.env.LINKEDIN_STUDIO_DATA;
process.env.LINKEDIN_STUDIO_DATA = data;
try {
if (seed) seed(data);
return fn(data);
} finally {
if (prev === undefined) delete process.env.LINKEDIN_STUDIO_DATA;
else process.env.LINKEDIN_STUDIO_DATA = prev;
rmSync(data, { recursive: true, force: true });
}
}
function seedSlots(data, config) {
mkdirSync(join(data, 'profile'), { recursive: true });
writeFileSync(join(data, 'profile', 'publishing-slots.json'), JSON.stringify(config));
}
function seedQueue(data, entries) {
mkdirSync(join(data, 'drafts'), { recursive: true });
writeFileSync(join(data, 'drafts', 'queue.json'), JSON.stringify({ version: 1, queue: entries }));
}
function seedRegister(data, editions) {
mkdirSync(join(data, 'editions'), { recursive: true });
writeFileSync(join(data, 'editions', 'register.json'), JSON.stringify({ schemaVersion: 1, editions }));
}
const row = (over = {}) => ({
series: 'serien',
editionId: '05',
title: 'En utgave',
path: '/series/serien',
currentPhase: 'draft',
nextAction: 'Step 4 — full draft',
slot: null,
startedAt: '2026-07-20T08:00:00.000Z',
updatedAt: '2026-07-22T08:00:00.000Z',
completedAt: null,
status: 'active',
...over,
});
const queueEntry = (over = {}) => ({
id: 'p1',
scheduled_date: '2026-07-28',
scheduled_time: '08:30',
status: 'scheduled',
...over,
});
describe('slots — config normalization (N13/A1-10)', () => {
test('accepts full weekday names and abbreviations, any case', () => {
const { slots } = normalizeSlots({
slots: [
{ day: 'Tuesday', time: '08:30' },
{ day: 'THU', time: '12:00', label: 'long-form' },
],
});
assert.deepEqual(
slots,
[
{ day: 'tue', time: '08:30', label: '' },
{ day: 'thu', time: '12:00', label: 'long-form' },
],
);
});
test('drops entries with an unknown day or a malformed time', () => {
const { slots } = normalizeSlots({
slots: [
{ day: 'funday', time: '08:30' },
{ day: 'mon', time: '25:00' },
{ day: 'mon', time: '8:30' },
{ day: 'wed', time: '09:00' },
],
});
assert.deepEqual(slots, [{ day: 'wed', time: '09:00', label: '' }]);
});
test('garbage in never throws — it yields an empty grid', () => {
for (const bad of [null, undefined, 42, 'nope', {}, { slots: 'x' }]) {
assert.deepEqual(normalizeSlots(bad).slots, [], `expected [] for ${JSON.stringify(bad)}`);
}
});
test('carries the timezone through as a label, defaulting to empty', () => {
assert.equal(normalizeSlots({ timezone: 'Europe/Oslo', slots: [] }).timezone, 'Europe/Oslo');
assert.equal(normalizeSlots({ slots: [] }).timezone, '');
});
test('exposes the schema version it reads', () => {
assert.equal(SLOTS_SCHEMA_VERSION, 1);
});
});
describe('slots — occurrence expansion (N13/A1-10)', () => {
const grid = [
{ day: 'tue', time: '08:30', label: '' },
{ day: 'thu', time: '12:00', label: 'long-form' },
];
test('expands the weekly grid across the horizon, chronologically', () => {
// 2026-07-27 is a Monday.
const occ = slotOccurrences(grid, '2026-07-27', 14);
assert.deepEqual(
occ.map((o) => `${o.date} ${o.time}`),
['2026-07-28 08:30', '2026-07-30 12:00', '2026-08-04 08:30', '2026-08-06 12:00'],
);
assert.equal(occ[1].label, 'long-form');
});
test('includes the start day itself — a slot today is still actionable', () => {
const occ = slotOccurrences(grid, '2026-07-28', 1);
assert.deepEqual(occ.map((o) => o.date), ['2026-07-28']);
});
test('two slots on the same day come out in time order', () => {
const occ = slotOccurrences(
[{ day: 'tue', time: '16:00', label: '' }, { day: 'tue', time: '08:30', label: '' }],
'2026-07-28',
1,
);
assert.deepEqual(occ.map((o) => o.time), ['08:30', '16:00']);
});
test('no slots, or a zero horizon, yields nothing', () => {
assert.deepEqual(slotOccurrences([], '2026-07-27', 14), []);
assert.deepEqual(slotOccurrences(grid, '2026-07-27', 0), []);
});
});
describe('slots — coverage and vacancy (N13/A1-10)', () => {
test('a scheduled queue entry covers its date', () => {
const cover = coverageByDate([queueEntry()], []);
assert.equal(cover.get('2026-07-28'), 1);
});
test('a published entry still counts — the slot was used', () => {
const cover = coverageByDate([queueEntry({ status: 'published' })], []);
assert.equal(cover.get('2026-07-28'), 1);
});
test('a cancelled entry does not cover — that slot fell vacant again', () => {
const cover = coverageByDate([queueEntry({ status: 'cancelled' })], []);
assert.equal(cover.get('2026-07-28'), undefined);
});
test('an editions-register row covers the date of its slot, completed rows included', () => {
const cover = coverageByDate([], [
row({ slot: '2026-07-30 12:00' }),
row({ editionId: '06', slot: '2026-08-06 12:00', status: 'complete', completedAt: '2026-08-01T00:00:00.000Z' }),
]);
assert.equal(cover.get('2026-07-30'), 1);
assert.equal(cover.get('2026-08-06'), 1);
});
test('rows without a claimed slot cover nothing', () => {
assert.equal(coverageByDate([], [row({ slot: null })]).size, 0);
});
test('vacancy is counted per date — two slots one day need two posts', () => {
const occ = slotOccurrences(
[{ day: 'tue', time: '08:30', label: '' }, { day: 'tue', time: '16:00', label: '' }],
'2026-07-28',
1,
);
const oneCovered = vacantSlots(occ, coverageByDate([queueEntry()], []));
assert.deepEqual(oneCovered.map((o) => o.time), ['16:00'], 'one post covers only the first slot that day');
const bothCovered = vacantSlots(occ, coverageByDate([queueEntry(), queueEntry({ id: 'p2' })], []));
assert.deepEqual(bothCovered, []);
});
test('uncovered occurrences survive in chronological order', () => {
const occ = slotOccurrences([{ day: 'tue', time: '08:30', label: '' }], '2026-07-27', 14);
const vacant = vacantSlots(occ, coverageByDate([queueEntry()], []));
assert.deepEqual(vacant.map((o) => o.date), ['2026-08-04']);
});
});
describe('slots — data-dir readers (N13/A1-10)', () => {
test('readSlots reads the per-user config under profile/', () => {
withDataRoot(
(d) => seedSlots(d, { schemaVersion: 1, timezone: 'Europe/Oslo', slots: [{ day: 'thu', time: '12:00' }] }),
() => {
const { slots, timezone } = readSlots();
assert.equal(timezone, 'Europe/Oslo');
assert.deepEqual(slots, [{ day: 'thu', time: '12:00', label: '' }]);
},
);
});
test('an absent config is silence, not an error — the un-configured user is never nagged', () => {
withDataRoot(null, () => {
assert.deepEqual(readSlots().slots, []);
assert.equal(nextFreeSlot({ from: '2026-07-27', days: 14 }), null);
});
});
test('a malformed config degrades to an empty grid instead of crashing session start', () => {
withDataRoot(
(d) => {
mkdirSync(join(d, 'profile'), { recursive: true });
writeFileSync(join(d, 'profile', 'publishing-slots.json'), '{ not json');
},
() => assert.deepEqual(readSlots().slots, []),
);
});
test('the config and register paths resolve under the per-user data root', () => {
withDataRoot(null, (d) => {
assert.equal(defaultSlotsPath(), join(d, 'profile', 'publishing-slots.json'));
assert.equal(defaultRegisterPath(), join(d, 'editions', 'register.json'));
});
});
test('reading vacancy never creates the queue file — a read-only check writes nothing', () => {
withDataRoot(
(d) => seedSlots(d, { slots: [{ day: 'tue', time: '08:30' }] }),
(d) => {
nextFreeSlot({ from: '2026-07-27', days: 14 });
assert.equal(
existsSync(join(d, 'drafts', 'queue.json')),
false,
'the vacancy read must not materialize queue.json',
);
},
);
});
});
describe('slots — nextFreeSlot end to end (N13/A1-10)', () => {
test('returns the earliest uncovered slot, skipping what the queue and register cover', () => {
withDataRoot(
(d) => {
seedSlots(d, { slots: [{ day: 'tue', time: '08:30' }, { day: 'thu', time: '12:00', label: 'long-form' }] });
seedQueue(d, [queueEntry()]); // covers Tue 2026-07-28
seedRegister(d, [row({ slot: '2026-07-30 12:00' })]); // covers Thu 2026-07-30
},
() => {
const next = nextFreeSlot({ from: '2026-07-27', days: 14 });
assert.equal(next.date, '2026-08-04');
assert.equal(next.time, '08:30');
},
);
});
test('null when every slot in the horizon is covered', () => {
withDataRoot(
(d) => {
seedSlots(d, { slots: [{ day: 'tue', time: '08:30' }] });
seedQueue(d, [queueEntry()]);
},
() => assert.equal(nextFreeSlot({ from: '2026-07-27', days: 7 }), null),
);
});
});
describe('slots — editions in flight (N13/A1-11 surfacing)', () => {
test('lists active rows only, oldest series first, with whole days in flight', () => {
withDataRoot(
(d) =>
seedRegister(d, [
row({ series: 'b-serien', editionId: '02' }),
row({ series: 'a-serien', editionId: '07', startedAt: '2026-07-24T00:00:00.000Z' }),
row({ series: 'a-serien', editionId: '01', status: 'complete', completedAt: '2026-07-21T00:00:00.000Z' }),
]),
() => {
const rows = activeEditions({ now: '2026-07-27T00:00:00.000Z' });
assert.deepEqual(
rows.map((r) => `${r.series}#${r.editionId}`),
['a-serien#07', 'b-serien#02'],
'complete rows drop out of the in-flight view',
);
assert.equal(rows[0].daysInFlight, 3);
// Started 2026-07-20 08:00Z, now 2026-07-27 00:00Z = 6.67 days — floored,
// like every other elapsed-day report in the hook layer.
assert.equal(rows[1].daysInFlight, 6);
},
);
});
test('an absent register is an empty view, never a crash', () => {
withDataRoot(null, () => assert.deepEqual(activeEditions({ now: '2026-07-27T00:00:00.000Z' }), []));
});
});

View file

@ -10,6 +10,15 @@ import { queueToday, queueOverdue, queueUpcoming } from './queue-manager.mjs';
import { applyWeekRollover } from './week-rollover.mjs';
import { getDataRoot } from './data-root.mjs';
import { migrateData } from './migrate-data.mjs';
import {
activeEditions,
readSlots,
slotOccurrences,
slotVacancies,
daysUntil,
formatSlot,
defaultSlotsPath,
} from './slots.mjs';
const __dirname = dirname(fileURLToPath(import.meta.url));
const PLUGIN_ROOT = join(__dirname, '..', '..');
@ -536,6 +545,49 @@ if (latestBrief && latestBrief.summary) {
context += `\\n## Morning Brief (${latestBrief.date})\\n${latestBrief.summary}\\n→ Full brief: ${latestBrief.file}\\n`;
}
// N13 (A1-10/A1-11): the week's production picture — long-form editions in
// flight, and publishing slots nothing covers yet. Unconditional like the brain
// nudge above (the fresh-install branch reassigns `context`, so an earlier
// append would be clobbered). Zero-tsx: slots.mjs reads the register, the queue
// and the grid as plain JSON, the same discipline as trendsNewestCapture.
// Both blocks are silent when their data is absent — an operator who has
// configured no slots and started no edition is never nagged.
const SLOT_HORIZON_DAYS = 14;
const SLOT_IMMINENT_DAYS = 3;
try {
const inFlight = activeEditions();
if (inFlight.length > 0) {
context += '\\n## Editions in Flight\\n';
for (const e of inFlight) {
const age = e.daysInFlight === null ? '' : ` | ${e.daysInFlight}d in flight`;
context += `- ${e.series} #${e.editionId}${e.title || 'untitled'} | phase: ${e.currentPhase}`;
context += ` | next: ${e.nextAction || 'unset'} | slot: ${e.slot || 'unclaimed'}${age}\\n`;
}
context += '- Resume an edition with /linkedin:newsletter (it reads edition-state.json, not this view).\\n';
}
const { slots } = readSlots();
if (slots.length > 0) {
const today = new Date().toISOString().slice(0, 10);
const planned = slotOccurrences(slots, today, SLOT_HORIZON_DAYS).length;
const vacancies = slotVacancies({ from: today, days: SLOT_HORIZON_DAYS });
context += '\\n## Publishing Slots\\n';
if (vacancies.length > 0) {
const until = daysUntil(today, vacancies[0].date);
context += `- Next open slot: ${formatSlot(vacancies[0], today)}\\n`;
context += `- Open in the next ${SLOT_HORIZON_DAYS} days: ${vacancies.length} of ${planned} slot(s)\\n`;
if (until !== null && until <= SLOT_IMMINENT_DAYS) {
context += '- Fill it: /linkedin:batch (short-form) or /linkedin:newsletter (long-form).\\n';
}
} else {
context += `- All ${planned} slot(s) in the next ${SLOT_HORIZON_DAYS} days are covered.\\n`;
}
context += `- Grid: ${defaultSlotsPath()}\\n`;
}
} catch {
// Non-critical: a broken grid or register must never block session start.
}
// Read REMEMBER.md for user session context
const rememberFile = join(getDataRoot(), 'REMEMBER.md');
const rememberTemplate = join(PLUGIN_ROOT, 'config', 'REMEMBER.template.md');

211
hooks/scripts/slots.mjs Normal file
View file

@ -0,0 +1,211 @@
#!/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}`;
}