// `umtool posts roles` -- A POST ITEM's READ, PIECE BY PIECE
// (umtool-report-to-video/post-thread.mjs; umtool/docs/knobs.md, "Thread
// reads"): the text each part of its read reads -- the post it answers, the
// post it quotes, his words, an attachment's -- its own (stored) or inferred,
// what the card shows for each, and whether anything read is not on screen.
//
// umtool posts roles
[- …] the read's pieces and the guard's verdict, per narrated item
// umtool posts roles
[- …] --write the inferred roles stored on each picked take's parts
// umtool posts roles
- --set 3=parent:0,4=post one part's role set by hand (n as `ls` shows it)
//
// Every write goes through updatePostNarration (`partRoles`), one undo point a
// run (updatePostNarrations).
//
// Plain ESM: the CLI runs under bare node.
import { isNarrated, pickedTake } from "umtool-report-to-video/post-narration";
import { partRoles, readPieces, threadLayout, threadReadErrors, threadReadWarnings } from "umtool-report-to-video/post-thread";
import { followKnobs } from "umtool-report-to-video/read-follow";
import { tileOfRole } from "umtool-report-to-video/post-screens";
import { planContext } from "umtool-report-to-video/post-conversation";
import { readManifest } from "../projects/report.mjs";
import { withEditNotes } from "./edit-guard.mjs";
import { manifestToken, updatePostNarrations } from "./manifest.mjs";
export const ROLES_USAGE = [
" umtool posts roles [
- …] [--write] [--set =,…] [--json] (+ --in-take or --take : a take's)",
" A READ's PIECES (post-thread.mjs): the text each part of a narrated item's read reads -- parent: (the post it",
" answers, nearest first), quoted, post (his words), media: (an attachment's words, a screenshot) -- its own",
" role, else INFERRED (its piece, para div 100, matched by its word pairs), what the card shows for each (full,",
" excerpt, context, carry, hidden: thread.parent / thread.quoted) and the build's guard: a part read off a text the",
" card does not show is refused. --write stores the inferred roles on the picked takes' parts (the import stores",
" them for every new take); --set n=role sets one part's by hand (n from 1, as listed; role off: inferred again).",
].join("\n");
export class RolesError extends Error {
constructor(message) {
super(message);
this.name = "RolesError";
}
}
const ROLE_RE = /^(post|quoted|parent:\d|media:\d|linked:\d|screen:[a-z0-9][a-z0-9-]{0,23}:\d{1,2})$/;
/**
* A narrated item's read, piece by piece: `{ id, take, pieces: [{ role, parts, source, mode }], errors, threaded }`.
* `ctx`: what it opens on (post-conversation.mjs planContext: the item before it, its run's scene).
*/
export function readListing(e, render, ctx) {
const t = pickedTake(e);
const roles = partRoles(e);
const L = threadLayout(e, render, ctx ?? {});
const mode = (role) => (!role ? null : role.startsWith("media:") ? "attachment" : L.tiles.find((x) => x.scope === tileOfRole(role))?.mode ?? "absent");
const pieces = readPieces(e, roles).map((p) => ({
role: p.role,
parts: p.parts.map((k) => k + 1),
source: p.parts.every((k) => roles[k].source === "stored") ? "stored" : p.parts.some((k) => roles[k].source === "stored") ? "mixed" : "inferred",
mode: mode(p.role),
words: p.parts.map((k) => String(t.parts[k]?.text ?? "")).join(" ").split(/\s+/).filter(Boolean).length,
}));
const tiles = L.tiles.filter((x) => !x.read && x.scope !== "post").map((x) => ({ scope: x.scope, mode: x.mode }));
return { id: e.id, take: t?.file ?? null, parts: t?.parts?.length ?? 0, pieces, unread: tiles, threaded: L.on && followKnobs(e, render).on, errors: threadReadErrors(e, render, { ...(ctx ?? {}), followOn: followKnobs(e, render).on }), warnings: threadReadWarnings(e) };
}
/**
* `umtool posts roles
[- …] [--write] [--set n=role,…]`.
* @param {{ id: string, dir: string }} project
* @param {string[]} ids
*/
export async function rolesCommand(project, ids, { write = false, set = null, json = false, out = (s) => console.log(s) } = {}) {
const manifest = await readManifest(project.dir);
if (!manifest) throw new RolesError(`${project.id} has no manifest`);
const tl = Array.isArray(manifest.timeline) ? manifest.timeline : [];
const want = new Set(ids);
const hit = (e) => !want.size || want.has(e.id) || want.has(String(e.post ?? "").split("/")[1]);
const items = tl.map((e, i) => ({ e, ctx: planContext(tl, i, manifest.render) })).filter(({ e }) => e?.type === "post" && isNarrated(e) && hit(e) && pickedTake(e)?.parts?.length);
for (const id of want) if (!tl.some((e) => e?.type === "post" && (e.id === id || String(e.post ?? "").split("/")[1] === id))) throw new RolesError(`no post item ${id} in ${project.id}`);
if (set !== null) {
if (items.length !== 1) throw new RolesError("--set names one item's parts: give exactly one narrated item with parts");
const { e } = items[0];
const t = pickedTake(e);
const roles = t.parts.map((p) => (typeof p.role === "string" ? p.role : null));
for (const pair of String(set).split(",").map((x) => x.trim()).filter(Boolean)) {
const m = /^(\d+)=(.+)$/.exec(pair);
if (!m) throw new RolesError(`--set ${pair}: n=role (n from 1, role post|quoted|parent:|media:|off)`);
const n = Number(m[1]);
if (!(n >= 1 && n <= t.parts.length)) throw new RolesError(`--set ${pair}: ${e.id}'s take has parts 1-${t.parts.length}`);
const role = m[2].trim();
if (role !== "off" && !ROLE_RE.test(role)) throw new RolesError(`--set ${pair}: a role is post, quoted, parent:, linked:, media: (or off: inferred)`);
roles[n - 1] = role === "off" ? null : role;
}
const take = (Number.isInteger(t.index) ? t.index : e.narration.pick ?? 0);
const { result } = await withEditNotes(project, async () => updatePostNarrations(project.dir, [{ id: e.id, patch: { partRoles: { take, roles } } }], { token: await manifestToken(project.dir) }));
const now = await readManifest(project.dir);
const after = (now?.timeline ?? []).find((x) => x?.id === e.id) ?? e;
const ntl = Array.isArray(now?.timeline) ? now.timeline : [];
const row = readListing(after, now?.render ?? manifest.render, planContext(ntl, ntl.indexOf(after), now?.render ?? manifest.render));
out(json ? JSON.stringify({ ok: true, item: row, token: result.token }, null, 2) : lines([row]).join("\n"));
return 0;
}
if (write) {
const patches = [];
for (const { e } of items) {
const t = pickedTake(e);
const inferred = partRoles(e);
const roles = t.parts.map((p, k) => (typeof p.role === "string" ? p.role : inferred[k]?.role ?? null));
if (roles.every((r, k) => r === (t.parts[k].role ?? null))) continue;
patches.push({ id: e.id, patch: { partRoles: { take: (Number.isInteger(t.index) ? t.index : e.narration.pick ?? 0), roles } } });
}
if (!patches.length) {
out(json ? JSON.stringify({ ok: true, written: 0 }, null, 2) : `every read's roles are stored already (${items.length} item(s))`);
return 0;
}
const { result } = await withEditNotes(project, async () => updatePostNarrations(project.dir, patches, { token: await manifestToken(project.dir) }));
out(json ? JSON.stringify({ ok: true, written: patches.length, token: result.token }, null, 2) : `stored the roles of ${patches.length} read(s) in ${project.id}`);
return 0;
}
const rows = items.map(({ e, ctx }) => readListing(e, manifest.render, ctx));
if (json) {
out(JSON.stringify({ ok: true, items: rows, refused: rows.filter((r) => r.errors.length).length, warned: rows.filter((r) => r.warnings.length).length }, null, 2));
return 0;
}
out(`${project.id}: ${rows.length} narrated item(s) read in parts, ${rows.filter((r) => r.threaded).length} threaded, ${rows.filter((r) => r.errors.length).length} refused, ${rows.filter((r) => r.warnings.length).length} warned`);
out(lines(rows).join("\n"));
return 0;
}
function lines(rows) {
const out = [];
for (const r of rows) {
out.push(` ${r.id} ${r.parts} part(s)${r.threaded ? " threaded" : ""}`);
for (const p of r.pieces) out.push(` parts ${p.parts.join(",")} ${p.role ?? "(no text on the card)"} ${p.source}${p.mode ? ` shown ${p.mode}` : ""} ${p.words} words`);
for (const u of r.unread) out.push(` not read: ${u.scope} shown ${u.mode}`);
for (const er of r.errors) out.push(` REFUSED: ${er}`);
for (const w of r.warnings ?? []) out.push(` WARNING: ${w}`);
}
return out;
}