bareloop 0.54.1 → 0.56.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 (149) hide show
  1. package/CHANGELOG.md +122 -0
  2. package/bareloop.context.md +67 -6
  3. package/package.json +3 -3
  4. package/src/authorflow.js +217 -238
  5. package/src/authoring.js +22 -6
  6. package/src/authorjob.js +138 -30
  7. package/src/authorreadout.js +15 -4
  8. package/src/authorrun.js +13 -4
  9. package/src/authorscout.js +9 -6
  10. package/src/behaviour.js +14 -0
  11. package/src/blockasks.js +43 -0
  12. package/src/cardschedule.js +42 -0
  13. package/src/checkblock.js +772 -0
  14. package/src/checklist.js +128 -0
  15. package/src/checkpick.js +294 -0
  16. package/src/checksuggest.js +28 -0
  17. package/src/checkwords.js +27 -0
  18. package/src/cli.js +1 -1
  19. package/src/config.js +24 -1
  20. package/src/declaredclose.js +30 -1
  21. package/src/destpoint.js +151 -0
  22. package/src/draftspend.js +85 -0
  23. package/src/facts.js +8 -1
  24. package/src/factwords.js +14 -1
  25. package/src/fitcheck.js +5 -3
  26. package/src/job.js +81 -1
  27. package/src/jobblock.js +9 -0
  28. package/src/labelscan.js +11 -0
  29. package/src/launcher.js +3 -2
  30. package/src/mcpchecks.js +52 -0
  31. package/src/mcppick.js +36 -0
  32. package/src/mcpsources.js +77 -0
  33. package/src/mcpuse.js +97 -0
  34. package/src/natural.js +23 -0
  35. package/src/pagemap.js +20 -5
  36. package/src/panel/authorroutes.js +105 -18
  37. package/src/panel/authorsession.js +293 -44
  38. package/src/panel/index.html +873 -41
  39. package/src/panel/jobgrid.js +117 -0
  40. package/src/panel/jobplan.js +103 -35
  41. package/src/panel/scheduler.js +80 -13
  42. package/src/panel/schedules.js +189 -28
  43. package/src/panel/schedulestart.js +44 -13
  44. package/src/panel/server.js +471 -39
  45. package/src/panel/settingsroutes.js +133 -3
  46. package/src/panel/status.js +19 -1
  47. package/src/panel/tickets.js +44 -0
  48. package/src/pickrecord.js +163 -0
  49. package/src/placerule.js +355 -0
  50. package/src/plan.js +31 -2
  51. package/src/planrun.js +71 -15
  52. package/src/prcheckout.js +259 -0
  53. package/src/promptregisters.js +11 -0
  54. package/src/questionbox.js +112 -0
  55. package/src/readshim.js +3 -2
  56. package/src/revises.js +56 -0
  57. package/src/rowedit.js +115 -0
  58. package/src/rubricstep.js +265 -132
  59. package/src/run.js +19 -2
  60. package/src/runexport.js +2 -0
  61. package/src/runlist.js +3 -2
  62. package/src/schedulewords.js +46 -4
  63. package/src/source.js +81 -7
  64. package/src/stepmcp.js +86 -0
  65. package/src/ticket.js +113 -0
  66. package/src/ticketfilter.js +76 -0
  67. package/src/ticketlabels.js +79 -0
  68. package/src/ticketmcp.js +111 -0
  69. package/src/ticketnext.js +35 -0
  70. package/src/ticketrepo.js +98 -0
  71. package/src/ticketschedule.js +32 -0
  72. package/src/ticketshape.js +45 -0
  73. package/src/tools.js +9 -0
  74. package/src/trigger.js +14 -2
  75. package/src/triggerclock.js +7 -3
  76. package/src/triggerfiles.js +19 -11
  77. package/src/triggertickets.js +244 -0
  78. package/src/userrun.js +191 -10
  79. package/src/validate.js +3 -1
  80. package/src/worktree.js +43 -1
  81. package/types/authorflow.d.ts +86 -93
  82. package/types/authorjob.d.ts +35 -4
  83. package/types/authorreadout.d.ts +4 -3
  84. package/types/authorscout.d.ts +4 -2
  85. package/types/behaviour.d.ts +12 -0
  86. package/types/blockasks.d.ts +37 -0
  87. package/types/cardschedule.d.ts +24 -0
  88. package/types/checkblock.d.ts +361 -0
  89. package/types/checklist.d.ts +134 -0
  90. package/types/checkpick.d.ts +160 -0
  91. package/types/checksuggest.d.ts +30 -0
  92. package/types/checkwords.d.ts +14 -0
  93. package/types/config.d.ts +7 -0
  94. package/types/declaredclose.d.ts +4 -0
  95. package/types/destpoint.d.ts +89 -0
  96. package/types/draftspend.d.ts +37 -0
  97. package/types/factwords.d.ts +7 -0
  98. package/types/fitcheck.d.ts +7 -1
  99. package/types/job.d.ts +13 -0
  100. package/types/jobblock.d.ts +9 -0
  101. package/types/labelscan.d.ts +7 -0
  102. package/types/launcher.d.ts +2 -2
  103. package/types/mcpchecks.d.ts +8 -0
  104. package/types/mcppick.d.ts +33 -0
  105. package/types/mcpsources.d.ts +51 -0
  106. package/types/mcpuse.d.ts +15 -0
  107. package/types/natural.d.ts +2 -0
  108. package/types/pagemap.d.ts +6 -1
  109. package/types/panel/authorroutes.d.ts +11 -2
  110. package/types/panel/authorsession.d.ts +69 -3
  111. package/types/panel/jobgrid.d.ts +405 -0
  112. package/types/panel/jobplan.d.ts +55 -11
  113. package/types/panel/scheduler.d.ts +7 -2
  114. package/types/panel/schedules.d.ts +124 -4
  115. package/types/panel/schedulestart.d.ts +21 -3
  116. package/types/panel/server.d.ts +432 -10
  117. package/types/panel/settingsroutes.d.ts +4 -2
  118. package/types/panel/status.d.ts +16 -2
  119. package/types/panel/tickets.d.ts +61 -0
  120. package/types/pickrecord.d.ts +100 -0
  121. package/types/placerule.d.ts +194 -0
  122. package/types/plan.d.ts +1 -0
  123. package/types/prcheckout.d.ts +151 -0
  124. package/types/questionbox.d.ts +87 -0
  125. package/types/readshim.d.ts +4 -3
  126. package/types/revises.d.ts +23 -0
  127. package/types/rowedit.d.ts +32 -0
  128. package/types/rubricstep.d.ts +100 -48
  129. package/types/run.d.ts +27 -1
  130. package/types/runlist.d.ts +6 -3
  131. package/types/schedulewords.d.ts +29 -2
  132. package/types/source.d.ts +40 -4
  133. package/types/stepmcp.d.ts +40 -0
  134. package/types/ticket.d.ts +114 -0
  135. package/types/ticketfilter.d.ts +34 -0
  136. package/types/ticketlabels.d.ts +44 -0
  137. package/types/ticketmcp.d.ts +84 -0
  138. package/types/ticketnext.d.ts +33 -0
  139. package/types/ticketrepo.d.ts +118 -0
  140. package/types/ticketschedule.d.ts +21 -0
  141. package/types/ticketshape.d.ts +37 -0
  142. package/types/tools.d.ts +1 -0
  143. package/types/trigger.d.ts +9 -1
  144. package/types/triggerclock.d.ts +6 -2
  145. package/types/triggerfiles.d.ts +13 -5
  146. package/types/triggertickets.d.ts +110 -0
  147. package/types/userrun.d.ts +50 -0
  148. package/types/validate.d.ts +1 -0
  149. package/types/worktree.d.ts +19 -0
package/src/run.js CHANGED
@@ -18,6 +18,7 @@ import { runPlan } from './planrun.js';
18
18
  import { SMOKE_STORE, resolveHumanRuling } from './kinds.js';
19
19
  import { readShimArm } from './readshim.js';
20
20
  import { codeVersion } from './codeversion.js';
21
+ import { bindPlaceValues } from './placerule.js';
21
22
 
22
23
  /** @typedef {{code: string, path: string, detail?: string}} Red */
23
24
 
@@ -112,6 +113,10 @@ async function primitiveSmoke(workdir) {
112
113
  * never a step knob and never agent-selectable; absent, a judged stage instrument-stops as
113
114
  * a wiring gap rather than grading on whatever binding happened to be at hand. Its spend
114
115
  * lands on this ledger as `judge-round` (see `ACCOUNTED_ROUND_TYPES`).
116
+ * @param {Record<string, string>|null} [opts.placeValues] PLACE RULES (src/placerule.js): the values this run's start read for the spec's place-rule facts, by key. Bound
117
+ * as those facts' phrases on the run's own in-memory copy AFTER the approval check and the `job-start` record, so the hash checked and the hash recorded stay the
118
+ * SIGNED one and the signed spec is never changed; the planner and the close read the copy. Absent = the signed words.
119
+ * @param {{workflowKey: string, rows: object[]}|null} [opts.placeRead] PLACE RULES: what the run start read (rows {key, kind, found, value, was, reason}); recorded once as a `place-rules` event right after `job-start`. Absent = the job has none (or this is a resume, whose first leg wrote it).
115
120
  * @param {number} [opts.capRuns] shell-owned iteration cap for the plan flow's
116
121
  * CLOSE-FIX loop (a plan STEP runs under the strike ladder instead)
117
122
  * @param {number} [opts.strikeLimit] shell-owned strike ceiling for a plan step's ladder
@@ -206,6 +211,11 @@ async function primitiveSmoke(workdir) {
206
211
  * collision walk would mint a `-2` beside the work the resume exists to continue. The
207
212
  * fold's precedent exactly: the chain's state is DECLARED, never re-derived. Forwarded
208
213
  * verbatim to the plan flow; absent is the cold path.
214
+ * @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`
215
+ * @param {import('./ticketrepo.js').RepoTicketRecord|null} [opts.ticketRecord] MCP + tickets piece 1a: a CODE-REPO job's frozen ticket (metadata only: number, title,
216
+ * 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`,
217
+ * 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`).
218
+ * @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
219
  * @param {boolean|'cap'|'diff'} [opts.readShim=false] THE READ SHIM (src/readshim.js) —
210
220
  * WHICH ARM to run, threaded to the plan flow. The Phase 2 pre-registration's four:
211
221
  * `false` A0 — off (the default)
@@ -275,7 +285,7 @@ async function primitiveSmoke(workdir) {
275
285
  * deliberately NOT in the resumable/checkpoint set (`src/reuse.js`) — an
276
286
  * unknown in-flight state is not a known-safe resume point.
277
287
  */
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 }) {
288
+ 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, placeValues = null, placeRead = null }) {
279
289
  // THE READ SHIM's ARM, resolved at the door — the FIRST thing this entry does,
280
290
  // before the ledger, before the approval gate, before a byte of the spec is read.
281
291
  // An unrecognised spelling throws here at zero cost instead of being coerced by
@@ -384,7 +394,7 @@ export async function runJob(rawSpec, { approvals, workdir, provider, nativeProv
384
394
  emit('job-end', { outcome: 'job-red', ...spend() });
385
395
  return 'job-red';
386
396
  }
387
- const job = /** @type {any} */ (jv.job);
397
+ let job = /** @type {any} */ (jv.job);
388
398
  /** F103 — the two TIME figures, resolved once here and read the same way by
389
399
  * `runPlan`'s clock. An unreadable ruling resolves to `fresh: false` and folds as
390
400
  * it always did; `runPlan` is where it is refused, so this never has to. */
@@ -412,6 +422,10 @@ export async function runJob(rawSpec, { approvals, workdir, provider, nativeProv
412
422
  // (an absent baseUrl is the vendor's own host, not an unknown).
413
423
  provider: typeof job.provider === 'string' ? job.provider : null,
414
424
  ...(typeof job.baseUrl === 'string' ? { baseUrl: job.baseUrl } : {}),
425
+ ...(ticketRecord === null ? {} : { ticket: ticketRecord }),
426
+ // 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.
427
+ ...(ticketUnsure === null ? {} : { ticketFilter: { unsure: ticketUnsure } }),
428
+ ...(prRecord === null ? {} : { pr: prRecord }),
415
429
  // F118: replay reads this; report-only. `dirty` is deliberately omitted —
416
430
  // it can't be known without a shell, and null = unknown, never faked.
417
431
  code: (() => { const { version, sha } = codeVersion(); return { version, sha }; })(),
@@ -451,6 +465,9 @@ export async function runJob(rawSpec, { approvals, workdir, provider, nativeProv
451
465
  ? { priorReplans: Math.floor(resumeReplans.count), priorReplanGrantUsed: resumeReplans.grantUsed === true }
452
466
  : {}),
453
467
  });
468
+ // PLACE RULES: the approval was checked on the signed spec and `job-start` recorded its hash; only now does the run's own copy take the values its start read
469
+ if (placeValues !== null) job = bindPlaceValues(job, placeValues);
470
+ if (placeRead !== null) emit('place-rules', placeRead);
454
471
 
455
472
  // F140/PRD item 28 (c) — the backstop that fires on the ABSENCE of a
456
473
  // `job-end`. A provider promise that never settles (BA-25's class; 0.42.0
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
  /**
package/src/stepmcp.js ADDED
@@ -0,0 +1,86 @@
1
+ // A plan step's MCP tools (MCP+tickets piece 6, ITEM33-BUILD addendum 2026-11-02, R2c). A step that carries `mcpTools` starts the person's own MCP server ONCE for
2
+ // the step, with exactly those tools (`allow`), and hands the worker the bridge tools beside its shell and ctx tools; the bridge closes after the step's last try.
3
+ // "Only granted names reach the Loop" (menu-is-inventory): an unsigned tool does not exist for the worker, and the gate's allowlist (below) is the second wall.
4
+ // The start options are the one set every place bareloop starts an MCP uses (src/ticketmcp.js): PATH+HOME only, no provider key; cwd = the home folder.
5
+ import { createMCPBridge, discoverServers } from 'bare-agent/mcp';
6
+ import { TOOL_BY_VERB, toolAction } from './tools.js';
7
+ import { redactSecrets } from './validate.js';
8
+ import { configForServer, remoteRefusal, startRefusal, firstLine, mcpStartOpts, mcpToolName, MCP_TIMEOUT_MS } from './ticketmcp.js';
9
+
10
+ /**
11
+ * The gate `tools.allowlist` for a step that grants MCP tools. bareguard's allowlist is EXCLUSIVE for every action (fwd F116 measured it denying fs too), and its
12
+ * identity for an action is `action.tool ?? action.type` — bareloop's `toolAction` sets no `tool`, so the identity is the action TYPE (`read`, `write`, `edit`,
13
+ * `ctx_stash`...), never the tool name (`shell_read`): a list of names denies the step's own reads (tested against the real Gate). A bridge tool has no
14
+ * translation, so its type IS its name (`github_issue_read`). So: the types of the step's granted verbs, taken from `toolAction` itself (no second spelling that
15
+ * could drift), plus the signed bridge names. Anything else, an unsigned bridge tool included, is denied by `tools.allowlist.exclusive`.
16
+ * @param {string[]} granted the step's verbs @param {string} server @param {string[]} mcpTools @param {string} workdir @returns {string[]}
17
+ */
18
+ export function mcpAllowlist(granted, server, mcpTools, workdir) {
19
+ const types = new Set(granted.map((v) => /** @type {string} */ (toolAction(/** @type {Record<string, string>} */ (TOOL_BY_VERB)[v], { path: workdir }, workdir).type)));
20
+ return [...types, ...mcpTools.map((t) => mcpToolName(server, t))];
21
+ }
22
+
23
+ /**
24
+ * Mask every secret shape in a tool reply with the ONE inventory (`redactSecrets`, src/validate.js), at capture. A reply enters the worker's transcript and a
25
+ * model copies what it reads (into a file, into its reply): measured with a planted `ghp_` token, the raw reply reaches the model and every file the model copies
26
+ * it into, while the audit, the carry memo and the spine never carried it. Masking here, before the model sees it, closes that path at its source (the same rule
27
+ * the ticket freeze follows: a secret in a ticket is MASKED, never refused). Walks strings, arrays and plain objects; anything else passes through.
28
+ * @param {any} v @returns {any}
29
+ */
30
+ export function maskReply(v) {
31
+ if (typeof v === 'string') return redactSecrets(v);
32
+ if (Array.isArray(v)) return v.map(maskReply);
33
+ if (v !== null && typeof v === 'object') return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, maskReply(x)]));
34
+ return v;
35
+ }
36
+
37
+ /** wrap a bridge tool so its reply, and the message of an error it throws, are masked before they leave the tool @param {any} tool */
38
+ function maskedTool(tool) {
39
+ const inner = tool.execute;
40
+ tool.execute = async (/** @type {any} */ args, /** @type {any} */ ctx) => {
41
+ try { return maskReply(await inner.call(tool, args, ctx)); } catch (e) {
42
+ if (e instanceof Error) e.message = redactSecrets(e.message);
43
+ throw e;
44
+ }
45
+ };
46
+ return tool;
47
+ }
48
+
49
+ /**
50
+ * Start the bridge for one step. Throws an Error in plain words (the cause named, at $0, before any token) when the server is not configured, will not start, or
51
+ * lacks a tool the job signed; the bridge is closed before it throws.
52
+ * @param {{mcp: {server: string, tools: string[]}, mcpTools: string[], configPath?: string, home?: string, timeoutMs?: number}} o
53
+ * `configPath`/`home` are test seams (an explicit MCP config file; the config home); production passes neither.
54
+ * @returns {Promise<{server: string, mcpTools: string[], tools: any[], names: string[], close: () => Promise<void>}>}
55
+ */
56
+ export async function startStepMcp({ mcp, mcpTools, configPath: explicit, home, timeoutMs = MCP_TIMEOUT_MS }) {
57
+ const { server } = mcp;
58
+ const { file, remote } = configForServer(server, explicit, home);
59
+ if (!discoverServers([file]).has(server)) throw refusal(`${server} is not in ~/.mcp.json`);
60
+ if (remote) throw refusal(remoteRefusal(server));
61
+ /** @type {any} */ let bridge;
62
+ try {
63
+ // confirmServer must return exactly `true` (bare-agent), and only for the server the job signed
64
+ bridge = await createMCPBridge({ configPaths: [file], ...mcpStartOpts(), timeout: timeoutMs, callTimeout: timeoutMs, confirmServer: (/** @type {string} */ n) => n === server, allow: { [server]: mcpTools } });
65
+ const failed = bridge.errors.find((/** @type {any} */ e) => e.server === server);
66
+ if (failed) throw refusal(`${server} did not start: ${firstLine(failed.error)}`);
67
+ const lacking = bridge.missing?.[0];
68
+ if (lacking) throw refusal(`${server} does not offer ${lacking.tool}`);
69
+ const names = mcpTools.map((t) => mcpToolName(server, t));
70
+ const tools = bridge.tools.filter((/** @type {{name: string}} */ t) => names.includes(t.name)).map(maskedTool);
71
+ const absent = names.find((n) => !tools.some((/** @type {{name: string}} */ t) => t.name === n));
72
+ if (absent) throw refusal(`${server} does not offer ${absent.slice(server.length + 1)}`);
73
+ const b = bridge;
74
+ return { server, mcpTools, tools, names, close: async () => { try { await b.close(); } catch { /* already closed */ } } };
75
+ } catch (e) {
76
+ try { await bridge?.close(); } catch { /* already closed */ }
77
+ throw /** @type {any} */ (e)?.category ? e : refusal(startRefusal(server, e));
78
+ }
79
+ }
80
+
81
+ /** an Error whose message is the plain-words cause; `interpreter-red` is the class a step-setup fault already lands in @param {string} message */
82
+ function refusal(message) {
83
+ const err = /** @type {Error & {category?: string}} */ (new Error(message));
84
+ err.category = 'interpreter-red';
85
+ return err;
86
+ }
package/src/ticket.js ADDED
@@ -0,0 +1,113 @@
1
+ // MCP + tickets piece 1b (ITEM33-BUILD addendum 2026-11-02): the ONE source-neutral ticket shape, whether a ticket came from an MCP server or from a page
2
+ // read with barebrowse. The filter, the ledger rows, the run's record and the grid read only this shape; none of them knows the source.
3
+ // Every ticket text is MASKED with the one secret inventory (`redactSecrets`, src/validate.js) BEFORE the sha is taken, so the sha, the frozen bytes and every
4
+ // record carry the masked text (a secret in a ticket is masked, never refused). The honest ceiling: `SECRET_PATTERNS` are token shapes only.
5
+ import { createHash } from 'node:crypto';
6
+ import { readTicketMcp } from './ticketmcp.js';
7
+ import { fetchPageText } from './pagefetch.js';
8
+ import { isTicketNumber } from './ticketshape.js';
9
+ import { redactSecrets, scanSecrets } from './validate.js';
10
+
11
+ /**
12
+ * @typedef {object} Ticket
13
+ * @property {'mcp'|'page'} source
14
+ * @property {string} url the address of this ticket
15
+ * @property {number|null} number null = a page address that carries no ticket number (the grid row reads `#?`)
16
+ * @property {string} title
17
+ * @property {'open'|'closed'|'unknown'} state
18
+ * @property {string[]|null} labels null = not readable (a page); a priority filter finds none, and `unsure` never skips
19
+ * @property {string} text the MASKED text, as frozen
20
+ * @property {string} sha256 of the masked text's UTF-8 bytes
21
+ * @property {number} bytes
22
+ * @property {number} masked how many secret-shaped strings were masked (a count; never the values)
23
+ * @property {{server: string, exposed: string[], missing: Array<{server: string, tool: string}>, calls: Array<Record<string, any>>}|null} record the MCP read's own record (null for a page)
24
+ */
25
+
26
+ /** said on the plan card, in code-owned words, when a ticket comes from a page */
27
+ export const PAGE_TICKET_LIMIT_WORDS = 'A ticket read from a page may lack its body, and its labels and state may be missing.';
28
+
29
+ const TITLE_MAX = 200;
30
+ const clip = (/** @type {string} */ s) => s.trim().replace(/\s+/g, ' ').slice(0, TITLE_MAX);
31
+
32
+ /**
33
+ * Mask a text and measure it: the masked text, its sha256 and byte length, and how many secret shapes it carried.
34
+ * @param {string} raw @returns {{text: string, sha256: string, bytes: number, masked: number}}
35
+ */
36
+ export function maskTicketText(raw) {
37
+ const masked = scanSecrets(raw).length;
38
+ const text = redactSecrets(raw);
39
+ const buf = Buffer.from(text, 'utf8');
40
+ return { text, sha256: createHash('sha256').update(buf).digest('hex'), bytes: buf.length, masked };
41
+ }
42
+
43
+ /** the number a GitHub ticket or pull address carries, or null @param {string} url @returns {number|null} */
44
+ function numberOfUrl(url) {
45
+ const m = /\/(?:issues|pull)\/(\d+)(?:[/?#]|$)/.exec(url);
46
+ const n = m ? Number(m[1]) : NaN;
47
+ return isTicketNumber(n) ? n : null;
48
+ }
49
+
50
+ /**
51
+ * A ticket from the text of a PAGE (barebrowse act mode). Weaker than an MCP read, said plainly: the body may be missing (fwd F89: a page reader drops it),
52
+ * labels are null (not read from a page), and state is `closed` only when the text says `Closed`, else `unknown`.
53
+ * @param {string} rawText @param {string} url @returns {Ticket}
54
+ */
55
+ export function ticketFromPage(rawText, url) {
56
+ const m = maskTicketText(rawText);
57
+ const firstLine = m.text.split('\n').map((l) => l.replace(/^#+\s*/, '').trim()).find((l) => l !== '') ?? '';
58
+ return { source: 'page', url, number: numberOfUrl(url), title: clip(firstLine), state: /\bClosed\b/.test(m.text) ? 'closed' : 'unknown', labels: null, ...m, record: null };
59
+ }
60
+
61
+ /**
62
+ * A ticket from an MCP `issue_read` reply (a JSON document on GitHub's server; anything else keeps its text, with the first line as the title and the
63
+ * state and labels unknown).
64
+ * @param {string} rawText @param {string} url @param {number} number
65
+ * @param {Ticket['record']} record @returns {Ticket}
66
+ */
67
+ export function ticketFromMcp(rawText, url, number, record) {
68
+ const m = maskTicketText(rawText);
69
+ /** @type {any} */
70
+ let doc = null;
71
+ try { doc = JSON.parse(rawText); } catch { doc = null; }
72
+ const obj = doc !== null && typeof doc === 'object' && !Array.isArray(doc) ? doc : null;
73
+ const firstLine = m.text.split('\n').find((l) => l.trim() !== '') ?? '';
74
+ const title = clip(typeof obj?.title === 'string' ? redactSecrets(obj.title) : firstLine);
75
+ const st = typeof obj?.state === 'string' ? obj.state.toLowerCase() : '';
76
+ const state = st === 'open' || st === 'closed' ? st : 'unknown';
77
+ /** @type {string[]|null} */
78
+ let labels = null;
79
+ if (Array.isArray(obj?.labels)) {
80
+ labels = obj.labels.map((/** @type {any} */ l) => (typeof l === 'string' ? l : typeof l?.name === 'string' ? l.name : null)).filter((/** @type {any} */ l) => typeof l === 'string').map((/** @type {string} */ l) => redactSecrets(l));
81
+ }
82
+ return { source: 'mcp', url, number, title, state, labels, ...m, record };
83
+ }
84
+
85
+ /**
86
+ * The pull request a `pull_request_read` ticket froze, as the object the checkout reads (`head.sha`, `base.ref`, `base.sha`): the parsed, MASKED reply (the same bytes the
87
+ * sha256 covers - a sha is not a secret shape, so masking leaves it whole). Null when the text is not a JSON object.
88
+ * @param {Ticket} ticket @returns {Record<string, any>|null}
89
+ */
90
+ export function prRecordOfTicket(ticket) {
91
+ try {
92
+ const doc = JSON.parse(ticket.text);
93
+ return doc !== null && typeof doc === 'object' && !Array.isArray(doc) ? doc : null;
94
+ } catch { return null; }
95
+ }
96
+
97
+ /**
98
+ * Read one ticket, whatever its source. An MCP-backed row (`mcp` present) goes to the MCP reader; a page row to the page reader.
99
+ * @param {{mcp?: {server: string, tools: string[]}, listUrl?: string, number?: number, url?: string}} row
100
+ * @param {{configPath?: string, home?: string, timeoutMs?: number, fetchPage?: typeof fetchPageText}} [deps] test seams
101
+ * @returns {Promise<{ok: true, ticket: Ticket} | {ok: false, error: string}>}
102
+ */
103
+ export async function readTicket(row, deps = {}) {
104
+ if (row.mcp) {
105
+ const r = await readTicketMcp({ listUrl: String(row.listUrl ?? ''), number: /** @type {number} */ (row.number), mcp: row.mcp, ...(deps.configPath ? { configPath: deps.configPath } : {}), ...(deps.home ? { home: deps.home } : {}), ...(deps.timeoutMs ? { timeoutMs: deps.timeoutMs } : {}) });
106
+ if (!r.ok) return r;
107
+ return { ok: true, ticket: ticketFromMcp(r.text, r.url, /** @type {number} */ (row.number), r.record) };
108
+ }
109
+ const url = String(row.url ?? '');
110
+ const p = await (deps.fetchPage ?? fetchPageText)(url);
111
+ if (!p.ok) return { ok: false, error: p.error };
112
+ return { ok: true, ticket: ticketFromPage(p.text, p.url || url) };
113
+ }