bareloop 0.54.1 → 0.55.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.
Files changed (130) hide show
  1. package/CHANGELOG.md +75 -0
  2. package/bareloop.context.md +65 -6
  3. package/package.json +3 -3
  4. package/src/authorflow.js +148 -46
  5. package/src/authoring.js +21 -4
  6. package/src/authorjob.js +82 -3
  7. package/src/authorreadout.js +20 -3
  8. package/src/authorrun.js +1 -1
  9. package/src/authorscout.js +9 -6
  10. package/src/cardschedule.js +42 -0
  11. package/src/checkpick.js +576 -0
  12. package/src/checksuggest.js +28 -0
  13. package/src/checkwords.js +25 -0
  14. package/src/cli.js +1 -1
  15. package/src/config.js +24 -1
  16. package/src/declaredclose.js +1 -1
  17. package/src/destpoint.js +149 -0
  18. package/src/draftspend.js +39 -0
  19. package/src/factwords.js +14 -1
  20. package/src/job.js +81 -1
  21. package/src/jobblock.js +9 -0
  22. package/src/labelscan.js +11 -0
  23. package/src/launcher.js +3 -2
  24. package/src/mcpchecks.js +52 -0
  25. package/src/mcppick.js +36 -0
  26. package/src/mcpsources.js +77 -0
  27. package/src/mcpuse.js +97 -0
  28. package/src/natural.js +23 -0
  29. package/src/pagemap.js +5 -2
  30. package/src/panel/authorroutes.js +90 -15
  31. package/src/panel/authorsession.js +183 -21
  32. package/src/panel/index.html +686 -26
  33. package/src/panel/jobgrid.js +117 -0
  34. package/src/panel/jobplan.js +31 -15
  35. package/src/panel/scheduler.js +80 -13
  36. package/src/panel/schedules.js +189 -28
  37. package/src/panel/schedulestart.js +44 -13
  38. package/src/panel/server.js +419 -32
  39. package/src/panel/settingsroutes.js +133 -3
  40. package/src/panel/status.js +19 -1
  41. package/src/panel/tickets.js +44 -0
  42. package/src/pickrecord.js +145 -0
  43. package/src/plan.js +31 -2
  44. package/src/planrun.js +71 -15
  45. package/src/prcheckout.js +259 -0
  46. package/src/readshim.js +3 -2
  47. package/src/revises.js +56 -0
  48. package/src/rubricstep.js +62 -16
  49. package/src/run.js +10 -1
  50. package/src/runexport.js +2 -0
  51. package/src/runlist.js +3 -2
  52. package/src/schedulewords.js +46 -4
  53. package/src/source.js +81 -7
  54. package/src/stepmcp.js +86 -0
  55. package/src/ticket.js +113 -0
  56. package/src/ticketfilter.js +76 -0
  57. package/src/ticketlabels.js +79 -0
  58. package/src/ticketmcp.js +111 -0
  59. package/src/ticketnext.js +35 -0
  60. package/src/ticketrepo.js +98 -0
  61. package/src/ticketschedule.js +32 -0
  62. package/src/ticketshape.js +45 -0
  63. package/src/tools.js +9 -0
  64. package/src/trigger.js +14 -2
  65. package/src/triggerclock.js +7 -3
  66. package/src/triggerfiles.js +19 -11
  67. package/src/triggertickets.js +244 -0
  68. package/src/userrun.js +145 -9
  69. package/src/validate.js +3 -1
  70. package/src/worktree.js +43 -1
  71. package/types/authorflow.d.ts +128 -28
  72. package/types/authorjob.d.ts +16 -3
  73. package/types/authorreadout.d.ts +9 -2
  74. package/types/authorscout.d.ts +4 -2
  75. package/types/cardschedule.d.ts +24 -0
  76. package/types/checkpick.d.ts +297 -0
  77. package/types/checksuggest.d.ts +30 -0
  78. package/types/checkwords.d.ts +14 -0
  79. package/types/config.d.ts +7 -0
  80. package/types/destpoint.d.ts +87 -0
  81. package/types/draftspend.d.ts +16 -0
  82. package/types/factwords.d.ts +7 -0
  83. package/types/job.d.ts +13 -0
  84. package/types/jobblock.d.ts +9 -0
  85. package/types/labelscan.d.ts +7 -0
  86. package/types/launcher.d.ts +2 -2
  87. package/types/mcpchecks.d.ts +8 -0
  88. package/types/mcppick.d.ts +33 -0
  89. package/types/mcpsources.d.ts +51 -0
  90. package/types/mcpuse.d.ts +15 -0
  91. package/types/natural.d.ts +2 -0
  92. package/types/pagemap.d.ts +2 -1
  93. package/types/panel/authorroutes.d.ts +11 -2
  94. package/types/panel/authorsession.d.ts +58 -3
  95. package/types/panel/jobgrid.d.ts +405 -0
  96. package/types/panel/jobplan.d.ts +10 -4
  97. package/types/panel/scheduler.d.ts +7 -2
  98. package/types/panel/schedules.d.ts +124 -4
  99. package/types/panel/schedulestart.d.ts +21 -3
  100. package/types/panel/server.d.ts +427 -6
  101. package/types/panel/settingsroutes.d.ts +4 -2
  102. package/types/panel/status.d.ts +16 -2
  103. package/types/panel/tickets.d.ts +61 -0
  104. package/types/pickrecord.d.ts +88 -0
  105. package/types/plan.d.ts +1 -0
  106. package/types/prcheckout.d.ts +151 -0
  107. package/types/readshim.d.ts +4 -3
  108. package/types/revises.d.ts +23 -0
  109. package/types/rubricstep.d.ts +14 -5
  110. package/types/run.d.ts +18 -1
  111. package/types/runlist.d.ts +6 -3
  112. package/types/schedulewords.d.ts +29 -2
  113. package/types/source.d.ts +40 -4
  114. package/types/stepmcp.d.ts +40 -0
  115. package/types/ticket.d.ts +114 -0
  116. package/types/ticketfilter.d.ts +34 -0
  117. package/types/ticketlabels.d.ts +44 -0
  118. package/types/ticketmcp.d.ts +84 -0
  119. package/types/ticketnext.d.ts +33 -0
  120. package/types/ticketrepo.d.ts +118 -0
  121. package/types/ticketschedule.d.ts +21 -0
  122. package/types/ticketshape.d.ts +37 -0
  123. package/types/tools.d.ts +1 -0
  124. package/types/trigger.d.ts +9 -1
  125. package/types/triggerclock.d.ts +6 -2
  126. package/types/triggerfiles.d.ts +13 -5
  127. package/types/triggertickets.d.ts +110 -0
  128. package/types/userrun.d.ts +50 -0
  129. package/types/validate.d.ts +1 -0
  130. package/types/worktree.d.ts +19 -0
@@ -29,6 +29,7 @@ import {
29
29
  readFileSync, existsSync, readdirSync, lstatSync, realpathSync,
30
30
  } from 'node:fs';
31
31
  import { createHash } from 'node:crypto';
32
+ import { execFileSync } from 'node:child_process';
32
33
  import {
33
34
  dirname, join, basename, relative, isAbsolute, sep,
34
35
  } from 'node:path';
@@ -43,19 +44,21 @@ import { readingOfQuestion, isAgree } from '../pagemap.js';
43
44
  import {
44
45
  replayOne, parseJsonl, resolveSiblings, isSidecarByName,
45
46
  } from '../replayio.js';
46
- import { summarizeForAllLine, auditWindowsOf } from '../replay.js';
47
+ import { summarizeForAllLine, auditWindowsOf, replayRun } from '../replay.js';
47
48
  import { legsOf, legsWallMs, stopFilePath, capKindOf } from '../legs.js';
48
49
  import { chainSpend } from '../ledger.js';
49
50
  import { runBehaviour } from '../behaviour.js';
50
51
  import { SPEND_RECORD_TYPES, floorsFromRecords } from '../ledger.js';
51
- import { jobSpecHash, workflowKey } from '../job.js';
52
+ import { jobSpecHash, workflowKey, flowTypeOf, FLOW_TYPE_LABELS } from '../job.js';
52
53
  import { attachMemos, learningsHanded, attachLearnings } from './handed.js';
53
54
  import { confirmProtections } from '../authorflow.js';
54
55
  import { createScheduleDoor } from './schedules.js';
56
+ import { buildJobGrid } from './jobgrid.js';
57
+ import { TICKET_LOOK_MS } from '../triggertickets.js';
55
58
  import { createStarter } from './schedulestart.js';
56
59
  import { createScheduler } from './scheduler.js';
57
60
  import {
58
- catchUpWords, dateTimeWords, jobScheduleWords, lowerFirst, scheduleSignFor, scheduledWords, sectionThisRunWords, skippedWords, startedAuditWords, startedWords, triesTailWords, SCHEDULE_WORDS,
61
+ catchUpWords, dateTimeWords, jobScheduleWords, lowerFirst, scheduleCardFill, scheduleSignFor, scheduledWords, sectionThisRunWords, skippedWords, startedAuditWords, startedWords, triesTailWords, SCHEDULE_WORDS,
59
62
  } from '../schedulewords.js';
60
63
  import { doorWaiting, heldScheduled } from '../reviewdoor.js';
61
64
  import { createAuthorRoutes, mintToken, checkHostGuard, panelMoney2 } from './authorroutes.js';
@@ -70,9 +73,11 @@ import { SHAPES } from '../providershapes.js';
70
73
  import { resolveProvider } from '../providers.js';
71
74
  import { readResume, checkpointAgeGate, CHECKPOINT_OUTCOMES } from '../reuse.js';
72
75
  import {
73
- statusFor, partStatusFor, GOAL_MET_LINE, doorViewOf, ACTOR_MARKER, DOOR_WORDS, isReusableGreen,
76
+ statusFor, partStatusFor, GOAL_MET_LINE, doorViewOf, ACTOR_MARKER, DOOR_WORDS, isReusableGreen, STATUS,
74
77
  } from './status.js';
75
78
  import { thinkingJobText } from '../thinking.js';
79
+ import { ticketFilterWords } from '../ticketfilter.js';
80
+ import { filterUnsure } from '../ticketlabels.js';
76
81
  import { judgedFilesOf, lineRules, stepFileRel, proseNotCheckedItems } from '../rubricstep.js';
77
82
  import { factPartOf, factSentence, ruleWords, moneyAs } from '../facts.js';
78
83
  import { createSettingsRoutes } from './settingsroutes.js';
@@ -126,10 +131,10 @@ export const DEFAULT_PORT = 4700;
126
131
  * running attempt and an archived spine that never reached its own end are
127
132
  * the same fact from this read-only side: no verdict has been recorded yet.
128
133
  * @param {string|null} outcome
129
- * @returns {'✓'|'✗'|'■'|'▶'}
134
+ * @returns {'✓'|'✗'|'■'|'▶'|'–'}
130
135
  */
131
136
  export function glyphForOutcome(outcome) {
132
- return /** @type {'✓'|'✗'|'■'|'▶'} */ (statusFor({ outcome }).sign);
137
+ return /** @type {'✓'|'✗'|'■'|'▶'|'–'} */ (statusFor({ outcome }).sign);
133
138
  }
134
139
 
135
140
  /**
@@ -815,14 +820,15 @@ function startingStub(row) {
815
820
  /**
816
821
  * A run that REFUSED before it started (its refetch of a web input was refused, run mvez8s54 shape): listed, settled at $0, no spine.
817
822
  * The status word is the table's `failed` (statusFor: "refusals, instrument stops -> failed"); the plain words ride on `endedLine`.
818
- * @param {{ runid: string, job: string, at: string, via: string }} row @param {string} words
823
+ * @param {{ runid: string, job: string, at: string, via: string }} row @param {string} words @param {'refused-before-start'|'skipped'} [outcome] @param {boolean} [reuseOffered] the Run tab's [Reuse workflow] shows (the run never ran its plan: {@link neverRanPlan}); `skipped` (R5): a ticket the job's filter did not let through, the same no-spine shape with its own status word
819
824
  * @returns {any}
820
825
  */
821
- function refusedStub(row, words) {
826
+ function refusedStub(row, words, outcome = 'refused-before-start', reuseOffered = false) {
827
+ const status = statusFor({ outcome });
822
828
  return {
823
- runid: row.runid, job: row.job, at: row.at, via: row.via, fileMissing: false, refused: true, live: false, needs: null, stoppedAt: null,
824
- died: false, glyph: statusFor({ outcome: 'refused-before-start' }).sign, status: statusFor({ outcome: 'refused-before-start' }),
825
- outcome: 'refused-before-start', endedLine: words, ended: null, resume: null, checkType: 'unknown', checkTypeTitle: null, model: null,
829
+ runid: row.runid, job: row.job, at: row.at, via: row.via, fileMissing: false, refused: outcome !== 'skipped', skipped: outcome === 'skipped', live: false, needs: null, stoppedAt: null,
830
+ died: false, glyph: status.sign, status,
831
+ outcome, endedLine: words, ended: null, reuseOffered, resume: null, checkType: 'unknown', checkTypeTitle: null, model: null,
826
832
  spend: '$0', wall: '', date: typeof row.at === 'string' ? row.at.slice(0, 10) : null, spentUsd: 0, spendComplete: true,
827
833
  spendFloorUsd: null, wallFloorMs: null, draftSpentUsd: null, draftSpendComplete: null, budgetUsd: null, steps: [], parts: [],
828
834
  };
@@ -834,6 +840,27 @@ function refusalWordsOf(events, row) {
834
840
  return e && typeof e.words === 'string' && e.words !== '' ? e.words : null;
835
841
  }
836
842
 
843
+ /**
844
+ * R5 (piece 2): the plain words of a run a Tickets job's filter SKIPPED at run start (leg 1), or null. Same home as a refusal: one `settled` event on the run's row, no spine.
845
+ * @param {any[]} events @param {{runid: string}} row
846
+ */
847
+ function skipWordsOf(events, row) {
848
+ const e = events.find((x) => x && x.type === 'settled' && x.runid === row.runid && x.reason === 'skipped' && !(x.leg > 1));
849
+ return e && typeof e.words === 'string' && e.words !== '' ? e.words : null;
850
+ }
851
+
852
+ /**
853
+ * R9 (9b.2, fwd 7a98141): did this run END BEFORE ITS FIRST STEP, at $0? The rule, from recorded facts only: the run has NO spine on disk, and its row carries a leg-1 `settled` event
854
+ * that is `refused before start` or `skipped` with `spentUsd` exactly 0 and `spendComplete` not false. Such a run never ran its plan (no step, no model call), so Reuse workflow with
855
+ * the job unchanged signs and goes with the signed job; a red run that DID run (it has a spine) still drafts.
856
+ * @param {any[]} events @param {{runid: string, spine: string}} row
857
+ */
858
+ export function neverRanPlan(events, row) {
859
+ if (existsSync(row.spine)) return false;
860
+ return events.some((x) => x && x.type === 'settled' && x.runid === row.runid && !(x.leg > 1)
861
+ && (x.reason === 'refused before start' || x.reason === 'skipped') && x.spentUsd === 0 && x.spendComplete !== false);
862
+ }
863
+
837
864
  /**
838
865
  * RULED 2026-10-15 (Remove from Needs you): the ONE place a run's Needs-you state is decided. `Accept` (a live door) is never removable and never ages out.
839
866
  * A `Resume` tag leaves when the person removed it AFTER (or at) the stop it is for — a removal covers only the ending it was made on, so a later stop
@@ -865,7 +892,9 @@ export function needsStateFor(f) {
865
892
  function summarizeRow(row, nowMs = Date.now(), removals = undefined, events = []) {
866
893
  if (!existsSync(row.spine)) {
867
894
  const refusal = refusalWordsOf(events, row);
868
- if (refusal !== null) return refusedStub(row, refusal);
895
+ if (refusal !== null) return refusedStub(row, refusal, 'refused-before-start', neverRanPlan(events, row));
896
+ const skipped = skipWordsOf(events, row);
897
+ if (skipped !== null) return refusedStub(row, skipped, 'skipped', neverRanPlan(events, row));
869
898
  if (runIsAlive(row)) return startingStub(row);
870
899
  return {
871
900
  runid: row.runid, job: row.job, at: row.at, via: row.via, fileMissing: true, live: false, needs: null, stoppedAt: null,
@@ -1386,11 +1415,310 @@ function cellText(v) {
1386
1415
  return '';
1387
1416
  }
1388
1417
 
1418
+ /**
1419
+ * Which Result tab a run wears: `'rubric'` (a soft-green run whose signed close has a rubric-step stage: the page-reading tab, unchanged), `'generic'`
1420
+ * (any other run that ENDED, green or failed: R7b item 4), or `null` (not ended yet, or died with no `job-end`). ONE owner for the tab's gate
1421
+ * ({@link getRunDetailBody}'s `hasResult`) and the route.
1422
+ * @param {{ at?: string }} row @param {any[]} records @param {any} spec
1423
+ * @returns {'rubric'|'generic'|null}
1424
+ */
1425
+ function resultKindOf(row, records, spec) {
1426
+ const start = records.findLast((r) => r && r.type === 'job-start');
1427
+ if (checkTypeLabel(typeof start?.verdictType === 'string' ? start.verdictType : null, row.at ?? null) === 'rubric' && rubricStagesOf(spec).length > 0) return 'rubric';
1428
+ return records.some((r) => r && r.type === 'job-end') ? 'generic' : null;
1429
+ }
1430
+
1431
+ /** the words of the work box and the diff box, code-owned (one spelling) */
1432
+ const RESULT_WORK_NOTE = 'shown as text; the merge is yours, no button runs it.';
1433
+
1434
+ /**
1435
+ * the allowed folder of a write fence entry in plain words: `src/**` is `src/`; an entry this cannot read as a folder or file is `null`
1436
+ * @param {string} entry
1437
+ */
1438
+ function scopePrefixOf(entry) {
1439
+ const m = /^(.*?)(?:\/\*\*?)?$/.exec(entry);
1440
+ const base = m ? m[1] : entry;
1441
+ return base !== '' && !/[*?[\]{}]/.test(base) ? base : null;
1442
+ }
1443
+
1444
+ /**
1445
+ * The generic Result tab's "What changed" box, from the spine's own `attempt-diff` records (they survive a deleted branch): the LAST edit's diff, every
1446
+ * edit behind a fold, and the header numbers counted over every diff the records hold. `null` when the run recorded no edit at all.
1447
+ * @param {any[]} records @param {string[]|null} writeScope
1448
+ */
1449
+ function changedOf(records, writeScope) {
1450
+ const diffs = records.filter((r) => r && r.type === 'attempt-diff' && Array.isArray(r.files));
1451
+ if (diffs.length === 0) return null;
1452
+ const edits = diffs.map((r, i) => ({
1453
+ n: i + 1,
1454
+ step: typeof r.step === 'string' ? r.step : null,
1455
+ files: r.files.filter((/** @type {any} */ f) => f && typeof f.path === 'string').map((/** @type {any} */ f) => ({
1456
+ path: f.path, diff: typeof f.diff === 'string' ? f.diff : '',
1457
+ cut: f.truncated === true ? (Number.isInteger(f.cutLines) ? f.cutLines : 0) : null,
1458
+ })),
1459
+ binary: Array.isArray(r.binary) ? r.binary.filter((/** @type {any} */ b) => typeof b === 'string') : [],
1460
+ }));
1461
+ const paths = [...new Set(edits.flatMap((e) => [...e.files.map((f) => f.path), ...e.binary]))];
1462
+ let plus = 0; let minus = 0; let anyCut = false;
1463
+ for (const e of edits) {
1464
+ for (const f of e.files) {
1465
+ if (f.cut !== null) anyCut = true;
1466
+ for (const line of f.diff.split('\n')) {
1467
+ if (line.startsWith('+') && !line.startsWith('+++')) plus += 1;
1468
+ else if (line.startsWith('-') && !line.startsWith('---')) minus += 1;
1469
+ }
1470
+ }
1471
+ }
1472
+ const shown = paths.length > 4 ? `${paths.slice(0, 4).join(', ')} and ${paths.length - 4} more` : paths.join(', ');
1473
+ const head = `${paths.length} file${paths.length === 1 ? '' : 's'} · ${shown} · +${plus} −${minus} lines over ${edits.length} edit${edits.length === 1 ? '' : 's'}`;
1474
+ const last = edits[edits.length - 1];
1475
+ const cutLines = last.files.reduce((a, f) => a + (f.cut ?? 0), 0);
1476
+ const note = [
1477
+ edits.length > 1 ? 'the last edit only' : null,
1478
+ last.files.some((f) => f.cut !== null) ? `${cutLines} more line${cutLines === 1 ? '' : 's'} cut` : null,
1479
+ ].filter(Boolean).join('; ');
1480
+ // the fence line: every path the run wrote inside what was allowed, or what lay outside
1481
+ let scopeLine = null;
1482
+ const prefixes = writeScope ? writeScope.map(scopePrefixOf) : [];
1483
+ if (writeScope && writeScope.length > 0 && prefixes.every((x) => x !== null)) {
1484
+ const inside = (/** @type {string} */ p) => prefixes.some((x) => p === x || p.startsWith(`${x}/`));
1485
+ const outside = paths.filter((p) => !inside(p));
1486
+ const allowed = prefixes.map((x) => (writeScope.includes(`${x}/**`) || writeScope.includes(`${x}/*`) ? `${x}/` : x)).join(', ');
1487
+ scopeLine = outside.length === 0
1488
+ ? `only ${allowed} was allowed; the run wrote ${paths.length} file${paths.length === 1 ? '' : 's'}, no other.`
1489
+ : `only ${allowed} was allowed, but the run wrote ${outside.join(', ')}.`;
1490
+ }
1491
+ return {
1492
+ head, files: paths.length, paths, plus, minus, edits: edits.length, anyCut,
1493
+ last: { files: last.files.map((f) => ({ path: f.path, diff: f.diff })), note: note === '' ? null : `...(${note})` },
1494
+ all: edits.map((e) => ({ n: e.n, step: e.step, files: e.files.map((f) => ({ path: f.path, diff: f.diff, cutNote: f.cut === null ? null : `...(${f.cut} more line${f.cut === 1 ? '' : 's'} cut)` })) })),
1495
+ foldWords: `show every edit of the run (${edits.length})`,
1496
+ scopeLine,
1497
+ };
1498
+ }
1499
+
1500
+ /**
1501
+ * The checks a run's STEPS ran in the loop, for a run the outer close never reached (a strike-ladder cap-halt, a stop): read through the Audit tab's own data owner
1502
+ * (`replayRun` parts, worded by {@link enrichPartsWithStageKind} / {@link tryChecksOf}), never a second reader of `check-run` / `exit-eval` records. Each check's standing is its LAST graded
1503
+ * try; a name a later step ran again takes that later standing. The in-loop record carries no structured number, so `value`/`baseline` are null (no figure is parsed out of the gap prose);
1504
+ * `tries` is how many times the step that ran it tried. `null` when no step ran any check.
1505
+ * @param {any[]} records @param {any} spec
1506
+ */
1507
+ function stepChecksOf(records, spec) {
1508
+ /** @type {any[]|null|undefined} */
1509
+ let parts;
1510
+ try { parts = enrichPartsWithStageKind(replayRun(records).parts, stageKindMetaFromSpec(spec), spec); } catch { return null; }
1511
+ /** @type {Map<string, any>} */
1512
+ const byName = new Map();
1513
+ for (const p of parts ?? []) {
1514
+ if (!p || p.kind !== 'step' || !Array.isArray(p.attempts)) continue;
1515
+ const graded = p.attempts.filter((/** @type {any} */ a) => Array.isArray(a.checks) && a.checks.length > 0);
1516
+ const last = graded.at(-1);
1517
+ if (!last) continue;
1518
+ for (const c of last.checks) {
1519
+ byName.set(c.name, {
1520
+ name: c.name, question: typeof c.question === 'string' && c.question ? c.question : null, passed: c.pass === true,
1521
+ status: c.pass === true ? STATUS.passed : STATUS.failed, value: null, baseline: null, direction: null, baselineKind: null,
1522
+ notes: null, tries: p.attempts.length,
1523
+ });
1524
+ }
1525
+ }
1526
+ const stages = [...byName.values()];
1527
+ if (stages.length === 0) return null;
1528
+ const ok = stages.filter((s) => s.passed).length;
1529
+ return {
1530
+ head: `${ok} of ${stages.length} passed · the steps ran them; the close never ran`,
1531
+ passed: ok, total: stages.length, allPassed: ok === stages.length, stages, notes: [],
1532
+ };
1533
+ }
1534
+
1535
+ /**
1536
+ * The generic Result tab's "The checks" box, from the run's LAST `outer-close` record: each stage's plain question ({@link stageQuestionText}'s one
1537
+ * owner, through the spec's own declaration), its pass/fail word from the status table, and the number the close read. A run the close never reached
1538
+ * falls back to the checks its steps ran ({@link stepChecksOf}); `null` when neither exists.
1539
+ * @param {any[]} records @param {any} spec
1540
+ */
1541
+ function checksOf(records, spec) {
1542
+ const oc = records.findLast((r) => r && r.type === 'outer-close' && Array.isArray(r.stages));
1543
+ if (!oc) return stepChecksOf(records, spec);
1544
+ const kindMeta = stageKindMetaFromSpec(spec);
1545
+ const stages = oc.stages.filter((/** @type {any} */ s) => s && typeof s.name === 'string').map((/** @type {any} */ raw) => {
1546
+ const s = attachStageKind(raw, kindMeta);
1547
+ const passed = s.verdict === 'satisfied';
1548
+ return {
1549
+ name: s.name, question: typeof s.question === 'string' && s.question ? s.question : null, passed,
1550
+ status: passed ? STATUS.passed : STATUS.failed,
1551
+ value: typeof s.value === 'number' ? s.value : null, baseline: typeof s.baseline === 'number' ? s.baseline : null,
1552
+ direction: s.direction ?? null, baselineKind: s.baselineKind ?? null,
1553
+ notes: typeof s.notes === 'string' && s.notes !== '' ? s.notes : null,
1554
+ };
1555
+ });
1556
+ const ok = stages.filter((/** @type {any} */ s) => s.passed).length;
1557
+ return {
1558
+ head: `${ok} of ${stages.length} passed · the close ran them after the worker stopped`,
1559
+ passed: ok, total: stages.length, allPassed: ok === stages.length, stages,
1560
+ notes: stages.filter((/** @type {any} */ s) => s.notes).map((/** @type {any} */ s) => ({ name: s.name, text: s.notes })),
1561
+ };
1562
+ }
1563
+
1564
+ /**
1565
+ * The generic Result tab's "The work" box: the run's work branch, but ONLY while that branch still exists in the person's repo (asked of git itself).
1566
+ * The merge and delete lines are TEXT; nothing runs them. `null` when the run has no work branch, no repo is known, or the branch is gone.
1567
+ * @param {{ spine: string }} row @param {any[]} records
1568
+ */
1569
+ function workOf(row, records) {
1570
+ const wb = records.findLast((r) => r && r.type === 'work-branch' && typeof r.branch === 'string') ?? null;
1571
+ const wt = worktreeOfRun(row, records);
1572
+ if (!wb || !wt || !wt.branch) return null;
1573
+ /** @type {string} */
1574
+ let final;
1575
+ try {
1576
+ final = execFileSync('git', ['-C', wt.repo, 'rev-parse', '--verify', '--quiet', `refs/heads/${wt.branch}`], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 5000 }).trim();
1577
+ } catch { return null; }
1578
+ if (final === '') return null;
1579
+ return {
1580
+ branch: wt.branch, finalCommit: final.slice(0, 7), madeFrom: typeof wb.base === 'string' ? wb.base.slice(0, 7) : null, repo: wt.repo,
1581
+ merge: `git merge ${wt.branch}`, drop: `git branch -D ${wt.branch}`, note: RESULT_WORK_NOTE,
1582
+ };
1583
+ }
1584
+
1585
+ /**
1586
+ * The ticket a run read, from its `job-start` record (`{number, title, url}`), or null. ONE reader: the generic Result tab's ticket box and the ticket grid's row both ask here.
1587
+ * @param {any} start the run's `job-start` record @returns {{number: number, title: string|null, url: string|null}|null}
1588
+ */
1589
+ function ticketOfStart(start) {
1590
+ const t = start && start.ticket && typeof start.ticket === 'object' ? start.ticket : null;
1591
+ if (!t || !Number.isInteger(t.number)) return null;
1592
+ return { number: t.number, title: typeof t.title === 'string' ? t.title : null, url: typeof t.url === 'string' && /^https?:\/\//i.test(t.url) ? t.url : null };
1593
+ }
1594
+
1595
+ /**
1596
+ * The generic Result tab (R7b item 4; hamr signed the mockup 2026-11-07) for a run that ENDED and is not a rubric job: five boxes of facts read
1597
+ * from the run's own records, plus the ticket a ticket job read. The page draws it; it decides nothing.
1598
+ * @param {string} runid @param {any} row @param {any[]} records @param {any} spec @param {any} opts
1599
+ */
1600
+ function genericResultOf(runid, row, records, spec, opts) {
1601
+ const start = records.findLast((r) => r && r.type === 'job-start') ?? null;
1602
+ const writeScope = Array.isArray(spec?.writeScope) && spec.writeScope.every((/** @type {any} */ x) => typeof x === 'string') ? spec.writeScope : null;
1603
+ const t0 = ticketOfStart(start);
1604
+ const ticket = t0 ? { number: t0.number, title: t0.title ?? '', url: t0.url } : null;
1605
+ const detail = getRunDetailBody(runid, opts);
1606
+ const plan = records.findLast((r) => r && r.type === 'plan-executed' && Array.isArray(r.steps)) ?? null;
1607
+ const spentUsd = detail && typeof detail.spentUsd === 'number' ? detail.spentUsd : null;
1608
+ const complete = detail ? detail.spendComplete !== false : true;
1609
+ const ids = plan ? plan.steps.map((/** @type {any} */ x) => String(x?.id)) : [];
1610
+ const replans = plan && Number.isInteger(plan.replans) ? plan.replans : 0;
1611
+ return {
1612
+ runid,
1613
+ kind: 'generic',
1614
+ job: { asked: jobTextFromSpec(spec) || (typeof start?.goal === 'string' ? start.goal : ''), scope: writeScope },
1615
+ ticket,
1616
+ changed: changedOf(records, writeScope),
1617
+ checks: checksOf(records, spec),
1618
+ work: workOf(row, records),
1619
+ run: {
1620
+ spent: spentUsd === null ? 'unknown' : `${complete ? '' : 'at least '}${panelMoney2(spentUsd)}`,
1621
+ spentNote: spentUsd !== null && !complete ? 'a floor: some rounds were unpriced' : null,
1622
+ time: detail && typeof detail.wallMs === 'number' ? formatDurationMs(detail.wallMs) : 'unknown',
1623
+ steps: plan ? `${ids.length} step${ids.length === 1 ? '' : 's'}${ids.length ? ` (${ids.join(', ')})` : ''}, ${replans === 0 ? 'no replan' : `${replans} replan${replans === 1 ? '' : 's'}`}` : null,
1624
+ },
1625
+ // R8: why the run ended, in the Run tab's own words (`detail.ended.reason`): the ticket grid's opened row says it for a run that did not pass
1626
+ endedWords: typeof detail?.ended?.reason === 'string' && detail.ended.reason !== '' ? detail.ended.reason : null,
1627
+ door: { head: DOOR_WORDS.waiting.head, ask: RESULT_DOOR_ASK },
1628
+ };
1629
+ }
1630
+
1631
+ /**
1632
+ * R8 (piece 10): the ticket grid of the job a run belongs to, or `null` when that job is not a Tickets job (no run of it read a ticket) or the run is unknown. ONE row per run of the job, from
1633
+ * the run list's own entry (`summarizeRow`: status, needs, money, wall, ending words), the ticket from `job-start` ({@link ticketOfStart}), the checks from {@link checksOf} and the steps from
1634
+ * the run's `plan-executed` record. The page opens a row through `GET /api/runs/:runid/result` (the generic payload, one owner): this reads no diff and no branch.
1635
+ * @param {string} runid @param {{ home?: string, now?: number, schedules?: ReturnType<typeof createScheduleDoor> }} [opts]
1636
+ */
1637
+ export function getJobGrid(runid, opts = {}) {
1638
+ const list = readRunList(opts);
1639
+ const anchor = list.rows.find((r) => r && r.runid === runid);
1640
+ if (!anchor || typeof anchor.job !== 'string') return null;
1641
+ const grid = ticketGridOfJob(anchor.job, list, opts);
1642
+ return grid === null ? null : { runid, job: anchor.job, ...grid };
1643
+ }
1644
+
1645
+ /**
1646
+ * Does this run's own record say it read a ticket? (the run list row's `ticket`, else its `job-start` ticket). The cheap gate before a whole job is read.
1647
+ * @param {any} row
1648
+ */
1649
+ function rowReadTicket(row) {
1650
+ if (Number.isInteger(row.ticket)) return true;
1651
+ if (!existsSync(row.spine)) return false;
1652
+ try { return ticketOfStart(parseJsonl(row.spine).records.findLast((/** @type {any} */ r) => r && r.type === 'job-start')) !== null; } catch { return false; }
1653
+ }
1654
+
1655
+ /**
1656
+ * @param {string} job @param {{rows: any[], events: any[]}} list @param {{ home?: string, now?: number, schedules?: ReturnType<typeof createScheduleDoor> }} opts
1657
+ */
1658
+ function ticketGridOfJob(job, list, opts) {
1659
+ const mine = list.rows.filter((r) => r && r.job === job);
1660
+ if (!mine.some((r) => rowReadTicket(r))) return null;
1661
+ const nowMs = typeof opts.now === 'number' ? opts.now : Date.now();
1662
+ const removals = readNeedsRemovals(opts);
1663
+ const nos = runNumbers(list.rows);
1664
+ const entries = mine.map((r) => {
1665
+ const e = summarizeRow(r, nowMs, removals, list.events);
1666
+ /** @type {any[]|null} */
1667
+ let records = null;
1668
+ if (existsSync(r.spine)) { try { records = parseJsonl(r.spine).records; } catch { records = null; } }
1669
+ const startRec = records ? records.findLast((/** @type {any} */ x) => x && x.type === 'job-start') : null;
1670
+ const t = records ? ticketOfStart(startRec) : null;
1671
+ const checks = records ? checksOf(records, resolveSpecForRow(r)) : null;
1672
+ const plan = records ? records.findLast((/** @type {any} */ x) => x && x.type === 'plan-executed' && Array.isArray(x.steps)) : null;
1673
+ const status = e.status ?? { key: 'failed', ...STATUS.failed };
1674
+ return {
1675
+ runId: r.runid, runNo: nos.get(r.runid) ?? null, at: Number.isFinite(atMs(r)) ? atMs(r) : null,
1676
+ statusKey: status.key, sign: status.sign, word: status.word, needs: e.needs ?? null,
1677
+ unsure: filterUnsure({ filter: startRec?.ticketFilter }),
1678
+ number: t ? t.number : (Number.isInteger(r.ticket) ? r.ticket : null), title: t ? t.title : null, url: t ? t.url : null,
1679
+ steps: plan ? { done: plan.steps.filter((/** @type {any} */ x) => isReusableGreen(x?.outcome)).length, total: plan.steps.length } : null,
1680
+ checks: checks ? { passed: checks.passed, total: checks.total } : null,
1681
+ spentUsd: typeof e.spentUsd === 'number' ? e.spentUsd : null, spendComplete: e.spendComplete === true, spendFloorUsd: typeof e.spendFloorUsd === 'number' ? e.spendFloorUsd : null,
1682
+ wall: typeof e.wall === 'string' && e.wall !== '' ? e.wall : null,
1683
+ reason: typeof e.endedLine === 'string' && e.endedLine !== '' ? e.endedLine : (e.fileMissing === true ? 'the run\'s log is no longer on disk' : null),
1684
+ };
1685
+ });
1686
+ let scheduleLine = null;
1687
+ try {
1688
+ const v = opts.schedules ? opts.schedules.view(job) : null;
1689
+ if (v && v.scheduled === true && typeof v.text === 'string') scheduleLine = `${v.text} · looks every ${TICKET_LOOK_MS / 60_000} min`;
1690
+ } catch { scheduleLine = null; }
1691
+ return buildJobGrid({ entries, scheduleLine });
1692
+ }
1693
+
1694
+ /**
1695
+ * Is ticket `number` a skipped ticket of `job` that nobody has run since? The ONE check behind `POST /api/author/ticket-anyway`: the grid's own skipped row says so.
1696
+ * @param {string} job @param {number} number @param {{ home?: string, now?: number }} [opts]
1697
+ */
1698
+ export function isSkippedTicket(job, number, opts = {}) {
1699
+ return skippedRunOf(job, number, opts) !== null;
1700
+ }
1701
+
1702
+ /**
1703
+ * The run id of the skipped row {@link isSkippedTicket} means (the newest one of that ticket, with Run it anyway on it), or null. The no-schedule "Run it anyway" (am3) starts from that
1704
+ * run's own saved signed job.
1705
+ * @param {string} job @param {number} number @param {{ home?: string, now?: number }} [opts]
1706
+ */
1707
+ export function skippedRunOf(job, number, opts = {}) {
1708
+ const list = readRunList(opts);
1709
+ const grid = ticketGridOfJob(job, list, opts);
1710
+ if (grid === null) return null;
1711
+ const skip = grid.groups.find((g) => g.key === 'skip');
1712
+ return skip?.rows.find((r) => r.number === number && r.anyway === true)?.runId ?? null;
1713
+ }
1714
+
1389
1715
  /**
1390
1716
  * `GET /api/runs/:runid/result` — the Result tab: for each rubric job line, its words and `~` rules from the signed spec, the facts it requires
1391
1717
  * (worded by {@link factSentence}), and — read from the run's own delivered step file, sha256-checked against its `destination-written`
1392
1718
  * record — one row per result with each fact's cell. `passed` is read from the run's own `check-run` record; the tab never re-decides. A red run
1393
1719
  * delivers nothing, so it has no rows: it carries the check's own first gap instead. `null` = no such run or no result tab for it.
1720
+ * Every OTHER job (R7b item 4) that ENDED gets the generic payload from {@link genericResultOf} (`kind: 'generic'`); the rubric payload below is
1721
+ * untouched and carries no `kind`.
1394
1722
  * @param {string} runid @param {{ home?: string }} opts
1395
1723
  */
1396
1724
  export function getRunResult(runid, /** @type {{ home?: string, sessionsRoot?: string }} */ opts = {}) {
@@ -1398,8 +1726,10 @@ export function getRunResult(runid, /** @type {{ home?: string, sessionsRoot?: s
1398
1726
  if (!row || row.via === 'import' || !existsSync(row.spine)) return null;
1399
1727
  const records = parseJsonl(row.spine).records;
1400
1728
  const spec = resolveSpecForRow(row);
1729
+ const kind = resultKindOf(row, records, spec);
1730
+ if (kind === 'generic') return genericResultOf(runid, row, records, spec, opts);
1731
+ if (kind === null) return null;
1401
1732
  const stages = rubricStagesOf(spec);
1402
- if (stages.length === 0) return null;
1403
1733
  const delivered = deliveredOf(records);
1404
1734
  const read = delivered.map((d) => readDelivered(d));
1405
1735
  const jobLines = Array.isArray(spec?.jobLines) ? spec.jobLines : [];
@@ -1584,7 +1914,8 @@ function scheduleExtrasFor(runid, job, rows, events, nos, opts, view) {
1584
1914
  lastWords = `last ${dateTimeWords(Number(lastRow.at))} · ${skippedWords(lastRow, true)}`;
1585
1915
  }
1586
1916
  }
1587
- schedule.line2 = [lastWords ?? 'no run yet', accept ? SCHEDULE_WORDS.acceptWaiting : null, nextWords].filter(Boolean).join(' · ');
1917
+ // R7: a schedule signed with the job says only that it waits (and a run waiting for the Accept, which is what a rubric job waits for)
1918
+ schedule.line2 = (view.waiting === true ? [accept ? SCHEDULE_WORDS.acceptWaiting : null, nextWords] : [lastWords ?? 'no run yet', accept ? SCHEDULE_WORDS.acceptWaiting : null, nextWords]).filter(Boolean).join(' · ');
1588
1919
  }
1589
1920
  }
1590
1921
  const row = rows.find((r) => r && r.runid === runid);
@@ -1601,7 +1932,7 @@ function scheduleExtrasFor(runid, job, rows, events, nos, opts, view) {
1601
1932
  const running = rows.some((r) => r && r.job === job && r.via !== 'import' && runIsAlive(r));
1602
1933
  const { sign, word } = scheduleSignFor({ running, red: !!(view && view.problem) });
1603
1934
  const words = scheduledWords(cur.trigger, door.userHome);
1604
- const head = [lowerFirst(words ?? ''), originNo === null ? null : `from run-${originNo}`, triesTailWords(tries.length) || null].filter(Boolean).join(' · ');
1935
+ const head = [lowerFirst(words ?? ''), originNo === null ? null : `from run-${originNo}`, door.isWaiting(job) ? lowerFirst(SCHEDULE_WORDS.waiting) : null, triesTailWords(tries.length) || null].filter(Boolean).join(' · ');
1605
1936
  const when = row ? dateTimeWords(atMs(row)) : '';
1606
1937
  const thisRun = rec ? sectionThisRunWords(rec) : `by hand.${runid === cur.originRunid ? ' The schedule was set from this run.' : ''}`;
1607
1938
  const shown = tries.slice(0, 7).map((x, i) => ({ label: i === 0 ? 'tries' : '', text: x.line }));
@@ -1622,8 +1953,11 @@ function getRunDetailBody(runid, opts) {
1622
1953
  const row = findRunRow(runid, opts);
1623
1954
  if (!row) return null;
1624
1955
  if (!existsSync(row.spine)) {
1625
- const refusal = refusalWordsOf(readRunList(opts).events, row);
1626
- if (refusal !== null) return refusedStub(row, refusal);
1956
+ const { events: settledEvents } = readRunList(opts);
1957
+ const refusal = refusalWordsOf(settledEvents, row);
1958
+ if (refusal !== null) return refusedStub(row, refusal, 'refused-before-start', neverRanPlan(settledEvents, row));
1959
+ const skipped = skipWordsOf(settledEvents, row);
1960
+ if (skipped !== null) return refusedStub(row, skipped, 'skipped', neverRanPlan(settledEvents, row));
1627
1961
  if (runIsAlive(row)) return startingStub(row);
1628
1962
  return {
1629
1963
  runid, job: row.job, at: row.at, via: row.via, fileMissing: true,
@@ -1916,7 +2250,7 @@ function getRunDetailBody(runid, opts) {
1916
2250
  accept: !runIsAlive(row) && doorWaiting(rawSpineRecords),
1917
2251
  // PRD v1.107 Part 6: the Result tab shows for a rubric run whose signed close has a rubric-step stage, never otherwise; `delivered` is the
1918
2252
  // files the run's own `destination-written` records name (the Result tab's downloads index into this list, never a path from a request)
1919
- hasResult: checkTypeLabel(summary.verdictType, row.at) === 'rubric' && rubricStagesOf(specForParts).length > 0,
2253
+ hasResult: resultKindOf(row, rawSpineRecords, specForParts) !== null,
1920
2254
  delivered: deliveredOf(rawSpineRecords).map(({ path, bytes, sha256 }) => ({ path, bytes, sha256 })),
1921
2255
  // T Part 7: why a SCHEDULED run started (the words `trigger.json` carried) and the fixed catch-up sentence; null on every hand run
1922
2256
  ...(() => {
@@ -3106,6 +3440,21 @@ function toolsListFromSpec(spec) {
3106
3440
  return names.length > 0 ? names : null;
3107
3441
  }
3108
3442
 
3443
+ /**
3444
+ * The Job tab's MCP rows (piece 8): the signed flow type (in the card's own words), the server and the tools the job signed, plus a ticket filter / watched fields when the spec
3445
+ * carries them. `null` for a plain job (no MCP rows at all).
3446
+ * @param {any} spec
3447
+ * @returns {{flowType: string, server: string, tools: string[], ticketFilter?: any, ticketFilterWords?: string|null, ticketWatch?: string[]}|null}
3448
+ */
3449
+ function mcpDetailFromSpec(spec) {
3450
+ const m = spec?.mcp;
3451
+ if (!m || typeof m.server !== 'string' || !Array.isArray(m.tools)) return null;
3452
+ return {
3453
+ flowType: FLOW_TYPE_LABELS[flowTypeOf(spec)], server: m.server, tools: m.tools.filter((/** @type {any} */ t) => typeof t === 'string'),
3454
+ ...(spec.ticketFilter ? { ticketFilter: spec.ticketFilter, ticketFilterWords: ticketFilterWords(spec.ticketFilter) } : {}), ...(Array.isArray(spec.ticketWatch) ? { ticketWatch: spec.ticketWatch } : {}),
3455
+ };
3456
+ }
3457
+
3109
3458
  /**
3110
3459
  * The granted tool list, verbatim, in declared order — `null` when the spec
3111
3460
  * carries none (a job may legally declare no `tools` at all).
@@ -3208,7 +3557,7 @@ export function getRunJob(runid, opts = {}) {
3208
3557
  trigger: cur ? cur.trigger : null, originNo: cur ? (nos.get(cur.originRunid) ?? null) : null,
3209
3558
  model: spec && typeof spec.model === 'string' ? spec.model : null,
3210
3559
  destination: cur ? (typeof cur.destination === 'string' && cur.destination !== '' ? cur.destination : (Array.isArray(spec?.writeScope) ? spec.writeScope.join(', ') : null)) : null,
3211
- home: door.userHome,
3560
+ home: door.userHome, waiting: cur ? door.isWaiting(job) : false,
3212
3561
  });
3213
3562
  return { ...body, started, schedule };
3214
3563
  } catch { return body; }
@@ -3236,7 +3585,8 @@ function getRunJobBody(runid, opts) {
3236
3585
  const row = findRunRow(runid, opts);
3237
3586
  if (!row) return null;
3238
3587
 
3239
- const near = existsSync(row.spine) ? sourceNearSpine(row.spine) : { specPath: null, sourceJsonPath: null };
3588
+ // a run that ended BEFORE it started (refused or skipped: a listed row, no spine file) still has its session folder: its path names it (R7b), so the signed job shows from there
3589
+ const near = sourceNearSpine(row.spine);
3240
3590
  let manifest = null;
3241
3591
  if (near.sourceJsonPath) {
3242
3592
  try { manifest = JSON.parse(readFileSync(near.sourceJsonPath, 'utf8')); } catch { manifest = null; }
@@ -3306,6 +3656,7 @@ function getRunJobBody(runid, opts) {
3306
3656
  guardrails: notRecorded(guardrailsFromSpec(spec)),
3307
3657
  tools: notRecorded(toolsFromSpec(spec)),
3308
3658
  toolsList: toolsListFromSpec(spec),
3659
+ mcp: mcpDetailFromSpec(spec),
3309
3660
  thinkingTick: spec.thinking === true,
3310
3661
  note,
3311
3662
  });
@@ -3524,19 +3875,22 @@ export function reuseLine(record) {
3524
3875
  * to copy: change the job: Clear the card). `null` when the runid is not listed.
3525
3876
  * @param {string} runid
3526
3877
  * @param {{ home?: string, model?: string, provider?: string }} [opts] `model` = the Model box's current Name (the estimate counts only runs on that worker); absent = the card's own Model
3527
- * @returns {{ok: true, origin: {runid: string, job: string}, outcome: string|null, card: Record<string, any>, from: 'signed job',
3878
+ * @returns {{ok: true, origin: {runid: string, job: string}, outcome: string|null, neverRan: boolean, card: Record<string, any>, from: 'signed job',
3528
3879
  * note: string|null,
3529
3880
  * specHash: string, workflowKey: string, spec: any, specPath: string, specNamesModel: boolean,
3530
3881
  * specWorker: {provider: string, endpoint: string, label: string},
3531
3882
  * trackRecord: ReturnType<typeof trackRecordFor>, line: string}|{ok: false, error: string}|null}
3532
3883
  */
3533
3884
  export function getStartFrom(runid, opts = {}) {
3534
- const { rows } = readRunList(opts);
3885
+ const { rows, events } = readRunList(opts);
3535
3886
  const row = rows.find((r) => r && r.runid === runid);
3536
3887
  if (!row) return null;
3537
- if (!existsSync(row.spine)) return { ok: false, error: 'this run has no log on disk — nothing to reuse' };
3538
- const records = parseJsonl(row.spine).records;
3539
- const signed = signedSpecForRun(row, records);
3888
+ // a ticket the job's filter SKIPPED has no log (R5) but its session kept the signed job beside where the log would be: the no-schedule "Run it anyway" (am3) starts from it
3889
+ // R9 (9b.2): so does a run refused before its first step (a refused run-start fetch, a locked-token look): it has no log either, and its session kept the signed job the same way
3890
+ const skipped = neverRanPlan(events, row);
3891
+ if (!existsSync(row.spine) && !skipped) return { ok: false, error: 'this run has no log on disk — nothing to reuse' };
3892
+ const records = skipped ? [] : parseJsonl(row.spine).records;
3893
+ const signed = skipped ? skippedSignedSpec(row) : signedSpecForRun(row, records);
3540
3894
  if (!signed) return { ok: false, error: "this run's signed job is not on disk — nothing to reuse (change the job: Clear the card and draft a new one)" };
3541
3895
  const near = sourceNearSpine(row.spine);
3542
3896
  const spec = signed.spec;
@@ -3574,6 +3928,8 @@ export function getStartFrom(runid, opts = {}) {
3574
3928
  const o = legsOf(records).at(-1)?.outcome ?? null;
3575
3929
  return isReusableGreen(o) && heldScheduled(records, triggerRecordOf(row)) ? 'green-held' : o;
3576
3930
  })(),
3931
+ // R9 (9b.2): the run ended before its first step at $0 (see neverRanPlan): the signed job stands, so an unchanged Reuse is "Sign & run", not a redraft
3932
+ neverRan: skipped,
3577
3933
  card,
3578
3934
  from: 'signed job',
3579
3935
  note: Array.isArray(spec.jobLines) && spec.jobLines.length ? null : 'older job — numbered lines were not saved',
@@ -3594,16 +3950,30 @@ export function getStartFrom(runid, opts = {}) {
3594
3950
  };
3595
3951
  }
3596
3952
 
3953
+ /**
3954
+ * The signed job a SKIPPED run's session left (`resolved-spec.json` beside where its log would be), or null. A skipped run has no `job-start` to name the hash, so the file stands as the
3955
+ * session saved it; whatever starts from it is signed afresh by the start's own gates.
3956
+ * @param {{ spine: string }} row @returns {{spec: any, specPath: string, specHash: string}|null}
3957
+ */
3958
+ function skippedSignedSpec(row) {
3959
+ const { specPath } = sourceNearSpine(row.spine);
3960
+ if (!specPath) return null;
3961
+ try {
3962
+ const spec = JSON.parse(readFileSync(specPath, 'utf8'));
3963
+ return spec && typeof spec === 'object' ? { spec, specPath, specHash: jobSpecHash(spec) } : null;
3964
+ } catch { return null; }
3965
+ }
3966
+
3597
3967
  /**
3598
3968
  * T Part 3: a job's listed runs, newest first, each with its signed spec (null when not on disk), its terminal outcome and
3599
3969
  * its parsed spine. The schedule door's gate (`greenFor`) reads this; nothing here builds a run context.
3600
3970
  * @param {string} job
3601
3971
  * @param {{ home?: string }} [opts]
3602
- * @returns {{runid: string, outcome: string|null, spec: any, records: any[]}[]}
3972
+ * @returns {{runid: string, outcome: string|null, spec: any, records: any[], ticket?: number}[]}
3603
3973
  */
3604
3974
  export function jobRunsOf(job, opts = {}) {
3605
3975
  const { rows } = readRunList(opts);
3606
- /** @type {{runid: string, outcome: string|null, spec: any, records: any[]}[]} */
3976
+ /** @type {{runid: string, outcome: string|null, spec: any, records: any[], ticket?: number}[]} */
3607
3977
  const out = [];
3608
3978
  for (let i = rows.length - 1; i >= 0; i -= 1) {
3609
3979
  const row = rows[i];
@@ -3612,7 +3982,11 @@ export function jobRunsOf(job, opts = {}) {
3612
3982
  try { records = parseJsonl(row.spine).records; } catch { continue; }
3613
3983
  const outcome = legsOf(records).at(-1)?.outcome ?? null;
3614
3984
  // T D.2: a scheduled run's green is HELD until accepted, so it is not a good run for the schedule gate either
3615
- out.push({ runid: row.runid, outcome: outcome === 'green' && heldScheduled(records, triggerRecordOf(row)) ? 'green-held' : outcome, spec: signedSpecForRun(row, records)?.spec ?? null, records });
3985
+ out.push({
3986
+ runid: row.runid, outcome: outcome === 'green' && heldScheduled(records, triggerRecordOf(row)) ? 'green-held' : outcome, spec: signedSpecForRun(row, records)?.spec ?? null, records,
3987
+ // a Tickets run's ticket number (the run list row carries it): the schedule signed with the job starts after this one (R7)
3988
+ ...(Number.isInteger(row.ticket) ? { ticket: row.ticket } : {}),
3989
+ });
3616
3990
  }
3617
3991
  return out;
3618
3992
  }
@@ -3670,6 +4044,8 @@ function reuseCardFromSpec(spec, extra) {
3670
4044
  destination: extra.destination || writeScope.join(', '),
3671
4045
  capUsd: typeof spec.budgetUsd === 'number' ? spec.budgetUsd : null,
3672
4046
  maxWallMs: typeof spec.maxWallMs === 'number' ? spec.maxWallMs : undefined,
4047
+ // piece 8: a job with an MCP shows its Flow type and server on the card; a plain job adds nothing (so its card is what it was)
4048
+ ...(spec.mcp && typeof spec.mcp.server === 'string' ? { flowType: flowTypeOf(spec), mcp: spec.mcp.server } : {}),
3673
4049
  };
3674
4050
  }
3675
4051
 
@@ -3771,7 +4147,7 @@ function sendText(res, code, text) {
3771
4147
  * only `createPanelServer` below always supplies one.
3772
4148
  * @param {import('node:http').IncomingMessage} req
3773
4149
  * @param {import('node:http').ServerResponse} res
3774
- * @param {{ home?: string, sessionsRoot?: string, version?: string, startedAt?: string, packageJsonPath?: string, port: number, token?: string, authorRoutes?: ReturnType<typeof createAuthorRoutes>, settingsRoutes?: ReturnType<typeof createSettingsRoutes>, runRoutes?: ReturnType<typeof createRunRoutes>, importRoutes?: ReturnType<typeof createImportRoutes>, schedules?: ReturnType<typeof createScheduleDoor> }} opts
4150
+ * @param {{ home?: string, mcpHome?: string, sessionsRoot?: string, version?: string, startedAt?: string, packageJsonPath?: string, port: number, token?: string, authorRoutes?: ReturnType<typeof createAuthorRoutes>, settingsRoutes?: ReturnType<typeof createSettingsRoutes>, runRoutes?: ReturnType<typeof createRunRoutes>, importRoutes?: ReturnType<typeof createImportRoutes>, schedules?: ReturnType<typeof createScheduleDoor> }} opts
3775
4151
  */
3776
4152
  export function handleRequest(req, res, opts) {
3777
4153
  /** the ONE writable route family for a path, or null — `/api/author/*` (authoring) or
@@ -3875,6 +4251,8 @@ export function handleRequest(req, res, opts) {
3875
4251
  // caller (no `opts.token`), which is fine: the page's own JS only reads
3876
4252
  // it to send on a POST, and there are none to send without P3's routes.
3877
4253
  html = html.replace(/__BARELOOP_PANEL_TOKEN__/g, String(opts.token ?? ''));
4254
+ // the New job card's Schedule row (R7): its words come from the schedule words table, never from the page
4255
+ for (const [token, words] of Object.entries(scheduleCardFill())) html = html.split(token).join(words);
3878
4256
  if (method === 'HEAD') {
3879
4257
  res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'content-length': Buffer.byteLength(html) });
3880
4258
  res.end();
@@ -3894,7 +4272,7 @@ export function handleRequest(req, res, opts) {
3894
4272
 
3895
4273
  if (pathname === '/api/runs') { send(200, runsListPayload({ home: opts.home, schedules: opts.schedules })); return; }
3896
4274
 
3897
- const runMatch = /^\/api\/runs\/([^/]+)(\/(audit|job|rounds|result|download))?$/.exec(pathname);
4275
+ const runMatch = /^\/api\/runs\/([^/]+)(\/(audit|job|rounds|result|download|grid))?$/.exec(pathname);
3898
4276
  if (runMatch) {
3899
4277
  const rawRunid = runMatch[1];
3900
4278
  const sub = runMatch[3] ?? null;
@@ -3922,6 +4300,12 @@ export function handleRequest(req, res, opts) {
3922
4300
  send(200, result);
3923
4301
  return;
3924
4302
  }
4303
+ if (sub === 'grid') {
4304
+ const result = getJobGrid(runid, { home: opts.home, schedules: opts.schedules });
4305
+ if (!result) { sendText(res, 404, 'no such run, or its job is not a Tickets job'); return; }
4306
+ send(200, result);
4307
+ return;
4308
+ }
3925
4309
  if (sub === 'download') {
3926
4310
  const got = getRunDownload(runid, url.searchParams.get('i'), { home: opts.home });
3927
4311
  if (!got.ok) { sendText(res, got.code, got.error); return; }
@@ -3988,7 +4372,7 @@ export function panelUrl(boundPort) {
3988
4372
  * @param {{ port?: number, home?: string, env?: Record<string,string|undefined>,
3989
4373
  * sessionsRoot?: string, spawnFn?: (...a: any[]) => any, bareloopBin?: string,
3990
4374
  * fetchImpl?: typeof fetch, settleMs?: number, userHome?: string,
3991
- * openFolderSpawn?: (cmd: string, args: string[], o: object) => any, platform?: string, packageJsonPath?: string,
4375
+ * openFolderSpawn?: (cmd: string, args: string[], o: object) => any, platform?: string, mcpHome?: string, packageJsonPath?: string,
3992
4376
  * scheduleNow?: () => number, sessionDeps?: Record<string, any>, schedulerIntervalMs?: number, acceptWaitMs?: number }} [opts] `scheduleNow`, `sessionDeps` and `schedulerIntervalMs` are TEST SEAMS (the schedule clock; createSession's stubs; the scheduler's timer, 0 = none)
3993
4377
  * @returns {Promise<{ server: import('node:http').Server, port: number, token: string, schedules: ReturnType<typeof createScheduleDoor>, scheduler: ReturnType<typeof createScheduler>, close: () => Promise<void> }>}
3994
4378
  */
@@ -4050,6 +4434,8 @@ export function createPanelServer(opts = {}) {
4050
4434
  schedulesRef = schedules;
4051
4435
  authorRoutes = createAuthorRoutes({
4052
4436
  schedules,
4437
+ isSkippedTicket: (job, n) => isSkippedTicket(job, n, { home }),
4438
+ skippedRunOf: (job, n) => skippedRunOf(job, n, { home }),
4053
4439
  runJobNames: () => readRunList({ home }).rows.flatMap((r) => (r && typeof r.job === 'string' ? [r.job] : [])),
4054
4440
  ...(opts.sessionDeps ? { sessionDeps: opts.sessionDeps } : {}),
4055
4441
  port: boundPort,
@@ -4060,6 +4446,7 @@ export function createPanelServer(opts = {}) {
4060
4446
  bareloopBin: opts.bareloopBin,
4061
4447
  fetchImpl: opts.fetchImpl,
4062
4448
  home,
4449
+ mcpHome: opts.mcpHome,
4063
4450
  startFrom: {
4064
4451
  get: (runid, o = {}) => getStartFrom(runid, { home, ...o }),
4065
4452
  getImport: (id, o = {}) => getStartFromImport(id, { home, ...o }),
@@ -4080,7 +4467,7 @@ export function createPanelServer(opts = {}) {
4080
4467
  scheduler.start();
4081
4468
  settingsRoutes = createSettingsRoutes({
4082
4469
  port: boundPort, token, home, env: opts.env, fetchImpl: opts.fetchImpl,
4083
- openFolderSpawn: opts.openFolderSpawn, platform: opts.platform,
4470
+ openFolderSpawn: opts.openFolderSpawn, platform: opts.platform, mcpHome: opts.mcpHome,
4084
4471
  });
4085
4472
  runRoutes = createRunRoutes({
4086
4473
  port: boundPort,