bareloop 0.54.0 → 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 (139) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/bareloop.context.md +73 -12
  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/bridges.js +4 -3
  11. package/src/cardschedule.js +42 -0
  12. package/src/carrystore.js +1 -1
  13. package/src/checkpick.js +576 -0
  14. package/src/checksuggest.js +28 -0
  15. package/src/checkwords.js +25 -0
  16. package/src/cli.js +1 -1
  17. package/src/config.js +24 -1
  18. package/src/declaredclose.js +1 -1
  19. package/src/destpoint.js +149 -0
  20. package/src/draftspend.js +39 -0
  21. package/src/factwords.js +14 -1
  22. package/src/job.js +81 -1
  23. package/src/jobblock.js +9 -0
  24. package/src/labelscan.js +11 -0
  25. package/src/launcher.js +10 -6
  26. package/src/learn.js +6 -4
  27. package/src/mcpchecks.js +52 -0
  28. package/src/mcppick.js +36 -0
  29. package/src/mcpsources.js +77 -0
  30. package/src/mcpuse.js +97 -0
  31. package/src/natural.js +23 -0
  32. package/src/pagemap.js +5 -2
  33. package/src/panel/authorroutes.js +90 -15
  34. package/src/panel/authorsession.js +183 -21
  35. package/src/panel/index.html +686 -26
  36. package/src/panel/jobgrid.js +117 -0
  37. package/src/panel/jobplan.js +31 -15
  38. package/src/panel/scheduler.js +80 -13
  39. package/src/panel/schedules.js +189 -28
  40. package/src/panel/schedulestart.js +44 -13
  41. package/src/panel/server.js +438 -33
  42. package/src/panel/settingsroutes.js +133 -3
  43. package/src/panel/status.js +22 -2
  44. package/src/panel/tickets.js +44 -0
  45. package/src/pickrecord.js +145 -0
  46. package/src/plan.js +31 -2
  47. package/src/planrun.js +71 -15
  48. package/src/prcheckout.js +259 -0
  49. package/src/readshim.js +3 -2
  50. package/src/replay.js +6 -0
  51. package/src/reuse.js +3 -3
  52. package/src/revises.js +56 -0
  53. package/src/rubricstep.js +62 -16
  54. package/src/run.js +10 -1
  55. package/src/runexport.js +2 -0
  56. package/src/runlist.js +3 -2
  57. package/src/schedulewords.js +46 -4
  58. package/src/source.js +81 -7
  59. package/src/stepmcp.js +86 -0
  60. package/src/ticket.js +113 -0
  61. package/src/ticketfilter.js +76 -0
  62. package/src/ticketlabels.js +79 -0
  63. package/src/ticketmcp.js +111 -0
  64. package/src/ticketnext.js +35 -0
  65. package/src/ticketrepo.js +98 -0
  66. package/src/ticketschedule.js +32 -0
  67. package/src/ticketshape.js +45 -0
  68. package/src/tools.js +9 -0
  69. package/src/trigger.js +14 -2
  70. package/src/triggerclock.js +7 -3
  71. package/src/triggerfiles.js +19 -11
  72. package/src/triggertickets.js +244 -0
  73. package/src/u-readout.js +2 -2
  74. package/src/userrun.js +146 -10
  75. package/src/validate.js +3 -1
  76. package/src/worktree.js +43 -1
  77. package/types/authorflow.d.ts +128 -28
  78. package/types/authorjob.d.ts +16 -3
  79. package/types/authorreadout.d.ts +9 -2
  80. package/types/authorscout.d.ts +4 -2
  81. package/types/bridges.d.ts +4 -3
  82. package/types/cardschedule.d.ts +24 -0
  83. package/types/checkpick.d.ts +297 -0
  84. package/types/checksuggest.d.ts +30 -0
  85. package/types/checkwords.d.ts +14 -0
  86. package/types/config.d.ts +7 -0
  87. package/types/destpoint.d.ts +87 -0
  88. package/types/draftspend.d.ts +16 -0
  89. package/types/factwords.d.ts +7 -0
  90. package/types/job.d.ts +13 -0
  91. package/types/jobblock.d.ts +9 -0
  92. package/types/labelscan.d.ts +7 -0
  93. package/types/launcher.d.ts +7 -2
  94. package/types/mcpchecks.d.ts +8 -0
  95. package/types/mcppick.d.ts +33 -0
  96. package/types/mcpsources.d.ts +51 -0
  97. package/types/mcpuse.d.ts +15 -0
  98. package/types/natural.d.ts +2 -0
  99. package/types/pagemap.d.ts +2 -1
  100. package/types/panel/authorroutes.d.ts +11 -2
  101. package/types/panel/authorsession.d.ts +58 -3
  102. package/types/panel/jobgrid.d.ts +405 -0
  103. package/types/panel/jobplan.d.ts +10 -4
  104. package/types/panel/scheduler.d.ts +7 -2
  105. package/types/panel/schedules.d.ts +124 -4
  106. package/types/panel/schedulestart.d.ts +21 -3
  107. package/types/panel/server.d.ts +427 -6
  108. package/types/panel/settingsroutes.d.ts +4 -2
  109. package/types/panel/status.d.ts +16 -2
  110. package/types/panel/tickets.d.ts +61 -0
  111. package/types/pickrecord.d.ts +88 -0
  112. package/types/plan.d.ts +1 -0
  113. package/types/prcheckout.d.ts +151 -0
  114. package/types/readshim.d.ts +4 -3
  115. package/types/replay.d.ts +3 -0
  116. package/types/reuse.d.ts +2 -2
  117. package/types/revises.d.ts +23 -0
  118. package/types/rubricstep.d.ts +14 -5
  119. package/types/run.d.ts +18 -1
  120. package/types/runlist.d.ts +6 -3
  121. package/types/schedulewords.d.ts +29 -2
  122. package/types/source.d.ts +40 -4
  123. package/types/stepmcp.d.ts +40 -0
  124. package/types/ticket.d.ts +114 -0
  125. package/types/ticketfilter.d.ts +34 -0
  126. package/types/ticketlabels.d.ts +44 -0
  127. package/types/ticketmcp.d.ts +84 -0
  128. package/types/ticketnext.d.ts +33 -0
  129. package/types/ticketrepo.d.ts +118 -0
  130. package/types/ticketschedule.d.ts +21 -0
  131. package/types/ticketshape.d.ts +37 -0
  132. package/types/tools.d.ts +1 -0
  133. package/types/trigger.d.ts +9 -1
  134. package/types/triggerclock.d.ts +6 -2
  135. package/types/triggerfiles.d.ts +13 -5
  136. package/types/triggertickets.d.ts +110 -0
  137. package/types/userrun.d.ts +50 -0
  138. package/types/validate.d.ts +1 -0
  139. package/types/worktree.d.ts +19 -0
package/src/userrun.js CHANGED
@@ -24,15 +24,21 @@
24
24
  // green ONE job end to end. That green GRADUATES the bridge: the plan the agent
25
25
  // authored is preserved from the spine as a reusable artifact, and the next run of
26
26
  // this shape reuses and fine-tunes it rather than starting cold.
27
- import { readFileSync, writeFileSync, appendFileSync, mkdirSync, existsSync, rmSync, readdirSync, openSync, readSync, closeSync, fstatSync, unlinkSync } from 'node:fs';
27
+ import { readFileSync, writeFileSync, appendFileSync, mkdirSync, existsSync, rmSync, rmdirSync, readdirSync, openSync, readSync, closeSync, fstatSync, unlinkSync } from 'node:fs';
28
28
  import { fileURLToPath } from 'node:url';
29
29
  import { execFileSync, spawn } from 'node:child_process';
30
30
  import { join, resolve, dirname, basename } from 'node:path';
31
- import { commitWork, removeWorktree } from './worktree.js';
31
+ import { commitWork, removeWorktree, removePrRef } from './worktree.js';
32
32
  import { moveFile } from './movefile.js';
33
33
  import { runJob } from './run.js';
34
34
  import { moneyWithDraft } from './replay.js';
35
- import { jobSpecHash, resolveWorkerModel, validateJob, workflowKey } from './job.js';
35
+ import { jobSpecHash, resolveWorkerModel, validateJob, workflowKey, flowTypeOf } from './job.js';
36
+ import { ticketNumberOf, TICKET_NUMBER_WORDS } from './ticketshape.js';
37
+ import { freezeRepoTicket } from './ticketrepo.js';
38
+ import { newestUnrunTicket } from './ticketnext.js';
39
+ import { decideTicket } from './ticketlabels.js';
40
+ import { skipWords } from './panel/status.js';
41
+ import { checkoutPrHead, prHeadIsAncestor, recordPrOnManifest } from './prcheckout.js';
36
42
  import { readShimArm } from './readshim.js';
37
43
  import { closeStagesOf } from './plan.js';
38
44
  import { resolveCloseTimeoutMs } from './closetimeout.js';
@@ -228,6 +234,7 @@ class ExitSignal extends Error {
228
234
  /**
229
235
  * @typedef {object} Deps
230
236
  * @property {Record<string,string|undefined>} [env]
237
+ * @property {{url: string, record: any, reread?: () => Promise<any>}} [pr] piece 12: the PR a FRESH run of a code-repo job is checked out at (see `RunCtx.pr`); the door the PR reader will use, and the test seam. No flag sets it.
231
238
  * @property {string} [keysHome] P4a — a test seam naming the home whose `.env` keys file is loaded
232
239
  * even when `env` is injected; production never sets it.
233
240
  * @property {string} [invokedAs] the command this run was actually reached through (`src/invoke.js`);
@@ -239,6 +246,8 @@ class ExitSignal extends Error {
239
246
  * @property {(tier: string) => any} [providerFor]
240
247
  * @property {(url: string) => Promise<{ok: true, text: string, url: string}|{ok: false, error: string}>} [fetchUrl] PART 1c - a test seam: how a web input is read at run start (production: barebrowse)
241
248
  * @property {any} [judgeProvider]
249
+ * @property {typeof newestUnrunTicket} [newestUnrunTicket] R6 - a test seam: how a Tickets run that names no `--ticket` finds the newest unrun ticket (production: the real look, src/ticketnext.js)
250
+ * @property {string} [mcpConfig] R6 - a test seam: the MCP config file that look reads (production: the person's own, found by src/mcpsources.js)
242
251
  * @property {string} [runlistHome] F196 — a test seam for `appendRun`'s
243
252
  * (src/runlist.js) `home` override, the same shape `deps.provider` already
244
253
  * is. Production never sets it; `appendRun` falls through to its own
@@ -306,6 +315,10 @@ class ExitSignal extends Error {
306
315
  * @property {string} spineName
307
316
  * @property {string} [into] see `RunOpts.into`
308
317
  * @property {boolean} [refreeze] a FRESH `--spec` run: fetch the web inputs again AFTER the run is listed (never on resume/door/decide)
318
+ * @property {{number: number, mcp: {server: string, tools: string[]}, repo?: true}} [ticket] a FRESH run of a job that reads tickets (flow type Tickets): the ticket number `--ticket` named (per run, never signed) and the job's signed `mcp`; `repo` = a code-repository (worktree) job, whose ticket is frozen into the worktree's private `.bareloop-input/` (src/ticketrepo.js) instead of the prepared copy's `input/`
319
+ * @property {{mcp: {server: string, tools: string[]}, repo?: boolean}} [pickNewest] R7b (5): a FRESH Tickets run that names no ticket: `execute` looks up the newest unrun one before it builds the run's row (so the row carries the number), and a refused look still lists the row and settles it at $0
320
+ * @property {{url: string, record: any, reread?: () => Promise<any>}} [pr] piece 12: a FRESH run of a code-repo job on a pull request: `url` = the PR address, `record` = the frozen PR record (its `head.sha` is what the worktree is checked out at, src/prcheckout.js), `reread` = read that record again once if the PR moved. Set by the PR reader (a repo job whose ticket line is a pulls list supplies it from its own frozen `pull_request_read`; this field is the override seam), never by a flag
321
+ * @property {boolean} [anyway] `--anyway`: run this ticket even if the job's filter would skip it (inert until the filter exists; it needs --ticket)
309
322
  * @property {string|null} model
310
323
  * @property {string|null} providerKey
311
324
  * @property {string|null} readShim
@@ -497,6 +510,12 @@ async function execute(ctx) {
497
510
  const WORKDIR = target.workdir;
498
511
  // `let`: a fresh run's refetch of its web inputs commits a NEW seed (below, after the run is listed)
499
512
  let SEED = target.seed;
513
+ /** @type {import('./ticketrepo.js').RepoTicketRecord|null} a code-repo job's frozen ticket (metadata), set at the run-start freeze; rides onto `job-start` */
514
+ let ticketRecord = null;
515
+ /** @type {string|null} R9 (9.4): the ticket filter's unsure reason when it let the ticket run anyway-unsure; rides onto `job-start` as `ticketFilter.unsure` */
516
+ let ticketUnsure = null;
517
+ /** @type {{number: number, ownerRepo: string, head: string, base: {ref: string|null, sha: string}|null, mergeBase: string|null}|null} a PR job's checkout (piece 12), set at the run-start seam; rides onto `job-start` as `pr` */
518
+ let prRecord = null;
500
519
  const specHash = jobSpecHash(spec);
501
520
  // the re-invocation commands this engine prints: a bundle names its own door and hash,
502
521
  // every other caller gets today's byte-identical strings.
@@ -1528,11 +1547,31 @@ async function execute(ctx) {
1528
1547
  const LEG = resuming ? deadLegs.length + 1 : 1;
1529
1548
  const foldedUsd = dead ? dead.restart.priorSpentUsd : (doorPrior?.spentUsd ?? 0);
1530
1549
  const legCapUsd = Math.max(0, spec.budgetUsd - (typeof foldedUsd === 'number' && Number.isFinite(foldedUsd) ? foldedUsd : 0));
1550
+ // a fresh Tickets run that names no ticket: the newest unrun ticket (src/ticketnext.js), looked up HERE so the row below carries the number it read. A look that is refused
1551
+ // (a locked pass, an unreadable list, nothing new) is not an exit with no trace: the run is listed and settled at $0 with the plain words (R7b 5, the refused-page-fetch shape).
1552
+ /** @type {typeof ctx.ticket} */
1553
+ let ticket = ctx.ticket;
1554
+ /** @type {string|null} */
1555
+ let pickRefusal = null;
1556
+ /** @type {string|null} */
1557
+ let pickSkip = null;
1558
+ if (ctx.pickNewest !== undefined && !resuming) {
1559
+ const home = deps.keysHome ?? deps.runlistHome;
1560
+ const rows = (() => { try { return readRunList({ home }).rows; } catch { return []; } })();
1561
+ const picked = await (deps.newestUnrunTicket ?? newestUnrunTicket)({ job: spec.job, rows, inputs: Array.isArray(spec.inputs) ? spec.inputs : [], mcp: ctx.pickNewest.mcp, ...(deps.mcpConfig ? { configPath: deps.mcpConfig } : {}) });
1562
+ if (picked.ok) {
1563
+ ticket = { number: picked.number, mcp: ctx.pickNewest.mcp, ...(ctx.pickNewest.repo ? { repo: /** @type {const} */ (true) } : {}) };
1564
+ out(`${SELECTOR}: no --ticket given, so this run takes the newest ticket it has not run: #${picked.number}.`);
1565
+ } else if (picked.nothingNew === true) pickSkip = `${picked.say} Nothing spent.`; // a race with a scheduled run: a quiet SKIP (the R5 shape), not a failure
1566
+ else pickRefusal = /did not start|Nothing spent\.$/.test(picked.say) ? picked.say : `${picked.say} The run did not start. Nothing spent.`;
1567
+ }
1531
1568
  // every row carries its runner's pid and the leg cap, limit set or not: a limit set LATER still holds it
1532
1569
  /** @type {import('./runlist.js').RunRow} */
1533
1570
  const runRow = {
1534
1571
  // a RESUMED run keeps its own start stamp (the row is listed only if the list has none; it is the run's, not the leg's)
1535
1572
  at: resuming ? (deadLegs[0]?.start?.ts ?? new Date().toISOString()) : new Date().toISOString(), runid, job: spec.job, spine: spineFile, patient: wd, via: ctx.bundle ? 'bundle' : 'run-u', pid: process.pid, capUsd: legCapUsd,
1573
+ // a Tickets run lists the ticket it reads (a fresh run only; a skipped or refused run keeps it too): "has run" for the by-hand pick of the newest unrun ticket (src/ticketnext.js)
1574
+ ...(ticket !== undefined ? { ticket: ticket.number } : {}),
1536
1575
  };
1537
1576
  let claimed = false;
1538
1577
  {
@@ -1592,19 +1631,81 @@ async function execute(ctx) {
1592
1631
  err(`WARNING: could not add this run to ~/.config/bareloop/runs.jsonl (${e.message}) — the run continues; the panel's list will be missing this row.`);
1593
1632
  }
1594
1633
 
1634
+ /** a run refused before it started: ONE settled event on its listed row ($0, complete), the claim freed, the plain words kept for the panel (Runs list + Ended block); never a `released` row, which would unlist it */
1635
+ const settleRefused = (/** @type {string} */ words) => {
1636
+ if (!claimedRow) return;
1637
+ try { appendRunEvent({ runid, type: 'settled', by: runid, reason: 'refused before start', words, spentUsd: 0, spendComplete: true, at: new Date().toISOString() }, { home: claimedRow.home }); } catch { /* the exit stands; the dead pid frees the claim */ }
1638
+ claimedRow = null;
1639
+ // R9 (Part B 3): the run folder made just above stays an EMPTY husk when nothing ran in it; take it back (rmdir refuses a folder with anything in it, so a bundle's or a resumed leg's never goes)
1640
+ if (!existsSync(spineFile)) { try { rmdirSync(spineDir); } catch { /* not empty, or already gone: leave it */ } }
1641
+ };
1642
+ if (pickSkip !== null) {
1643
+ out(`${SELECTOR}: skipped: ${pickSkip}`);
1644
+ if (claimedRow) {
1645
+ try { appendRunEvent({ runid, type: 'settled', by: runid, reason: 'skipped', words: pickSkip, spentUsd: 0, spendComplete: true, at: new Date().toISOString() }, { home: claimedRow.home }); } catch { /* the exit stands; the dead pid frees the claim */ }
1646
+ claimedRow = null; // settled, not released: the row stays listed, grey, with the words
1647
+ }
1648
+ throw new ExitSignal(0);
1649
+ }
1650
+ if (pickRefusal !== null) {
1651
+ err(`${SELECTOR}: ${pickRefusal}`);
1652
+ settleRefused(pickRefusal);
1653
+ throw new ExitSignal(2);
1654
+ }
1655
+
1595
1656
  // RUN START REFETCH (PART 1c RF22; moved here 2026-10-19, run mvez8s54: the ~18 s barebrowse fetch ran in main() BEFORE this run was
1596
1657
  // listed, so Sign & run showed nothing for 18 s). The run is listed FIRST (row above, with its pid and cap = the monthly claim), THEN
1597
1658
  // fetches: the Run tab reads "fetching the page…" while source.json has no refrozenAt at or after the row. A refusal cannot be a
1598
1659
  // `released` row (that unlists the run and its words); it SETTLES the claim at $0 and keeps the plain reason for the panel.
1599
1660
  if (ctx.refreeze === true && ctx.into !== undefined) {
1600
- const fresh = await refreezeUrlInputs({ into: ctx.into, ...(deps.fetchUrl ? { fetchUrl: deps.fetchUrl } : {}) });
1661
+ // a CODE-REPO job's ticket (piece 1a) is frozen into the worktree's private `.bareloop-input/` (nothing committed, the seed does not move); every other job's
1662
+ // ticket is the one Inputs row `refreezeUrlInputs` re-reads. The record rides onto this run's `job-start` (metadata only, never the text).
1663
+ /** @type {{ok: true, refreshed: string[], seed: string|null, ticketText?: string}|{ok: false, error: string}} */
1664
+ let fresh;
1665
+ // piece 12's door: `ctx.pr` (a test seam / caller) wins; otherwise a PULLS ticket line of a repo job supplies it from its own frozen read
1666
+ let prIn = ctx.pr;
1667
+ if (ticket?.repo === true) {
1668
+ const frozen = await freezeRepoTicket({ workdir: wd, inputs: Array.isArray(spec.inputs) ? spec.inputs : [], ticket });
1669
+ if (frozen.ok) { ticketRecord = frozen.record; prIn ??= frozen.pr; }
1670
+ fresh = frozen.ok ? { ok: true, refreshed: [], seed: null, ticketText: frozen.ticketText } : frozen;
1671
+ } else {
1672
+ fresh = await refreezeUrlInputs({ into: ctx.into, ...(deps.fetchUrl ? { fetchUrl: deps.fetchUrl } : {}), ...(ticket ? { ticket } : {}) });
1673
+ }
1674
+ // piece 2 (R5): the job's signed `ticketFilter` (and a closed ticket, always) decides RUN or SKIP from the frozen ticket's labels and state, by CODE, before any worker or
1675
+ // model call and before piece 12 fetches a PR head. A skip is a quiet end: ONE `settled` event on the already-listed row ($0, complete), the claim freed, no spine, no
1676
+ // learnings note, no bridge/credit row; exit 0 (a clean end, not a refusal). `--anyway` runs it regardless. An UNSURE verdict (off-scale or unreadable label) never skips.
1677
+ if (fresh.ok && ticket !== undefined && typeof fresh.ticketText === 'string') {
1678
+ const verdict = decideTicket({ text: fresh.ticketText, filter: spec.ticketFilter });
1679
+ if (verdict.outcome === 'skip' && ctx.anyway !== true) {
1680
+ const words = skipWords(verdict.reason, spec.ticketFilter);
1681
+ out(`${SELECTOR}: skipped: ${words}. Nothing spent.`);
1682
+ if (claimedRow) {
1683
+ try { appendRunEvent({ runid, type: 'settled', by: runid, reason: 'skipped', words, spentUsd: 0, spendComplete: true, at: new Date().toISOString() }, { home: claimedRow.home }); } catch { /* the exit stands; the dead pid's claim is closed by the next run */ }
1684
+ claimedRow = null; // settled, not released: the row stays listed so the person sees the ticket was skipped, and why
1685
+ }
1686
+ throw new ExitSignal(0);
1687
+ }
1688
+ if (verdict.outcome === 'run' && verdict.unsure !== undefined) ticketUnsure = verdict.unsure;
1689
+ if (verdict.outcome === 'run' && verdict.unsure !== undefined) out(`${SELECTOR}: the ticket filter was unsure (${verdict.unsure}), so the ticket runs.`);
1690
+ }
1691
+ // piece 12: a PR job's worktree is moved to the PR's head BEFORE the seed is read and the work branch is made (planrun, later); every refusal ends in "Nothing spent."
1692
+ if (fresh.ok && prIn !== undefined) {
1693
+ const read = await readSourceManifest(ctx.into);
1694
+ const repoRoot = read.stop === null && read.present && typeof read.manifest?.repo === 'string' ? read.manifest.repo : null;
1695
+ if (repoRoot === null) fresh = { ok: false, error: 'This pull request job has no repository to check the code out of. The run did not start. Nothing spent.' };
1696
+ else {
1697
+ const co = await checkoutPrHead({ repo: repoRoot, worktree: wd, pr: prIn });
1698
+ if (co.ok) {
1699
+ recordPrOnManifest(ctx.into, co.checkout);
1700
+ SEED = co.checkout.sha;
1701
+ prRecord = { number: co.checkout.number, ownerRepo: co.checkout.ownerRepo, head: co.checkout.sha, base: co.checkout.base, mergeBase: co.checkout.mergeBase };
1702
+ } else fresh = { ok: false, error: co.error };
1703
+ }
1704
+ }
1601
1705
  if (!fresh.ok) {
1602
- const words = /did not start/.test(fresh.error) ? fresh.error : `${fresh.error}. The run did not start. Nothing spent.`;
1706
+ const words = /did not start|Nothing spent\.$/.test(fresh.error) ? fresh.error : `${fresh.error}. The run did not start. Nothing spent.`;
1603
1707
  err(`${SELECTOR}: ${fresh.error}`);
1604
- if (claimedRow) {
1605
- try { appendRunEvent({ runid, type: 'settled', by: runid, reason: 'refused before start', words, spentUsd: 0, spendComplete: true, at: new Date().toISOString() }, { home: claimedRow.home }); } catch { /* the exit stands; the dead pid's claim is closed by the next run */ }
1606
- claimedRow = null; // settled, not released: a released leg-1 row is unlisted, and the person must see why
1607
- }
1708
+ settleRefused(words); // settled, not released: a released leg-1 row is unlisted, and the person must see why
1608
1709
  throw new ExitSignal(2);
1609
1710
  }
1610
1711
  if (fresh.refreshed.length > 0 && typeof fresh.seed === 'string' && fresh.seed) SEED = fresh.seed;
@@ -1626,6 +1727,13 @@ async function execute(ctx) {
1626
1727
  throw new ExitSignal(2);
1627
1728
  }
1628
1729
  out(`patient ${gate.detail ?? 'clean — the halted run left no uncommitted work'} (store kept: it is indexing this run already paid for)`);
1730
+ // piece 12 (item 12): a PR job resumes WITHOUT fetching; the work branch must still hold the PR's code, or it is the existing "gone branch" stop
1731
+ const prHead = ((m) => (m.stop === null && m.present ? m.manifest?.prHead : undefined))(await readSourceManifest(into));
1732
+ if (typeof prHead === 'string' && !(await prHeadIsAncestor(wd, prHead))) {
1733
+ err(`PATIENT REFUSED — the pull request's code (${prHead.slice(0, 12)}) is no longer in this run's branch, so it cannot be resumed.`);
1734
+ err('This is a decision for you, not the harness: start the pull request again.');
1735
+ throw new ExitSignal(2);
1736
+ }
1629
1737
  } else {
1630
1738
  // the patient starts at the seed, every time — a run that inherits the previous
1631
1739
  // run's edits is measuring the wrong thing. COLD MEANS COLD (P design record): the
@@ -1915,6 +2023,9 @@ async function execute(ctx) {
1915
2023
  try {
1916
2024
  outcome = await runJob(spec, {
1917
2025
  stopFile,
2026
+ ...(ticketRecord === null ? {} : { ticketRecord }),
2027
+ ...(ticketUnsure === null ? {} : { ticketUnsure }),
2028
+ ...(prRecord === null ? {} : { prRecord }),
1918
2029
  ...(learnHints === null ? {} : { learnHints }),
1919
2030
  // PRD item 27/M3 — the SAME `emit` the pre-run close-timing reading above
1920
2031
  // used (never a second `makeSpine(spineFile)` here: two independent
@@ -2087,6 +2198,8 @@ async function execute(ctx) {
2087
2198
  if (doorHere) worktreeLine = `\nWORKTREE ${done}${wb || fin.committed ? ` on ${onBranch}` : ''}; the worktree folder is KEPT for the review door — ${wd}`;
2088
2199
  else {
2089
2200
  const gone = removeWorktree(wtManifest.repo, wd);
2201
+ // piece 12 item 3: the PR's private ref goes with the worktree (the branch holds the code now)
2202
+ if (gone && Number.isSafeInteger(wtManifest.prNumber)) removePrRef(wtManifest.repo, wtManifest.prNumber);
2090
2203
  worktreeLine = `\nWORKTREE ${done}${wb || fin.committed ? ` on ${onBranch}` : ''}; ${gone ? 'the worktree folder is removed' : `the worktree folder could not be removed — ${wd}`}`;
2091
2204
  }
2092
2205
  } catch (e) {
@@ -2311,7 +2424,7 @@ async function execute(ctx) {
2311
2424
  // still names (soft-green today) — a green-class row is born RELEASED, because a
2312
2425
  // machine proved it and there was never a credit to quarantine
2313
2426
  out(quarantinesCredit(spec.verdictType)
2314
- ? ' HELD: this green\'s learning credit is quarantined until you release it at the door below'
2427
+ ? ' HELD: this green\'s reuse credit is quarantined until you release it at the door below'
2315
2428
  : ' RELEASED: a machine proved this green, so its row carries no credit to quarantine');
2316
2429
  } else if (REGISTRY_ROW.write !== null) {
2317
2430
  // a REFUSED write is said out loud rather than swallowed — the door below is about to
@@ -2569,6 +2682,7 @@ export async function main(argv, deps = {}) {
2569
2682
  * spec's own path for `--spec` (it has no `jobs/` home to point at). */
2570
2683
  let SPEC_DESC;
2571
2684
  let refreeze = false;
2685
+ let worktreeJob = false;
2572
2686
  let spec;
2573
2687
 
2574
2688
  if (jobArg !== null) {
@@ -2662,6 +2776,7 @@ export async function main(argv, deps = {}) {
2662
2776
  // P6 item 1: a repo job's tree is a WORKTREE in the person's own repo, recorded in the manifest; every other prepared
2663
2777
  // copy keeps its tree at `<into>/tree`
2664
2778
  const worktreeRun = typeof manifestRead.manifest.worktree === 'string' && manifestRead.manifest.worktree !== '';
2779
+ worktreeJob = worktreeRun;
2665
2780
  const specWorkdir = worktreeRun ? manifestRead.manifest.worktree : join(into, 'tree');
2666
2781
  if (!existsSync(specWorkdir) || !existsSync(join(specWorkdir, '.git'))) {
2667
2782
  die(worktreeRun
@@ -2683,6 +2798,23 @@ export async function main(argv, deps = {}) {
2683
2798
  SPEC_DESC = specPath;
2684
2799
  }
2685
2800
 
2801
+ // MCP + tickets (piece 1): `--ticket <n>` names the ticket this run reads (per run, never signed); `--anyway` runs it past the job's filter. Judged here, at $0,
2802
+ // before the approval gate. A resume or door keeps the copy its first start froze, so only a fresh run needs a ticket.
2803
+ const ticketArg = argFlag('ticket');
2804
+ const anyway = argv.includes('--anyway');
2805
+ const tickets = flowTypeOf(spec) === 'tickets';
2806
+ if (anyway && ticketArg === null) die('--anyway needs --ticket <number>: it runs that one ticket even when the job\'s filter would skip it.');
2807
+ /** @type {number|undefined} */
2808
+ let ticketNumber;
2809
+ if (ticketArg !== null) {
2810
+ ticketNumber = ticketNumberOf(ticketArg);
2811
+ if (ticketNumber === undefined) die(`--ticket takes ${TICKET_NUMBER_WORDS}, not "${ticketArg}".`);
2812
+ if (!tickets) die('--ticket is for a job that reads tickets, and this job has no ticket source.');
2813
+ }
2814
+ // a fresh Tickets run that names no ticket takes the NEWEST UNRUN one (piece 8; fwd newestUnrunTicket): `execute` makes the schedule's own look at $0 over the job's signed
2815
+ // `list_issues`, AFTER the run's own row is built so a look that is refused is a LISTED, settled run (R7b 5), never a silent exit. A typed `--ticket` never reaches it.
2816
+ const pickNewest = tickets && refreeze && ticketNumber === undefined;
2817
+
2686
2818
  const ctx = {
2687
2819
  spec,
2688
2820
  specPath,
@@ -2693,6 +2825,10 @@ export async function main(argv, deps = {}) {
2693
2825
  spineName: target.spine,
2694
2826
  ...(target.into === undefined ? {} : { into: target.into }),
2695
2827
  ...(refreeze ? { refreeze: true } : {}),
2828
+ ...(tickets && refreeze && ticketNumber !== undefined ? { ticket: { number: ticketNumber, mcp: spec.mcp, ...(worktreeJob ? { repo: /** @type {const} */ (true) } : {}) } } : {}),
2829
+ ...(pickNewest ? { pickNewest: { mcp: spec.mcp, repo: worktreeJob } } : {}),
2830
+ ...(deps.pr !== undefined && refreeze ? { pr: deps.pr } : {}),
2831
+ ...(anyway ? { anyway: true } : {}),
2696
2832
  model: argFlag('model'),
2697
2833
  providerKey: argFlag('provider'),
2698
2834
  readShim: argFlag('read-shim'),
package/src/validate.js CHANGED
@@ -11,6 +11,7 @@
11
11
  // housed here, they were never part of the dead schema.
12
12
 
13
13
  import { redact } from 'bareguard';
14
+ import { TICKET_INPUT_DIR } from './worktree.js';
14
15
 
15
16
  /**
16
17
  * Map a schema writeScope entry to its enforcement prefix. bareguard
@@ -58,9 +59,10 @@ export function globToPrefix(scope) {
58
59
  * `.git` per repo, always at the workdir root, so its own runtime belt is a
59
60
  * single `fs.deny` entry). Both are inexpressible at declaration time, the
60
61
  * same law #1 already applies to `..`.
62
+ * The frozen-ticket folder (`.bareloop-input`, one spelling in worktree.js) is bareloop's own write, never the worker's: a fence naming it is refused the same way.
61
63
  * @type {readonly string[]}
62
64
  */
63
- export const FORBIDDEN_SCOPE_SEGMENTS = Object.freeze(['.git', 'node_modules']);
65
+ export const FORBIDDEN_SCOPE_SEGMENTS = Object.freeze(['.git', 'node_modules', TICKET_INPUT_DIR]);
64
66
 
65
67
  /**
66
68
  * A scope may never reach the arbiter's inputs (design law #1): it must
package/src/worktree.js CHANGED
@@ -68,12 +68,33 @@ export function shortHead(repo) {
68
68
  * @returns {boolean} true when the line was added now
69
69
  */
70
70
  export function hideBareloopDir(repo) {
71
+ return addExcludeLines(repo, [EXCLUDE_LINE, NODE_MODULES_LINE]);
72
+ }
73
+
74
+ /** the folder inside a repo job's worktree that holds a frozen ticket (MCP + tickets piece 1a): one spelling */
75
+ export const TICKET_INPUT_DIR = '.bareloop-input';
76
+
77
+ /** the line that hides it (anchored at the top of each worktree) */
78
+ export const TICKET_INPUT_EXCLUDE_LINE = `/${TICKET_INPUT_DIR}/`;
79
+
80
+ /**
81
+ * Hide the frozen-ticket folder (`.bareloop-input/`) from `git status` and from `git add -A` in `dir` (a worktree) through the PRIVATE exclude:
82
+ * the COMMON git dir's `info/exclude`, which every linked worktree of that repo reads (a linked worktree has no `info/exclude` of its own). Never the tracked
83
+ * `.gitignore`. Idempotent.
84
+ * @param {string} dir a worktree (or repo) root @returns {boolean} true when the line was added now
85
+ */
86
+ export function hideTicketInput(dir) {
87
+ return addExcludeLines(dir, [TICKET_INPUT_EXCLUDE_LINE]);
88
+ }
89
+
90
+ /** @param {string} repo @param {string[]} lines @returns {boolean} true when any line was added now */
91
+ function addExcludeLines(repo, lines) {
71
92
  const common = execFileSync('git', ['-C', repo, 'rev-parse', '--git-common-dir'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
72
93
  const exclude = join(resolve(repo, common), 'info', 'exclude');
73
94
  mkdirSync(dirname(exclude), { recursive: true });
74
95
  const text = existsSync(exclude) ? readFileSync(exclude, 'utf8') : '';
75
96
  const have = new Set(text.split('\n').map((l) => l.trim()));
76
- const missing = [EXCLUDE_LINE, NODE_MODULES_LINE].filter((l) => !have.has(l));
97
+ const missing = lines.filter((l) => !have.has(l));
77
98
  if (missing.length === 0) return false;
78
99
  const add = `${missing.join('\n')}\n`;
79
100
  if (text === '') writeFileSync(exclude, add);
@@ -94,6 +115,27 @@ export function removeWorktree(repo, dir) {
94
115
  return !existsSync(dir);
95
116
  }
96
117
 
118
+ /** the private ref a PR job's fetched head lives under (piece 12): bareloop's own namespace, so no branch, tag or the person's refs are touched and the object survives gc during the run @param {number} n */
119
+ export function prRefName(n) {
120
+ return `refs/bareloop/pr-${n}`;
121
+ }
122
+
123
+ /**
124
+ * Delete a PR job's private ref from `repo` (`git update-ref -d`). A leftover ref is harmless (one pointer into the object store) but is not left behind. Never throws.
125
+ * @param {string} repo @param {number} n
126
+ * @returns {boolean} true when the ref is gone afterwards (a ref that never existed counts)
127
+ */
128
+ export function removePrRef(repo, n) {
129
+ const ref = prRefName(n);
130
+ try {
131
+ execFileSync('git', [...NO_HOOKS, '-C', repo, 'update-ref', '-d', ref], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
132
+ return true;
133
+ } catch { /* fall through: report what is there */ }
134
+ try {
135
+ return execFileSync('git', ['-C', repo, 'for-each-ref', ref], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim() === '';
136
+ } catch { return false; }
137
+ }
138
+
97
139
  /** a commit bareloop makes in the person's repo is authored by bareloop (never their global config), signs nothing, runs none of their hooks */
98
140
  const COMMIT_CONFIG = [
99
141
  '-c', 'user.name=bareloop', '-c', 'user.email=bareloop@localhost', '-c', 'commit.gpgsign=false',