feat(linkedin-studio): N12 — editions-register CLI + phaseLog-telemetri (TDD) [skip-docs]

Two things were structurally invisible: WHICH editions are in flight (readable
only by opening every series folder's edition-state.json by hand) and HOW LONG an
edition takes (not recorded anywhere). At two editions a week both are
load-bearing — a production line cannot be dimensioned on numbers never collected.

Register (scripts/editions, new module beside distillate.ts): one row per edition
in ${LINKEDIN_STUDIO_DATA}/editions/register.json — series, edition, title, series
path, current phase, next action, slot, startedAt/completedAt. Data-dir placement
(M0) because the register spans ALL series; the distillate is per-series and stays
in the series root. Verbs: register-upsert / register-list / register-complete.

phaseLog: articles.NN.phaseLog[{phase, completedAt}] in edition-state, additive so
schemaVersion stays 1 — pre-N12 editions load unchanged and their absence reads as
"not measured", never as zero. Per-article, mirroring articles.NN.phase: lead time
is a property of an edition.

One call per transition, both writes: newsletter.md gains a phase-transition
protocol defined once beside the resumption table, and all 16 canonical phases
invoke it. register-upsert appends the phase-log entry AND mirrors the register
row. Deliberately one command, not two — telemetry the command layer must remember
to write separately is incomplete inside a week, and an incomplete log measures
nothing. Step 10 closes the row and prints the measured lead time.

Mirror discipline: resumption still reads edition-state.json and only that. Delete
the register and the next transition rebuilds it; a failed upsert is reported, never
a reason to stop the pipeline. startedAt is the one unrecoverable value, so it never
moves — re-upserting a completed edition reactivates the same row (what
/linkedin:pivot does), keeping the clock on real elapsed production time.

Deterministic: no clock in the core (now passed in, --at/--now at the edge, as the
distillate takes lockedAt). Idempotent where a re-run is legitimate (repeated
transition logs once; completing twice keeps the first completedAt), not where it is
real work (a phase recurring after another one is logged again — a pivot back through
cleared gates is production time that happened). Missing facts are refused at the
edge, not defaulted: a row naming the wrong phase is worse than no row.

TDD (Iron Law): all three test files written first and verified red before any
implementation existed (register.test.ts + editionState.test.ts failed on missing
modules, cli-register.test.ts on "unknown command: register-upsert").

Suites: editions 27 -> 72 (floor raised) · test-runner 173 -> 184 (Section 16s: 11
unconditional greps incl. a 16-phase coverage sweep + non-vacuity self-test;
anti-erosion floor 155 -> 166) · trends 300/0 · brain 134/0 · specifics-bank 45/0 ·
hooks 140/0 · tests 35/0 · render 60/0. tsc --noEmit clean.

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 06:55:44 +02:00
commit 657539ef09
13 changed files with 1454 additions and 20 deletions

View file

@ -1,18 +1,32 @@
#!/usr/bin/env node
/**
* CLI for the series distillate (N11 serie-nivå-vern).
* CLI for series-level edition memory: the distillate (N11 serie-nivå-vern)
* and the editions register (N12 A1-11 / A1-12).
*
* node --import tsx src/cli.ts distil-append --distillate <path> --series <slug> --extract <extract.json>
* node --import tsx src/cli.ts distil-check --distillate <path> --skeleton <skeleton.json>
* [--threshold <0..1>] [--json]
* node --import tsx src/cli.ts distil-append --distillate <path> --series <slug> --extract <extract.json>
* node --import tsx src/cli.ts distil-check --distillate <path> --skeleton <skeleton.json>
* [--threshold <0..1>] [--json]
* node --import tsx src/cli.ts register-upsert --edition-state <path> [--next <text>] [--slot <text>]
* [--path <series-root>] [--register <path>] [--at <ISO>]
* node --import tsx src/cli.ts register-list [--all] [--json] [--register <path>] [--now <ISO>]
* node --import tsx src/cli.ts register-complete --series <slug> --edition <NN>
* [--register <path>] [--at <ISO>]
*
* `distil-append` runs at Step 8 lock: the command layer writes the AI extract
* (the anecdotes/arguments/hooks the edition actually spent) to a JSON file, and
* this folds it in deterministically. `distil-check` runs at Step 2.5, before
* prose, and reports re-use into the annotation gate.
*
* `register-upsert` runs at EVERY phase transition it appends the `phaseLog`
* entry to the edition-state AND mirrors the row into the register in one call,
* so the telemetry cannot drift out of step with the state it describes.
* `register-complete` runs at Step 10 when the edition is scheduled.
*
* Clock at the edge only: `--at` / `--now` override it so runs are reproducible.
*
* Exit code: 0 on success (INCLUDING a REUSE verdict the check is advisory by
* design, unlike the binding gate's BLOCK), 2 on usage error.
* design, unlike the binding gate's BLOCK), 1 on a failed operation, 2 on usage
* error.
*/
import { readFileSync } from "node:fs";
@ -24,7 +38,23 @@ import {
loadDistillate,
saveDistillate,
} from "./distillate.js";
import type { DistillateEntry, SkeletonCandidate } from "./types.js";
import {
appendPhase,
editionFacts,
readEditionState,
saveEditionState,
seriesRootFromStatePath,
} from "./editionState.js";
import {
completeEdition,
defaultRegisterPath,
elapsedDays,
listEditions,
loadRegister,
saveRegister,
upsertEdition,
} from "./register.js";
import type { DistillateEntry, EditionRow, SkeletonCandidate } from "./types.js";
function parseFlags(args: string[]): Record<string, string> {
const out: Record<string, string> = {};
@ -48,12 +78,22 @@ function usage(msg: string): never {
console.error(`error: ${msg}`);
console.error(
"usage:\n" +
" distil-append --distillate <path> --series <slug> --extract <extract.json>\n" +
" distil-check --distillate <path> --skeleton <skeleton.json> [--threshold <0..1>] [--json]",
" distil-append --distillate <path> --series <slug> --extract <extract.json>\n" +
" distil-check --distillate <path> --skeleton <skeleton.json> [--threshold <0..1>] [--json]\n" +
" register-upsert --edition-state <path> [--next <text>] [--slot <text>] [--path <series-root>]\n" +
" [--register <path>] [--at <ISO>]\n" +
" register-list [--all] [--json] [--register <path>] [--now <ISO>]\n" +
" register-complete --series <slug> --edition <NN> [--register <path>] [--at <ISO>]",
);
process.exit(2);
}
/** A failed operation (as opposed to a malformed invocation). */
function fail(msg: string): never {
console.error(`error: ${msg}`);
process.exit(1);
}
/** A flag that was given a real value (not absent, not a bare boolean flag). */
function value(flags: Record<string, string>, key: string): string | undefined {
const v = flags[key];
@ -92,6 +132,28 @@ function toEntry(raw: unknown): DistillateEntry {
};
}
/**
* One edition as the operator reads it: what it is, where it stands, what the
* one next move is, and how long it has been running. This block IS the WIP
* answer if it needs a follow-up file to be useful, the register has failed.
*/
function renderRow(row: EditionRow, now: string): string {
const days = elapsedDays(row.startedAt, row.completedAt ?? now);
const age =
days === null
? "age unknown"
: row.status === "complete"
? `lead time ${days} day(s)`
: `${days} day(s) in flight`;
return (
`\n · ${row.series}/${row.editionId}${row.title ? ` — "${row.title}"` : ""}\n` +
` phase: ${row.currentPhase} → next: ${row.nextAction ?? "—"}\n` +
` ${age} · slot: ${row.slot ?? "—"}\n` +
` ${row.path}`
);
}
function main(): void {
const [command, ...rest] = process.argv.slice(2);
const flags = parseFlags(rest);
@ -161,6 +223,99 @@ function main(): void {
return;
}
if (command === "register-upsert") {
const statePath = value(flags, "edition-state");
if (!statePath) usage("register-upsert needs --edition-state <path>");
const at = value(flags, "at") ?? new Date().toISOString();
const registerPath = value(flags, "register") ?? defaultRegisterPath();
let state;
try {
state = readEditionState(statePath);
} catch (err) {
usage(`could not read edition-state at ${statePath}: ${(err as Error).message}`);
}
let facts;
try {
facts = editionFacts(state);
} catch (err) {
usage((err as Error).message);
}
// Log first, mirror second: the state file is the source of truth, and a
// register row for a transition that was never logged would be a lie.
const logged = appendPhase(state, facts.editionId, facts.currentPhase, at);
if (logged.appended) saveEditionState(statePath, logged.state);
const { register, row, created } = upsertEdition(
loadRegister(registerPath),
{
series: facts.series,
editionId: facts.editionId,
title: facts.title,
path: value(flags, "path") ?? seriesRootFromStatePath(statePath),
currentPhase: facts.currentPhase,
nextAction: value(flags, "next"),
slot: value(flags, "slot"),
},
at,
);
saveRegister(registerPath, register);
console.log(
`${created ? "Registered" : "Updated"} ${row.series}/${row.editionId} at phase ${row.currentPhase} ` +
`(${logged.appended ? "phase logged" : "phase already logged"}) — ${registerPath}`,
);
return;
}
if (command === "register-list") {
const registerPath = value(flags, "register") ?? defaultRegisterPath();
const includeComplete = flags.all === "true";
const now = value(flags, "now") ?? new Date().toISOString();
const rows = listEditions(loadRegister(registerPath), { includeComplete });
if (asJson) {
console.log(JSON.stringify(rows, null, 2));
return;
}
if (rows.length === 0) {
console.log(includeComplete ? "No editions in the register." : "No editions in flight.");
return;
}
console.log(
includeComplete
? `${rows.length} edition(s) in the register:`
: `${rows.length} edition(s) in flight:`,
);
for (const row of rows) console.log(renderRow(row, now));
return;
}
if (command === "register-complete") {
const series = value(flags, "series");
const editionId = value(flags, "edition");
if (!series || !editionId) usage("register-complete needs --series <slug> and --edition <NN>");
const at = value(flags, "at") ?? new Date().toISOString();
const registerPath = value(flags, "register") ?? defaultRegisterPath();
const { register, row } = completeEdition(loadRegister(registerPath), { series, editionId }, at);
if (!row) fail(`no register row for ${series}/${editionId} — nothing to complete`);
saveRegister(registerPath, register);
const lead = elapsedDays(row.startedAt, row.completedAt ?? at);
console.log(
`Completed ${row.series}/${row.editionId}` +
(lead === null ? "" : ` — lead time ${lead} day(s)`) +
`${registerPath}`,
);
return;
}
usage(command ? `unknown command: ${command}` : "no command given");
}

View file

@ -0,0 +1,106 @@
/**
* The edition-state side of the register (N12 A1-12).
*
* Two jobs, both deterministic:
* 1. read the handful of facts the register mirrors (series, edition, title,
* phase) refusing to guess when any of them is missing;
* 2. append the `phaseLog` entry that makes lead time measurable.
*
* Why code and not the command layer: the phase log is only useful if it is
* complete, and "remember to append the right JSON object at all ~17 transitions"
* is exactly the discipline a model quietly drops mid-pipeline. One CLI call at
* each transition writes both the log and the register, or neither.
*
* The state file is read and written whole this package touches `phaseLog` and
* nothing else. `edition-state.json` stays owned by /linkedin:newsletter.
*/
import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
import { dirname } from "node:path";
import type { EditionFacts, EditionStateFile, PhaseLogEntry } from "./types.js";
/** Read the state file. A missing file throws — the register mirrors state, it never invents it. */
export function readEditionState(path: string): EditionStateFile {
return JSON.parse(readFileSync(path, "utf8")) as EditionStateFile;
}
/** Write the state back, preserving everything this package did not touch. */
export function saveEditionState(path: string, state: EditionStateFile): void {
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, JSON.stringify(state, null, 2) + "\n", "utf8");
}
/**
* Extract what the register mirrors. Every missing field is an error rather than
* a default: a row naming the wrong phase is worse than no row, because the
* whole point is that the operator trusts the list without opening files.
* The title is the one exception it is telemetry, not a gate.
*/
export function editionFacts(state: EditionStateFile): EditionFacts {
const series = state.series?.slug;
if (typeof series !== "string" || series.trim().length === 0) {
throw new Error("edition-state is missing series.slug");
}
const editionId = state.currentArticle;
if (typeof editionId !== "string" || editionId.trim().length === 0) {
throw new Error("edition-state is missing currentArticle");
}
const article = state.articles?.[editionId];
if (!article || typeof article !== "object") {
throw new Error(`edition-state has no articles entry for currentArticle ${editionId}`);
}
const currentPhase = state.currentPhase;
if (typeof currentPhase !== "string" || currentPhase.trim().length === 0) {
throw new Error("edition-state is missing currentPhase");
}
return { series, editionId, title: typeof article.title === "string" ? article.title : "", currentPhase };
}
export interface AppendPhaseResult {
state: EditionStateFile;
/** false iff the same transition was already the newest entry. */
appended: boolean;
}
/**
* Append one completed phase to the article's log.
*
* Idempotent against an immediately repeated transition (a re-run of the same
* step), but NOT against a phase that recurs after another one: `/linkedin:pivot`
* legitimately sends an edition back through cleared gates, and that second pass
* is real production time collapsing it would understate the lead time of
* exactly the editions that cost the most.
*/
export function appendPhase(
state: EditionStateFile,
editionId: string,
phase: string,
at: string,
): AppendPhaseResult {
const article = state.articles?.[editionId];
if (!article || typeof article !== "object") {
throw new Error(`edition-state has no articles entry for ${editionId}`);
}
const log: PhaseLogEntry[] = Array.isArray(article.phaseLog) ? article.phaseLog : [];
article.phaseLog = log;
if (log.length > 0 && log[log.length - 1].phase === phase) return { state, appended: false };
log.push({ phase, completedAt: at });
return { state, appended: true };
}
/**
* Derive the series root from the conventional
* `<serie>/linkedin/edition-state.json` layout, so a transition does not have to
* repeat a path the state file's own location already carries.
*/
export function seriesRootFromStatePath(statePath: string): string {
return dirname(dirname(statePath));
}

View file

@ -0,0 +1,171 @@
/**
* The editions register (N12 A1-11 / A1-12).
*
* One row per edition in production, so the week's work-in-progress is readable
* without opening a single `edition-state.json`, and lead time (first transition
* completion) is measured rather than assumed.
*
* Pure where it matters: every mutation takes `now` as an argument, exactly like
* the distillate takes `lockedAt`. No clock in the core means no run-to-run
* variance in the tests and no hidden timezone behaviour in the data.
*
* Mirror discipline: nothing here is authoritative. Rows are derived from
* edition-state files at phase transitions; `startedAt` is the only value that
* cannot be recovered by re-running one, which is why it never moves.
*/
import { readFileSync, writeFileSync, existsSync, mkdirSync } from "node:fs";
import { dirname, join } from "node:path";
import { homedir } from "node:os";
import { REGISTER_SCHEMA_VERSION } from "./types.js";
import type { EditionRegister, EditionRow, EditionStatus, UpsertInput } from "./types.js";
export { REGISTER_SCHEMA_VERSION } from "./types.js";
const MS_PER_DAY = 86_400_000;
export function emptyRegister(): EditionRegister {
return { schemaVersion: REGISTER_SCHEMA_VERSION, editions: [] };
}
/** Read the register; a missing file is an empty one (the first edition is not an error). */
export function loadRegister(path: string): EditionRegister {
if (!existsSync(path)) return emptyRegister();
const parsed = JSON.parse(readFileSync(path, "utf8")) as Partial<EditionRegister>;
return {
schemaVersion: parsed.schemaVersion ?? REGISTER_SCHEMA_VERSION,
editions: Array.isArray(parsed.editions) ? parsed.editions : [],
};
}
/** Write as pretty JSON with a trailing newline, creating the parent dir if needed. */
export function saveRegister(path: string, register: EditionRegister): void {
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, JSON.stringify(register, null, 2) + "\n", "utf8");
}
export interface UpsertResult {
register: EditionRegister;
row: EditionRow;
/** true iff the edition had no row yet. */
created: boolean;
}
/**
* Mirror one phase transition into the register.
*
* Omitted optionals are preserved: a transition reports the phase it just
* completed, and it must not blank the slot or the title just because it had no
* reason to mention them. Re-upserting a completed edition REACTIVATES its row
* `/linkedin:pivot` re-opens an edition, and the lead-time clock it started
* should keep running rather than fork a second row.
*/
export function upsertEdition(register: EditionRegister, input: UpsertInput, now: string): UpsertResult {
const at = register.editions.findIndex(
(e) => e.series === input.series && e.editionId === input.editionId,
);
if (at < 0) {
const row: EditionRow = {
series: input.series,
editionId: input.editionId,
title: input.title ?? "",
path: input.path,
currentPhase: input.currentPhase,
nextAction: input.nextAction ?? null,
slot: input.slot ?? null,
startedAt: now,
updatedAt: now,
completedAt: null,
status: "active",
};
register.editions.push(row);
return { register, row, created: true };
}
const existing = register.editions[at];
const row: EditionRow = {
...existing,
title: input.title ?? existing.title,
path: input.path,
currentPhase: input.currentPhase,
nextAction: input.nextAction ?? existing.nextAction,
slot: input.slot ?? existing.slot,
updatedAt: now,
completedAt: null,
status: "active",
};
register.editions[at] = row;
return { register, row, created: false };
}
export interface CompleteResult {
register: EditionRegister;
/** null iff no row matched — completing an edition that was never registered is a caller error. */
row: EditionRow | null;
}
/**
* Close an edition. Idempotent by design: a second call keeps the FIRST
* `completedAt`, so re-running Step 10 cannot quietly stretch the measured lead
* time of an edition that was already done.
*/
export function completeEdition(
register: EditionRegister,
key: { series: string; editionId: string },
now: string,
): CompleteResult {
const at = register.editions.findIndex((e) => e.series === key.series && e.editionId === key.editionId);
if (at < 0) return { register, row: null };
const existing = register.editions[at];
if (existing.status === "complete") return { register, row: existing };
const row: EditionRow = { ...existing, status: "complete", completedAt: now, updatedAt: now };
register.editions[at] = row;
return { register, row };
}
export interface ListOptions {
/** Include finished editions — the history behind the in-flight view. */
includeComplete?: boolean;
}
const STATUS_ORDER: Record<EditionStatus, number> = { active: 0, complete: 1 };
/** Deterministic order: in flight first, then by series, then by edition id. */
export function listEditions(register: EditionRegister, options: ListOptions = {}): EditionRow[] {
const rows = options.includeComplete
? [...register.editions]
: register.editions.filter((e) => e.status === "active");
return rows.sort(
(a, b) =>
STATUS_ORDER[a.status] - STATUS_ORDER[b.status] ||
a.series.localeCompare(b.series) ||
a.editionId.localeCompare(b.editionId),
);
}
/**
* Days between two ISO stamps, to two decimals the lead-time primitive.
* Sub-day precision matters: at two editions a week, "1 day" and "0.5 days" are
* a different production reality. An unparseable stamp yields null, never NaN.
*/
export function elapsedDays(from: string, to: string): number | null {
const a = Date.parse(from);
const b = Date.parse(to);
if (Number.isNaN(a) || Number.isNaN(b)) return null;
return Math.round(((b - a) / MS_PER_DAY) * 100) / 100;
}
/**
* Default register path under the per-user data dir (M0 data-path convention),
* so the WIP view survives plugin upgrades/reinstalls. `LINKEDIN_STUDIO_DATA`
* overrides the root; otherwise `~/.claude/linkedin-studio`.
*/
export function defaultRegisterPath(): string {
const root = process.env.LINKEDIN_STUDIO_DATA ?? join(homedir(), ".claude", "linkedin-studio");
return join(root, "editions", "register.json");
}

View file

@ -69,6 +69,97 @@ export interface ReuseHit {
export type ReuseVerdict = "CLEAR" | "REUSE";
/* ------------------------------------------------------------------ *
* Editions register (N12 A1-11 / A1-12)
*
* A second, orthogonal grain of series memory: the distillate above answers
* "has the reader heard this before?", the register answers "what is in flight
* right now, and how long has it taken?". At two editions a week the expensive
* blind spot is not content it is that the only record of an in-flight edition
* lives inside its own `edition-state.json`, so seeing the week means opening
* every series folder by hand, and lead time is never measured at all.
*
* The register is a MIRROR, never a source of truth: every row is derived from
* an `edition-state.json` at a phase transition. Losing it costs telemetry, not
* an edition rebuild by re-running the transitions.
* ------------------------------------------------------------------ */
export const REGISTER_SCHEMA_VERSION = 1;
export type EditionStatus = "active" | "complete";
/** One in-flight (or finished) edition, keyed by `(series, editionId)`. */
export interface EditionRow {
/** Series slug — `series.slug` in edition-state.json. */
series: string;
/** Edition id within the series — `currentArticle`, e.g. "05". */
editionId: string;
title: string;
/** Absolute path to the series root holding this edition. */
path: string;
/** Last completed phase, mirrored from `currentPhase`. */
currentPhase: string;
/** The one next concrete step, in the operator's words. */
nextAction: string | null;
/** Publishing slot, once one is claimed (N13 wires the slot layer). */
slot: string | null;
/** First transition seen — the lead-time anchor. Never moves. */
startedAt: string;
updatedAt: string;
completedAt: string | null;
status: EditionStatus;
}
export interface EditionRegister {
schemaVersion: number;
editions: EditionRow[];
}
/** What a phase transition supplies. Omitted optionals are PRESERVED, not blanked. */
export interface UpsertInput {
series: string;
editionId: string;
path: string;
currentPhase: string;
title?: string;
nextAction?: string;
slot?: string;
}
/* ---- edition-state.json: the mirrored source of truth ---- */
/** One completed phase transition — the raw material for lead-time measurement. */
export interface PhaseLogEntry {
phase: string;
/** ISO timestamp. Supplied by the caller (CLI edge) — no clock in the pure core. */
completedAt: string;
}
/** Structurally open: this package reads a few fields and must preserve the rest verbatim. */
export interface EditionArticle {
title?: string;
phase?: string;
phaseLog?: PhaseLogEntry[];
[key: string]: unknown;
}
export interface EditionStateFile {
schemaVersion?: number;
series?: { slug?: string; title?: string };
currentArticle?: string;
currentPhase?: string;
articles: Record<string, EditionArticle>;
[key: string]: unknown;
}
/** The fields the register mirrors out of an edition-state file. */
export interface EditionFacts {
series: string;
editionId: string;
title: string;
currentPhase: string;
}
/**
* Advisory by design this reports into the annotation gate the operator
* already reads at Step 2.5; it never blocks. Re-use is sometimes the right