feat(linkedin-studio): trend-store staleness nudge — SessionStart B-S3 [skip-docs]

SessionStart now warns (>=7d, warn-only) when the persistent trend store's
newest capture is stale, firing ONLY when the store already holds captures
(a never-scanned user is never nagged). Neutral wording — "scan for trends"
hits trend-spotter's own trigger; no hardcoded beat (de-niche invariant).

- store.ts: newestCaptureDate() — pure max-capturedAt staleness signal (SSOT)
- cli.ts: status [--json] subcommand (count + newest + daysStale)
- session-start.mjs: trendsNewestCapture() reads trends.json as raw JSON
  (no tsx spawn at session start) + the reminder line, beside import-staleness
- tests: +3 store tests (newestCaptureDate) + hook subprocess test (3 cases:
  >=7d fires, <7d silent, absent/empty silent + no crash)
- test-runner.sh: trends floor 21->24

Verified: trends 24/24 · all hook tests 131/131 · gate 89/0/0 · real render
confirms "Trend signals are N days old. Scan for trends…".

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RigJBiRFNtFZKCz21qNbQ4
This commit is contained in:
Kjell Tore Guttormsen 2026-06-23 12:23:53 +02:00
commit 0907b2b92d
6 changed files with 186 additions and 2 deletions

View file

@ -0,0 +1,79 @@
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';
// B-S3: SessionStart emits a warn-only "trend signals are N days old" nudge,
// driven by the trend store's newest capturedAt, and ONLY when the store already
// holds captures. 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-remember.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 NUDGE = 'Trend signals are';
const isoDaysAgo = (n) => new Date(Date.now() - n * 86400000).toISOString().slice(0, 10);
// Run the hook against an isolated HOME + data root; optionally seed a trend
// store. Returns the additionalContext string the hook injected at session start.
function runHook({ captures }) {
const home = mkdtempSync(join(tmpdir(), 'lis-ts-home-'));
const data = mkdtempSync(join(tmpdir(), 'lis-ts-data-'));
try {
// The reminders block only runs when the state file already exists; the
// template is the canonical valid state, so copy it into the isolated HOME.
mkdirSync(join(home, '.claude'), { recursive: true });
copyFileSync(STATE_TEMPLATE, join(home, '.claude', 'linkedin-studio.local.md'));
if (captures) {
mkdirSync(join(data, 'trends'), { recursive: true });
writeFileSync(
join(data, 'trends', 'trends.json'),
JSON.stringify({ schemaVersion: 1, trends: captures }),
);
}
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 trend = (capturedAt) => ({
id: 't' + capturedAt,
title: 'Some trend ' + capturedAt,
url: 'https://example.com/' + capturedAt,
source: 'tavily',
capturedAt,
topics: ['x'],
});
describe('session-start — trend-store staleness nudge (B-S3)', () => {
test('fires when newest capture is >=7 days old', () => {
const ctx = runHook({ captures: [trend('2026-01-01'), trend(isoDaysAgo(10))] });
assert.ok(ctx.includes(NUDGE), 'expected the trend-staleness nudge for a 10-day-old store');
});
test('does NOT fire when newest capture is fresh (<7 days)', () => {
const ctx = runHook({ captures: [trend(isoDaysAgo(2))] });
assert.ok(!ctx.includes(NUDGE), 'a 2-day-old store must not trigger the nudge');
});
test('does NOT fire (and does not crash) when the store is absent/empty', () => {
const absent = runHook({ captures: null });
assert.ok(!absent.includes(NUDGE), 'no store => no nudge');
const empty = runHook({ captures: [] });
assert.ok(!empty.includes(NUDGE), 'empty store => no nudge (never-scanned user is never nagged)');
});
});

View file

@ -29,6 +29,28 @@ function daysSince(dateStr) {
return Math.floor((Date.now() - epoch) / 86400000);
}
// B-S3: newest trend capture (ISO date) from the persistent trend store, read
// as raw JSON. The hook must NOT spawn the tsx CLI at session start (slow +
// needs node_modules/tsx); the store schema (trends[].capturedAt) is stable and
// versioned, so a direct read is safe. Twin of scripts/trends/src/store.ts:
// newestCaptureDate (max capturedAt). Returns null when the store is absent,
// unreadable, or empty — no captures yet ⇒ no nudge.
function trendsNewestCapture(storePath) {
if (!existsSync(storePath)) return null;
try {
const parsed = JSON.parse(readFileSync(storePath, 'utf-8'));
const trends = Array.isArray(parsed?.trends) ? parsed.trends : [];
let newest = null;
for (const t of trends) {
const d = typeof t?.capturedAt === 'string' ? t.capturedAt : null;
if (d && (newest === null || d > newest)) newest = d;
}
return newest;
} catch {
return null;
}
}
function isoWeek() {
const d = new Date();
const dayNum = d.getUTCDay() || 7;
@ -309,6 +331,16 @@ if (existsSync(STATE_FILE)) {
reminders += '- No analytics data imported yet. Run /linkedin:import to start tracking performance.\\n';
}
// Trend-store staleness (B-S3): warn-only, ≥7 days. Fires ONLY when the store
// already holds captures (newest === null ⇒ no nudge), so a never-scanned user
// is never nagged. Neutral wording — "scan for trends" hits trend-spotter's own
// trigger; no hardcoded beat (de-niche invariant, §17 guard).
const newestTrendCapture = trendsNewestCapture(join(getDataRoot('trends'), 'trends.json'));
const daysSinceTrend = daysSince(newestTrendCapture);
if (daysSinceTrend !== null && daysSinceTrend >= 7) {
reminders += `- Trend signals are ${daysSinceTrend} days old. Scan for trends to refresh the digest before planning content.\\n`;
}
// Milestone reminders
if (milestonePhase && followerCount > 0) {
if (milestoneStatus === 'SIGNIFICANTLY BEHIND') {

View file

@ -683,7 +683,7 @@ if [ -x "$TR_DIR/node_modules/.bin/tsx" ]; then
TR_OUT=$( set +e; (cd "$TR_DIR" && npm test) 2>&1; echo "TR_EXIT:$?" )
TR_EXIT=$(echo "$TR_OUT" | grep -oE 'TR_EXIT:[0-9]+' | grep -oE '[0-9]+' | head -1)
TR_TESTS=$(echo "$TR_OUT" | grep -oE 'tests [0-9]+' | grep -oE '[0-9]+' | tail -1)
TRENDS_TESTS_FLOOR=21
TRENDS_TESTS_FLOOR=24 # B-S3: +3 newestCaptureDate tests (staleness signal)
if [ "$TR_EXIT" = "0" ] && [ -n "$TR_TESTS" ] && [ "$TR_TESTS" -ge "$TRENDS_TESTS_FLOOR" ]; then
pass "trends-store suite green: $TR_TESTS tests pass (floor $TRENDS_TESTS_FLOOR)"
else

View file

@ -6,6 +6,7 @@
* [--source <s>] [--summary "<s>"] [--store <path>]
* node --import tsx src/cli.ts query --topics <a,b> [--store <path>] [--json]
* node --import tsx src/cli.ts list [--since <YYYY-MM-DD>] [--limit <n>] [--store <path>] [--json]
* node --import tsx src/cli.ts status [--store <path>] [--json]
*
* The capture agent (research-engine) calls `add` to fold a freshly-polled trend
* into the store, and `query`/`list` to reason over accumulated history. The
@ -19,6 +20,7 @@ import {
defaultStorePath,
history,
loadStore,
newestCaptureDate,
queryByTopic,
saveStore,
} from "./store.js";
@ -55,7 +57,8 @@ function usage(msg: string): never {
"usage:\n" +
' add --title "<t>" --url "<u>" --topics <a,b> [--source <s>] [--summary "<s>"] [--store <path>]\n' +
" query --topics <a,b> [--store <path>] [--json]\n" +
" list [--since <YYYY-MM-DD>] [--limit <n>] [--store <path>] [--json]",
" list [--since <YYYY-MM-DD>] [--limit <n>] [--store <path>] [--json]\n" +
" status [--store <path>] [--json]",
);
process.exit(2);
}
@ -64,6 +67,11 @@ function today(): string {
return new Date().toISOString().slice(0, 10);
}
/** Whole days from one ISO date to another (floor); negative if `from` is later. */
function daysBetween(fromIso: string, toIso: string): number {
return Math.floor((new Date(toIso).getTime() - new Date(fromIso).getTime()) / 86400000);
}
function main(): void {
const [command, ...rest] = process.argv.slice(2);
const flags = parseFlags(rest);
@ -140,6 +148,24 @@ function main(): void {
return;
}
if (command === "status") {
const store = loadStore(storePath);
const newest = newestCaptureDate(store);
const daysStale = newest === null ? null : daysBetween(newest, today());
if (asJson) {
console.log(JSON.stringify({ store: storePath, count: store.trends.length, newest, daysStale }));
return;
}
console.log(`Store: ${storePath}`);
console.log(` trends: ${store.trends.length}`);
if (newest === null) {
console.log(" newest: — (empty store; no captures yet)");
} else {
console.log(` newest: ${newest} (${daysStale}d ago)`);
}
return;
}
usage(command ? `unknown command: ${command}` : "no command given");
}

View file

@ -161,6 +161,17 @@ export function history(store: TrendStore, opts: HistoryOptions = {}): TrendReco
return out;
}
/**
* The most recent capturedAt across the store (ISO date), or null when the
* store is empty. The staleness signal behind the SessionStart trend-freshness
* nudge (B-S3) and the `status` CLI subcommand: reuses history()'s newest-first
* ordering so the module has a single notion of "newest". Pure the days-stale
* arithmetic (needs "today") lives in the caller, not here.
*/
export function newestCaptureDate(store: TrendStore): string | null {
return history(store, { limit: 1 })[0]?.capturedAt ?? null;
}
/**
* Default store path under the per-user data dir (M0 data-path convention), so
* the trend history survives plugin upgrades/reinstalls. `LINKEDIN_STUDIO_DATA`

View file

@ -13,6 +13,7 @@ import {
addTrend,
queryByTopic,
history,
newestCaptureDate,
} from "../src/store.js";
import { SCHEMA_VERSION } from "../src/types.js";
import type { TrendStore } from "../src/types.js";
@ -294,4 +295,39 @@ describe("trends store", () => {
assert.deepEqual(h.map((t) => t.title), ["Newest"]);
});
});
describe("newestCaptureDate (B-S3 staleness signal)", () => {
test("empty store → null (no captures yet → no nudge)", () => {
assert.equal(newestCaptureDate(emptyStore()), null);
});
test("single trend → its capturedAt", () => {
const store = addTrend(emptyStore(), {
title: "Solo",
url: "https://example.com/solo",
source: "tavily",
capturedAt: "2026-06-05",
topics: ["x"],
}).store;
assert.equal(newestCaptureDate(store), "2026-06-05");
});
test("multiple trends → the max (newest) capturedAt, regardless of insertion order", () => {
let store = emptyStore();
for (const [title, capturedAt] of [
["Middle", "2026-05-01"],
["Newest", "2026-06-01"],
["Oldest", "2026-04-01"],
] as const) {
store = addTrend(store, {
title,
url: `https://example.com/${title}`,
source: "tavily",
capturedAt,
topics: ["x"],
}).store;
}
assert.equal(newestCaptureDate(store), "2026-06-01");
});
});
});