feat(linkedin-studio): N11 — serie-destillat + skjelett-sjekk + specifics-bank bruks-logging [skip-docs]

Every long-form gate agent sees ONE edition, so «the reader has heard this
before» was structurally invisible — and the specifics-bank dedupe actively
encouraged re-surfacing the same material. At series cadence that is the
fastest-growing defect class. N11 makes it visible BEFORE the skeleton is
approved, at two grains:

- Series grain — new scripts/editions package: each locked edition's spent
  anecdotes/arguments/hooks are written to <serie>/linkedin/series-distillate.json
  at Step 8 lock (distil-append), and the next skeleton is checked against it at
  Step 2.5 (distil-check) with the finding folded into the annotation gate the
  operator already reads. Advisory, never blocking: a deliberate callback is a
  legitimate move, an unnoticed retread is not.
- Material grain — specifics-bank usedIn log: record-usage stamps «used in
  edition NN» on the specifics an edition actually consumed (read from the bound
  slot-map, so abstrakt/ekstern stamp nothing). At lock, so it means published;
  idempotent under a pivot re-lock. Additive-optional, schema stays v1.

Placement deviates from the plan text (${DATA}) after premise-verification:
per-series state belongs in the series root beside edition-state.json, where
Step 0 already resolves the path and no slug→path map is needed. Operator
approved. The distillate module also lands in scripts/editions now rather than
at N12, since the AC required a testable roundtrip and N12 planned that package
anyway — N12 extends it instead of creating it.

Similarity is character-trigram Jaccard, not word overlap: the plugin is
language-general and inflection (migrere/migreringen) breaks word tokens.
Calibrated on real paraphrase pairs — retellings 0.44-0.55, unrelated 0.04-0.06,
same-topic-different-story 0.24 — so the default threshold sits in the gap at
0.40. Word-Jaccard scored a shortened hook paraphrase at 0.11.

TDD (Iron Law): tests written first and verified red before implementation, for
both the new package and the bank logging.

Suites: editions 27/0 (new suite line + guard, floor 27) · specifics-bank
28 -> 45 · test-runner 163 -> 173 (Section 16r: 9 unconditional greps +
non-vacuity self-test; anti-erosion floor 146 -> 155) · trends 300/0 ·
brain 134/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:29:01 +02:00
commit b54e450c3e
20 changed files with 2152 additions and 19 deletions

View file

@ -142,6 +142,56 @@ export function queryByTopic(bank: Bank, tags: string[]): QueryHit[] {
return hits;
}
/** What a caller supplies to recordUsage. */
export interface UsageInput {
/** Bank ids the edition actually consumed — see `boundSpecificIds` in binding.ts. */
ids: string[];
/** The edition the material was published in, e.g. "seres/05". */
editionId: string;
}
export interface UsageResult {
bank: Bank;
/** ids that gained this edition now. */
recorded: string[];
/** ids already carrying it — a re-lock after a pivot is idempotent. */
alreadyRecorded: string[];
/** ids absent from the bank; the caller decides how loud to be. */
unknown: string[];
}
/**
* Stamp "used in edition NN" on the specifics an edition consumed. Called at
* LOCK (Step 8) rather than at binding (Step 2.5), so an abandoned draft never
* pollutes the history `usedIn` means published, not considered.
* Archived material still records: the use is historical fact.
*/
export function recordUsage(bank: Bank, input: UsageInput): UsageResult {
const editionId = input.editionId.trim();
if (editionId.length === 0) {
throw new Error("recordUsage: editionId must be non-blank — an unattributable use is worse than none");
}
const byId = new Map<string, Specific>(bank.specifics.map((s) => [s.id, s]));
const recorded: string[] = [];
const alreadyRecorded: string[] = [];
const unknown: string[] = [];
for (const id of input.ids) {
const specific = byId.get(id);
if (!specific) {
unknown.push(id);
continue;
}
const usedIn = specific.usedIn ?? [];
if (usedIn.includes(editionId)) {
alreadyRecorded.push(id);
continue;
}
specific.usedIn = [...usedIn, editionId];
recorded.push(id);
}
return { bank, recorded, alreadyRecorded, unknown };
}
/**
* Default bank path under the per-user data dir (M0 data-path convention), so the
* bank survives plugin upgrades/reinstalls. `LINKEDIN_STUDIO_DATA` overrides the

View file

@ -154,3 +154,21 @@ export function validateBinding(ls: LivedSpecifics, bank: Bank): BindingResult {
coverage,
};
}
/**
* The bank ids an edition's slot-map actually consumed slot order, deduped.
* Pure. This is the input to `recordUsage` at lock: only `specific` bindings
* count as consumption (abstrakt/ekstern/unresolved consume no bank material).
*/
export function boundSpecificIds(ls: LivedSpecifics): string[] {
const seen = new Set<string>();
const ids: string[] = [];
for (const slot of ls.slots) {
if (slot.binding.type !== "specific") continue;
const { specificId } = slot.binding;
if (seen.has(specificId)) continue;
seen.add(specificId);
ids.push(specificId);
}
return ids;
}

View file

@ -21,9 +21,10 @@ import {
defaultBankPath,
loadBank,
queryByTopic,
recordUsage,
saveBank,
} from "./bank.js";
import { validateBinding } from "./binding.js";
import { boundSpecificIds, validateBinding } from "./binding.js";
import { renderKilder } from "./kilder.js";
import type { LivedSpecifics } from "./binding.js";
import type { SpecificType, Verification } from "./types.js";
@ -72,7 +73,8 @@ function usage(msg: string): never {
' add --type <t> --content "<text>" --tags <a,b> [--source <s>] [--verification <v>] [--bank <path>]\n' +
" list [--bank <path>] [--json]\n" +
" validate-binding --edition <edition-state.json> [--article <id>] [--bank <path>] [--json]\n" +
" render-kilder --edition <edition-state.json> [--article <id>] [--bank <path>] [--out <path>]",
" render-kilder --edition <edition-state.json> [--article <id>] [--bank <path>] [--out <path>]\n" +
" record-usage --edition <edition-state.json> --edition-id <slug/NN> [--article <id>] [--bank <path>] [--json]",
);
process.exit(2);
}
@ -213,6 +215,32 @@ function main(): void {
return;
}
if (command === "record-usage") {
if (!flags.edition || flags.edition === "true") usage("record-usage needs --edition <path>");
const editionId = flags["edition-id"];
if (!editionId || editionId === "true") {
usage("record-usage needs --edition-id <slug/NN> — an unattributable use is worse than none");
}
const edition = loadEdition(flags.edition);
const { id, article } = resolveArticle(edition, flags.article);
const ids = boundSpecificIds(article.livedSpecifics ?? EMPTY_LS);
const res = recordUsage(loadBank(bankPath), { ids, editionId });
saveBank(bankPath, res.bank);
if (asJson) {
console.log(JSON.stringify({ article: id, editionId, ...res, bank: undefined }, null, 2));
return;
}
console.log(
`Usage recorded for article ${id} as "${editionId}": ` +
`${res.recorded.length} stamped, ${res.alreadyRecorded.length} already logged.`,
);
if (res.unknown.length > 0) {
console.log(`${res.unknown.length} bound id(s) absent from the bank: ${res.unknown.join(", ")}`);
}
return;
}
usage(command ? `unknown command: ${command}` : "no command given");
}

View file

@ -55,6 +55,14 @@ export interface Specific {
/** Numbers must be fact-checked before a draft asserts them as fact (regel 6/7). */
verification: Verification;
status: SpecificStatus;
/**
* Editions this material was actually published in ("seres/05"), appended at
* lock. Additive-optional: absent means never used, so existing banks load
* unchanged and the schema stays v1. The dedupe in `addSpecific` deliberately
* ENCOURAGES re-surfacing the same material; this field is what makes the
* re-use visible to the operator at Step 1.5 instead of silent (N11 / C-5).
*/
usedIn?: string[];
}
export interface Bank {

View file

@ -0,0 +1,142 @@
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, writeFileSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { addSpecific, emptyBank, specificId, saveBank } from "../src/bank.js";
// Resolve the package root so the subprocess `src/cli.ts` path + the `tsx` loader
// resolve regardless of the runner's cwd.
const bankDir = fileURLToPath(new URL("..", import.meta.url));
function run(args: string[]): { status: number | null; stdout: string; stderr: string } {
const res = spawnSync("node", ["--import", "tsx", "src/cli.ts", ...args], {
encoding: "utf8",
cwd: bankDir,
});
return { status: res.status, stdout: res.stdout, stderr: res.stderr };
}
const tmp = () => mkdtempSync(join(tmpdir(), "specifics-cli-usage-"));
const CONTENT = "Vi målte 40 prosent kortere ledetid etter omleggingen.";
/** A bank + an edition-state whose slot-map binds one slot to the bank specific. */
function fixture(dir: string): { bankPath: string; editionPath: string; id: string } {
const bankPath = join(dir, "specifics-bank.json");
const id = specificId(CONTENT);
const bank = addSpecific(emptyBank(), {
type: "number",
content: CONTENT,
topicTags: ["ai"],
provenance: { capturedAt: "2026-06-20", source: "test" },
}).bank;
saveBank(bankPath, bank);
const editionPath = join(dir, "edition-state.json");
writeFileSync(
editionPath,
JSON.stringify({
currentArticle: "05",
articles: {
"05": {
title: "Da pipelinen brøt sammen",
livedSpecifics: {
status: "bound",
slots: [
{ slotId: "kp1", kind: "key-point", label: "ledetid", binding: { type: "specific", specificId: id } },
{ slotId: "kp2", kind: "key-point", label: "annet", binding: { type: "abstrakt", rationale: "bevisst" } },
],
},
},
},
}),
"utf8",
);
return { bankPath, editionPath, id };
}
describe("specifics-bank CLI — record-usage (Step 8 lock)", () => {
test("stamps the edition on the bound specifics and persists it", () => {
const dir = tmp();
try {
const { bankPath, editionPath, id } = fixture(dir);
const res = run(["record-usage", "--edition", editionPath, "--edition-id", "seres/05", "--bank", bankPath]);
assert.equal(res.status, 0, res.stderr);
const onDisk = JSON.parse(readFileSync(bankPath, "utf8"));
const stamped = onDisk.specifics.find((s: { id: string }) => s.id === id);
assert.deepEqual(stamped.usedIn, ["seres/05"]);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
test("only specific-bound slots are stamped — abstrakt/ekstern consume no bank material", () => {
const dir = tmp();
try {
const { bankPath, editionPath } = fixture(dir);
const res = run(["record-usage", "--edition", editionPath, "--edition-id", "seres/05", "--bank", bankPath, "--json"]);
assert.equal(res.status, 0, res.stderr);
const out = JSON.parse(res.stdout);
assert.equal(out.recorded.length, 1);
assert.deepEqual(out.unknown, []);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
test("re-running after a pivot re-lock is idempotent", () => {
const dir = tmp();
try {
const { bankPath, editionPath, id } = fixture(dir);
run(["record-usage", "--edition", editionPath, "--edition-id", "seres/05", "--bank", bankPath]);
const again = run(["record-usage", "--edition", editionPath, "--edition-id", "seres/05", "--bank", bankPath, "--json"]);
assert.equal(again.status, 0, again.stderr);
const out = JSON.parse(again.stdout);
assert.deepEqual(out.recorded, []);
assert.equal(out.alreadyRecorded.length, 1);
const onDisk = JSON.parse(readFileSync(bankPath, "utf8"));
const stamped = onDisk.specifics.find((s: { id: string }) => s.id === id);
assert.deepEqual(stamped.usedIn, ["seres/05"], "a re-lock must not double-stamp");
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
test("an edition with no bound specifics is a no-op, exit 0", () => {
const dir = tmp();
try {
const { bankPath } = fixture(dir);
const empty = join(dir, "empty-edition.json");
writeFileSync(empty, JSON.stringify({ currentArticle: "06", articles: { "06": {} } }), "utf8");
const res = run(["record-usage", "--edition", empty, "--edition-id", "seres/06", "--bank", bankPath, "--json"]);
assert.equal(res.status, 0, res.stderr);
assert.deepEqual(JSON.parse(res.stdout).recorded, []);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
test("bad invocations exit 2", () => {
const dir = tmp();
try {
const { bankPath, editionPath } = fixture(dir);
assert.equal(run(["record-usage", "--bank", bankPath]).status, 2); // no --edition
assert.equal(
run(["record-usage", "--edition", editionPath, "--bank", bankPath]).status,
2, // no --edition-id: an unattributable use is worse than none
);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
});

View file

@ -0,0 +1,157 @@
import { describe, test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { addSpecific, emptyBank, loadBank, recordUsage, saveBank, specificId } from "../src/bank.js";
import { boundSpecificIds } from "../src/binding.js";
import type { LivedSpecifics } from "../src/binding.js";
import type { Bank } from "../src/types.js";
const tmp = () => mkdtempSync(join(tmpdir(), "specifics-usage-"));
const CONTENT = {
a: "Vi målte 40 prosent kortere ledetid etter omleggingen.",
b: "Kunden avlyste pilotene fordi ingen eide dataene.",
};
function bankWith(...contents: string[]): Bank {
let bank = emptyBank();
for (const content of contents) {
bank = addSpecific(bank, {
type: "number",
content,
topicTags: ["ai"],
provenance: { capturedAt: "2026-06-20", source: "test" },
}).bank;
}
return bank;
}
describe("specifics-bank — usage logging (N11: «used in edition NN»)", () => {
test("recording usage stamps the edition on the specific", () => {
const bank = bankWith(CONTENT.a);
const id = specificId(CONTENT.a);
const res = recordUsage(bank, { ids: [id], editionId: "seres/05" });
assert.deepEqual(res.recorded, [id]);
assert.deepEqual(res.alreadyRecorded, []);
assert.deepEqual(res.unknown, []);
assert.deepEqual(res.bank.specifics[0].usedIn, ["seres/05"]);
});
test("recording the same edition twice is idempotent (a re-lock does not double-count)", () => {
const bank = bankWith(CONTENT.a);
const id = specificId(CONTENT.a);
const once = recordUsage(bank, { ids: [id], editionId: "seres/05" });
const twice = recordUsage(once.bank, { ids: [id], editionId: "seres/05" });
assert.deepEqual(twice.recorded, []);
assert.deepEqual(twice.alreadyRecorded, [id]);
assert.deepEqual(twice.bank.specifics[0].usedIn, ["seres/05"]);
});
test("a second edition appends, preserving order", () => {
const bank = bankWith(CONTENT.a);
const id = specificId(CONTENT.a);
const first = recordUsage(bank, { ids: [id], editionId: "seres/05" });
const second = recordUsage(first.bank, { ids: [id], editionId: "seres/06" });
assert.deepEqual(second.bank.specifics[0].usedIn, ["seres/05", "seres/06"]);
});
test("an id absent from the bank is reported as unknown, not silently dropped", () => {
const bank = bankWith(CONTENT.a);
const res = recordUsage(bank, { ids: [specificId(CONTENT.a), "deadbeef1234"], editionId: "seres/05" });
assert.deepEqual(res.unknown, ["deadbeef1234"]);
assert.deepEqual(res.recorded, [specificId(CONTENT.a)]);
});
test("archived material still records use — the use is historical fact", () => {
let bank = emptyBank();
bank = addSpecific(bank, {
type: "named-case",
content: CONTENT.b,
topicTags: ["ai"],
provenance: { capturedAt: "2026-06-20", source: "test" },
status: "archived",
}).bank;
const res = recordUsage(bank, { ids: [specificId(CONTENT.b)], editionId: "seres/05" });
assert.deepEqual(res.recorded, [specificId(CONTENT.b)]);
assert.deepEqual(res.bank.specifics[0].usedIn, ["seres/05"]);
});
test("recording touches only the named specifics", () => {
const bank = bankWith(CONTENT.a, CONTENT.b);
const res = recordUsage(bank, { ids: [specificId(CONTENT.a)], editionId: "seres/05" });
assert.deepEqual(res.bank.specifics[0].usedIn, ["seres/05"]);
assert.equal(res.bank.specifics[1].usedIn, undefined);
});
test("an empty id list is a no-op, not an error", () => {
const bank = bankWith(CONTENT.a);
const res = recordUsage(bank, { ids: [], editionId: "seres/05" });
assert.deepEqual(res.recorded, []);
assert.equal(res.bank.specifics[0].usedIn, undefined);
});
test("a blank edition id throws — an unattributable use is worse than none", () => {
const bank = bankWith(CONTENT.a);
assert.throws(() => recordUsage(bank, { ids: [specificId(CONTENT.a)], editionId: " " }), /editionId/);
});
test("usedIn survives a save/load round-trip; an untouched bank stays field-free", () => {
const dir = tmp();
try {
const path = join(dir, "specifics-bank.json");
const bank = bankWith(CONTENT.a, CONTENT.b);
const res = recordUsage(bank, { ids: [specificId(CONTENT.a)], editionId: "seres/05" });
saveBank(path, res.bank);
const back = loadBank(path);
assert.deepEqual(back.specifics[0].usedIn, ["seres/05"]);
// additive-optional: never-used material carries no field at all (schema stays v1)
assert.equal("usedIn" in back.specifics[1], false);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
});
describe("specifics-bank — boundSpecificIds (what an edition actually consumed)", () => {
const ls = (slots: LivedSpecifics["slots"]): LivedSpecifics => ({ slots, status: "bound" });
test("extracts the ids of specific-bound slots only", () => {
const res = boundSpecificIds(
ls([
{ slotId: "kp1", kind: "key-point", label: "a", binding: { type: "specific", specificId: "aaa111" } },
{ slotId: "kp2", kind: "key-point", label: "b", binding: { type: "abstrakt", rationale: "bevisst" } },
{ slotId: "kp3", kind: "section", label: "c", binding: { type: "ekstern", source: "https://x" } },
{ slotId: "kp4", kind: "section", label: "d", binding: { type: "unresolved" } },
]),
);
assert.deepEqual(res, ["aaa111"]);
});
test("dedupes an id bound in several slots", () => {
const res = boundSpecificIds(
ls([
{ slotId: "kp1", kind: "key-point", label: "a", binding: { type: "specific", specificId: "aaa111" } },
{ slotId: "kp2", kind: "section", label: "b", binding: { type: "specific", specificId: "aaa111" } },
{ slotId: "kp3", kind: "section", label: "c", binding: { type: "specific", specificId: "bbb222" } },
]),
);
assert.deepEqual(res, ["aaa111", "bbb222"]);
});
test("an empty slot map yields no ids", () => {
assert.deepEqual(boundSpecificIds(ls([])), []);
});
});