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
package/src/rubricstep.js CHANGED
@@ -3,6 +3,7 @@ import { readFile, lstat } from 'node:fs/promises';
3
3
  import { join, dirname } from 'node:path';
4
4
  import { createRubric, checkStep, renderGaps, numbersInQuote } from 'bareguard';
5
5
  import { dropRows, dropLine } from './pagedropwords.js';
6
+ import { OFFERED } from './checkwords.js';
6
7
  import { factPartOf, factShapeReds, factDecides, factClaims, factRows, plainFactItem, factBrief, writtenSpans } from './facts.js';
7
8
 
8
9
  // PART 1a (docs/product/ITEM33-BUILD.md, "Addendum 2026-10-12"): the rubric job on LOCAL FILES — what one job line leaves
@@ -37,9 +38,10 @@ export function stepFileContract() {
37
38
  ' ** or __ marks do not matter). Every number in a claim must also appear in its quote.',
38
39
  ' In each claim, copy every number, time and price exactly as the input writes it (for example "9:27 AM", not "09:27"),',
39
40
  ' because the check matches the numbers in your claim against your quote.',
40
- 'A job line the brief below marks as a FACTS line is different: its file holds ONLY {"results": [{"quote": "...", "values":',
41
+ 'A job line the brief below marks as a FACTS line is different: its file holds {"results": [{"quote": "...", "values":',
41
42
  '{"<fact>": "<value>"}}]} — one result per thing found, one quote copied exactly from the text of that one result, the values written as the quote',
42
- 'writes them; no "text" and no "cites". A line the brief marks as a TEXT line keeps "text" (free words), and every number in it',
43
+ 'writes them; no "cites". It holds a "text" too only when the brief says it is also a TEXT line (the person asked for limits on the words, so',
44
+ 'the same file carries both "results" and "text"). A line the brief marks as a TEXT line keeps "text" (free words), and every number in it',
43
45
  'must be copied from a quote of an earlier facts line.',
44
46
  'Write nothing outside output/, and never edit the files under input/. The file must be complete, valid JSON: a file cut',
45
47
  'off before its closing brace counts as not written.',
@@ -65,10 +67,14 @@ export function lineBriefs(closeDecl) {
65
67
  const count = !c ? 'one result for every one you find' : c.min !== undefined && c.max !== undefined
66
68
  ? (c.min === c.max ? `exactly ${c.min} result${c.min === 1 ? '' : 's'}` : `${c.min} to ${c.max} results`)
67
69
  : c.min !== undefined ? `at least ${c.min} results` : `at most ${c.max} results`;
70
+ // keep-both: the person's picks (countable parts) sit beside the fact on this line, so the same file also carries the "text" they limit
71
+ const alsoText = st.params.parts.some((/** @type {any} */ q) => isRec(q) && q.class === 'countable');
68
72
  out.push({
69
73
  line: n,
70
74
  text: [
71
- `Job line ${n} is a FACTS line. Write ${stepFileRel(n)} as {"results": [{"quote": "...", "values": {...}}]} and nothing else — no "text", no "cites".`,
75
+ alsoText
76
+ ? `Job line ${n} is a FACTS line AND a TEXT line. Write ${stepFileRel(n)} as {"results": [{"quote": "...", "values": {...}}], "text": "..."} — the results are the facts below, the "text" is your answer to the line in your own words (its limits are in the line's ~ rules); no "cites".`
77
+ : `Job line ${n} is a FACTS line. Write ${stepFileRel(n)} as {"results": [{"quote": "...", "values": {...}}]} and nothing else — no "text", no "cites".`,
72
78
  ` One result per thing you find in the input "${fp.source}": ${count}.`,
73
79
  ' "quote": ONE quote per result, copied exactly from that result\'s own text in the input (at most 4000 characters) — never joined from two results.',
74
80
  ' "values": one entry per fact below, written exactly as the quote writes it (for example "9:27 AM", not "09:27"; "389", not "389.00").',
@@ -156,6 +162,12 @@ export const COUNT_CHECKS = Object.freeze({
156
162
  maxLines: Object.freeze(['value']),
157
163
  sections: Object.freeze(['names']),
158
164
  sectionWords: Object.freeze(['names', 'wordsPerSection']),
165
+ // R10 (bareguard 0.31, fwdloop v0.29.0 OFFERED): the five text checks a person's pick may carry; the drafter never writes them
166
+ nonEmpty: Object.freeze([]),
167
+ listItems: Object.freeze(['value']),
168
+ sectionOrder: Object.freeze(['names']),
169
+ mustCarry: Object.freeze(['phrases']),
170
+ blockLines: Object.freeze(['size', 'phrases']),
159
171
  cited: Object.freeze(['source']),
160
172
  // a COUNT of the claims listed under an input: the code counts the list (flattenStep), bareguard's own min/max compares it
161
173
  minClaims: Object.freeze(['value', 'source']),
@@ -165,12 +177,16 @@ export const COUNT_CHECKS = Object.freeze({
165
177
  numbersFromFacts: Object.freeze(['from']),
166
178
  });
167
179
  /** every field a part may carry, whatever its class */
168
- const PART_FIELDS = Object.freeze(['text', 'class', 'check', 'value', 'names', 'wordsPerSection', 'source', 'domains', 'covers', 'rules', 'from', 'record', 'facts', 'count', 'tested', 'sample']);
180
+ const PART_FIELDS = Object.freeze(['text', 'class', 'check', 'value', 'names', 'wordsPerSection', 'source', 'domains', 'phrases', 'size', 'covers', 'rules', 'from', 'record', 'facts', 'count', 'tested', 'sample']);
169
181
 
170
182
  /** @typedef {{code: string, path: string, detail: string}} ShapeRed */
171
183
 
172
184
  /** @param {unknown} v @returns {v is Record<string, any>} */
173
185
  const isRec = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
186
+ /** @param {unknown} v @returns {string} JSON with every object's keys sorted, so two equal parts compare equal whatever order their keys were written in */
187
+ const sortedJson = (v) => JSON.stringify(v, (_k, x) => (isRec(x) ? Object.fromEntries(Object.entries(x).sort(([a], [b]) => (a < b ? -1 : 1))) : x));
188
+ /** @param {unknown} a @param {unknown} b */
189
+ const sameJson = (a, b) => sortedJson(a) === sortedJson(b);
174
190
  /** @param {unknown} v @returns {v is string} */
175
191
  const nonEmpty = (v) => typeof v === 'string' && v.trim() !== '';
176
192
  /** @param {unknown} v @returns {v is string[]} */
@@ -214,12 +230,13 @@ export function rubricStepShapeReds(p, at) {
214
230
  if (part.class !== 'countable') return;
215
231
  if (!Object.hasOwn(COUNT_CHECKS, part.check)) { red('invalid-value', `${w}.check`, `one of ${Object.keys(COUNT_CHECKS).join(' | ')}`); return; }
216
232
  for (const f of COUNT_CHECKS[part.check]) {
217
- const ok = f === 'value' || f === 'wordsPerSection' ? Number.isInteger(part[f]) && part[f] >= 1
218
- : f === 'names' ? nameList(part.names)
233
+ const ok = f === 'value' || f === 'wordsPerSection' || f === 'size' ? Number.isInteger(part[f]) && part[f] >= 1
234
+ : f === 'names' || f === 'phrases' ? nameList(part[f])
219
235
  : f === 'from' ? Array.isArray(part.from) && part.from.length > 0 && new Set(part.from).size === part.from.length && part.from.every((/** @type {unknown} */ x) => Number.isInteger(x) && /** @type {number} */ (x) >= 1)
220
236
  : nonEmpty(part.source) && part.source.length <= 128;
221
237
  if (!ok) {
222
238
  red('invalid-value', `${w}.${f}`, f === 'names' ? 'a non-empty array of section names'
239
+ : f === 'phrases' ? 'a non-empty array of words or phrases'
223
240
  : f === 'source' ? 'the label of the input a quote must come from'
224
241
  : f === 'from' ? 'the numbers of the earlier fact lines whose checked quotes the text\'s numbers come from (distinct integers, 1 or more)'
225
242
  : 'an integer, 1 or more');
@@ -246,7 +263,8 @@ export function citedLabels(params) {
246
263
  */
247
264
  export function buildStepSpec(params, inputShas) {
248
265
  /** @type {Record<string, any>[]} */
249
- const checks = factPartOf(params) ? [] : [{ id: 'text-present', rule: 'nonEmpty', field: 'text' }];
266
+ // a fact step has no text to floor, unless the person's picks put text checks on its line (keep-both): then "text" must be there, or an upper bound alone (maxWords) would pass an empty file
267
+ const checks = factPartOf(params) && !params.parts.some((x) => x.class === 'countable') ? [] : [{ id: 'text-present', rule: 'nonEmpty', field: 'text' }];
250
268
  params.parts.forEach((part, i) => {
251
269
  if (part.class === 'fact') {
252
270
  // ONE bareguard `cited` check per fact part: the quote is in the frozen input, every value is in the quote and meets its rule
@@ -261,6 +279,11 @@ export function buildStepSpec(params, inputShas) {
261
279
  case 'maxWords': case 'minWords': case 'maxLines': checks.push({ id, rule: part.check, field: 'text', value: part.value }); break;
262
280
  case 'sections': checks.push({ id, rule: 'sections', field: 'text', names: [...part.names] }); break;
263
281
  case 'sectionWords': checks.push({ id, rule: 'sectionWords', field: 'text', names: [...part.names], wordsPerSection: part.wordsPerSection }); break;
282
+ case 'nonEmpty': checks.push({ id, rule: 'nonEmpty', field: 'text' }); break;
283
+ case 'listItems': checks.push({ id, rule: 'listItems', field: 'text', value: part.value }); break;
284
+ case 'sectionOrder': checks.push({ id, rule: 'sectionOrder', field: 'text', names: [...part.names] }); break;
285
+ case 'mustCarry': checks.push({ id, rule: 'mustCarry', field: 'text', phrases: [...part.phrases] }); break;
286
+ case 'blockLines': checks.push({ id, rule: 'blockLines', field: 'text', size: part.size, phrases: [...part.phrases] }); break;
264
287
  case 'cited': checks.push({ id, rule: 'cited', claims: `cites:${part.source}`, source: part.source }); break;
265
288
  case 'minClaims': checks.push({ id, rule: 'min', field: `claims:${part.source}`, value: part.value }); break;
266
289
  case 'maxClaims': checks.push({ id, rule: 'max', field: `claims:${part.source}`, value: part.value }); break;
@@ -394,6 +417,10 @@ export function plainStepGap(step, why, g, params = null) {
394
417
  if (g.check === 'minWords') return `${at}: "text" has ${g.measured} words, at least ${g.limit} are required`;
395
418
  if (g.check === 'maxLines') return `${at}: "text" has ${g.measured} lines, at most ${g.limit} are allowed`;
396
419
  if (g.check === 'sections') return `${at}: "text" is missing section(s): ${(g.items ?? []).join(', ')}`;
420
+ if (g.check === 'listItems') return `${at}: "text" has ${g.measured} list items, exactly ${g.limit} are required`;
421
+ if (g.check === 'sectionOrder') return `${at}: "text" does not hold its sections in the asked order (${(g.items ?? []).map((/** @type {string} */ x) => x.replace(/^[^:]*:/, '')).join(', ')} out of place)`;
422
+ if (g.check === 'mustCarry') return `${at}: "text" does not carry: ${(g.items ?? []).join(', ')}`;
423
+ if (g.check === 'blockLines') return `${at}: "text" is not in blocks of ${g.limit} lines each carrying the asked words (${(g.items ?? []).join(', ')})`;
397
424
  if ((g.check === 'min' || g.check === 'max') && String(g.field ?? '').startsWith('claims:')) {
398
425
  const label = String(g.field).slice('claims:'.length);
399
426
  return g.check === 'min'
@@ -532,6 +559,12 @@ function dupUnitWords(p, path) {
532
559
  return null;
533
560
  }
534
561
 
562
+ /** The legal example the `rubric-fact-twice` red carries as its drafter-only `hint` (the person's text is the plain sentence): one fact part holding two facts, the rule it carries listed in "rules", no "count" (a picked count is a pick). */
563
+ const factTwiceExample = (/** @type {unknown} */ source) => ({
564
+ class: 'fact', source: typeof source === 'string' ? source : 'Changelog', text: 'the release heading and a section word', rules: [1],
565
+ facts: [{ name: 'release heading', shape: 'phrase', phrase: '## [0.54.1] - 2026-11-04' }, { name: 'section word', shape: 'phrase', phrase: '### Fixed' }],
566
+ });
567
+
535
568
  /**
536
569
  * R11 — the drafting-time rules for the `rubric-step` stages of a declaration, each a red in the person's plain words that
537
570
  * names the job line and ends "Nothing spent." where nothing was. Pure; never throws. Judged parts are RED in this build
@@ -544,10 +577,11 @@ function dupUnitWords(p, path) {
544
577
  * naming both parts and both numbers;
545
578
  * - a `cited` part names a label the person's inputs do not have.
546
579
  * @param {any[]} stages the declaration's stages
547
- * @param {{inputLabels?: string[]|null, red: (code: string, path: string, detail: string, extra?: object) => void}} o
548
- * `inputLabels` absent = the label rule is not run (a caller with no inputs in hand)
580
+ * @param {{inputLabels?: string[]|null, picks?: {line: number, part: any}[]|null, red: (code: string, path: string, detail: string, extra?: object) => void}} o
581
+ * `inputLabels` absent = the label rule is not run (a caller with no inputs in hand);
582
+ * `picks` = the record of the person's picks (`declaration.picks`, `{line, part}` each): the only countable parts a fact line may carry
549
583
  */
550
- export function checkRubricParts(stages, { inputLabels = null, red }) {
584
+ export function checkRubricParts(stages, { inputLabels = null, red, picks = null }) {
551
585
  /** @type {Map<number, string>} */
552
586
  const owner = new Map();
553
587
  /** the stage index of each fact line (PART 1b: a prose step ties its numbers to fact lines that are checked BEFORE it) @type {Map<number, number>} */
@@ -596,7 +630,7 @@ export function checkRubricParts(stages, { inputLabels = null, red }) {
596
630
  red('rubric-part-source', `${w}.source`, `line ${line}: '${said}' asks for quotes from "${sayText(part.source ?? '')}", but the job's inputs are ${inputLabels.map((l) => `"${l}"`).join(', ')}.`, { line: step, stage: label });
597
631
  }
598
632
  if (p.parts.filter((/** @type {any} */ x) => isRec(x) && x.class === 'fact').length > 1) {
599
- red('rubric-fact-twice', w, `line ${line}: '${said}' is a second fact list on the same line. One line has one list of facts; put them all in one. Nothing spent.`, { line: step, stage: label });
633
+ red('rubric-fact-twice', w, `line ${line}: '${said}' is a second fact list on the same line. One line has one list of facts; put them all in one. Nothing spent.`, { line: step, stage: label, hint: `Example of ONE part holding two facts: ${JSON.stringify(factTwiceExample(part.source))}` });
600
634
  }
601
635
  } else if (part.class === 'countable') {
602
636
  if (part.check === 'numbersFromFacts') {
@@ -606,7 +640,9 @@ export function checkRubricParts(stages, { inputLabels = null, red }) {
606
640
  }
607
641
  return;
608
642
  }
609
- if (factLine) {
643
+ // keep-both: a fact line may carry a countable part only when it IS one of the person's recorded picks (an offered check, its `rules`, the same line, the same words)
644
+ const isPick = factLine && Array.isArray(picks) && picks.some((x) => isRec(x) && x.line === step && sameJson(x.part, part)) && OFFERED.includes(part.check) && Array.isArray(part.rules);
645
+ if (factLine && !isPick) {
610
646
  red('rubric-fact-text', w, `line ${line}: '${said}' counts or quotes free text, but this line lists facts and has no text. Say it as a fact (a shape and a rule) or remove it. Nothing spent.`, { line: step, stage: label });
611
647
  return;
612
648
  }
@@ -869,6 +905,11 @@ export function partSentence(part) {
869
905
  case 'maxLines': return `the text is at most ${n(part.value, 'line')}`;
870
906
  case 'sections': return `the text has the section(s): ${list(part.names)}`;
871
907
  case 'sectionWords': return `each section (${list(part.names)}) is about ${part.wordsPerSection} words`;
908
+ case 'nonEmpty': return 'the text is not empty';
909
+ case 'listItems': return `the text has exactly ${n(part.value, 'list item')}`;
910
+ case 'sectionOrder': return `the text has the section(s) ${list(part.names)}, in that order`;
911
+ case 'mustCarry': return `the text carries ${list(part.phrases)}`;
912
+ case 'blockLines': return `the text is in blocks of ${n(part.size, 'line')}, each carrying ${list(part.phrases)}`;
872
913
  case 'cited': return `every claim is backed by a quote copied from "${part.source}"`;
873
914
  case 'minClaims': return `at least ${part.value} claim(s) are listed under "${part.source}"`;
874
915
  case 'maxClaims': return `at most ${part.value} claim(s) are listed under "${part.source}"`;
@@ -880,16 +921,21 @@ export function partSentence(part) {
880
921
  /**
881
922
  * The checks a signed close actually runs, per job line, in plain code-written sentences: one per countable part of every
882
923
  * rubric-step stage. This is the ONE reader both the plan card and the sign-time invariant use.
924
+ * Each row says who added the check (`by`): `you` = one of the person's picks, as the signed close's own record (`closeDecl.picks`) names it; `agent` = the drafter's;
925
+ * `null` = code's own tie (the numbers of a text step come from the fact quotes), which is neither.
883
926
  * @param {any} closeDecl
884
- * @returns {{line: number, text: string, covers: number[]}[]}
927
+ * @returns {{line: number, text: string, covers: number[], by: 'agent'|'you'|null}[]}
885
928
  */
886
929
  export function checksOfClose(closeDecl) {
887
930
  const stages = isRec(closeDecl) && Array.isArray(closeDecl.stages) ? closeDecl.stages : [];
931
+ const record = isRec(closeDecl) && Array.isArray(closeDecl.picks) ? closeDecl.picks : [];
888
932
  return stages.flatMap((/** @type {any} */ st) => (isRec(st) && st.kind === 'rubric-step' && isRec(st.params) && Array.isArray(st.params.parts)
889
933
  ? st.params.parts.filter((/** @type {any} */ p) => isRec(p) && (p.class === 'countable' || p.class === 'fact')).flatMap((/** @type {any} */ p) => {
890
934
  const covers = Array.isArray(p.covers) ? p.covers.filter(Number.isInteger) : [];
935
+ /** @type {'agent'|'you'|null} */
936
+ const by = p.check === 'numbersFromFacts' ? null : record.some((/** @type {any} */ x) => isRec(x) && x.line === st.params.step && sameJson(x.part, p)) ? 'you' : 'agent';
891
937
  // a fact part is one plan row per fact (and one for its count): the person signs the rows, the close runs the same list
892
- return (p.class === 'fact' ? factRows(p) : [partSentence(p)]).map((/** @type {string} */ text) => ({ line: st.params.step, text, covers }));
938
+ return (p.class === 'fact' ? factRows(p) : [partSentence(p)]).map((/** @type {string} */ text) => ({ line: st.params.step, text, covers, by }));
893
939
  })
894
940
  : []));
895
941
  }
@@ -912,14 +958,14 @@ export function signedFactNames(closeDecl) {
912
958
  * silently dropped (run mv5bk400: "lists 3 releases" was confirmed, then left out of the signed close without a word).
913
959
  * @param {{confirmed: {text: string, fromLine: number[]|null}[], notChecked: string[], closeDecl: any, jobLines?: any[]|null}} o
914
960
  * `jobLines` — the person's numbered lines, so a ~ rule the drafter listed as Not checked reads in the person's own words
915
- * @returns {{checkItems: {text: string, fromLine: number[]}[], notChecked: string[], moved: {text: string, fromLine: number[]|null}[]}}
961
+ * @returns {{checkItems: {text: string, fromLine: number[], by: 'agent'|'you'|null}[], notChecked: string[], moved: {text: string, fromLine: number[]|null}[]}}
916
962
  */
917
963
  export function reconcileRubricPlan({ confirmed, notChecked, closeDecl, jobLines = null }) {
918
964
  const real = checksOfClose(closeDecl);
919
965
  const covered = new Set(real.flatMap((c) => c.covers));
920
966
  const moved = confirmed.filter((_, i) => !covered.has(i + 1));
921
967
  return {
922
- checkItems: real.map((c) => ({ text: c.text, fromLine: [c.line] })),
968
+ checkItems: real.map((c) => ({ text: c.text, fromLine: [c.line], by: c.by })),
923
969
  notChecked: [
924
970
  ...notChecked,
925
971
  ...proseNotChecked(closeDecl),
package/src/run.js CHANGED
@@ -206,6 +206,11 @@ async function primitiveSmoke(workdir) {
206
206
  * collision walk would mint a `-2` beside the work the resume exists to continue. The
207
207
  * fold's precedent exactly: the chain's state is DECLARED, never re-derived. Forwarded
208
208
  * verbatim to the plan flow; absent is the cold path.
209
+ * @param {string|null} [opts.ticketUnsure] R9 (9.4): the ticket filter's `unsure` reason when it let the ticket run unsure; rides onto `job-start` as `ticketFilter.unsure`
210
+ * @param {import('./ticketrepo.js').RepoTicketRecord|null} [opts.ticketRecord] MCP + tickets piece 1a: a CODE-REPO job's frozen ticket (metadata only: number, title,
211
+ * state, source, sha256, bytes, masked count, the frozen file's relative path, the MCP record - never the text). Report-only: it rides onto `job-start` as `ticket`,
212
+ * so the run's books name the exact bytes the worker could read. Absent = the job reads no ticket (or froze it in its prepared copy's `source.json`).
213
+ * @param {{number: number, ownerRepo: string, head: string, base: {ref: string|null, sha: string}|null, mergeBase: string|null}|null} [opts.prRecord] MCP + tickets piece 12: the PR a worktree job was checked out at (the head sha the seed is, the base and the merge-base for the readout). Report-only: rides onto `job-start` as `pr`.
209
214
  * @param {boolean|'cap'|'diff'} [opts.readShim=false] THE READ SHIM (src/readshim.js) —
210
215
  * WHICH ARM to run, threaded to the plan flow. The Phase 2 pre-registration's four:
211
216
  * `false` A0 — off (the default)
@@ -275,7 +280,7 @@ async function primitiveSmoke(workdir) {
275
280
  * deliberately NOT in the resumable/checkpoint set (`src/reuse.js`) — an
276
281
  * unknown in-flight state is not a known-safe resume point.
277
282
  */
278
- export async function runJob(rawSpec, { approvals, workdir, provider, nativeProvider, providerFor, judgeProvider = null, judgeModel = null, rates = null, judgeRates = null, emit, capRuns = 3, strikeLimit, shellCapUsd = 2, closeTimeoutMs, closeDir = null, layerRoot = false, readShim = false, scout = true, bridge = null, draftSpentUsd = 0, draftSpendComplete = true, priorSpentUsd = 0, priorSpendComplete = true, priorWallMs = 0, resumeSeed = null, resumeGrades = [], resumeReplans = null, resumeBranch = null, humanRuling = null, heldRuling = null, reviewDoor = null, doorRerun = null, resumable = true, stopFile = null, learnHints = null }) {
283
+ export async function runJob(rawSpec, { approvals, workdir, provider, nativeProvider, providerFor, judgeProvider = null, judgeModel = null, rates = null, judgeRates = null, emit, capRuns = 3, strikeLimit, shellCapUsd = 2, closeTimeoutMs, closeDir = null, layerRoot = false, readShim = false, scout = true, bridge = null, draftSpentUsd = 0, draftSpendComplete = true, priorSpentUsd = 0, priorSpendComplete = true, priorWallMs = 0, resumeSeed = null, resumeGrades = [], resumeReplans = null, resumeBranch = null, humanRuling = null, heldRuling = null, reviewDoor = null, doorRerun = null, resumable = true, stopFile = null, learnHints = null, ticketRecord = null, ticketUnsure = null, prRecord = null }) {
279
284
  // THE READ SHIM's ARM, resolved at the door — the FIRST thing this entry does,
280
285
  // before the ledger, before the approval gate, before a byte of the spec is read.
281
286
  // An unrecognised spelling throws here at zero cost instead of being coerced by
@@ -412,6 +417,10 @@ export async function runJob(rawSpec, { approvals, workdir, provider, nativeProv
412
417
  // (an absent baseUrl is the vendor's own host, not an unknown).
413
418
  provider: typeof job.provider === 'string' ? job.provider : null,
414
419
  ...(typeof job.baseUrl === 'string' ? { baseUrl: job.baseUrl } : {}),
420
+ ...(ticketRecord === null ? {} : { ticket: ticketRecord }),
421
+ // R9 (fwd 9.4): the ticket filter ran UNSURE about this ticket (an off-scale or unreadable label), so the ticket ran; the grid wears a grey mark. The reason text only, never the ticket.
422
+ ...(ticketUnsure === null ? {} : { ticketFilter: { unsure: ticketUnsure } }),
423
+ ...(prRecord === null ? {} : { pr: prRecord }),
415
424
  // F118: replay reads this; report-only. `dirty` is deliberately omitted —
416
425
  // it can't be known without a shell, and null = unknown, never faked.
417
426
  code: (() => { const { version, sha } = codeVersion(); return { version, sha }; })(),
package/src/runexport.js CHANGED
@@ -60,6 +60,8 @@ export function checkExportable(row, name) {
60
60
  const signed = signedSpecForRun(row, records);
61
61
  if (!signed) return { ok: false, why: `the signed job file for "${name}" is not beside its log, or none matches the hash it ran under` };
62
62
  const spec = signed.spec;
63
+ // MCP + tickets (hamr's ruling 2026-11-02): no export for a job with an `mcp` source. A bundle runs without the person's MCP config, and the server and its tools are theirs, not the bundle's.
64
+ if (spec.mcp !== undefined) return { ok: false, why: `"${name}" uses an MCP${typeof spec.mcp?.server === 'string' ? ` (${spec.mcp.server})` : ''}, and a job that uses an MCP cannot be exported` };
63
65
  // repo jobs only for now ($0): say which kind this is
64
66
  if (spec.verdictType !== 'green') return { ok: false, why: `${REPO_ONLY}: "${name}" is a rubric job, graded by a judge (${spec.verdictType ?? 'no class recorded'})` };
65
67
  if (Array.isArray(spec.inputs) && spec.inputs.some((/** @type {any} */ i) => isUrl(i?.value))) return { ok: false, why: `${REPO_ONLY}: "${name}" reads a page link` };
package/src/runlist.js CHANGED
@@ -58,7 +58,8 @@ export function runlistPath(home) {
58
58
  }
59
59
 
60
60
  /**
61
- * @typedef {{ at: string, runid: string, job: string, spine: string, patient: string|null, via: 'run-u'|'bundle'|'backfill', pid?: number, capUsd?: number, leg?: number }} RunRow
61
+ * @typedef {{ at: string, runid: string, job: string, spine: string, patient: string|null, via: 'run-u'|'bundle'|'backfill', pid?: number, capUsd?: number, leg?: number, ticket?: number }} RunRow
62
+ * `ticket` (a Tickets run, ITEM33-BUILD R6): the ticket number this run reads; older rows have none.
62
63
  * `pid`/`capUsd` (optional; older and backfilled rows carry neither): the runner's process id and the
63
64
  * leg's $ cap — what the monthly limit holds while that pid is a live bareloop runner (src/monthly.js).
64
65
  * `leg` (P5-R; only on a row {@link readRunList} FOLDED from `leg-start` entries, i.e. a RESUMED run):
@@ -105,7 +106,7 @@ export function appendRun(row, opts = {}) {
105
106
 
106
107
  /**
107
108
  * @typedef {{ runid: string, type: 'settled'|'released', by: string, at: string, reason?: string, words?: string, spentUsd?: number, spendComplete?: boolean, leg?: number }} RunEvent
108
- * `words` (2026-10-19): on a `settled` with `reason: 'refused before start'`, the plain refusal the panel shows for that run (it has no spine).
109
+ * `words` (2026-10-19): on a `settled` with `reason: 'refused before start'` (or, R5, `reason: 'skipped'`: a ticket the job's filter did not let through), the plain words the panel shows for that run (it has no spine).
109
110
  * `leg` (P5-R): which leg of the run the write-back is about; absent = leg 1 (every entry written before P5-R).
110
111
  * A resumed run is ONE row, so `settled`/`released` are per leg: a later leg's `released` gives back THAT leg's
111
112
  * claim and never removes the run.
@@ -52,6 +52,7 @@ export const SCHEDULE_WORDS = Object.freeze({
52
52
  weekly: 'Every <day> at HH:MM',
53
53
  'file-updated': 'When <file> is updated',
54
54
  'new-file': 'When a new file arrives in <folder>',
55
+ 'new-ticket': 'When a new ticket arrives in <input>',
55
56
  }),
56
57
  // RULED 2026-10-15: the Needs-you pill of a schedule that gave up (hamr may reword)
57
58
  gaveUpPill: 'Check',
@@ -59,11 +60,41 @@ export const SCHEDULE_WORDS = Object.freeze({
59
60
  problemNext: 'next: fix it in Cancel / modify schedule',
60
61
  monthNext: 'next: raise the limit in Settings, or it starts on the 1st',
61
62
  acceptWaiting: 'waiting for your Accept (the next run does not wait)',
63
+ // R7 (piece 9, fwd SCHEDULE_WAITING_SAY): a schedule signed with the job on the New job card is off until the job's first green run (a rubric job: until that run is accepted)
64
+ waiting: 'Schedule waiting for a green run',
62
65
  scheduleGroup: 'schedule',
63
66
  notGreen: 'This job has not had a good run yet. Run it by hand and get it right first; then you can set when it runs. A rubric job also needs your Accept once. Nothing was changed.',
67
+ // R7: the New job card's Schedule row (fwd's three words and two hints; the rubric hint is bareloop's own, because a judged green waits for the Accept)
68
+ card: Object.freeze({
69
+ label: 'Schedule',
70
+ options: Object.freeze({ hand: 'By hand', 'new-ticket': 'When a new ticket arrives', daily: 'Every day at HH:MM' }),
71
+ hint: 'off until the first green run, then turns on',
72
+ rubricHint: 'off until the first green run is accepted, then turns on',
73
+ ticketHint: 'the first run reads the newest ticket at the time it starts; older tickets never run',
74
+ }),
64
75
  stale: 'What you were shown is not what is on the card now. Nothing was signed. Look again, then sign.',
65
76
  });
66
77
 
78
+ /** `&`, `<`, `>` and quotes made safe for page markup. @param {string} s */
79
+ const markup = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
80
+
81
+ /**
82
+ * R7 (piece 9): the New job card's Schedule row is served with its words from {@link SCHEDULE_WORDS}`.card`, never typed into the page: each token in `index.html` is replaced by
83
+ * the server when the page is sent (the way the port is), so a reword is ONE edit here. @returns {Record<string, string>} token -> escaped words
84
+ */
85
+ export function scheduleCardFill() {
86
+ const c = SCHEDULE_WORDS.card;
87
+ return {
88
+ __BARELOOP_SCHED_LABEL__: markup(c.label),
89
+ __BARELOOP_SCHED_OPT_HAND__: markup(c.options.hand),
90
+ __BARELOOP_SCHED_OPT_TICKET__: markup(c.options['new-ticket']),
91
+ __BARELOOP_SCHED_OPT_DAILY__: markup(c.options.daily),
92
+ __BARELOOP_SCHED_HINT__: markup(c.hint),
93
+ __BARELOOP_SCHED_HINT_RUBRIC__: markup(c.rubricHint),
94
+ __BARELOOP_SCHED_HINT_TICKET__: markup(c.ticketHint),
95
+ };
96
+ }
97
+
67
98
  /**
68
99
  * What starts the job, in words. `null` (by hand) has no sentence.
69
100
  * @param {Trigger|null|undefined} t @param {string} [home]
@@ -75,6 +106,7 @@ export function scheduledWords(t, home) {
75
106
  if (t.kind === 'weekdays') return `Weekdays at ${hhmm(t)}`;
76
107
  if (t.kind === 'weekly') return `${DAY_PLURAL[/** @type {keyof typeof DAY_PLURAL} */ (t.day)] ?? t.day} at ${hhmm(t)}`;
77
108
  if (t.kind === 'file-updated') return `When ${basename(t.path)} is updated`;
109
+ if (t.kind === 'new-ticket') return `When a new ticket arrives in ${t.input}`;
78
110
  const folder = tilde(/** @type {{folder: string}} */ (t).folder, home);
79
111
  return `When a new file arrives in ${folder.endsWith('/') ? folder : `${folder}/`}`;
80
112
  }
@@ -106,6 +138,9 @@ export function nextInWords(ms, now) {
106
138
  return hours < 48 ? `next in ${hours}h` : `next in ${Math.floor(hours / 24)}d`;
107
139
  }
108
140
 
141
+ /** R9 (fwd 9b.3): the one red line for a ticket look that could not read, with its cause (never "0 new"). The look cadence is fixed at 15 minutes. @param {{at: number, why: string}} p */
142
+ export const lookProblemWords = (p) => `could not read the tickets: ${String(p.why).trim().replace(/\.$/, '').replace(/([?!])$/, '$1')}${/[?!]$/.test(String(p.why).trim()) ? '' : '.'} It looks again in 15 minutes.`;
143
+
109
144
  /**
110
145
  * NEXT of a scheduled job: one sentence, first match wins.
111
146
  * 1. a run of this job is waiting for the person's Accept (the next scheduled run does NOT wait for it, T7);
@@ -113,16 +148,17 @@ export function nextInWords(ms, now) {
113
148
  * 3. a clock kind with a next slot; 4. a file kind that is armed; 5. not armed yet.
114
149
  * A last outcome of `refused` goes in front of 3-5, so a trigger that cannot start is never silent.
115
150
  * `red` is the typed flag for "the person must act": the page paints it and never guesses from the text.
116
- * @param {{trigger: Trigger, armed: boolean, nextSlotMs: number|null, lastOutcome: any, waitingRunNo: number|null, now: number, retryInMs?: number|null, gaveUp?: any}} f
151
+ * @param {{trigger: Trigger, armed: boolean, nextSlotMs: number|null, lastOutcome: any, waitingRunNo: number|null, now: number, retryInMs?: number|null, gaveUp?: any, lookProblem?: {at: number, why: string}|null}} f
117
152
  * `lastOutcome` = the newest outcome row of the CURRENT signing (`kind`, `at` in ms, `why`, `leftUsd`, `needUsd`, `atLeast`)
118
153
  * @returns {{text: string, red: boolean}}
119
154
  */
120
155
  export function scheduledNextFor(f) {
121
- const { trigger, armed, nextSlotMs, lastOutcome, waitingRunNo, now, retryInMs = null, gaveUp = null } = f;
156
+ const { trigger, armed, nextSlotMs, lastOutcome, waitingRunNo, now, retryInMs = null, gaveUp = null, lookProblem = null } = f;
122
157
  /** @param {string} text @param {boolean} [red] */
123
158
  const say = (text, red = false) => ({ text, red });
124
159
  if (waitingRunNo !== null) return say(`Run ${waitingRunNo} is waiting for your Accept. The next scheduled run does not wait for it.`);
125
160
  if (gaveUp && typeof gaveUp === 'object') return say(gaveUpNextWords(gaveUp.why), true);
161
+ if (lookProblem) return say(`The last look ${lookProblemWords(lookProblem)}`, true); // R9 (fwd 9b.3): a look that could not read is never "waiting for a new ticket"
126
162
  const last = lastOutcome && typeof lastOutcome === 'object' ? lastOutcome : null;
127
163
  const sameMonth = last !== null && sameMonthAs(last.at, now);
128
164
  if (last !== null && last.kind === 'monthly-exhausted' && sameMonth && typeof last.leftUsd === 'number' && typeof last.needUsd === 'number') {
@@ -134,6 +170,7 @@ export function scheduledNextFor(f) {
134
170
  if (!armed) return say(`${lead}Not armed yet: the panel arms it on its next check.`, red);
135
171
  if (trigger.kind === 'file-updated') return say(`${lead}Watching for it. A run starts when its contents change.`, red);
136
172
  if (trigger.kind === 'new-file') return say(`${lead}Watching for it. A run starts for each new file.`, red);
173
+ if (trigger.kind === 'new-ticket') return say(`${lead}Watching for it. A run starts for each new ticket.`, red);
137
174
  if (nextSlotMs === null) return say(`${lead}Not armed yet: the panel arms it on its next check.`, red);
138
175
  return say(`${lead}Next run ${slotWords(nextSlotMs)}.`, red);
139
176
  }
@@ -207,7 +244,9 @@ export function startedWords(rec, atMs) {
207
244
  if (!rec || typeof rec !== 'object') return `${SCHEDULE_WORDS.byHand}${when}`;
208
245
  const trig = typeof rec.trigger === 'string' ? rec.trigger : '';
209
246
  let how;
210
- if (rec.kind === 'file') {
247
+ if (rec.kind === 'ticket') {
248
+ how = `By a new ticket: #${rec.ticket}`;
249
+ } else if (rec.kind === 'file') {
211
250
  const name = basename(String(rec.file ?? ''));
212
251
  how = isNewFile(rec) ? `By a new file: ${name}` : `By a file update: ${name}`;
213
252
  } else {
@@ -225,6 +264,7 @@ export function startedWords(rec, atMs) {
225
264
  */
226
265
  export function startedAuditWords(rec, originNo) {
227
266
  const from = originNo === null ? '' : ` · from run-${originNo}`;
267
+ if (rec.kind === 'ticket') return `started by the schedule · new ticket #${rec.ticket}${from}`;
228
268
  if (rec.kind === 'file') return `started by the schedule · ${isNewFile(rec) ? 'new file' : 'file update'} ${basename(String(rec.file ?? ''))}${from}`;
229
269
  const slot = typeof rec.slot === 'number' ? ` · slot ${two(new Date(rec.slot).getHours())}:${two(new Date(rec.slot).getMinutes())}` : '';
230
270
  return `started by the schedule · ${lowerFirst(String(rec.trigger ?? ''))}${slot}${from}${rec.catchUp === true ? ' · catch-up' : ''}`;
@@ -253,12 +293,13 @@ export function skippedWords(row, short = false) {
253
293
  /**
254
294
  * Job tab, "Schedule": the job's schedule NOW and what it is bound to. The first part IS the Run tab's line ({@link scheduledWords}),
255
295
  * first letter lowered, so the two can never disagree.
256
- * @param {{trigger: Trigger|null, originNo: number|null, model: string|null, destination: string|null, home?: string}} f
296
+ * @param {{trigger: Trigger|null, originNo: number|null, model: string|null, destination: string|null, home?: string, waiting?: boolean}} f `waiting` (R7): signed with the job and still off
257
297
  */
258
298
  export function jobScheduleWords(f) {
259
299
  const w = f.trigger ? scheduledWords(f.trigger, f.home) : null;
260
300
  if (w === null) return 'none';
261
301
  const parts = [lowerFirst(w)];
302
+ if (f.waiting === true) parts.push(lowerFirst(SCHEDULE_WORDS.waiting));
262
303
  if (f.originNo !== null) parts.push(`from run-${f.originNo}`);
263
304
  if (f.model) parts.push(f.model);
264
305
  if (f.destination) parts.push(tilde(f.destination, f.home));
@@ -284,6 +325,7 @@ export function scheduleSignFor(f) {
284
325
 
285
326
  /** Audit schedule section, the `this run` words of a run the schedule started (the head already says which schedule and from where). @param {any} rec `trigger.json` */
286
327
  export function sectionThisRunWords(rec) {
328
+ if (rec.kind === 'ticket') return `started by the schedule · new ticket #${rec.ticket}`;
287
329
  if (rec.kind === 'file') return `started by the schedule · ${isNewFile(rec) ? 'new file' : 'file update'} ${basename(String(rec.file ?? ''))}`;
288
330
  let late = '';
289
331
  if (rec.catchUp === true) {
package/src/source.js CHANGED
@@ -22,6 +22,7 @@
22
22
  // (src/kinds.js) already use for a $0 precheck a runner has to print and act
23
23
  // on rather than catch.
24
24
 
25
+ import { execFileSync } from 'node:child_process';
25
26
  import { createHash } from 'node:crypto';
26
27
  import { tmpdir } from 'node:os';
27
28
  import { existsSync, lstatSync, readFileSync } from 'node:fs';
@@ -33,6 +34,9 @@ import { MAX_BUFFER } from './kinds.js';
33
34
  import { PROVIDER_TIMEOUT_MS } from './clock.js';
34
35
  import { scanSecrets, SECRET_PATTERNS, SECRET_PATTERN_NAMES } from './validate.js';
35
36
  import { fetchPageText, isWebUrl } from './pagefetch.js';
37
+ import { parseTicketList } from './ticketshape.js';
38
+ import { readTicket } from './ticket.js';
39
+ import { proveTicketLine } from './ticketrepo.js';
36
40
 
37
41
  /** @typedef {{stop: string, code: string}} SourceRefusal a named, non-throwing stop */
38
42
 
@@ -179,6 +183,40 @@ export function looksLikeRepoSource(source) {
179
183
  } catch { return false; }
180
184
  }
181
185
 
186
+ /**
187
+ * The files of a repo's COMMITTED tree (`git ls-tree -r HEAD`: what a job's worktree holds), or null when git cannot read it.
188
+ * @param {string} root the repo's (or worktree's) top folder @returns {string[]|null}
189
+ */
190
+ export function repoTrackedFiles(root) {
191
+ try { return execFileSync('git', ['-C', root, 'ls-tree', '-r', '--name-only', '-z', 'HEAD'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 256 * 1024 * 1024 }).split('\0').filter(Boolean); } catch { return null; }
192
+ }
193
+
194
+ /**
195
+ * R7b (F287): the first piece of a repo Destination (comma or line separated) that the repo's COMMITTED tree does not have, or null when every piece exists.
196
+ * A piece is a folder (`src`, `src/`), a file, or a glob whose folder part exists (`src/**\/*.js`); `.` is the repo root. A tree that cannot be read is null:
197
+ * the copy step refuses that repo with its own words, this check never invents a refusal from a failure.
198
+ * @param {string} root the repo's top folder @param {string} destination @returns {string|null}
199
+ */
200
+ export function destinationMissingInRepo(root, destination) {
201
+ const files = repoTrackedFiles(root);
202
+ if (files === null) return null;
203
+ const hasDir = (/** @type {string} */ dir) => files.some((f) => f.startsWith(`${dir}/`));
204
+ for (const raw of destination.split(/[,\n]/)) {
205
+ const piece = raw.trim();
206
+ if (piece === '') continue;
207
+ const t = piece.replace(/^(\.\/)+/, '').replace(/\/+$/, '');
208
+ if (t === '' || t === '.') continue;
209
+ const wild = t.search(/[*?[{]/);
210
+ if (wild !== -1) {
211
+ const dir = t.slice(0, wild).includes('/') ? t.slice(0, t.slice(0, wild).lastIndexOf('/')) : '';
212
+ if (dir === '' || hasDir(dir)) continue;
213
+ return piece;
214
+ }
215
+ if (!files.includes(t) && !hasDir(t)) return piece;
216
+ }
217
+ return null;
218
+ }
219
+
182
220
  /** @param {Buffer} buf @returns {boolean} */
183
221
  function hasNulByte(buf) {
184
222
  // "first 8 KB" (PRD/M2 text) — a NUL anywhere further in a huge log-shaped
@@ -1174,10 +1212,14 @@ export function nonRepoSourceMessage(kind) {
1174
1212
  * file. A known secret shape in its content is NOT a refusal (masked where recorded, as the P6 worktree door does).
1175
1213
  * A folder value is checked for existence and tracking only (its files are the repo's own, which the worktree door
1176
1214
  * already masks). Reads the tree; writes nothing.
1215
+ * MCP + tickets piece 1a: with `opts.mcp` (the job's signed `{server, tools}`), a line 2+ whose value is a GitHub issues address is a TICKET line, not a repo path: it is proven at $0
1216
+ * as "the MCP can read it" (`proveTicketLine`: server named in the person's config, not remote, `issue_read` signed). Only one such line; it is read and frozen at run start.
1217
+ * Without `opts.mcp` the same line is the old refusal ("only files inside the repo for now").
1177
1218
  * @param {{n: number, label: string, value: string}[]} inputs the parsed Inputs (`parseInputs`)
1219
+ * @param {{mcp?: {server: string, tools: string[]}, configPath?: string}} [opts]
1178
1220
  * @returns {Promise<{ok: true, repo: string, root: string|null}|{ok: false, error: string}>} `repo` = line 1's absolute path; `root` = the git root it sits in (null when line 1 alone was given and it is not in a git repo)
1179
1221
  */
1180
- export async function proveInputFiles(inputs) {
1222
+ export async function proveInputFiles(inputs, opts = {}) {
1181
1223
  const first = inputs[0];
1182
1224
  if (!first) return { ok: false, error: 'Inputs, line 1: the repo is required' };
1183
1225
  /** @param {number} n @param {string} msg @returns {{ok: false, error: string}} */
@@ -1195,8 +1237,16 @@ export async function proveInputFiles(inputs) {
1195
1237
  const root = found.dir;
1196
1238
  const rootReal = await realpath(root);
1197
1239
  const repoReal = await realpath(repo);
1240
+ let ticketLines = 0;
1198
1241
  for (const inp of inputs.slice(1)) {
1199
1242
  const { n, label, value } = inp;
1243
+ if (opts.mcp !== undefined && parseTicketList(value).ok) {
1244
+ if (++ticketLines > 1) return bad(n, 'only one ticket address per job - a second issues or pulls address is not read');
1245
+ const listed = parseTicketList(value);
1246
+ const proof = proveTicketLine(opts.mcp, opts.configPath === undefined ? {} : { configPath: opts.configPath }, listed.ok ? listed.kind : 'issue');
1247
+ if (!proof.ok) return bad(n, proof.error);
1248
+ continue;
1249
+ }
1200
1250
  if (/^search$/i.test(label) || /^[a-z][a-z0-9+.-]*:\/\//i.test(value)) return bad(n, 'only files inside the repo for now');
1201
1251
  // like-for-like: resolve against the repo as the REAL filesystem sees it, so a repo reached through a symlinked parent
1202
1252
  // compares against `rootReal` in the same spelling (a symlinked INPUT FILE is still refused below, by lstat)
@@ -1345,10 +1395,16 @@ export function looksLikeRubricInput(value) {
1345
1395
  * copy. It is written into the prepared tree, committed as the new seed (so the page is never read as a worker write), and
1346
1396
  * `source.json` is rewritten (new sha256 per input, new seed, `draftSha256` keeps what the look saw). Nothing but the text of a
1347
1397
  * recorded web address is ever refetched; a job with only file inputs returns at once and changes nothing.
1348
- * @param {{into: string, fetchUrl?: (url: string) => Promise<{ok: true, text: string, url: string}|{ok: false, error: string}>}} o `into` - the prepared copy (source.json + tree/)
1349
- * @returns {Promise<{ok: true, refreshed: string[], seed: string|null}|{ok: false, error: string}>}
1398
+ *
1399
+ * MCP + tickets (piece 1): with `ticket` (a job that reads tickets: `{number, mcp}`, the number per run from `--ticket`), the ONE input row whose address is a
1400
+ * GitHub issues list is read through the person's MCP server instead of the page reader: the ticket's reply, MASKED with the one secret inventory before the sha
1401
+ * (a secret in a ticket is masked, never refused; page rows keep their refusal), is the run's frozen input. The row keeps its signed `url` (the list address) and
1402
+ * gains `mcp:{server,exposed,missing,calls}`, `ticket:{number,title,state,source}` and `masked:<count>`. Any refusal (server or tool missing, a device login,
1403
+ * an empty reply, no list row or two) is the same plain `did not start` words at $0.
1404
+ * @param {{into: string, fetchUrl?: (url: string) => Promise<{ok: true, text: string, url: string}|{ok: false, error: string}>, ticket?: {number: number, mcp: {server: string, tools: string[]}}}} o `into` - the prepared copy (source.json + tree/)
1405
+ * @returns {Promise<{ok: true, refreshed: string[], seed: string|null, ticketText?: string}|{ok: false, error: string}>}
1350
1406
  */
1351
- export async function refreezeUrlInputs({ into, fetchUrl = (u) => fetchPageText(u) }) {
1407
+ export async function refreezeUrlInputs({ into, fetchUrl = (u) => fetchPageText(u), ticket }) {
1352
1408
  const read = await readSourceManifest(into);
1353
1409
  if (read.stop !== null) return { ok: false, error: read.stop };
1354
1410
  if (!read.present || !read.manifest) return { ok: true, refreshed: [], seed: null };
@@ -1356,9 +1412,21 @@ export async function refreezeUrlInputs({ into, fetchUrl = (u) => fetchPageText(
1356
1412
  const rows = Array.isArray(manifest.inputs) ? manifest.inputs.filter((/** @type {any} */ r) => r && typeof r.url === 'string' && r.url !== '') : [];
1357
1413
  if (rows.length === 0) return { ok: true, refreshed: [], seed: null };
1358
1414
  const tree = join(resolve(into), 'tree');
1359
- /** @type {{row: any, buf: Buffer}[]} */
1415
+ /** @type {{row: any, buf: Buffer, ticket?: import('./ticket.js').Ticket}[]} */
1360
1416
  const fresh = [];
1417
+ const listRows = ticket === undefined ? [] : rows.filter((/** @type {any} */ r) => parseTicketList(r.url).ok);
1418
+ if (ticket !== undefined && listRows.length !== 1) {
1419
+ return { ok: false, error: listRows.length === 0
1420
+ ? 'This job reads a ticket, but none of its Inputs is the issues or pulls page of a GitHub repository (owner/repo/issues or owner/repo/pulls). The run did not start. Nothing spent.'
1421
+ : 'This job reads one ticket, but more than one of its Inputs is a GitHub issues or pulls address. The run did not start. Nothing spent.' };
1422
+ }
1361
1423
  for (const row of rows) {
1424
+ if (ticket !== undefined && listRows[0] === row) {
1425
+ const t = await readTicket({ mcp: ticket.mcp, listUrl: row.url, number: ticket.number });
1426
+ if (!t.ok) return { ok: false, error: `Input "${row.label}": ${t.error}. The run did not start. Nothing spent.` };
1427
+ fresh.push({ row, buf: Buffer.from(t.ticket.text, 'utf8'), ticket: t.ticket });
1428
+ continue;
1429
+ }
1362
1430
  const got = await fetchUrl(row.url);
1363
1431
  if (!got.ok) return { ok: false, error: `Input "${row.label}": ${got.error}. The run did not start. Nothing spent.` };
1364
1432
  const leak = secretPatternNames(got.text);
@@ -1374,9 +1442,14 @@ export async function refreezeUrlInputs({ into, fetchUrl = (u) => fetchPageText(
1374
1442
  if (!head.ok) return { ok: false, error: `git rev-parse HEAD failed in ${tree}: ${head.err}. The run did not start. Nothing spent.` };
1375
1443
  const seed = head.out.trim();
1376
1444
  const byLabel = new Map(fresh.map((f) => [f.row.label, f.buf]));
1445
+ const ticketByLabel = new Map(fresh.filter((f) => f.ticket !== undefined).map((f) => [f.row.label, /** @type {import('./ticket.js').Ticket} */ (f.ticket)]));
1377
1446
  const inputs = manifest.inputs.map((/** @type {any} */ r) => {
1378
1447
  const buf = byLabel.get(r.label);
1379
- return buf === undefined || typeof r.url !== 'string' ? r : { ...r, draftSha256: r.draftSha256 ?? r.sha256, sha256: sha256Hex(buf) };
1448
+ if (buf === undefined || typeof r.url !== 'string') return r;
1449
+ const next = { ...r, draftSha256: r.draftSha256 ?? r.sha256, sha256: sha256Hex(buf) };
1450
+ const tk = ticketByLabel.get(r.label);
1451
+ if (tk === undefined) return next;
1452
+ return { ...next, mcp: tk.record, ticket: { number: tk.number, title: tk.title, state: tk.state, source: tk.source }, masked: tk.masked };
1380
1453
  });
1381
1454
  const files = Array.isArray(manifest.files) ? manifest.files.map((/** @type {any} */ m) => {
1382
1455
  const hit = inputs.find((/** @type {any} */ r) => typeof r.url === 'string' && r.rel === `input/${m.path}`);
@@ -1386,7 +1459,8 @@ export async function refreezeUrlInputs({ into, fetchUrl = (u) => fetchPageText(
1386
1459
  }) : manifest.files;
1387
1460
  const next = { ...manifest, inputs, files, seed, refrozenAt: new Date().toISOString() };
1388
1461
  await writeFile(join(resolve(into), 'source.json'), `${JSON.stringify(next, null, 2)}\n`);
1389
- return { ok: true, refreshed: rows.map((/** @type {any} */ r) => r.label), seed };
1462
+ const read1 = fresh.find((f) => f.ticket !== undefined)?.ticket;
1463
+ return { ok: true, refreshed: rows.map((/** @type {any} */ r) => r.label), seed, ...(read1 === undefined ? {} : { ticketText: read1.text }) };
1390
1464
  }
1391
1465
 
1392
1466
  /**