feat(linkedin-studio): RE-R3e — brief history + day-over-day diff (surfaced: frontmatter + Nytt siden sist) [skip-docs]

Closes hull #7 ("ingen brief-historikk"). Each morning brief now records the
trend ids it showed into its own YAML frontmatter (surfaced: <id-csv> =
surfacedIds(ranking)) and renders a day-over-day diff against the most recent
prior brief — a "## Nytt siden sist (<prior-date>)" section that leads the
ranked list, plus a " N nye siden sist." marker on the one-line summary the
SessionStart hook surfaces (no hook change).

- brief.ts: BRIEF_SCHEMA_VERSION 1->2 (artifact frontmatter gained surfaced:;
  the store's SCHEMA_VERSION stays 4 — no store field). Three PURE helpers
  (diffSurfaced / parseSurfacedFrontmatter / selectPriorBriefFile) + the
  surfaced: emit + the section + the summary marker. No fs/clock in brief.ts.
- cli.ts: the brief handler discovers the prior dated file (existsSync-guarded
  readdirSync -> selectPriorBriefFile, strict < today so a same-day re-run is
  byte-identical), parses its surfaced: line, computes the diff, threads it into
  renderBrief AND the shared briefSummary(ranking, diff) (one-source: file
  frontmatter == --json summary, cli.test one-source invariant). --json gains a
  diff:{priorDate,added,carried,dropped} counts object; the console line appends
  the delta. Any fs error degrades to the empty-prior (first-brief) path.

TDD two-phase: stubs -> 17 value-RED (no module-not-found) -> GREEN. Trends suite
216 -> 245 (brief +27, cli +2), 0 fail. New unconditional gate Section 16n (6
checks); ASSERT_BASELINE_FLOOR 117 -> 123; TRENDS_TESTS_FLOOR -> 245. Full gate
FAIL=0; hook suite 139/139 + R3c schedule/run-daily green untouched. Behavioural:
real two-day rename-real-write diff + same-day byte-identity confirmed. Counts
29/19/27 unchanged; no version bump (additive, v0.5.2 dev).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011vmzxpsFpc8q19LaogAWLD
This commit is contained in:
Kjell Tore Guttormsen 2026-06-26 14:40:09 +02:00
commit 5b51b4baeb
7 changed files with 462 additions and 18 deletions

View file

@ -8,6 +8,9 @@ import {
briefSummary,
defaultBriefDir,
surfacedIds,
diffSurfaced,
parseSurfacedFrontmatter,
selectPriorBriefFile,
temporalSignal,
BRIEF_SCHEMA_VERSION,
} from "../src/brief.js";
@ -571,7 +574,7 @@ describe("rankForBrief — no schema/score mutation (RE-R3d / SC8)", () => {
const before = t.score!.composite;
rankForBrief(mkStore([t]), ["AI"], TODAY);
assert.equal(t.score!.composite, before, "rankForBrief must not mutate the stored composite");
assert.equal(BRIEF_SCHEMA_VERSION, 1);
assert.equal(BRIEF_SCHEMA_VERSION, 2); // RE-R3e: artifact frontmatter gained surfaced: (1->2); store SCHEMA_VERSION stays 4
assert.equal(SCHEMA_VERSION, 4);
});
});
@ -597,3 +600,135 @@ describe("rankForBrief — prior-day surfacings exclude today (RE-R3d / same-day
assert.equal(e.temporal.surfacings, 1);
});
});
// --- RE-R3e: brief history + day-over-day diff ---
describe("diffSurfaced — partitions + order + empty prior (RE-R3e / SC1)", () => {
test("symmetric set difference, order-stable", () => {
const d = diffSurfaced(["a", "b", "c"], ["b", "c", "d"], "2026-06-25");
assert.deepEqual(d, { priorDate: "2026-06-25", added: ["a"], carried: ["b", "c"], dropped: ["d"] });
});
test("empty prior ⇒ everything added, nothing dropped", () => {
const d = diffSurfaced(["a", "b"], [], null);
assert.deepEqual(d, { priorDate: null, added: ["a", "b"], carried: [], dropped: [] });
});
test("the three partitions are mutually disjoint (cross-partition exclusivity)", () => {
const d = diffSurfaced(["a", "b", "c"], ["b", "c", "d"], "2026-06-25");
const all = [...d.added, ...d.carried, ...d.dropped];
assert.equal(new Set(all).size, all.length, "no id appears in two buckets");
});
test("pure: same inputs → same output", () => {
assert.deepEqual(diffSurfaced(["x"], ["y"], "2026-06-20"), diffSurfaced(["x"], ["y"], "2026-06-20"));
});
});
describe("parseSurfacedFrontmatter — read + degrade (RE-R3e / SC2)", () => {
const block = (surfaced: string) =>
`---\ndate: 2026-06-26\nsummary: hi\nsurfaced: ${surfaced}\nstore: { trends: 3 }\nschemaVersion: 2\n---\nbody`;
test("parses a csv of ids", () => {
assert.deepEqual(parseSurfacedFrontmatter(block("1a2b,3c4d,5e6f")), ["1a2b", "3c4d", "5e6f"]);
});
test("trims whitespace around ids", () => {
assert.deepEqual(parseSurfacedFrontmatter(block(" a , b ,c ")), ["a", "b", "c"]);
});
test("a blank surfaced: line → []", () => {
assert.deepEqual(parseSurfacedFrontmatter(block("")), []);
});
test("an absent surfaced: line (a pre-R3e brief) → []", () => {
assert.deepEqual(parseSurfacedFrontmatter(`---\ndate: 2026-06-26\nsummary: hi\nschemaVersion: 1\n---\nbody`), []);
});
test("line-anchored: a summary: with commas does not leak in", () => {
assert.deepEqual(parseSurfacedFrontmatter(`---\ndate: 2026-06-26\nsummary: a,b,c\nschemaVersion: 1\n---`), []);
});
test("never throws on malformed input", () => {
assert.doesNotThrow(() => parseSurfacedFrontmatter("not a brief at all"));
});
});
describe("selectPriorBriefFile — strict-prior selection (RE-R3e / SC3)", () => {
const files = ["2026-06-24.md", "2026-06-25.md", "2026-06-26.md", "README.md", "2026-06-30.md"];
test("greatest dated file strictly < today (excludes today + future, ignores non-dated)", () => {
assert.equal(selectPriorBriefFile(files, "2026-06-26"), "2026-06-25.md");
});
test("no file < today → null", () => {
assert.equal(selectPriorBriefFile(["2026-06-26.md", "2026-06-30.md"], "2026-06-26"), null);
});
test("empty list → null", () => {
assert.equal(selectPriorBriefFile([], "2026-06-26"), null);
});
});
describe("renderBrief/briefSummary — surfaced: + diff section + marker (RE-R3e / SC4SC8)", () => {
const pillars = ["AI", "gov"];
const store = mkStore([
mkTrend({ title: "Alpha", url: "https://e/a", topics: ["ai", "gov"], publishedAt: "2026-06-22", capturedAt: "2026-06-22", score: mkScore(9.0, "Immediate") }),
mkTrend({ title: "Beta", url: "https://e/b", topics: ["ai"], publishedAt: "2026-06-20", capturedAt: "2026-06-20", score: mkScore(7.0, "High") }),
]);
const r = rankForBrief(store, pillars, TODAY);
const ids = surfacedIds(r);
const emptyDiff = { priorDate: null, added: [], carried: [], dropped: [] };
test("SC4: one surfaced: line = surfacedIds(r).join(','), before schemaVersion: 2", () => {
const md = renderBrief(r, emptyDiff);
const m = md.match(/^surfaced: (.*)$/m);
assert.ok(m, "a surfaced: frontmatter line exists");
assert.equal(m![1], ids.join(","));
assert.ok(md.indexOf("\nsurfaced:") < md.indexOf("\nschemaVersion:"), "surfaced: precedes schemaVersion:");
assert.match(md, /\nschemaVersion: 2\n/);
});
test("SC4: round-trips via parseSurfacedFrontmatter", () => {
assert.deepEqual(parseSurfacedFrontmatter(renderBrief(r, emptyDiff)), ids);
});
test("SC4: an empty store → a blank surfaced: line", () => {
const empty = rankForBrief(mkStore([]), pillars, TODAY);
assert.match(renderBrief(empty, emptyDiff), /\nsurfaced: \n/);
});
test("SC5: section header present + precedes Topp-treff (delta leads)", () => {
const md = renderBrief(r, emptyDiff);
assert.ok(md.includes("## 🆕 Nytt siden sist"), "section header present");
assert.ok(md.indexOf("## 🆕 Nytt siden sist") < md.indexOf("## 🎯 Topp-treff"), "delta precedes the ranked list");
});
test("SC5: first brief with added → 'Første brief — alt nedenfor er nytt'", () => {
assert.ok(renderBrief(r, { priorDate: null, added: ids, carried: [], dropped: [] }).includes("Første brief — alt nedenfor er nytt"));
});
test("SC5: empty first brief → 'Første brief.'", () => {
assert.ok(renderBrief(r, emptyDiff).includes("_Første brief._"));
});
test("SC5: prior + added → the added title + the carried/dropped tally", () => {
const md = renderBrief(r, { priorDate: "2026-06-23", added: [ids[0]], carried: [ids[1]], dropped: ["gone"] });
assert.ok(md.includes("Alpha"), "the added entry's title is rendered");
assert.ok(md.includes("1 båret over, 1 ikke vist i dag"), "the carried/dropped tally");
});
test("SC5: prior + no added → 'Ingenting nytt siden <date>' + tally", () => {
const md = renderBrief(r, { priorDate: "2026-06-23", added: [], carried: ids, dropped: [] });
assert.ok(md.includes("Ingenting nytt siden 2026-06-23"));
assert.ok(md.includes("båret over"));
});
test("SC6: marker ' N nye siden sist.' when prior + added", () => {
const s = briefSummary(r, { priorDate: "2026-06-25", added: ["x", "y"], carried: [], dropped: [] });
assert.ok(s.endsWith(" 2 nye siden sist."), `marker appended: ${s}`);
});
test("SC6: no marker on the first brief or when nothing new", () => {
assert.ok(!briefSummary(r, { priorDate: null, added: ["x"], carried: [], dropped: [] }).includes("nye siden sist"));
assert.ok(!briefSummary(r, { priorDate: "2026-06-25", added: [], carried: [], dropped: [] }).includes("nye siden sist"));
});
test("SC6: briefSummary(r) === briefSummary(r, emptyDiff) (keeps the :166 summary-equality test green)", () => {
assert.equal(briefSummary(r), briefSummary(r, emptyDiff));
});
test("SC6: the marker carries no quote/newline", () => {
const s = briefSummary(r, { priorDate: "2026-06-25", added: ["x"], carried: [], dropped: [] });
assert.ok(!s.includes('"') && !s.includes("\n"));
});
test("SC7: BRIEF_SCHEMA_VERSION === 2; SCHEMA_VERSION === 4", () => {
assert.equal(BRIEF_SCHEMA_VERSION, 2);
assert.equal(SCHEMA_VERSION, 4);
});
test("SC8: same (r, diff) → byte-identical render", () => {
const d = { priorDate: "2026-06-23", added: [ids[0]], carried: [ids[1]], dropped: [] };
assert.equal(renderBrief(r, d), renderBrief(r, d));
});
});

View file

@ -2,7 +2,7 @@ import { describe, test } from "node:test";
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { mkdtempSync, rmSync, readFileSync, existsSync, writeFileSync } from "node:fs";
import { mkdtempSync, rmSync, readFileSync, existsSync, writeFileSync, renameSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
@ -669,3 +669,74 @@ describe("trends CLI — brief temporal flags (RE-R3d / SC6)", () => {
}
});
});
describe("trends CLI — brief history + day-over-day diff (RE-R3e / SC9)", () => {
const fixture = () => {
const dir = mkdtempSync(join(tmpdir(), "trends-r3e-"));
return { dir, store: join(dir, "trends.json"), out: join(dir, "briefs") };
};
// freshIso keeps the seeds inside the freshness window regardless of when the test runs.
const fresh = new Date(Date.now() - 2 * 86400000).toISOString().slice(0, 10);
const seedOnPillar = (store: string, title: string, url: string): void => {
const batch = JSON.stringify([
{
source: "tavily",
title,
url,
topics: ["ai", "gov"],
publishedAt: fresh,
score: { mode: "kortform", dimensions: { pillar: 9, audience: 8, timing: 9, angle: 7, authority: 6 } },
},
]);
run(["capture", "--store", store], batch);
};
const briefJson = (store: string, out: string) =>
JSON.parse(run(["brief", "--pillars", "ai,gov", "--out", out, "--store", store, "--json"], "").stdout);
test("two-day (rename-real-write): day-2 shows the new trend; --json carries the diff", () => {
const { dir, store, out } = fixture();
try {
// Day 1 — two on-pillar trends. The brief records its surfaced cohort + a null-prior diff.
seedOnPillar(store, "Alpha", "https://e/a");
seedOnPillar(store, "Beta", "https://e/b");
const o1 = briefJson(store, out);
assert.equal(o1.diff.priorDate, null, "first brief has no prior (empty dir)");
assert.match(readFileSync(o1.path, "utf8"), /^surfaced: .+/m, "day-1 records a non-empty surfaced: line");
// Rename the REAL day-1 brief to a fixed past date — its surfaced: ids are genuine store
// ids, so the day-2 diff's carried/added are id-exact, clock-free (no today() advance).
const prior = "2026-06-20";
renameSync(o1.path, join(out, `${prior}.md`));
// Day 2 — capture one NEW on-pillar trend, re-run. It is the sole "added".
seedOnPillar(store, "Gamma", "https://e/g");
const o2 = briefJson(store, out);
assert.equal(o2.diff.priorDate, prior, "day-2 discovers the renamed strict-prior");
assert.ok(o2.diff.added >= 1, "at least the new trend is added");
assert.equal(o2.diff.carried, 2, "the two day-1 trends carry over");
assert.equal(o2.diff.dropped, 0, "nothing dropped");
const md2 = readFileSync(o2.path, "utf8");
assert.ok(md2.includes(`## 🆕 Nytt siden sist (${prior})`), "the diff section names the prior date");
assert.ok(md2.includes("Gamma"), "the new trend's title is in the Nytt-siden-sist section");
// The non-JSON console line appends the delta marker.
const console2 = run(["brief", "--pillars", "ai,gov", "--out", out, "--store", store], "").stdout;
assert.ok(console2.includes("nye siden sist"), `console line carries the delta: ${console2}`);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
test("a first run (empty dir) → diff.priorDate === null, no Nytt-siden-sist date", () => {
const { dir, store, out } = fixture();
try {
seedOnPillar(store, "Solo", "https://e/s");
const o = briefJson(store, out);
assert.equal(o.diff.priorDate, null);
const md = readFileSync(o.path, "utf8");
assert.ok(md.includes("Første brief"), "a first brief says 'Første brief'");
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
});