linkedin-studio/scripts/specifics-bank/src/cli.ts
Kjell Tore Guttormsen b54e450c3e 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
2026-07-25 06:29:01 +02:00

247 lines
8.7 KiB
JavaScript

#!/usr/bin/env node
/**
* CLI for the lived-specifics bank (Fix #2 — kilde-så-draft).
*
* node --import tsx src/cli.ts query --tags <a,b> [--bank <path>] [--json]
* node --import tsx src/cli.ts add --type <t> --content "<text>" --tags <a,b>
* [--source <s>] [--verification <v>] [--bank <path>]
* node --import tsx src/cli.ts list [--bank <path>] [--json]
*
* The command layer (Step 1.5) calls `query` to surface inventory the operator
* already has for an edition's topics, and `add` to fold newly-elicited material
* back in. Deterministic store; the elicitation interview itself lives upstream.
*
* Exit code: 0 on success, 2 on usage error.
*/
import { readFileSync, writeFileSync } from "node:fs";
import {
addSpecific,
defaultBankPath,
loadBank,
queryByTopic,
recordUsage,
saveBank,
} from "./bank.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";
const VALID_TYPES: SpecificType[] = [
"number",
"named-case",
"what-broke",
"contrarian",
"mind-change",
"other",
];
const VALID_VERIFICATION: Verification[] = ["verified", "unverified", "n/a"];
function parseFlags(args: string[]): Record<string, string> {
const out: Record<string, string> = {};
for (let i = 0; i < args.length; i++) {
const a = args[i];
if (a.startsWith("--")) {
const key = a.slice(2);
const next = args[i + 1];
if (next === undefined || next.startsWith("--")) {
out[key] = "true";
} else {
out[key] = next;
i++;
}
}
}
return out;
}
function splitTags(raw: string | undefined): string[] {
if (!raw) return [];
return raw
.split(",")
.map((t) => t.trim())
.filter((t) => t.length > 0);
}
function usage(msg: string): never {
console.error(`error: ${msg}`);
console.error(
"usage:\n" +
" query --tags <a,b> [--bank <path>] [--json]\n" +
' 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>]\n" +
" record-usage --edition <edition-state.json> --edition-id <slug/NN> [--article <id>] [--bank <path>] [--json]",
);
process.exit(2);
}
/** Minimal shape of edition-state.json that the binding subcommands read. */
interface EditionArticle {
title?: string;
livedSpecifics?: LivedSpecifics;
}
interface EditionState {
currentArticle?: string;
articles?: Record<string, EditionArticle>;
}
const EMPTY_LS: LivedSpecifics = { slots: [], status: "pending" };
function loadEdition(path: string): EditionState {
return JSON.parse(readFileSync(path, "utf8")) as EditionState;
}
/** Resolve the target article: explicit --article, else currentArticle, else "01". */
function resolveArticle(edition: EditionState, flag?: string): { id: string; article: EditionArticle } {
const id = flag ?? edition.currentArticle ?? "01";
return { id, article: edition.articles?.[id] ?? {} };
}
function today(): string {
return new Date().toISOString().slice(0, 10);
}
function main(): void {
const [command, ...rest] = process.argv.slice(2);
const flags = parseFlags(rest);
const bankPath = flags.bank ?? defaultBankPath();
const asJson = flags.json === "true";
if (command === "query") {
const tags = splitTags(flags.tags);
if (tags.length === 0) usage("query needs --tags <a,b>");
const hits = queryByTopic(loadBank(bankPath), tags);
if (asJson) {
console.log(JSON.stringify(hits, null, 2));
return;
}
if (hits.length === 0) {
console.log(`No lived specifics found for tags: ${tags.join(", ")}`);
console.log("→ elicit fresh material from the operator (Step 1.5), then `add` it.");
return;
}
console.log(`${hits.length} lived specific(s) for: ${tags.join(", ")}`);
for (const { specific, tagOverlap } of hits) {
const v = specific.verification === "verified" ? "" : ` [${specific.verification}]`;
console.log(`\n · (${specific.type}, overlap ${tagOverlap})${v} ${specific.content}`);
console.log(` tags: ${specific.topicTags.join(", ")} — from ${specific.provenance.source}`);
}
return;
}
if (command === "add") {
const type = flags.type as SpecificType;
if (!VALID_TYPES.includes(type)) usage(`--type must be one of: ${VALID_TYPES.join(", ")}`);
const content = flags.content;
if (!content || content === "true") usage("add needs --content \"<text>\"");
const tags = splitTags(flags.tags);
if (tags.length === 0) usage("add needs --tags <a,b>");
const verification = (flags.verification as Verification) ?? "unverified";
if (!VALID_VERIFICATION.includes(verification)) {
usage(`--verification must be one of: ${VALID_VERIFICATION.join(", ")}`);
}
const bank = loadBank(bankPath);
const res = addSpecific(bank, {
type,
content,
topicTags: tags,
provenance: { capturedAt: today(), source: flags.source ?? "manual" },
verification,
});
saveBank(bankPath, res.bank);
if (res.added) {
console.log(`Added (${type}): ${content}`);
} else {
console.log(`Duplicate — already in bank${res.merged ? " (tags unioned)" : ""}: ${content}`);
}
console.log(`Bank: ${bankPath} (${res.bank.specifics.length} specifics)`);
return;
}
if (command === "list") {
const bank = loadBank(bankPath);
if (asJson) {
console.log(JSON.stringify(bank, null, 2));
return;
}
console.log(`Bank: ${bankPath}${bank.specifics.length} specific(s)`);
for (const s of bank.specifics) {
const flag = s.status === "active" ? "" : ` (${s.status})`;
console.log(` · [${s.type}]${flag} ${s.content} {${s.topicTags.join(", ")}}`);
}
return;
}
if (command === "validate-binding") {
if (!flags.edition || flags.edition === "true") usage("validate-binding needs --edition <path>");
const edition = loadEdition(flags.edition);
const { id, article } = resolveArticle(edition, flags.article);
const ls = article.livedSpecifics ?? EMPTY_LS;
const res = validateBinding(ls, loadBank(bankPath));
if (asJson) {
console.log(JSON.stringify({ article: id, ...res }, null, 2));
} else {
const c = res.coverage;
console.log(`Binding for article ${id}: ${res.verdict}`);
console.log(
` slots ${c.total} — levd ${c.specific} · abstrakt ${c.abstrakt} · ekstern ${c.ekstern} · uavklart ${c.unresolved}`,
);
for (const p of res.problems) console.log(`${p.slotId}: ${p.reason}${p.detail}`);
for (const w of res.warnings) console.log(`${w.slotId}: ${w.detail}`);
}
process.exit(res.verdict === "BLOCK" ? 1 : 0);
}
if (command === "render-kilder") {
if (!flags.edition || flags.edition === "true") usage("render-kilder needs --edition <path>");
const edition = loadEdition(flags.edition);
const { id, article } = resolveArticle(edition, flags.article);
const md = renderKilder({
articleId: id,
title: article.title ?? id,
livedSpecifics: article.livedSpecifics ?? EMPTY_LS,
bank: loadBank(bankPath),
});
if (flags.out && flags.out !== "true") {
writeFileSync(flags.out, md, "utf8");
console.log(`Wrote ${flags.out}`);
} else {
process.stdout.write(md);
}
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");
}
main();