@software-dlc/cli 0.178.0 → 0.181.0

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.
@@ -1,9 +1,11 @@
1
1
  import { execFile } from 'node:child_process';
2
+ import { existsSync } from 'node:fs';
2
3
  import { createRequire } from 'node:module';
3
4
  import path from 'node:path';
4
5
  import { engineLayout } from '../checkout.js';
5
6
  import { LIST_ID, LOCAL_TASK_OFFERS, localTaskMembers, localTaskPage, localTaskStatuses, localWaitingOnYou, taskBoardRead } from './app-tasks-read.js';
6
7
  import { localTaskRelated, localTaskSections, taskOnBoard } from './app-task-sections.js';
8
+ import { localBatch, localCandidate, localPlannedList, localPlannedRelease, localRelease, localReleaseDetail, localReleaseRelated } from './app-releases.js';
7
9
  const ENGINE_TIMEOUT_MS = 120_000;
8
10
  /** How long an answer serves later requests, by what it reads. */
9
11
  const KEEP_MS = { board: 15_000, issues: 10_000, issue: 10_000, releases: 30_000, task: 10_000 };
@@ -14,7 +16,8 @@ const LOCAL = 'local';
14
16
  const TRUE = new Set(['true', '1']);
15
17
  const ISSUE_STATUSES = new Set(['open', 'triaged', 'escalated', 'waiting_on_fix', 'resolved', 'closed']);
16
18
  const RESOLUTIONS = new Set(['fixed', 'works_as_intended', 'planned', 'duplicate', 'wont_fix', 'cannot_reproduce']);
17
- const BUMPS = new Set(['patch', 'minor', 'major']);
19
+ // The kept reads the Releases page's Read again and Try again drop (fresh=1).
20
+ const RELEASE_KEYS = /^(releases|planned-list|serving|release-related:|planned:)/;
18
21
  class Refusal extends Error {
19
22
  status;
20
23
  reason;
@@ -206,8 +209,306 @@ export function localIssue(row) {
206
209
  placement: text(row.placement)
207
210
  };
208
211
  }
212
+ const SEEN_ENVS = ['local', 'staging', 'production'];
213
+ const COLLECTION_ID = /^col-\d+$/;
214
+ /** core.js recentIssues: resolved ones older than this are left out, unless a collection counts them. */
215
+ const RESOLVED_KEPT_S = 7 * 86400;
216
+ const SEEN_SHOWN = 5;
217
+ /** The list's local filters, as the route's query gives them; unknown values are refused. */
218
+ export function issueQuery(query) {
219
+ const seen = query.getAll('seen');
220
+ for (const env of seen)
221
+ if (!SEEN_ENVS.includes(env))
222
+ throw new Refusal(400, 'Unknown seen.');
223
+ const collection = query.get('collection') || undefined;
224
+ if (collection !== undefined && !COLLECTION_ID.test(collection))
225
+ throw new Refusal(400, 'Unknown collection.');
226
+ return {
227
+ ...(query.get('search') ? { search: query.get('search') } : {}),
228
+ ...(query.get('owner') ? { owner: query.get('owner') } : {}),
229
+ ...(TRUE.has(query.get('urgent') ?? '') ? { urgent: true } : {}),
230
+ ...(seen.length ? { seen } : {}),
231
+ ...(query.getAll('label').length ? { labels: query.getAll('label') } : {}),
232
+ ...(collection ? { collection } : {})
233
+ };
234
+ }
235
+ /** What the list's issues read keeps of `issue list --all`, as core.js keepIssues does. */
236
+ export function recentIssues(rows, nowSec) {
237
+ return rows.filter((row) => row.status !== 'resolved' ||
238
+ nowSec - (Number(row.resolved_at) || 0) <= RESOLVED_KEPT_S ||
239
+ (Array.isArray(row.collections) && row.collections.length > 0));
240
+ }
241
+ const collectionRefs = (value) => list(value)
242
+ .map(record)
243
+ .filter((c) => text(c.collection))
244
+ .map((c) => ({ collection: String(c.collection), title: text(c.title) ?? String(c.collection), ref: text(c.ref) }));
245
+ const strings = (value) => list(value).filter((v) => typeof v === 'string' && v !== '');
246
+ /**
247
+ * An issue's board group without the backlog read, as model.js issueGroup words it with `listed`
248
+ * null: an escalated issue no handoff or release batch took counts as unowned.
249
+ */
250
+ export function issueGroupOf(row) {
251
+ if (row.status === 'resolved')
252
+ return 'resolved';
253
+ if (row.status === 'waiting_on_fix')
254
+ return 'fixing';
255
+ if (row.status !== 'escalated')
256
+ return 'unplaced';
257
+ const kind = text(record(row.route).kind);
258
+ return kind === 'handoff' || kind === 'batch' ? 'routed' : 'unowned';
259
+ }
260
+ /** One issue with the board's local-ahead fields: its group, status word, urgency, owner, labels and collections. */
261
+ function boardIssue(row, part, word, group) {
262
+ return {
263
+ ...localIssue(row),
264
+ group,
265
+ status_word: word,
266
+ // Urgent only while open: a board row read before the issue was resolved does not mark it.
267
+ urgent: row.status !== 'resolved' && group !== 'resolved' && (part ? part.urgentAny === true : row.urgent === true),
268
+ owner_title: text(part?.owner) ?? null,
269
+ labels: strings(row.labels),
270
+ collections: collectionRefs(row.collections)
271
+ };
272
+ }
273
+ /**
274
+ * The local Issues list (la-issues): the issues the VS Code Issues tab lists (model.js issueBoard
275
+ * over core.js keepIssues' read), in board order, narrowed by model.js issueMatches, with the
276
+ * groups the narrowing kept, the toolbar's counts over every listed issue and the collections.
277
+ * The owner narrows exactly, as the page's Owner select names it ('none': no owner), not by
278
+ * issueMatches' part of a title, so it keeps what the owner facet counts.
279
+ */
280
+ export function localIssueList({ issues, backlog, threads, filter, model, now }) {
281
+ const kept = recentIssues(issues, now);
282
+ const by_id = new Map(kept.map((row) => [String(row.issue), row]));
283
+ const listed = new Map(backlog.map((entry, at) => [String(entry.issue), { ...entry, at }]));
284
+ const board = model.issueBoard({ issues: kept, backlog, threads, now });
285
+ const rows = board.groups.flatMap((g) => g.rows.map((part) => ({ part, group: g.key })));
286
+ const status = filter.status ?? null;
287
+ const { owner, ...rest } = filter;
288
+ const ownerKeeps = (part) => owner === undefined || (owner === 'none' ? !text(part.owner) : part.owner === owner);
289
+ const matched = rows.filter(({ part }) => model.issueMatches(part, rest) && ownerKeeps(part) && (status === null || by_id.get(String(part.issue))?.status === status));
290
+ const count = (pick) => {
291
+ const counts = new Map();
292
+ for (const { part } of rows)
293
+ for (const key of pick(part))
294
+ counts.set(key, (counts.get(key) ?? 0) + 1);
295
+ return counts;
296
+ };
297
+ const owners = count((part) => (text(part.owner) ? [String(part.owner)] : []));
298
+ const labels = count((part) => strings(part.labels));
299
+ const seen = count((part) => (text(part.seen) ? [String(part.seen)] : []));
300
+ // A collection's Updated is its latest member change, each member dated as its row is.
301
+ const updatedAt = (issue) => {
302
+ const row = by_id.get(String(issue));
303
+ return row ? localIssue(row).updated_at : '';
304
+ };
305
+ return {
306
+ issues: matched.map(({ part, group }) => {
307
+ const row = by_id.get(String(part.issue)) ?? {};
308
+ return boardIssue(row, part, model.issueBadgeWord(row, listed).word, group);
309
+ }),
310
+ total: matched.length,
311
+ local: {
312
+ read_at: new Date(now * 1000).toISOString(),
313
+ scope: 'project',
314
+ folder: null,
315
+ groups: board.groups
316
+ .map((g) => ({ key: g.key, label: g.label, count: matched.filter((m) => m.group === g.key).length }))
317
+ .filter((g) => g.count > 0),
318
+ facets: {
319
+ owners: [...owners].map(([title, n]) => ({ key: title, title, count: n })).sort((a, b) => a.title.localeCompare(b.title)),
320
+ labels: [...labels].map(([label, n]) => ({ label, count: n })).sort((a, b) => b.count - a.count || a.label.localeCompare(b.label)),
321
+ urgent: rows.filter(({ part }) => part.urgentAny === true).length,
322
+ seen: Object.fromEntries(SEEN_ENVS.map((env) => [env, seen.get(env) ?? 0]))
323
+ },
324
+ listed: rows.length,
325
+ collections: list(board.collections)
326
+ .map(record)
327
+ .map((c) => {
328
+ const members = list(c.members).map(record);
329
+ const resolved = members.filter((m) => m.group === 'resolved');
330
+ return {
331
+ collection: String(c.collection),
332
+ title: text(c.title) ?? String(c.collection),
333
+ resolved: resolved.length,
334
+ total: members.length,
335
+ updated_at: members.map((m) => updatedAt(m.issue)).reduce((latest, at) => (at > latest ? at : latest), '')
336
+ };
337
+ })
338
+ }
339
+ };
340
+ }
341
+ // Where routing sent an issue, in the words model.js routeText uses.
342
+ function routeWords(route, nameOf) {
343
+ const kind = text(route.kind);
344
+ if (!kind)
345
+ return null;
346
+ if (kind === 'handoff')
347
+ return `Handoff to ${text(route.named) ?? nameOf(String(route.to ?? ''))}`;
348
+ if (kind === 'batch')
349
+ return `Release batch ${String(route.batch ?? '')}${text(route.finding) ? `, finding ${route.finding}` : ''}`;
350
+ return `Unowned task ${String(route.task ?? '')}${text(route.suggested) ? ` · suggested owner ${route.suggested}` : ''}`;
351
+ }
352
+ /** A thread key, execution or tool as the issue page names it (model.js issueNamer). */
353
+ export function issueNamer(threads) {
354
+ const titles = new Map(threads.map((t) => [t.key, t.title]));
355
+ return (key) => {
356
+ if (key === 'user')
357
+ return 'You';
358
+ const title = titles.get(key);
359
+ if (title)
360
+ return title;
361
+ const thread = /^(claude|codex):([0-9a-z]{8})/i.exec(key);
362
+ if (thread)
363
+ return `${thread[1]} ${thread[2]}`;
364
+ const exec = /^exec-([0-9a-z]{8})/i.exec(key);
365
+ return exec ? `execution ${exec[1]}` : key;
366
+ };
367
+ }
368
+ /**
369
+ * `issue show`'s issue as the local issue page's sections: placement, what happens, routing, its
370
+ * anchors, the latest sightings, its labels and collections (counted as the board counts them),
371
+ * and what it duplicates.
372
+ */
373
+ export function localIssueSections(shown, { nameOf, counted }) {
374
+ const where = record(shown.seen);
375
+ const route = record(shown.route);
376
+ const triage = record(shown.triage);
377
+ const placed = text(shown.placement);
378
+ const owner = text(shown.claimed_by_title) ?? (text(shown.claimed_by) ? nameOf(String(shown.claimed_by)) : null) ?? text(shown.owner);
379
+ const reporter = text(shown.reported_by) ?? text(shown.reporter);
380
+ return {
381
+ placement: {
382
+ placed,
383
+ unplaced_why: placed
384
+ ? null
385
+ : list(shown.anchors).length
386
+ ? 'triage has not placed it yet'
387
+ : 'nothing says where it shows yet: no file, node, test or commit points at it'
388
+ },
389
+ report: {
390
+ actual: text(shown.actual),
391
+ expected: text(shown.expected),
392
+ steps: strings(shown.steps),
393
+ where: text(where.env) || text(where.sha) ? { env: text(where.env), sha: text(where.sha) } : text(shown.seen) ? { env: text(shown.seen), sha: null } : null
394
+ },
395
+ routing: {
396
+ route: routeWords(route, nameOf),
397
+ owner,
398
+ none: !text(route.kind) && triage.owner === null && Object.keys(triage).length > 0
399
+ },
400
+ anchors: list(shown.anchors)
401
+ .map(record)
402
+ .map((a) => ({ kind: String(a.kind ?? ''), value: String(a.value ?? ''), by: text(a.by) ? nameOf(String(a.by)) : null })),
403
+ seen: list(shown.recent_occurrences)
404
+ .map(record)
405
+ .sort((a, b) => (Number(b.at) || 0) - (Number(a.at) || 0))
406
+ .slice(0, SEEN_SHOWN)
407
+ .map((o) => ({
408
+ at: iso(o.at) ?? '',
409
+ env: text(o.env),
410
+ sha: text(o.sha),
411
+ who: text(o.reporter) ? (o.reporter === 'user' ? 'You' : String(o.reporter)) : null,
412
+ note: text(o.note)
413
+ })),
414
+ labels: strings(shown.labels),
415
+ collections: collectionRefs(shown.collections).map((c) => ({ ...c, ...(counted.get(c.collection) ?? { resolved: 0, total: 0 }) })),
416
+ duplicate_of: text(shown.duplicate_of),
417
+ reporter: reporter ? nameOf(reporter) : null
418
+ };
419
+ }
420
+ // How a thread relates to an issue, in the issue page's words (release_links.py issue_related's via;
421
+ // frame 8c4e1f20-…6f14), each followed by the thread's phase when its execution records one.
422
+ const ISSUE_VIA = {
423
+ owns_fix: 'Owns its fix',
424
+ landed_fix: 'Landed its fix',
425
+ suggested: 'Suggested owner',
426
+ reported: 'Reported it',
427
+ routed: 'Routed to it',
428
+ waits_on: 'Waits on it'
429
+ };
430
+ const issueVia = (via) => strings(Array.isArray(via) ? via : typeof via === 'string' ? [via] : [])
431
+ .map((key) => ISSUE_VIA[key] ?? key.replace(/_/g, ' '))
432
+ .join(', ');
433
+ const words = (value) => text(value)?.replace(/_/g, ' ') ?? null;
434
+ const withPart = (words, part) => (part ? `${words} · ${part}` : words);
435
+ /** The Release relations an issue holds, in the order the issue page's Release pair picks one. */
436
+ const ISSUE_RELEASE_RELATIONS = { fixed: 'Fixed in', fixing: 'Being fixed in', planned: 'The release planned to fix it' };
437
+ /**
438
+ * release_links.py view --issue's answer as the Related table's rows: the threads, the fix tasks,
439
+ * the issue it duplicates and those duplicating it, the releases that fixed, are fixing or plan to
440
+ * fix it, and what found it and the checks that ran on its fix's landings. The view prints the
441
+ * threads' titles inside its issue (issue_threads), and `duplicate_of` names the issue the shown
442
+ * one duplicates (issue show's), since its issue rows carry no relation of their own.
443
+ */
444
+ export function localIssueRelated(view, duplicate_of = null) {
445
+ const issue = record(view.issue);
446
+ const related = record(issue.related);
447
+ const titles = record(issue.threads);
448
+ const older = record(view.threads);
449
+ const titleOf = (key) => text(record(titles[key]).title) ?? text(record(older[key]).title) ?? key;
450
+ const duplicates = duplicate_of ?? text(issue.duplicate_of);
451
+ const rows = [
452
+ ...list(related.threads)
453
+ .map(record)
454
+ .map((row) => ({
455
+ kind: 'thread',
456
+ id: String(row.thread ?? ''),
457
+ label: titleOf(String(row.thread ?? '')),
458
+ relation: withPart(issueVia(row.via), words(row.phase))
459
+ })),
460
+ ...list(related.tasks)
461
+ .map(record)
462
+ .map((row) => ({
463
+ kind: 'task',
464
+ id: String(row.id ?? ''),
465
+ label: text(row.objective) ?? String(row.id ?? ''),
466
+ relation: withPart(text(row.via) === 'landed_fix' ? 'Its landing fixed it' : 'Its fix task', words(row.state))
467
+ })),
468
+ ...list(related.issues)
469
+ .map(record)
470
+ .map((row) => {
471
+ const id = String(row.id ?? row.issue ?? '');
472
+ return {
473
+ kind: 'issue',
474
+ id,
475
+ label: text(row.title) ?? id,
476
+ relation: id === duplicates ? 'Duplicate of' : 'Its duplicate'
477
+ };
478
+ }),
479
+ ...list(related.releases)
480
+ .map(record)
481
+ .flatMap((row) => {
482
+ const relation = text(row.relation);
483
+ if (text(row.planned_release)) {
484
+ const id = String(row.planned_release);
485
+ return [{ kind: 'release', id, planned: true, label: text(row.name) ?? id, relation: ISSUE_RELEASE_RELATIONS.planned }];
486
+ }
487
+ const version = text(row.version) ?? text(row.release);
488
+ if (!version)
489
+ return [];
490
+ return [
491
+ {
492
+ kind: 'release',
493
+ id: version,
494
+ label: version === 'candidate' ? 'Release candidate' : version,
495
+ relation: relation === 'fixed' ? ISSUE_RELEASE_RELATIONS.fixed : relation === 'fixing' ? ISSUE_RELEASE_RELATIONS.fixing : 'Part of it'
496
+ }
497
+ ];
498
+ }),
499
+ ...list(related.tests)
500
+ .map(record)
501
+ .map((row) => ({
502
+ kind: 'test',
503
+ id: [row.sha, row.name].filter((part) => part !== undefined && part !== null).map(String).join(':'),
504
+ label: String(row.name ?? ''),
505
+ relation: `${text(row.result) === 'pass' ? 'Passed' : text(row.result) === 'fail' ? 'Failed' : (text(row.result) ?? 'Ran')} on its fix's landing${text(row.sha) ? ` ${String(row.sha).slice(0, 10)}` : ''}`
506
+ }))
507
+ ];
508
+ return rows.filter((row) => row.id);
509
+ }
209
510
  /** A local issue's history as the Maintain issue's events. */
210
- export function localIssueEvents(history) {
511
+ export function localIssueEvents(history, nameOf) {
211
512
  return history.map(record).map((entry, index) => {
212
513
  const [key, value] = Object.entries(entry).find(([k]) => k !== 'at' && k !== 'actor') ?? ['changed', null];
213
514
  const resolved = key === 'resolved';
@@ -224,73 +525,29 @@ export function localIssueEvents(history) {
224
525
  assignee_id: null,
225
526
  assignee_username: null,
226
527
  actor_id: null,
227
- actor_username: text(entry.actor),
528
+ actor_username: text(entry.actor) && nameOf ? nameOf(String(entry.actor)) : text(entry.actor),
228
529
  created_at: iso(entry.at) ?? '',
229
- note: `${key.replace(/_/g, ' ')}${typeof value === 'string' ? `: ${value}` : ''}`
530
+ note: `${key.replace(/_/g, ' ')}${eventDetails(value) ? `: ${eventDetails(value)}` : ''}`
230
531
  };
231
532
  });
232
533
  }
233
- // ---- Releases ----------------------------------------------------------------------------------
234
- /** A Release's or the candidate's bump reasons as its change lines. */
235
- function releaseChanges(entry) {
236
- return list(entry.reason_lines)
237
- .map(record)
238
- .map((line) => ({
239
- node_id: String(line.node ?? ''),
240
- node_type: String(line.type ?? ''),
241
- label: String(line.label ?? ''),
242
- change: String(line.change ?? ''),
243
- bump: null,
244
- why: text(line.why),
245
- modeling_only: false
246
- }));
247
- }
248
534
  /**
249
- * One of release_history.py's Releases in the hosted Release's shape. Its version is its label (the
250
- * app version, or its batch when it has no app section, so two Releases never share one); the
251
- * previous Release is the next older one listed, given by the caller.
535
+ * A history entry's details as words: a string as it is, a list of labels joined, a list of
536
+ * anchors by their values ('labelled: staging, releases', 'anchored: 1e815502').
252
537
  */
253
- export function localRelease(entry, previous) {
254
- const override = record(entry.override);
255
- const version = String(entry.version ?? entry.id);
256
- return {
257
- id: String(entry.id ?? version),
258
- version,
259
- computed_bump: text(entry.computed),
260
- bump: text(entry.bump),
261
- declared_reason: text(override.reason),
262
- declared_by_name: text(override.by),
263
- source_judged: entry.unjudged === 0,
264
- marks_approximate: entry.lower_bound === true,
265
- written_by_name: null,
266
- written_at: iso(entry.released_at) ?? '',
267
- previous_release_id: previous ? String(previous.id ?? previous.version) : null,
268
- breaking: entry.bump === 'major',
269
- commit: text(entry.commit),
270
- ...(typeof entry.landings === 'number' ? { landings: entry.landings } : {})
271
- };
272
- }
273
- /**
274
- * release_history.py's candidate as the hosted candidate. Its previous Release is the newest one
275
- * listed, given by the caller and named by its label as the list names it (the candidate's own
276
- * `previous` is that Release's app version, which a Release with no app section shares).
277
- */
278
- export function localCandidate(entry, newest) {
279
- const bump = String(entry.bump ?? '');
280
- const previous = newest ? localRelease(newest, undefined) : null;
281
- const version = text(entry.app_version) ?? text(entry.version) ?? text(entry.previous) ?? '';
282
- return {
283
- head_commit_id: String(entry.commit ?? ''),
284
- previous_release: previous ? { id: previous.id, version: previous.version } : null,
285
- next_version: version,
286
- version,
287
- commits_since: typeof entry.commits === 'number' ? entry.commits : null,
288
- classification: BUMPS.has(bump)
289
- ? { bump: bump, marks_approximate: entry.lower_bound === true }
290
- : null,
291
- changes: releaseChanges(entry)
292
- };
538
+ function eventDetails(value) {
539
+ if (typeof value === 'string')
540
+ return value;
541
+ if (!Array.isArray(value))
542
+ return '';
543
+ return value
544
+ .map((item) => (typeof item === 'string' ? item : text(record(item).value) ?? ''))
545
+ .filter(Boolean)
546
+ .join(', ');
293
547
  }
548
+ // ---- Releases ----------------------------------------------------------------------------------
549
+ // The mappings are app-releases.ts's; the readers that feed them run below.
550
+ export { localCandidate, localRelease } from './app-releases.js';
294
551
  // ---- The reader --------------------------------------------------------------------------------
295
552
  /** The read behind sdlc viewer's api/app/ routes. */
296
553
  export function appContractReader(input) {
@@ -339,10 +596,78 @@ export function appContractReader(input) {
339
596
  const done = input.done === true;
340
597
  const engine = async (file, args) => result(await run(script(file), ['--repo', input.repo, ...args]), file);
341
598
  const issues = () => keep('issues', KEEP_MS.issues, async () => list((await engine('issue', ['list', '--all'])).issues).map(record));
599
+ const backlogRead = () => keep('issue-backlog', KEEP_MS.issues, async () => list((await engine('issue', ['backlog'])).backlog).map(record));
600
+ // The Issues list reads both, as core.js readIssuesNow: either failing refuses the list.
601
+ const issueBoardInput = async () => {
602
+ const [all, backlog, threads] = await Promise.all([issues(), backlogRead(), namedThreads()]);
603
+ return { issues: all, backlog, threads };
604
+ };
605
+ // The board's thread titles name owners; without a board read, issueNamer's short keys do.
606
+ // The board is the whole threads snapshot (seconds to tens of seconds on a busy machine), and
607
+ // the issue reads need only its titles: once one board read has answered, they use the last
608
+ // titles at once and read the board again behind them, so only the first issue read waits.
609
+ let lastNames = null;
610
+ const readNames = async () => {
611
+ try {
612
+ const names = (await board()).threads?.flatMap((t) => (text(t.key) ? [{ key: String(t.key), title: text(t.title) ?? String(t.key) }] : [])) ?? [];
613
+ lastNames = names;
614
+ return names;
615
+ }
616
+ catch {
617
+ return lastNames ?? [];
618
+ }
619
+ };
620
+ const namedThreads = async () => {
621
+ if (lastNames === null)
622
+ return readNames();
623
+ void readNames();
624
+ return lastNames;
625
+ };
626
+ const issueModel = () => {
627
+ const loaded = model();
628
+ // View code from before the Issues board's rule cannot list issues as the other surfaces do.
629
+ if (typeof loaded.issueBoard !== 'function' || typeof loaded.issueMatches !== 'function' || typeof loaded.issueBadgeWord !== 'function')
630
+ throw new Refusal(409, 'This viewer reads no Issues board; restart sdlc viewer.', 'view_outdated');
631
+ return loaded;
632
+ };
342
633
  const history = () => keep('releases', KEEP_MS.releases, () => engine('release_history.py', []));
343
- const releases = async () => list((await history()).releases)
344
- .map(record)
345
- .filter((entry) => !('error' in entry));
634
+ // Every listed Release, a record that cannot be read among them; readable() leaves those out.
635
+ const releases = async () => list((await history()).releases).map(record);
636
+ const readable = async () => (await releases()).filter((entry) => !('error' in entry));
637
+ const plannedList = () => keep('planned-list', KEEP_MS.releases, async () => {
638
+ const printed = record(JSON.parse(await run(script('release_plan.py'), ['--repo', input.repo, 'list'])));
639
+ if (printed.ok !== true)
640
+ throw new Error(`release_plan.py: ${String(printed.error ?? 'it did not answer')}`);
641
+ return localPlannedList(printed.result);
642
+ });
643
+ // release_links.py: an unknown subject is a 404, view code without it is too old for the read.
644
+ const links = async (key, args) => {
645
+ if (!(input.exists ?? existsSync)(script('release_links.py')))
646
+ throw new Refusal(409, 'This viewer reads no release links; update the main checkout and restart sdlc viewer.', 'view_outdated');
647
+ return keep(key, KEEP_MS.releases, async () => {
648
+ // A failed run keeps its message, so a locked store still reads as busy (503 with retry).
649
+ const out = await run(script('release_links.py'), ['--repo', input.repo, ...args]);
650
+ let printed;
651
+ try {
652
+ printed = record(JSON.parse(out));
653
+ }
654
+ catch {
655
+ throw new Error('release_links.py printed no JSON');
656
+ }
657
+ if (typeof printed.unknown === 'string')
658
+ throw new Refusal(404, printed.unknown, 'not_found');
659
+ if (printed.ok !== true)
660
+ throw new Error(`release_links.py: ${String(printed.error ?? 'it did not answer')}`);
661
+ return record(printed.result);
662
+ });
663
+ };
664
+ const dropReleases = () => {
665
+ for (const key of [...kept.keys(), ...reading.keys()])
666
+ if (RELEASE_KEYS.test(key)) {
667
+ kept.delete(key);
668
+ reading.delete(key);
669
+ }
670
+ };
346
671
  const answer = async (segments, query) => {
347
672
  const [domain, ...rest] = segments;
348
673
  const route = rest.join('/');
@@ -395,15 +720,16 @@ export function appContractReader(input) {
395
720
  const status = query.get('status');
396
721
  if (status !== null && !ISSUE_STATUSES.has(status))
397
722
  throw new Refusal(400, 'Unknown status.');
723
+ const filter = { ...issueQuery(query), status };
724
+ const answer = localIssueList({ ...(await issueBoardInput()), filter, model: issueModel(), now: now() / 1000 });
725
+ // Paged only when asked: the local page lists every group uncapped.
726
+ if (!query.has('limit') && !query.has('offset'))
727
+ return answer;
398
728
  const limit = Math.min(Math.max(Number(query.get('limit') ?? 100) || 100, 1), 500);
399
729
  const offset = Math.max(Number(query.get('offset') ?? 0) || 0, 0);
400
- const rows = (await issues())
401
- .map(localIssue)
402
- .filter((issue) => status === null || issue.status === status)
403
- .sort((a, b) => b.created_at.localeCompare(a.created_at));
404
- return { issues: rows.slice(offset, offset + limit), total: rows.length };
730
+ return { ...answer, issues: answer.issues.slice(offset, offset + limit) };
405
731
  }
406
- if (rest.length === 1) {
732
+ if (rest.length === 1 || (rest.length === 2 && (rest[1] === 'sections' || rest[1] === 'related'))) {
407
733
  const id = rest[0];
408
734
  if (!ISSUE_ID.test(id))
409
735
  throw notFound();
@@ -417,16 +743,72 @@ export function appContractReader(input) {
417
743
  throw error;
418
744
  }
419
745
  });
420
- return { issue: localIssue(shown), events: localIssueEvents(list(shown.history)) };
746
+ if (rest[1] === 'related') {
747
+ const view = await keep(`issue-related:${id}`, KEEP_MS.issue, () => engine('release_links.py', ['view', '--issue', id, '--threads']));
748
+ return localIssueRelated(view, text(shown.duplicate_of));
749
+ }
750
+ const threads = await namedThreads();
751
+ const nameOf = issueNamer(threads);
752
+ if (rest[1] === 'sections') {
753
+ const input = await issueBoardInput();
754
+ const board = issueModel().issueBoard({ issues: recentIssues(input.issues, now() / 1000), backlog: input.backlog, threads, now: now() / 1000 });
755
+ const counted = new Map(list(board.collections)
756
+ .map(record)
757
+ .map((c) => {
758
+ const members = list(c.members).map(record);
759
+ return [String(c.collection), { resolved: members.filter((m) => m.group === 'resolved').length, total: members.length }];
760
+ }));
761
+ // A collection the board leaves out (resolved long ago) counts as `issue collection show` does.
762
+ for (const [key, summary] of Object.entries(record(board.counted))) {
763
+ const match = /^(\d+) of (\d+) resolved/.exec(String(summary));
764
+ if (match && !counted.has(key))
765
+ counted.set(key, { resolved: Number(match[1]), total: Number(match[2]) });
766
+ }
767
+ return localIssueSections(shown, { nameOf, counted });
768
+ }
769
+ const input = await issueBoardInput().catch(() => null);
770
+ const listed = input ? new Map(input.backlog.map((entry) => [String(entry.issue), entry])) : null;
771
+ const model = issueModel();
772
+ const board = input
773
+ ? model.issueBoard({ issues: recentIssues(input.issues, now() / 1000), backlog: input.backlog, threads, now: now() / 1000 })
774
+ : null;
775
+ const part = board?.groups.flatMap((g) => g.rows.map((row) => ({ row, group: g.key }))).find((r) => r.row.issue === id);
776
+ const word = model.issueBadgeWord(shown, listed);
777
+ // Off the board (no board read, or resolved before the board's 7 days): issueGroup's rule
778
+ // without the backlog.
779
+ const group = part?.group ?? issueGroupOf(shown);
780
+ return {
781
+ issue: boardIssue(shown, part?.row, word.word, group),
782
+ events: localIssueEvents(list(shown.history), nameOf)
783
+ };
421
784
  }
422
785
  }
423
786
  if (domain === 'releases') {
787
+ // Read again and Try again read past what is kept (fresh=1); the board read is the Tasks page's.
788
+ if (query.get('fresh') === '1')
789
+ dropReleases();
790
+ // In this order, so candidate, planned and related are never read as a label.
424
791
  if (!route) {
792
+ const all = await releases();
793
+ let planned;
794
+ let planned_error;
795
+ try {
796
+ planned = await plannedList();
797
+ }
798
+ catch (error) {
799
+ // A failed Planned Releases read never costs the list.
800
+ process.stderr.write(`sdlc viewer: releases planned failed: ${error instanceof Error ? error.message : String(error)}\n`);
801
+ planned_error = 'release_plan.py could not list them; see the sdlc viewer terminal.';
802
+ }
803
+ const listed = all.filter((entry) => !('error' in entry));
425
804
  return {
426
805
  release_branch: null,
427
- releases: (await releases()).map((entry, index, all) => localRelease(entry, all[index + 1])),
806
+ releases: all.map((entry) => localRelease(entry, listed[listed.indexOf(entry) + 1])),
428
807
  next_before: null,
429
- can_write: false
808
+ can_write: false,
809
+ local: { read_at: new Date(now()).toISOString() },
810
+ ...(planned ? { planned } : {}),
811
+ ...(planned_error ? { planned_error } : {})
430
812
  };
431
813
  }
432
814
  if (route === 'candidate') {
@@ -436,16 +818,44 @@ export function appContractReader(input) {
436
818
  const entry = record(candidate);
437
819
  if (typeof entry.error === 'string')
438
820
  throw new Error(`the candidate cannot be described: ${entry.error}`);
439
- return { candidate: localCandidate(entry, (await releases())[0]) };
821
+ return { candidate: localCandidate(entry, (await readable())[0]) };
822
+ }
823
+ if (route === 'candidate/batch') {
824
+ let raw;
825
+ try {
826
+ raw = (await board()).release_batch;
827
+ }
828
+ catch (error) {
829
+ // A failed board read never refuses the candidate: its batch reads unknown.
830
+ process.stderr.write(`sdlc viewer: releases batch failed: ${error instanceof Error ? error.message : String(error)}\n`);
831
+ }
832
+ return { batch: localBatch(raw) };
833
+ }
834
+ if (rest.length === 2 && rest[0] === 'planned') {
835
+ const id = rest[1];
836
+ const view = await links(`planned:${id}`, ['view', '--planned', id]);
837
+ const [open, serving, titles] = await Promise.all([
838
+ plannedList().catch(() => []),
839
+ links('serving', ['threads']).catch(() => null),
840
+ board()
841
+ .then((read) => new Map((read.threads ?? []).map((t) => [String(t.key), String(t.title ?? t.key)])))
842
+ .catch(() => new Map())
843
+ ]);
844
+ return localPlannedRelease(view, open, serving, titles);
845
+ }
846
+ if (rest.length === 2 && rest[1] === 'related') {
847
+ const label = rest[0];
848
+ const view = await links(`release-related:${label}`, ['view', '--release', label, '--threads']);
849
+ const names = new Map((await plannedList().catch(() => [])).map((p) => [p.id, p.name]));
850
+ return localReleaseRelated(view, names);
440
851
  }
441
852
  if (rest.length === 1) {
442
853
  const version = rest[0];
443
- const all = await releases();
854
+ const all = await readable();
444
855
  const index = all.findIndex((entry) => entry.id === version || entry.version === version);
445
856
  if (index < 0)
446
857
  throw notFound();
447
- const found = all[index];
448
- return { release: { ...localRelease(found, all[index + 1]), changes: releaseChanges(found) } };
858
+ return { release: localReleaseDetail(all[index], all[index + 1]) };
449
859
  }
450
860
  }
451
861
  throw notFound();