@deskwork/studio 0.9.5 → 0.9.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,992 @@
1
+ /**
2
+ * Studio dashboard page — `/dev/editorial-studio`.
3
+ *
4
+ * Ported from audiocontrol.org's `editorial-studio.astro`. Reads each
5
+ * site's calendar + the review pipeline + the report, then renders the
6
+ * five-stage editorial calendar with site filtering, the shortform
7
+ * coverage matrix for Published blog entries, awaiting-press / recent-
8
+ * proofs panels, and a voice-drift signal sidebar.
9
+ *
10
+ * The audiocontrol original was tightly coupled to two hardcoded sites
11
+ * (`'audiocontrol' | 'editorialcontrol'`) and the `feature-image`
12
+ * pipeline. Both go away here:
13
+ *
14
+ * - Sites come from `ctx.config.sites`. The two-letter site label
15
+ * (was `'AC' | 'EC'`) is the first 2 letters uppercased.
16
+ * - The feature-image pipeline isn't part of deskwork core yet; the
17
+ * "feature image →" / "✓ baked" affordances are dropped. The
18
+ * scrapbook chip stays — `@deskwork/core/scrapbook` provides
19
+ * `countScrapbook`.
20
+ */
21
+
22
+ import { readCalendar } from '@deskwork/core/calendar';
23
+ import {
24
+ buildReport,
25
+ type ReviewReport,
26
+ } from '@deskwork/core/review/report';
27
+ import { readWorkflows } from '@deskwork/core/review/pipeline';
28
+ import type { DraftWorkflowItem } from '@deskwork/core/review/types';
29
+ import { bodyState, type BodyState } from '@deskwork/core/body-state';
30
+ import { countScrapbook, countScrapbookForEntry } from '@deskwork/core/scrapbook';
31
+ import {
32
+ PLATFORMS,
33
+ STAGES,
34
+ effectiveContentType,
35
+ hasRepoContent,
36
+ type CalendarEntry,
37
+ type DistributionRecord,
38
+ type Platform,
39
+ type Stage,
40
+ } from '@deskwork/core/types';
41
+ import {
42
+ resolveCalendarPath,
43
+ resolveBlogFilePath,
44
+ findEntryFile,
45
+ } from '@deskwork/core/paths';
46
+ import type { ContentIndex } from '@deskwork/core/content-index';
47
+ import type { StudioContext } from '../routes/api.ts';
48
+ import { html, unsafe, type RawHtml } from './html.ts';
49
+ import { layout } from './layout.ts';
50
+ import { renderEditorialFolio } from './chrome.ts';
51
+
52
+ /**
53
+ * Per-request content-index getter. The route layer wires this to the
54
+ * Hono context's memoized cache so a single dashboard render only
55
+ * builds the index once per site even though many entries call
56
+ * `entryBodyStateOf`. When omitted (e.g., a non-route caller), the
57
+ * dashboard falls back to the slug-template path.
58
+ */
59
+ export type DashboardIndexGetter = (site: string) => ContentIndex;
60
+
61
+ interface SitedEntry {
62
+ site: string;
63
+ entry: CalendarEntry;
64
+ }
65
+ interface SitedDistribution {
66
+ site: string;
67
+ platform: string;
68
+ slug: string;
69
+ /**
70
+ * Stable id of the joined calendar entry. Phase 19d: keys
71
+ * (site, entryId) when present, falls back to (site, slug) for
72
+ * pre-id distribution records.
73
+ */
74
+ entryId: string | null;
75
+ shortform: boolean;
76
+ }
77
+
78
+ const PLATFORMS_ORDER: readonly Platform[] = [
79
+ 'reddit',
80
+ 'linkedin',
81
+ 'youtube',
82
+ 'instagram',
83
+ ];
84
+
85
+ const STAGE_ORNAMENTS: Record<Stage, string> = {
86
+ Ideas: '◇',
87
+ Planned: '§',
88
+ Outlining: '⊹',
89
+ Drafting: '✎',
90
+ Review: '※',
91
+ Paused: '⏸',
92
+ Published: '✓',
93
+ };
94
+
95
+ const MONTH_NAMES = [
96
+ 'January', 'February', 'March', 'April', 'May', 'June',
97
+ 'July', 'August', 'September', 'October', 'November', 'December',
98
+ ];
99
+
100
+ function isPlatform(value: string): value is Platform {
101
+ return (PLATFORMS as readonly string[]).includes(value);
102
+ }
103
+
104
+ function siteLabel(site: string): string {
105
+ return site.slice(0, 2).toUpperCase();
106
+ }
107
+
108
+ function stateLabel(state: string): string {
109
+ return state.replace('-', ' ');
110
+ }
111
+
112
+ /**
113
+ * Internal correlation key for the dashboard's `Map<key, …>` joins.
114
+ * Phase 19d: prefer the calendar entry's stable UUID when present,
115
+ * falling back to the slug for legacy data (workflows / entries
116
+ * created before frontmatter ids landed). The function is overloaded
117
+ * via two arities — `covKey(site, slug)` for slug-only callers and
118
+ * `covKey(site, slug, entryId)` for callers that have access to the
119
+ * id. The latter form picks `entryId` when it's a non-empty string,
120
+ * else falls through to `slug`. Display still uses slug as the human
121
+ * label; this key only correlates internally.
122
+ *
123
+ * The "fallback" here is the legacy migration path — not the kind of
124
+ * silent fallback the project rules forbid. Doctor reports the legacy
125
+ * cases so operators can backfill ids.
126
+ */
127
+ function covKey(site: string, slug: string, entryId?: string | null): string {
128
+ const stable = entryId !== undefined && entryId !== null && entryId !== ''
129
+ ? entryId
130
+ : slug;
131
+ return `${site}::${stable}`;
132
+ }
133
+
134
+ function fmtRelTime(iso: string, now: Date): string {
135
+ const t = new Date(iso).getTime();
136
+ const s = Math.max(0, Math.floor((now.getTime() - t) / 1000));
137
+ if (s < 60) return `${s}s ago`;
138
+ const m = Math.floor(s / 60);
139
+ if (m < 60) return `${m}m ago`;
140
+ const h = Math.floor(m / 60);
141
+ if (h < 48) return `${h}h ago`;
142
+ return `${Math.floor(h / 24)}d ago`;
143
+ }
144
+
145
+ function workflowLink(w: DraftWorkflowItem): string {
146
+ if (w.contentKind === 'shortform') {
147
+ // Phase 21c: shortform now renders inside the unified review
148
+ // surface. Workflow-id deep-links land on the right workflow
149
+ // without first resolving an entry id — the route handler
150
+ // recognises a workflow id and dispatches accordingly.
151
+ return `/dev/editorial-review/${w.id}`;
152
+ }
153
+ // Phase 19d: prefer the canonical id-based URL when the workflow
154
+ // carries entryId. The legacy slug URL still works (server.ts will
155
+ // 302-redirect it), but emitting the canonical form skips the
156
+ // redirect round trip and makes the UI's outbound links honest.
157
+ const key = w.entryId ?? w.slug;
158
+ const kindBit = w.contentKind === 'outline' ? '&kind=outline' : '';
159
+ return `/dev/editorial-review/${key}?site=${w.site}${kindBit}`;
160
+ }
161
+
162
+ function blogPreviewLink(site: string, slug: string, host: string, entry: CalendarEntry): string {
163
+ if (entry.stage === 'Published') return `https://${host}/blog/${slug}/`;
164
+ // Phase 19d: prefer the canonical id-based URL.
165
+ const key = entry.id ?? slug;
166
+ return `/dev/editorial-review/${key}?site=${site}`;
167
+ }
168
+
169
+ interface DashboardData {
170
+ calendarEntries: SitedEntry[];
171
+ distributions: SitedDistribution[];
172
+ slugsBySite: Record<string, string[]>;
173
+ workflows: DraftWorkflowItem[];
174
+ approved: DraftWorkflowItem[];
175
+ terminal: DraftWorkflowItem[];
176
+ publishedBlogEntries: SitedEntry[];
177
+ shortformCoverage: Map<string, Set<Platform>>;
178
+ activeBySitedSlug: Map<string, DraftWorkflowItem[]>;
179
+ report: ReviewReport;
180
+ }
181
+
182
+ function loadDashboardData(
183
+ ctx: StudioContext,
184
+ getIndex?: DashboardIndexGetter,
185
+ ): DashboardData {
186
+ // `getIndex` is currently consumed downstream by renderRow →
187
+ // entryBodyStateOf, not here. Threading it through keeps the call
188
+ // signature symmetric with renderDashboard and leaves room for
189
+ // future load-time uses (e.g., joining workflows by entry id).
190
+ void getIndex;
191
+ const calendarEntries: SitedEntry[] = [];
192
+ const distributions: SitedDistribution[] = [];
193
+ const slugsBySite: Record<string, string[]> = {};
194
+ const sites = Object.keys(ctx.config.sites);
195
+
196
+ for (const site of sites) {
197
+ slugsBySite[site] = [];
198
+ const calendarPath = resolveCalendarPath(ctx.projectRoot, ctx.config, site);
199
+ const cal = readCalendar(calendarPath);
200
+ // Build a slug → id map up front so distributions can resolve
201
+ // their entry's stable id even when the DistributionRecord
202
+ // pre-dates the entryId field.
203
+ const idBySlug = new Map<string, string>();
204
+ for (const entry of cal.entries) {
205
+ calendarEntries.push({ site, entry });
206
+ slugsBySite[site].push(entry.slug);
207
+ if (entry.id) idBySlug.set(entry.slug, entry.id);
208
+ }
209
+ for (const d of cal.distributions) {
210
+ const dr: DistributionRecord = d;
211
+ const entryId = dr.entryId ?? idBySlug.get(dr.slug) ?? null;
212
+ distributions.push({
213
+ site,
214
+ platform: dr.platform,
215
+ slug: dr.slug,
216
+ entryId,
217
+ shortform: typeof dr.shortform === 'string' && dr.shortform.length > 0,
218
+ });
219
+ }
220
+ }
221
+
222
+ const workflows = readWorkflows(ctx.projectRoot, ctx.config);
223
+ const approved = workflows.filter((w) => w.state === 'approved');
224
+ const terminal = workflows
225
+ .filter((w) => w.state === 'applied' || w.state === 'cancelled')
226
+ .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))
227
+ .slice(0, 10);
228
+
229
+ const shortformCoverage = new Map<string, Set<Platform>>();
230
+ for (const d of distributions) {
231
+ if (!d.shortform) continue;
232
+ if (!isPlatform(d.platform)) continue;
233
+ const key = covKey(d.site, d.slug, d.entryId);
234
+ const set = shortformCoverage.get(key) ?? new Set<Platform>();
235
+ set.add(d.platform);
236
+ shortformCoverage.set(key, set);
237
+ }
238
+ // Phase 21c — shortform workflows count as coverage too. Distributions
239
+ // come from the calendar (an `editorial-publish` side-effect), so a
240
+ // freshly-started shortform draft (no published-yet distribution
241
+ // record) wouldn't show in the matrix without this branch.
242
+ for (const w of workflows) {
243
+ if (w.contentKind !== 'shortform') continue;
244
+ if (w.state === 'applied' || w.state === 'cancelled') continue;
245
+ if (!w.platform || !isPlatform(w.platform)) continue;
246
+ const key = covKey(w.site, w.slug, w.entryId);
247
+ const set = shortformCoverage.get(key) ?? new Set<Platform>();
248
+ set.add(w.platform);
249
+ shortformCoverage.set(key, set);
250
+ }
251
+
252
+ const publishedBlogEntries = calendarEntries
253
+ .filter(
254
+ ({ entry }) =>
255
+ entry.stage === 'Published' && effectiveContentType(entry) === 'blog',
256
+ )
257
+ .sort((a, b) =>
258
+ (b.entry.datePublished ?? '').localeCompare(a.entry.datePublished ?? ''),
259
+ );
260
+
261
+ const activeBySitedSlug = new Map<string, DraftWorkflowItem[]>();
262
+ for (const w of workflows) {
263
+ if (w.state === 'applied' || w.state === 'cancelled') continue;
264
+ const key = covKey(w.site, w.slug, w.entryId);
265
+ const list = activeBySitedSlug.get(key) ?? [];
266
+ list.push(w);
267
+ activeBySitedSlug.set(key, list);
268
+ }
269
+
270
+ const report: ReviewReport = buildReport(ctx.projectRoot, ctx.config, {});
271
+
272
+ return {
273
+ calendarEntries,
274
+ distributions,
275
+ slugsBySite,
276
+ workflows,
277
+ approved,
278
+ terminal,
279
+ publishedBlogEntries,
280
+ shortformCoverage,
281
+ activeBySitedSlug,
282
+ report,
283
+ };
284
+ }
285
+
286
+ function entryBodyStateOf(
287
+ ctx: StudioContext,
288
+ site: string,
289
+ entry: CalendarEntry,
290
+ getIndex?: DashboardIndexGetter,
291
+ ): BodyState {
292
+ if (!hasRepoContent(effectiveContentType(entry))) return 'missing';
293
+ // When the entry has a stable id AND the route layer wired in a
294
+ // per-request index getter, use the id-driven content-index lookup
295
+ // — this matches files whose path doesn't follow the slug template
296
+ // (e.g., writingcontrol-shape projects where slug `the-outbound`
297
+ // resolves to `projects/the-outbound/index.md` while the calendar
298
+ // slug doesn't bake the path). Without an id or getter, fall back
299
+ // to the slug-template behavior so non-route callers still work.
300
+ if (entry.id !== undefined && entry.id !== '' && getIndex) {
301
+ const path = findEntryFile(
302
+ ctx.projectRoot,
303
+ ctx.config,
304
+ site,
305
+ entry.id,
306
+ getIndex(site),
307
+ { slug: entry.slug },
308
+ );
309
+ if (path !== undefined) return bodyState(path);
310
+ }
311
+ const fallback = resolveBlogFilePath(ctx.projectRoot, ctx.config, site, entry.slug);
312
+ return bodyState(fallback);
313
+ }
314
+
315
+ function findStageWorkflow(
316
+ data: DashboardData,
317
+ site: string,
318
+ entry: CalendarEntry,
319
+ stage: Stage,
320
+ ): DraftWorkflowItem | undefined {
321
+ const list =
322
+ data.activeBySitedSlug.get(covKey(site, entry.slug, entry.id)) ?? [];
323
+ if (stage === 'Outlining') return list.find((w) => w.contentKind === 'outline');
324
+ return list.find((w) => w.contentKind === 'longform');
325
+ }
326
+
327
+ // ---------------------------------------------------------------------------
328
+ // Section renderers
329
+ // ---------------------------------------------------------------------------
330
+
331
+ function renderHeader(
332
+ data: DashboardData,
333
+ ctx: StudioContext,
334
+ now: Date,
335
+ ): RawHtml {
336
+ const volume = '01';
337
+ const issueNum = String(data.workflows.length).padStart(2, '0');
338
+ const issueDate = `${now.getDate()} ${MONTH_NAMES[now.getMonth()]} ${now.getFullYear()}`;
339
+ return unsafe(html`
340
+ <header class="er-pagehead er-pagehead--centered">
341
+ <p class="er-pagehead__kicker">
342
+ Vol. ${volume} &middot; № ${issueNum} &middot; Press-check
343
+ </p>
344
+ <h1 class="er-pagehead__title">
345
+ Editorial <em>Studio</em>
346
+ </h1>
347
+ <p class="er-pagehead__deck">
348
+ Project: <code>${ctx.projectRoot}</code>
349
+ &nbsp;·&nbsp; <a class="er-link-marginalia" href="/dev/editorial-help">the manual</a>
350
+ </p>
351
+ <p class="er-pagehead__meta">
352
+ <span>${issueDate}</span>
353
+ <span class="sep">·</span>
354
+ <span>${data.calendarEntries.length} on the calendar</span>
355
+ <span class="sep">·</span>
356
+ <span>${data.activeBySitedSlug.size} in review</span>
357
+ <span class="sep">·</span>
358
+ <span>${data.approved.length} awaiting press</span>
359
+ </p>
360
+ </header>`);
361
+ }
362
+
363
+ function renderFilterStrip(sites: readonly string[]): RawHtml {
364
+ return unsafe(html`
365
+ <section class="er-filter" data-filter-strip>
366
+ <span class="er-filter-label">Find</span>
367
+ <input type="search" data-filter-input placeholder="slug, title…" autocomplete="off" />
368
+ <span class="er-filter-label er-filter-label--gap">Site</span>
369
+ <div class="er-chips" role="tablist">
370
+ <button class="er-chip" aria-pressed="true" data-site-chip="all">all</button>
371
+ ${sites.map(
372
+ (s) =>
373
+ unsafe(html`<button class="er-chip" data-site-chip="${s}">${siteLabel(s).toLowerCase()}</button>`),
374
+ )}
375
+ </div>
376
+ <span class="er-filter-label er-filter-label--gap">Stage</span>
377
+ <div class="er-chips" role="tablist">
378
+ <button class="er-chip" aria-pressed="true" data-stage-chip="all">all</button>
379
+ ${STAGES.map(
380
+ (s) =>
381
+ unsafe(html`<button class="er-chip" data-stage-chip="${s}">${s.toLowerCase()}</button>`),
382
+ )}
383
+ </div>
384
+ </section>`);
385
+ }
386
+
387
+ const STAGE_EMPTY_MESSAGES: Record<Stage, string> = {
388
+ Ideas: 'No open ideas. Run /editorial-add to capture one.',
389
+ Planned: 'Nothing planned. /editorial-plan <slug> to promote an idea.',
390
+ Outlining: 'Nothing in outlining. /editorial-outline <slug> to start one.',
391
+ Drafting: 'No posts in drafting.',
392
+ Review: 'Nothing in review stage.',
393
+ Paused: 'Nothing paused. /deskwork:pause <slug> sets an entry aside without losing where it was.',
394
+ Published: 'No published posts yet.',
395
+ };
396
+
397
+ function renderRowMeta(
398
+ ctx: StudioContext,
399
+ site: string,
400
+ entry: CalendarEntry,
401
+ stage: Stage,
402
+ hasFile: boolean,
403
+ getIndex?: DashboardIndexGetter,
404
+ ): RawHtml {
405
+ const kind = effectiveContentType(entry);
406
+ const parts: RawHtml[] = [];
407
+ if (entry.targetKeywords && entry.targetKeywords.length > 0 && stage === 'Planned') {
408
+ parts.push(
409
+ unsafe(html`<span class="er-calendar-meta"><em>kw:</em> ${entry.targetKeywords.join(', ')}</span>`),
410
+ );
411
+ }
412
+ if (entry.issueNumber && entry.issueNumber > 0) {
413
+ parts.push(unsafe(html`<span class="er-calendar-meta">issue #${entry.issueNumber}</span>`));
414
+ }
415
+ if (entry.datePublished && stage === 'Published') {
416
+ parts.push(unsafe(html`<span class="er-calendar-meta">${entry.datePublished}</span>`));
417
+ }
418
+ if (stage === 'Paused' && entry.pausedFrom) {
419
+ parts.push(
420
+ unsafe(html`<span class="er-calendar-meta"><em>was:</em> ${entry.pausedFrom}</span>`),
421
+ );
422
+ }
423
+ if (kind !== 'blog') {
424
+ parts.push(unsafe(html`<span class="er-calendar-meta er-calendar-meta-kind">${kind}</span>`));
425
+ }
426
+ if (kind === 'blog' && hasFile) {
427
+ // Phase 19c+: prefer the id-driven content-index lookup so entries
428
+ // whose on-disk path doesn't match the slug template (e.g.
429
+ // writingcontrol-shape projects) report the correct count. When the
430
+ // entry has no id binding OR no per-request index getter is wired,
431
+ // fall through to the slug-template path. The fallback is the
432
+ // legacy migration path, not a silent default — doctor reports the
433
+ // unbound cases so operators can backfill ids.
434
+ const n =
435
+ entry.id !== undefined && entry.id !== '' && getIndex
436
+ ? countScrapbookForEntry(
437
+ ctx.projectRoot,
438
+ ctx.config,
439
+ site,
440
+ entry,
441
+ getIndex(site),
442
+ )
443
+ : countScrapbook(ctx.projectRoot, ctx.config, site, entry.slug);
444
+ if (n > 0) {
445
+ const label = n === 1 ? 'scrapbook item' : 'scrapbook items';
446
+ parts.push(
447
+ unsafe(html`<a class="er-calendar-meta er-calendar-meta-scrapbook er-calendar-meta-link"
448
+ href="/dev/scrapbook/${site}/${entry.slug}"
449
+ title="${n} ${label}">scrapbook · <span class="er-calendar-meta-scrapbook-count">${n}</span> →</a>`),
450
+ );
451
+ }
452
+ }
453
+ return unsafe(parts.map((p) => p.__raw).join(''));
454
+ }
455
+
456
+ function renderRowActions(
457
+ site: string,
458
+ entry: CalendarEntry,
459
+ stage: Stage,
460
+ hasFile: boolean,
461
+ bodyWritten: boolean,
462
+ wf: DraftWorkflowItem | undefined,
463
+ ): RawHtml {
464
+ const kind = effectiveContentType(entry);
465
+ const buttons: string[] = [];
466
+ if (stage === 'Ideas') {
467
+ buttons.push(html`<button class="er-btn er-btn-small er-copy-btn" type="button"
468
+ data-copy="/editorial-plan --site ${site} ${entry.slug}" title="copy command">plan →</button>`);
469
+ }
470
+ if (stage === 'Planned' && !hasFile) {
471
+ buttons.push(html`<button class="er-btn er-btn-small er-btn-primary" type="button"
472
+ data-action="scaffold-draft" data-site="${site}" data-slug="${entry.slug}">scaffold →</button>`);
473
+ }
474
+ if (stage === 'Planned' && hasFile) {
475
+ buttons.push(html`<button class="er-btn er-btn-small er-btn-primary er-copy-btn" type="button"
476
+ data-copy="/editorial-outline --site ${site} ${entry.slug}"
477
+ title="scaffold file exists — copy to sketch the outline in Claude Code">outline →</button>`);
478
+ }
479
+ if (stage === 'Outlining' && wf && wf.state === 'iterating') {
480
+ buttons.push(html`<button class="er-btn er-btn-small er-btn-primary er-copy-btn" type="button"
481
+ data-copy="/editorial-iterate --kind outline --site ${site} ${entry.slug}"
482
+ title="operator clicked Iterate">iterate outline →</button>`);
483
+ }
484
+ if (stage === 'Outlining' && wf && wf.state === 'approved') {
485
+ buttons.push(html`<button class="er-btn er-btn-small er-btn-approve er-copy-btn" type="button"
486
+ data-copy="/editorial-outline-approve --site ${site} ${entry.slug}"
487
+ title="outline approved — advance to Drafting">approve outline →</button>`);
488
+ }
489
+ if (
490
+ stage === 'Outlining' &&
491
+ wf &&
492
+ (wf.state === 'open' || wf.state === 'in-review')
493
+ ) {
494
+ buttons.push(html`<a class="er-btn er-btn-small" href="${workflowLink(wf)}"
495
+ title="open the review surface to annotate / edit the outline">review outline →</a>`);
496
+ }
497
+ if (stage === 'Outlining' && !wf) {
498
+ buttons.push(html`<button class="er-btn er-btn-small er-btn-primary er-copy-btn" type="button"
499
+ data-copy="/editorial-outline --site ${site} ${entry.slug}"
500
+ title="no outline workflow found — copy to (re)start one">outline →</button>`);
501
+ }
502
+ if ((stage === 'Drafting' || stage === 'Review') && !bodyWritten) {
503
+ buttons.push(html`<button class="er-btn er-btn-small er-btn-primary er-copy-btn" type="button"
504
+ data-copy="/editorial-draft --site ${site} ${entry.slug}"
505
+ title="body is still the placeholder">draft body →</button>`);
506
+ }
507
+ if ((stage === 'Drafting' || stage === 'Review') && bodyWritten && !wf) {
508
+ buttons.push(html`<button class="er-btn er-btn-small er-btn-primary" type="button"
509
+ data-action="enqueue-review" data-site="${site}" data-slug="${entry.slug}"
510
+ title="body is drafted — create a longform review workflow">review →</button>`);
511
+ }
512
+ if (stage === 'Drafting' || stage === 'Review') {
513
+ buttons.push(html`<button class="er-btn er-btn-small er-btn-approve" type="button"
514
+ data-action="mark-published" data-site="${site}" data-slug="${entry.slug}"
515
+ title="flip to Published + set date">publish →</button>`);
516
+ }
517
+ if (stage === 'Published' && !wf) {
518
+ buttons.push(html`<button class="er-btn er-btn-small er-copy-btn" type="button"
519
+ data-copy="/editorial-draft-review --site ${site} ${entry.slug}"
520
+ title="re-review a published post">re-review</button>`);
521
+ }
522
+ // #27 — Paused gets a "resume" copy; pausable stages get a "pause" copy.
523
+ if (stage === 'Paused') {
524
+ buttons.push(html`<button class="er-btn er-btn-small er-btn-primary er-copy-btn" type="button"
525
+ data-copy="/deskwork:resume --site ${site} ${entry.slug}"
526
+ title="restore to ${entry.pausedFrom ?? 'prior stage'}">resume →</button>`);
527
+ } else if (
528
+ stage === 'Ideas' ||
529
+ stage === 'Planned' ||
530
+ stage === 'Outlining' ||
531
+ stage === 'Drafting' ||
532
+ stage === 'Review'
533
+ ) {
534
+ buttons.push(html`<button class="er-btn er-btn-small er-copy-btn" type="button"
535
+ data-copy="/deskwork:pause --site ${site} ${entry.slug}"
536
+ title="set aside without losing the prior stage">pause</button>`);
537
+ }
538
+ if (kind === 'blog') {
539
+ buttons.push(html`<button class="er-btn er-btn-small" type="button" data-action="rename-open"
540
+ title="rename the slug — copies /editorial-rename-slug to clipboard">rename →</button>`);
541
+ }
542
+ return unsafe(`<span class="er-calendar-action">${buttons.join('')}</span>`);
543
+ }
544
+
545
+ function renderRow(
546
+ ctx: StudioContext,
547
+ data: DashboardData,
548
+ sited: SitedEntry,
549
+ stage: Stage,
550
+ index: number,
551
+ getIndex?: DashboardIndexGetter,
552
+ ): RawHtml {
553
+ const { site, entry } = sited;
554
+ const kind = effectiveContentType(entry);
555
+ const body = entryBodyStateOf(ctx, site, entry, getIndex);
556
+ const hasFile = body !== 'missing';
557
+ const bodyWritten = body === 'written';
558
+ const wf = findStageWorkflow(data, site, entry, stage);
559
+ const search = [
560
+ entry.slug,
561
+ entry.title,
562
+ (entry.targetKeywords ?? []).join(' '),
563
+ kind,
564
+ site,
565
+ ].join(' ').toLowerCase();
566
+ const host = ctx.config.sites[site]?.host ?? site;
567
+ const slugCell = wf
568
+ ? unsafe(html`<a href="${workflowLink(wf)}" title="open the review surface">${entry.slug}</a>`)
569
+ : hasFile
570
+ ? unsafe(html`<a href="${blogPreviewLink(site, entry.slug, host, entry)}"
571
+ title="${entry.stage === 'Published' ? 'read the published article' : 'open the review surface for this draft'}">${entry.slug}</a>`)
572
+ : entry.slug;
573
+
574
+ const fileDot = hasRepoContent(kind)
575
+ ? unsafe(html`<span class="er-file-dot er-file-${body}"
576
+ title="${body === 'missing'
577
+ ? 'no blog file'
578
+ : body === 'placeholder'
579
+ ? 'scaffold present, body is the placeholder'
580
+ : 'body written'}">●</span>`)
581
+ : '';
582
+ const stamp = wf
583
+ ? unsafe(html`<span class="er-stamp er-stamp-${wf.state}">${stateLabel(wf.state)} v${wf.currentVersion}</span>`)
584
+ : '';
585
+
586
+ const renameForm =
587
+ kind === 'blog'
588
+ ? unsafe(html`<form class="er-rename-inline" data-rename-form
589
+ data-site="${site}" data-slug="${entry.slug}" hidden>
590
+ <span class="er-rename-kicker" aria-hidden="true">rename →</span>
591
+ <code class="er-rename-old" title="current slug; will 301 after rename">${entry.slug}</code>
592
+ <span class="er-rename-arrow" aria-hidden="true">→</span>
593
+ <input type="text" name="new-slug" data-rename-input autocomplete="off" spellcheck="false"
594
+ placeholder="new-slug-here" aria-label="new slug" required />
595
+ <small class="er-rename-hint" data-rename-hint>lowercase, digits, hyphens</small>
596
+ <button type="button" class="er-btn er-btn-small" data-action="rename-cancel">cancel</button>
597
+ <button type="submit" class="er-btn er-btn-small er-btn-primary"
598
+ data-action="rename-copy">copy /rename →</button>
599
+ </form>`)
600
+ : '';
601
+
602
+ // Hierarchical entries (slugs containing `/`) get a depth indicator the
603
+ // CSS layer indents off of. Storage stays flat; this is a display-only
604
+ // marker. Depth = number of `/` in the slug (so "the-outbound" → 0,
605
+ // "the-outbound/characters" → 1, etc.).
606
+ const depth = entry.slug.split('/').length - 1;
607
+ const depthAttrs =
608
+ depth > 0
609
+ ? unsafe(html` data-depth="${depth}" style="--er-row-depth: ${depth}"`)
610
+ : '';
611
+ // For nested entries, show only the leaf segment as the prominent
612
+ // identifier — the ancestor segments are implied by the visual indent
613
+ // and the position in the sorted list.
614
+ const slugDisplay =
615
+ depth > 0
616
+ ? unsafe(
617
+ html`<span class="er-row-slug-ancestors" aria-hidden="true">${entry.slug.slice(0, entry.slug.lastIndexOf('/') + 1)}</span><span class="er-row-slug-leaf">${entry.slug.slice(entry.slug.lastIndexOf('/') + 1)}</span>`,
618
+ )
619
+ : '';
620
+ const slugCellWithHierarchy = depth > 0 ? slugDisplay : slugCell;
621
+
622
+ return unsafe(html`
623
+ <div class="er-calendar-row-wrap" data-row-wrap data-search="${search}"${depthAttrs}>
624
+ <div class="er-calendar-row" data-stage="${stage}" data-site="${site}"
625
+ data-slug="${entry.slug}" data-search="${search}">
626
+ <span class="er-row-num">№ ${String(index + 1).padStart(2, '0')}</span>
627
+ <div class="er-calendar-body">
628
+ <span class="er-row-site er-row-site--${site}" title="${host}">${siteLabel(site)}</span>
629
+ <span class="er-row-slug">${depth > 0 ? slugCellWithHierarchy : slugCell}</span>
630
+ <span class="er-calendar-title">${entry.title}</span>
631
+ ${renderRowMeta(ctx, site, entry, stage, hasFile, getIndex)}
632
+ </div>
633
+ <span class="er-calendar-status">${fileDot}${stamp}</span>
634
+ ${renderRowActions(site, entry, stage, hasFile, bodyWritten, wf)}
635
+ </div>
636
+ ${renameForm}
637
+ </div>`);
638
+ }
639
+
640
+ function renderStageSection(
641
+ ctx: StudioContext,
642
+ data: DashboardData,
643
+ stage: Stage,
644
+ entries: SitedEntry[],
645
+ sites: readonly string[],
646
+ getIndex?: DashboardIndexGetter,
647
+ ): RawHtml {
648
+ const intakeBlock =
649
+ stage === 'Ideas'
650
+ ? unsafe(html`
651
+ <div class="er-intake-form" data-intake-form hidden>
652
+ <p class="er-intake-hint">
653
+ Fill in what you know; the agent will use the values verbatim.
654
+ </p>
655
+ <div class="er-intake-grid">
656
+ <label>
657
+ <span>Site</span>
658
+ <select data-intake-field="site">
659
+ ${sites.map((s) => unsafe(html`<option value="${s}">${s}</option>`))}
660
+ </select>
661
+ </label>
662
+ <label>
663
+ <span>Content type</span>
664
+ <select data-intake-field="contentType">
665
+ <option value="blog">blog (default)</option>
666
+ <option value="youtube">youtube</option>
667
+ <option value="tool">tool</option>
668
+ </select>
669
+ </label>
670
+ <label class="er-intake-wide">
671
+ <span>Title</span>
672
+ <input type="text" data-intake-field="title" placeholder="Working title" />
673
+ </label>
674
+ <label class="er-intake-wide">
675
+ <span>Description</span>
676
+ <textarea data-intake-field="description" rows="4"></textarea>
677
+ </label>
678
+ <label class="er-intake-wide" data-intake-content-url hidden>
679
+ <span>Content URL</span>
680
+ <input type="url" data-intake-field="contentUrl" placeholder="https://..." />
681
+ </label>
682
+ </div>
683
+ <div class="er-intake-actions">
684
+ <button class="er-btn er-btn-small" type="button" data-action="intake-cancel">cancel</button>
685
+ <button class="er-btn er-btn-small er-btn-primary" type="button"
686
+ data-action="intake-copy">copy intake →</button>
687
+ </div>
688
+ </div>`)
689
+ : '';
690
+
691
+ const intakeButton =
692
+ stage === 'Ideas'
693
+ ? unsafe(html`<button class="er-btn er-btn-small er-section-action" type="button"
694
+ data-action="intake-toggle"
695
+ title="fill out an intake sheet">intake new idea →</button>`)
696
+ : '';
697
+
698
+ const body =
699
+ entries.length === 0
700
+ ? unsafe(html`<div class="er-empty" style="padding: 1rem 0.25rem; font-size: 0.95rem;">
701
+ ${STAGE_EMPTY_MESSAGES[stage]}
702
+ </div>`)
703
+ : unsafe(
704
+ entries
705
+ .map((e, i) => renderRow(ctx, data, e, stage, i, getIndex).__raw)
706
+ .join(''),
707
+ );
708
+
709
+ return unsafe(html`
710
+ <section class="er-section" data-stage-section="${stage}">
711
+ <h2 class="er-section-head">
712
+ <span>${stage}</span>
713
+ <span class="ornament">${STAGE_ORNAMENTS[stage]}</span>
714
+ <span class="count">№ ${entries.length}</span>
715
+ ${intakeButton}
716
+ </h2>
717
+ ${intakeBlock}
718
+ ${body}
719
+ </section>`);
720
+ }
721
+
722
+ /**
723
+ * Shortform workflow lookup keyed by (site, entryId|slug, platform).
724
+ * Built once per dashboard render so the coverage matrix can render
725
+ * each covered cell as a direct link to the workflow's review surface
726
+ * — phase 21c replaces the prior "✓" sigil + copy-CLI-command flow.
727
+ */
728
+ function indexShortformWorkflows(
729
+ data: DashboardData,
730
+ ): Map<string, DraftWorkflowItem> {
731
+ const out = new Map<string, DraftWorkflowItem>();
732
+ for (const w of data.workflows) {
733
+ if (w.contentKind !== 'shortform') continue;
734
+ if (w.state === 'applied' || w.state === 'cancelled') continue;
735
+ if (!w.platform) continue;
736
+ const key = `${covKey(w.site, w.slug, w.entryId)}::${w.platform}`;
737
+ out.set(key, w);
738
+ }
739
+ return out;
740
+ }
741
+
742
+ function renderShortformMatrix(data: DashboardData, ctx: StudioContext): RawHtml {
743
+ if (data.publishedBlogEntries.length === 0) return unsafe('');
744
+ const wfIndex = indexShortformWorkflows(data);
745
+ const rows = data.publishedBlogEntries.map(({ site, entry }) => {
746
+ const covered =
747
+ data.shortformCoverage.get(covKey(site, entry.slug, entry.id)) ??
748
+ new Set<Platform>();
749
+ const cells = PLATFORMS_ORDER.map((p) => {
750
+ const has = covered.has(p);
751
+ const wfKey = `${covKey(site, entry.slug, entry.id)}::${p}`;
752
+ const wf = wfIndex.get(wfKey);
753
+ // A covered cell with a live workflow → link straight into the
754
+ // unified review surface. A covered cell without a workflow
755
+ // (distribution recorded outside the studio's pipeline — legacy
756
+ // data) keeps the static "✓" so the matrix doesn't lie about
757
+ // what's clickable. Empty cells render a real start button that
758
+ // POSTs to /api/dev/editorial-review/start-shortform and
759
+ // navigates to the new workflow's review URL.
760
+ let inner: string;
761
+ if (has && wf) {
762
+ inner = html`<a class="er-sf-link" href="/dev/editorial-review/${wf.id}"
763
+ title="${p} workflow · open in review">✓</a>`;
764
+ } else if (has) {
765
+ inner = html`<span class="er-sf-check" title="${p} copy drafted">✓</span>`;
766
+ } else {
767
+ inner = html`<button class="er-sf-start-btn" type="button"
768
+ data-action="start-shortform"
769
+ data-site="${site}"
770
+ data-slug="${entry.slug}"
771
+ data-platform="${p}"
772
+ title="Start a ${p} shortform draft for ${entry.slug}">start</button>`;
773
+ }
774
+ const cls = has ? 'er-sf-cell er-sf-cell-covered' : 'er-sf-cell er-sf-cell-empty';
775
+ return html`<td class="${cls}">${unsafe(inner)}</td>`;
776
+ }).join('');
777
+ const host = ctx.config.sites[site]?.host ?? site;
778
+ return html`
779
+ <tr data-site="${site}">
780
+ <th scope="row" class="er-sf-slug">
781
+ <span class="er-row-site er-row-site--${site}" title="${host}">${siteLabel(site)}</span>
782
+ ${entry.slug}
783
+ </th>
784
+ ${unsafe(cells)}
785
+ </tr>`;
786
+ }).join('');
787
+
788
+ return unsafe(html`
789
+ <section class="er-section">
790
+ <h2 class="er-section-head">
791
+ <span>Short form · coverage</span>
792
+ <span class="count">${data.publishedBlogEntries.length} × ${PLATFORMS_ORDER.length}</span>
793
+ </h2>
794
+ <table class="er-sf-matrix">
795
+ <thead>
796
+ <tr>
797
+ <th scope="col" class="er-sf-slug-col">slug</th>
798
+ ${PLATFORMS_ORDER.map(
799
+ (p) => unsafe(html`<th scope="col" class="er-sf-platform er-sf-platform-${p}">${p}</th>`),
800
+ )}
801
+ </tr>
802
+ </thead>
803
+ <tbody>${unsafe(rows)}</tbody>
804
+ </table>
805
+ </section>`);
806
+ }
807
+
808
+ function renderApprovedSection(data: DashboardData, ctx: StudioContext): RawHtml {
809
+ if (data.approved.length === 0) return unsafe('');
810
+ const rows = data.approved
811
+ .map((w) => {
812
+ const host = ctx.config.sites[w.site]?.host ?? w.site;
813
+ const platformBit =
814
+ w.contentKind === 'shortform' && w.platform
815
+ ? html`<span class="er-row-channel"> · ${w.platform}${w.channel ? ` · ${w.channel}` : ''}</span>`
816
+ : '';
817
+ const flagBit =
818
+ w.contentKind === 'shortform' && w.platform
819
+ ? ` --platform ${w.platform}${w.channel ? ` --channel ${w.channel}` : ''}`
820
+ : '';
821
+ return html`
822
+ <a class="er-row" href="${workflowLink(w)}" data-slug="${w.slug}"
823
+ data-site="${w.site}" data-state="${w.state}">
824
+ <span class="er-row-num">→</span>
825
+ <span class="er-row-site er-row-site--${w.site}" title="${host}">${siteLabel(w.site)}</span>
826
+ <span class="er-row-slug">${w.slug}</span>
827
+ <span class="er-row-kind">${w.contentKind}${unsafe(platformBit)}</span>
828
+ <span class="er-stamp er-stamp-approved">approved</span>
829
+ <span class="er-row-ts">v${w.currentVersion}</span>
830
+ <span class="er-row-hint">
831
+ Run · <code>/editorial-approve --site ${w.site} ${w.slug}${flagBit}</code>
832
+ </span>
833
+ </a>`;
834
+ })
835
+ .join('');
836
+ return unsafe(html`
837
+ <section class="er-section">
838
+ <h2 class="er-section-head">
839
+ <span>Awaiting press</span>
840
+ <span class="count">№ ${data.approved.length}</span>
841
+ </h2>
842
+ ${unsafe(rows)}
843
+ </section>`);
844
+ }
845
+
846
+ function renderTerminalSection(data: DashboardData, ctx: StudioContext, now: Date): RawHtml {
847
+ if (data.terminal.length === 0) return unsafe('');
848
+ const rows = data.terminal
849
+ .map((w) => {
850
+ const host = ctx.config.sites[w.site]?.host ?? w.site;
851
+ const platformBit =
852
+ w.contentKind === 'shortform' && w.platform
853
+ ? html`<span class="er-row-channel"> · ${w.platform}</span>`
854
+ : '';
855
+ return html`
856
+ <div class="er-row" data-state="${w.state}" data-site="${w.site}">
857
+ <span class="er-row-num">—</span>
858
+ <span class="er-row-site er-row-site--${w.site}" title="${host}">${siteLabel(w.site)}</span>
859
+ <span class="er-row-slug" style="color: var(--er-ink-soft);">${w.slug}</span>
860
+ <span class="er-row-kind">${w.contentKind}${unsafe(platformBit)}</span>
861
+ <span class="er-stamp er-stamp-${w.state}">${w.state}</span>
862
+ <span class="er-row-ts">${fmtRelTime(w.updatedAt, now)}</span>
863
+ </div>`;
864
+ })
865
+ .join('');
866
+ return unsafe(html`
867
+ <section class="er-section">
868
+ <h2 class="er-section-head">
869
+ <span>Recent proofs</span>
870
+ <span class="count">last ${data.terminal.length}</span>
871
+ </h2>
872
+ ${unsafe(rows)}
873
+ </section>`);
874
+ }
875
+
876
+ function renderSidebar(data: DashboardData): RawHtml {
877
+ const totalTerminal = data.report.all.approvedCount + data.report.all.cancelledCount;
878
+ const hasEnoughSignal = totalTerminal >= 5;
879
+ const topTwo = data.report.topCategories.filter((c) => c.count > 0).slice(0, 2);
880
+
881
+ const driftBody = hasEnoughSignal && topTwo.length > 0
882
+ ? unsafe(html`
883
+ <p class="er-drift-primary">
884
+ <em>${topTwo[0].category}</em>
885
+ <span class="count"> ${topTwo[0].count}</span>
886
+ </p>
887
+ ${
888
+ topTwo[1]
889
+ ? unsafe(html`<p class="er-drift-secondary" style="margin: 0;">
890
+ then <em style="color: var(--er-red-pencil);">${topTwo[1].category}</em> · ${topTwo[1].count}
891
+ </p>`)
892
+ : ''
893
+ }
894
+ <div style="margin-top: var(--er-space-2); font-family: var(--er-font-mono); font-size: 0.68rem; color: var(--er-faded);">
895
+ from ${data.report.all.approvedCount} approved · ${data.report.all.cancelledCount} cancelled<br />
896
+ <code style="margin-top: 0.25rem; display: inline-block;">/editorial-review-report --site &lt;site&gt;</code>
897
+ </div>`)
898
+ : unsafe(html`
899
+ <p style="font-family: var(--er-font-display); font-style: italic; color: var(--er-ink-soft); margin: 0;">
900
+ ${
901
+ totalTerminal === 0
902
+ ? 'No proofs yet. The signal builds with use.'
903
+ : `Only ${totalTerminal} terminal ${totalTerminal === 1 ? 'proof' : 'proofs'} so far — need ${5 - totalTerminal} more.`
904
+ }
905
+ </p>`);
906
+
907
+ return unsafe(html`
908
+ <aside>
909
+ <section class="er-drift">
910
+ <div class="er-drift-label">Voice-drift · signal</div>
911
+ ${driftBody}
912
+ </section>
913
+ <section class="er-slip" style="margin-top: var(--er-space-4);">
914
+ <div class="er-slip-header">Short form</div>
915
+ <h3 class="er-slip-title">Social copy</h3>
916
+ <p style="font-size: 0.85rem; margin: 0 0 var(--er-space-1); color: var(--er-ink-soft);">
917
+ Click <em>start</em> in the coverage matrix above to begin a
918
+ shortform draft. Edit, iterate, and approve in the unified
919
+ review surface.
920
+ </p>
921
+ <p style="margin-top: var(--er-space-2);">
922
+ <a href="/dev/editorial-review-shortform">Go to the shortform desk →</a>
923
+ </p>
924
+ </section>
925
+ </aside>`);
926
+ }
927
+
928
+ // ---------------------------------------------------------------------------
929
+ // Entry point
930
+ // ---------------------------------------------------------------------------
931
+
932
+ export function renderDashboard(
933
+ ctx: StudioContext,
934
+ getIndex?: DashboardIndexGetter,
935
+ ): string {
936
+ const sites = Object.keys(ctx.config.sites);
937
+ const data = loadDashboardData(ctx, getIndex);
938
+ const now = ctx.now ? ctx.now() : new Date();
939
+
940
+ const stageSections = STAGES.map((stage) => {
941
+ // Sort by (site, slug) so hierarchical entries cluster under their
942
+ // ancestor — `the-outbound` immediately precedes `the-outbound/characters`
943
+ // and `the-outbound/characters/strivers`. This is purely a display
944
+ // ordering; the underlying calendar storage stays a flat table.
945
+ const stageEntries = data.calendarEntries
946
+ .filter((e) => e.entry.stage === stage)
947
+ .sort((a, b) => {
948
+ const siteCmp = a.site.localeCompare(b.site);
949
+ if (siteCmp !== 0) return siteCmp;
950
+ return a.entry.slug.localeCompare(b.entry.slug);
951
+ });
952
+ return renderStageSection(ctx, data, stage, stageEntries, sites, getIndex).__raw;
953
+ }).join('\n');
954
+
955
+ const body = html`
956
+ ${renderEditorialFolio('dashboard', 'press-check')}
957
+ ${renderHeader(data, ctx, now)}
958
+ <main class="er-container">
959
+ ${renderFilterStrip(sites)}
960
+ <div class="er-layout">
961
+ <div>
962
+ ${unsafe(stageSections)}
963
+ ${renderShortformMatrix(data, ctx)}
964
+ ${renderApprovedSection(data, ctx)}
965
+ ${renderTerminalSection(data, ctx, now)}
966
+ </div>
967
+ ${renderSidebar(data)}
968
+ </div>
969
+ </main>
970
+ <div class="er-toast" data-toast hidden></div>
971
+ <div class="er-poll-indicator" data-poll>auto-refresh · 10s</div>`;
972
+
973
+ return layout({
974
+ title: 'Editorial Studio — dev',
975
+ cssHrefs: [
976
+ '/static/css/editorial-review.css',
977
+ '/static/css/editorial-nav.css',
978
+ '/static/css/editorial-studio.css',
979
+ ],
980
+ bodyAttrs: 'data-review-ui="studio"',
981
+ bodyHtml: body,
982
+ embeddedJson: [
983
+ {
984
+ id: '',
985
+ attr: 'data-rename-slugs',
986
+ data: data.slugsBySite,
987
+ },
988
+ ],
989
+ scriptModules: ['/static/dist/editorial-studio-client.js'],
990
+ });
991
+ }
992
+