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/userrun.js CHANGED
@@ -24,17 +24,25 @@
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';
44
+ import { placeFactsOf, readPlaceRules, valueInWords, stopWords, lastPlaceRead, placeValuesOfEvents, bindPlaceValues, NO_PLACE_RECORD_WORDS } from './placerule.js';
45
+ import { readFrozenInputs } from './rubricstep.js';
38
46
  import { resolveCloseTimeoutMs } from './closetimeout.js';
39
47
  import { makeSpine } from './spine.js';
40
48
  // PRD item 33/M2 — the source front door. `readSourceManifest` finds the
@@ -228,6 +236,7 @@ class ExitSignal extends Error {
228
236
  /**
229
237
  * @typedef {object} Deps
230
238
  * @property {Record<string,string|undefined>} [env]
239
+ * @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
240
  * @property {string} [keysHome] P4a — a test seam naming the home whose `.env` keys file is loaded
232
241
  * even when `env` is injected; production never sets it.
233
242
  * @property {string} [invokedAs] the command this run was actually reached through (`src/invoke.js`);
@@ -239,6 +248,8 @@ class ExitSignal extends Error {
239
248
  * @property {(tier: string) => any} [providerFor]
240
249
  * @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
250
  * @property {any} [judgeProvider]
251
+ * @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)
252
+ * @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
253
  * @property {string} [runlistHome] F196 — a test seam for `appendRun`'s
243
254
  * (src/runlist.js) `home` override, the same shape `deps.provider` already
244
255
  * is. Production never sets it; `appendRun` falls through to its own
@@ -306,6 +317,10 @@ class ExitSignal extends Error {
306
317
  * @property {string} spineName
307
318
  * @property {string} [into] see `RunOpts.into`
308
319
  * @property {boolean} [refreeze] a FRESH `--spec` run: fetch the web inputs again AFTER the run is listed (never on resume/door/decide)
320
+ * @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/`
321
+ * @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
322
+ * @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
323
+ * @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
324
  * @property {string|null} model
310
325
  * @property {string|null} providerKey
311
326
  * @property {string|null} readShim
@@ -497,6 +512,12 @@ async function execute(ctx) {
497
512
  const WORKDIR = target.workdir;
498
513
  // `let`: a fresh run's refetch of its web inputs commits a NEW seed (below, after the run is listed)
499
514
  let SEED = target.seed;
515
+ /** @type {import('./ticketrepo.js').RepoTicketRecord|null} a code-repo job's frozen ticket (metadata), set at the run-start freeze; rides onto `job-start` */
516
+ let ticketRecord = null;
517
+ /** @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` */
518
+ let ticketUnsure = null;
519
+ /** @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` */
520
+ let prRecord = null;
500
521
  const specHash = jobSpecHash(spec);
501
522
  // the re-invocation commands this engine prints: a bundle names its own door and hash,
502
523
  // every other caller gets today's byte-identical strings.
@@ -1240,6 +1261,8 @@ async function execute(ctx) {
1240
1261
  // budget — money folds on every path, time does not.
1241
1262
  /** @type {{text: string, fromRunid: string, receivedAt: string}|null} */
1242
1263
  let DOOR_RERUN = null;
1264
+ /** @type {Record<string, string>|null} PLACE RULES: a door rerun's values, taken from the answered run's own record (it re-reads nothing) */
1265
+ let DOOR_PLACE_VALUES = null;
1243
1266
  if (doorSpineFile !== null) {
1244
1267
  if (RULING === null) {
1245
1268
  err('NO DECISION — this run is standing at its review door and no decision was given.');
@@ -1248,6 +1271,20 @@ async function execute(ctx) {
1248
1271
  throw new ExitSignal(2);
1249
1272
  }
1250
1273
  const answeredAt = new Date().toISOString();
1274
+ // PLACE RULES: an accept's re-proof and a rerun (which re-reads nothing: no refreeze at the door) use the values THIS run read, from its own `place-rules`
1275
+ // record (what a resume rebinds); never the signed drafting words, never a new read. No record = refused in plain words. The signed spec is not touched.
1276
+ /** @type {any} */
1277
+ let doorSpec = spec;
1278
+ if (RULING.decision !== 'pause' && placeFactsOf(spec).length > 0) {
1279
+ const doorPlaceValues = placeValuesOfEvents(doorEvents ?? []);
1280
+ if (doorPlaceValues === null) {
1281
+ err(`DOOR REFUSED (${RULING.decision}) — nothing was recorded and nothing was released.`);
1282
+ err(NO_PLACE_RECORD_WORDS);
1283
+ throw new ExitSignal(2);
1284
+ }
1285
+ doorSpec = bindPlaceValues(spec, doorPlaceValues);
1286
+ if (RULING.decision === 'rerun') DOOR_PLACE_VALUES = doorPlaceValues;
1287
+ }
1251
1288
  // PRD item 27/M3 — the door's mechanical re-run needs the same effective
1252
1289
  // ceiling the run itself would use; resolved through the identical
1253
1290
  // function (`resolveCloseTimeoutMs`), never a second guess. Paid only on
@@ -1276,7 +1313,7 @@ async function execute(ctx) {
1276
1313
  // `timedOut: true`, already handled above.
1277
1314
  if (doorCloseTiming.closeTimeoutMs === null) throw new Error('unreachable: resolveCloseTimeoutMs sets closeTimeoutMs whenever timedOut is false');
1278
1315
  const ans = await answerReviewDoor({
1279
- job: spec,
1316
+ job: doorSpec,
1280
1317
  workdir: wd,
1281
1318
  events: doorEvents ?? [],
1282
1319
  decision: RULING.decision,
@@ -1528,11 +1565,31 @@ async function execute(ctx) {
1528
1565
  const LEG = resuming ? deadLegs.length + 1 : 1;
1529
1566
  const foldedUsd = dead ? dead.restart.priorSpentUsd : (doorPrior?.spentUsd ?? 0);
1530
1567
  const legCapUsd = Math.max(0, spec.budgetUsd - (typeof foldedUsd === 'number' && Number.isFinite(foldedUsd) ? foldedUsd : 0));
1568
+ // 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
1569
+ // (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).
1570
+ /** @type {typeof ctx.ticket} */
1571
+ let ticket = ctx.ticket;
1572
+ /** @type {string|null} */
1573
+ let pickRefusal = null;
1574
+ /** @type {string|null} */
1575
+ let pickSkip = null;
1576
+ if (ctx.pickNewest !== undefined && !resuming) {
1577
+ const home = deps.keysHome ?? deps.runlistHome;
1578
+ const rows = (() => { try { return readRunList({ home }).rows; } catch { return []; } })();
1579
+ 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 } : {}) });
1580
+ if (picked.ok) {
1581
+ ticket = { number: picked.number, mcp: ctx.pickNewest.mcp, ...(ctx.pickNewest.repo ? { repo: /** @type {const} */ (true) } : {}) };
1582
+ out(`${SELECTOR}: no --ticket given, so this run takes the newest ticket it has not run: #${picked.number}.`);
1583
+ } 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
1584
+ else pickRefusal = /did not start|Nothing spent\.$/.test(picked.say) ? picked.say : `${picked.say} The run did not start. Nothing spent.`;
1585
+ }
1531
1586
  // every row carries its runner's pid and the leg cap, limit set or not: a limit set LATER still holds it
1532
1587
  /** @type {import('./runlist.js').RunRow} */
1533
1588
  const runRow = {
1534
1589
  // 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
1590
  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,
1591
+ // 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)
1592
+ ...(ticket !== undefined ? { ticket: ticket.number } : {}),
1536
1593
  };
1537
1594
  let claimed = false;
1538
1595
  {
@@ -1592,22 +1649,109 @@ async function execute(ctx) {
1592
1649
  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
1650
  }
1594
1651
 
1652
+ /** 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 */
1653
+ const settleRefused = (/** @type {string} */ words) => {
1654
+ if (!claimedRow) return;
1655
+ 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 */ }
1656
+ claimedRow = null;
1657
+ // 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)
1658
+ if (!existsSync(spineFile)) { try { rmdirSync(spineDir); } catch { /* not empty, or already gone: leave it */ } }
1659
+ };
1660
+ if (pickSkip !== null) {
1661
+ out(`${SELECTOR}: skipped: ${pickSkip}`);
1662
+ if (claimedRow) {
1663
+ 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 */ }
1664
+ claimedRow = null; // settled, not released: the row stays listed, grey, with the words
1665
+ }
1666
+ throw new ExitSignal(0);
1667
+ }
1668
+ if (pickRefusal !== null) {
1669
+ err(`${SELECTOR}: ${pickRefusal}`);
1670
+ settleRefused(pickRefusal);
1671
+ throw new ExitSignal(2);
1672
+ }
1673
+
1674
+ /** @type {Record<string, string>|null} PLACE RULES: the values the run start read for the spec's place-rule facts (key to value), handed to `runJob`; null = none */
1675
+ let placeValues = DOOR_PLACE_VALUES;
1676
+ /** @type {{workflowKey: string, rows: object[]}|null} PLACE RULES: the record the spine keeps of that read; null on a resume (its first leg wrote it) */
1677
+ let placeRead = null;
1678
+ // a RESUME does not re-read: it rebinds the values its own first leg recorded, so the close grades on the words the run started with
1679
+ if (dead) placeValues = placeValuesOfEvents(deadAllEvents);
1595
1680
  // 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
1681
  // 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
1682
  // 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
1683
  // `released` row (that unlists the run and its words); it SETTLES the claim at $0 and keeps the plain reason for the panel.
1599
1684
  if (ctx.refreeze === true && ctx.into !== undefined) {
1600
- const fresh = await refreezeUrlInputs({ into: ctx.into, ...(deps.fetchUrl ? { fetchUrl: deps.fetchUrl } : {}) });
1685
+ // 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
1686
+ // ticket is the one Inputs row `refreezeUrlInputs` re-reads. The record rides onto this run's `job-start` (metadata only, never the text).
1687
+ /** @type {{ok: true, refreshed: string[], seed: string|null, ticketText?: string}|{ok: false, error: string}} */
1688
+ let fresh;
1689
+ // 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
1690
+ let prIn = ctx.pr;
1691
+ if (ticket?.repo === true) {
1692
+ const frozen = await freezeRepoTicket({ workdir: wd, inputs: Array.isArray(spec.inputs) ? spec.inputs : [], ticket });
1693
+ if (frozen.ok) { ticketRecord = frozen.record; prIn ??= frozen.pr; }
1694
+ fresh = frozen.ok ? { ok: true, refreshed: [], seed: null, ticketText: frozen.ticketText } : frozen;
1695
+ } else {
1696
+ fresh = await refreezeUrlInputs({ into: ctx.into, ...(deps.fetchUrl ? { fetchUrl: deps.fetchUrl } : {}), ...(ticket ? { ticket } : {}) });
1697
+ }
1698
+ // 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
1699
+ // 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
1700
+ // 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.
1701
+ if (fresh.ok && ticket !== undefined && typeof fresh.ticketText === 'string') {
1702
+ const verdict = decideTicket({ text: fresh.ticketText, filter: spec.ticketFilter });
1703
+ if (verdict.outcome === 'skip' && ctx.anyway !== true) {
1704
+ const words = skipWords(verdict.reason, spec.ticketFilter);
1705
+ out(`${SELECTOR}: skipped: ${words}. Nothing spent.`);
1706
+ if (claimedRow) {
1707
+ 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 */ }
1708
+ claimedRow = null; // settled, not released: the row stays listed so the person sees the ticket was skipped, and why
1709
+ }
1710
+ throw new ExitSignal(0);
1711
+ }
1712
+ if (verdict.outcome === 'run' && verdict.unsure !== undefined) ticketUnsure = verdict.unsure;
1713
+ if (verdict.outcome === 'run' && verdict.unsure !== undefined) out(`${SELECTOR}: the ticket filter was unsure (${verdict.unsure}), so the ticket runs.`);
1714
+ }
1715
+ // 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."
1716
+ if (fresh.ok && prIn !== undefined) {
1717
+ const read = await readSourceManifest(ctx.into);
1718
+ const repoRoot = read.stop === null && read.present && typeof read.manifest?.repo === 'string' ? read.manifest.repo : null;
1719
+ 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.' };
1720
+ else {
1721
+ const co = await checkoutPrHead({ repo: repoRoot, worktree: wd, pr: prIn });
1722
+ if (co.ok) {
1723
+ recordPrOnManifest(ctx.into, co.checkout);
1724
+ SEED = co.checkout.sha;
1725
+ prRecord = { number: co.checkout.number, ownerRepo: co.checkout.ownerRepo, head: co.checkout.sha, base: co.checkout.base, mergeBase: co.checkout.mergeBase };
1726
+ } else fresh = { ok: false, error: co.error };
1727
+ }
1728
+ }
1601
1729
  if (!fresh.ok) {
1602
- const words = /did not start/.test(fresh.error) ? fresh.error : `${fresh.error}. The run did not start. Nothing spent.`;
1730
+ const words = /did not start|Nothing spent\.$/.test(fresh.error) ? fresh.error : `${fresh.error}. The run did not start. Nothing spent.`;
1603
1731
  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
- }
1732
+ settleRefused(words); // settled, not released: a released leg-1 row is unlisted, and the person must see why
1608
1733
  throw new ExitSignal(2);
1609
1734
  }
1610
1735
  if (fresh.refreshed.length > 0 && typeof fresh.seed === 'string' && fresh.seed) SEED = fresh.seed;
1736
+ // PLACE RULES: every place-rule fact of the signed spec is read, by CODE, from this run's own copy of its input (the copy the refetch above just froze); the values are
1737
+ // bound as those facts' phrases on the run's in-memory copy inside `runJob`, after the approval check, and are never written to the signed spec. Any rule not found
1738
+ // stops the run here, before any provider call.
1739
+ const placeFacts = placeFactsOf(spec);
1740
+ if (placeFacts.length > 0) {
1741
+ const frozen = await readFrozenInputs(join(ctx.into, 'tree'), [...new Set(placeFacts.map((f) => f.source))]);
1742
+ // "last read": the newest earlier run of this workflow's own record, else the drafting words
1743
+ let earlier = {};
1744
+ if (cfgOn) { try { earlier = lastPlaceRead({ rows: readRunList({ home: cfgHome }).rows, job: spec.job, workflowKey: workflowKey(spec), runid }); } catch { /* no earlier record is the drafting words */ } }
1745
+ const read = readPlaceRules(placeFacts.map((fact) => ({ fact, text: frozen.ok ? (frozen.texts[fact.source] ?? null) : null, was: /** @type {Record<string, string>} */ (earlier)[fact.key] ?? valueInWords(fact.place, fact.phrase) })));
1746
+ if (!read.proceed) {
1747
+ const words = stopWords(read.rows);
1748
+ err(`${SELECTOR}: ${words}`);
1749
+ settleRefused(words);
1750
+ throw new ExitSignal(2);
1751
+ }
1752
+ placeValues = read.values;
1753
+ placeRead = { workflowKey: workflowKey(spec), rows: read.rows.map(({ name: _n, ...r }) => r) };
1754
+ }
1611
1755
  }
1612
1756
 
1613
1757
  const git = (/** @type {string[]} */ a) => execFileSync('git', ['-C', wd, ...a], { encoding: 'utf8' }).trim();
@@ -1626,6 +1770,13 @@ async function execute(ctx) {
1626
1770
  throw new ExitSignal(2);
1627
1771
  }
1628
1772
  out(`patient ${gate.detail ?? 'clean — the halted run left no uncommitted work'} (store kept: it is indexing this run already paid for)`);
1773
+ // 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
1774
+ const prHead = ((m) => (m.stop === null && m.present ? m.manifest?.prHead : undefined))(await readSourceManifest(into));
1775
+ if (typeof prHead === 'string' && !(await prHeadIsAncestor(wd, prHead))) {
1776
+ 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.`);
1777
+ err('This is a decision for you, not the harness: start the pull request again.');
1778
+ throw new ExitSignal(2);
1779
+ }
1629
1780
  } else {
1630
1781
  // the patient starts at the seed, every time — a run that inherits the previous
1631
1782
  // run's edits is measuring the wrong thing. COLD MEANS COLD (P design record): the
@@ -1915,6 +2066,11 @@ async function execute(ctx) {
1915
2066
  try {
1916
2067
  outcome = await runJob(spec, {
1917
2068
  stopFile,
2069
+ ...(placeValues === null ? {} : { placeValues }),
2070
+ ...(placeRead === null ? {} : { placeRead }),
2071
+ ...(ticketRecord === null ? {} : { ticketRecord }),
2072
+ ...(ticketUnsure === null ? {} : { ticketUnsure }),
2073
+ ...(prRecord === null ? {} : { prRecord }),
1918
2074
  ...(learnHints === null ? {} : { learnHints }),
1919
2075
  // PRD item 27/M3 — the SAME `emit` the pre-run close-timing reading above
1920
2076
  // used (never a second `makeSpine(spineFile)` here: two independent
@@ -2087,6 +2243,8 @@ async function execute(ctx) {
2087
2243
  if (doorHere) worktreeLine = `\nWORKTREE ${done}${wb || fin.committed ? ` on ${onBranch}` : ''}; the worktree folder is KEPT for the review door — ${wd}`;
2088
2244
  else {
2089
2245
  const gone = removeWorktree(wtManifest.repo, wd);
2246
+ // piece 12 item 3: the PR's private ref goes with the worktree (the branch holds the code now)
2247
+ if (gone && Number.isSafeInteger(wtManifest.prNumber)) removePrRef(wtManifest.repo, wtManifest.prNumber);
2090
2248
  worktreeLine = `\nWORKTREE ${done}${wb || fin.committed ? ` on ${onBranch}` : ''}; ${gone ? 'the worktree folder is removed' : `the worktree folder could not be removed — ${wd}`}`;
2091
2249
  }
2092
2250
  } catch (e) {
@@ -2569,6 +2727,7 @@ export async function main(argv, deps = {}) {
2569
2727
  * spec's own path for `--spec` (it has no `jobs/` home to point at). */
2570
2728
  let SPEC_DESC;
2571
2729
  let refreeze = false;
2730
+ let worktreeJob = false;
2572
2731
  let spec;
2573
2732
 
2574
2733
  if (jobArg !== null) {
@@ -2662,6 +2821,7 @@ export async function main(argv, deps = {}) {
2662
2821
  // 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
2822
  // copy keeps its tree at `<into>/tree`
2664
2823
  const worktreeRun = typeof manifestRead.manifest.worktree === 'string' && manifestRead.manifest.worktree !== '';
2824
+ worktreeJob = worktreeRun;
2665
2825
  const specWorkdir = worktreeRun ? manifestRead.manifest.worktree : join(into, 'tree');
2666
2826
  if (!existsSync(specWorkdir) || !existsSync(join(specWorkdir, '.git'))) {
2667
2827
  die(worktreeRun
@@ -2683,6 +2843,23 @@ export async function main(argv, deps = {}) {
2683
2843
  SPEC_DESC = specPath;
2684
2844
  }
2685
2845
 
2846
+ // 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,
2847
+ // before the approval gate. A resume or door keeps the copy its first start froze, so only a fresh run needs a ticket.
2848
+ const ticketArg = argFlag('ticket');
2849
+ const anyway = argv.includes('--anyway');
2850
+ const tickets = flowTypeOf(spec) === 'tickets';
2851
+ if (anyway && ticketArg === null) die('--anyway needs --ticket <number>: it runs that one ticket even when the job\'s filter would skip it.');
2852
+ /** @type {number|undefined} */
2853
+ let ticketNumber;
2854
+ if (ticketArg !== null) {
2855
+ ticketNumber = ticketNumberOf(ticketArg);
2856
+ if (ticketNumber === undefined) die(`--ticket takes ${TICKET_NUMBER_WORDS}, not "${ticketArg}".`);
2857
+ if (!tickets) die('--ticket is for a job that reads tickets, and this job has no ticket source.');
2858
+ }
2859
+ // 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
2860
+ // `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.
2861
+ const pickNewest = tickets && refreeze && ticketNumber === undefined;
2862
+
2686
2863
  const ctx = {
2687
2864
  spec,
2688
2865
  specPath,
@@ -2693,6 +2870,10 @@ export async function main(argv, deps = {}) {
2693
2870
  spineName: target.spine,
2694
2871
  ...(target.into === undefined ? {} : { into: target.into }),
2695
2872
  ...(refreeze ? { refreeze: true } : {}),
2873
+ ...(tickets && refreeze && ticketNumber !== undefined ? { ticket: { number: ticketNumber, mcp: spec.mcp, ...(worktreeJob ? { repo: /** @type {const} */ (true) } : {}) } } : {}),
2874
+ ...(pickNewest ? { pickNewest: { mcp: spec.mcp, repo: worktreeJob } } : {}),
2875
+ ...(deps.pr !== undefined && refreeze ? { pr: deps.pr } : {}),
2876
+ ...(anyway ? { anyway: true } : {}),
2696
2877
  model: argFlag('model'),
2697
2878
  providerKey: argFlag('provider'),
2698
2879
  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',