linkedin-studio/hooks/scripts/__tests__/session-start-slots.test.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

181 lines
7.6 KiB
JavaScript

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');
});
});