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/planrun.js CHANGED
@@ -28,14 +28,15 @@ import { Gate } from 'bareguard';
28
28
  import { LiteCtx } from 'litectx';
29
29
  import { runClose, runStages, ralph, CLOSE_FAULTS, boundGap } from './ralph.js';
30
30
  import { validatePlan, pairEditGrant, legalScopes, closeStagesOf } from './plan.js';
31
- import { WRITE_VERBS, EXIT_TYPES, MAX_EXITS_PER_STEP, MAX_PLAN_STEPS, MAX_SCOPE_MENU, RETRIEVAL_PAIR, EXIT_EXAMPLE } from './plan.js';
31
+ import { WRITE_VERBS, EXIT_TYPES, MAX_EXITS_PER_STEP, MAX_PLAN_STEPS, MAX_SCOPE_MENU, RETRIEVAL_PAIR, EXIT_EXAMPLE, mcpToolsExample } from './plan.js';
32
32
  import { snapshotScope, evalExits, CHECK_GAP_MAX } from './exits.js';
33
33
  import { createRoot } from './root.js';
34
34
  import { createStallWatch, STALL_MS, MAX_STALLS } from './stall.js';
35
35
  import { createLadder, STRIKE_LIMIT } from './ladder.js';
36
36
  import { createTrend, FIX_STRIKE_LIMIT } from './trend.js';
37
- import { TOOL_MENU, STORE_VERBS, checkMenu } from './job.js';
38
- import { TOOL_BY_VERB, CTX_TOOLS, createCtxTools, toolAction, gatedShellOptions, trackedAtSeedGuard, PERSONA_TOOLS, strategyFor } from './tools.js';
37
+ import { TOOL_MENU, STORE_VERBS, checkMenu, flowTypeOf } from './job.js';
38
+ import { TOOL_BY_VERB, CTX_TOOLS, createCtxTools, toolAction, gatedShellOptions, trackedAtSeedGuard, PERSONA_TOOLS, strategyFor, mcpStrategy } from './tools.js';
39
+ import { startStepMcp, mcpAllowlist } from './stepmcp.js';
39
40
  import { anySuppressionWarning } from './authoring.js';
40
41
  import { createReadShim, readShimArm, readShimStrategy } from './readshim.js';
41
42
  import { createCarryStore } from './carrystore.js';
@@ -739,6 +740,16 @@ export function planPrompt(job, scoutBlob, reds, maxStepRounds, failure, scopes,
739
740
  // does not exist and neither does this sentence (the A0 and A2 renders). The
740
741
  // sentence also states the 24KB bound as its reason, which is the second
741
742
  // reason it cannot render for A2: that bound is not in force there.
743
+ // R2c (MCP+tickets piece 6): `mcpTools` exists only for a job that signed an MCP server, and ONLY then does the prompt say so (a plain job's render is
744
+ // byte-identical). A validator rule the drafter is not told about fails every draft, so the rule, the legal values and a legal example ride together;
745
+ // the same example line (`mcpToolsExample`) is what the validator's red carries.
746
+ const mcpLaw = (typeof job.mcp === 'object' && job.mcp !== null) && Array.isArray(job.mcp.tools) && job.mcp.tools.length > 0
747
+ ? `\n- "mcpTools" (optional): the MCP tools this step may call — a non-empty unique subset of ${JSON.stringify(job.mcp.tools)}, the tools of server "${job.mcp.server}" the person signed.
748
+ A tool outside that list is rejected: you may narrow a step to a subset, never reach beyond it. Example: ${mcpToolsExample(job.mcp)}.
749
+ The worker calls a granted tool by the name "${job.mcp.server}_<tool>", using the exact tool name above. A step without "mcpTools" has no MCP tool at all. The job's server and tool list were set by the program, not by you, and the plan has no field for them.${flowTypeOf(job) === 'mcp'
750
+ ? `\n This is an MCP job: at least one step must carry "mcpTools", or the plan is rejected.`
751
+ : `\n The job's own ticket read needs no step; give "mcpTools" only to a step that must call a signed tool itself.`}`
752
+ : '';
742
753
  const readShimLaw = readShimArm(readShim).g1
743
754
  ? `\n A step granting "read" must also grant "recall" and "get": a read of a large file
744
755
  returns only its next 24KB, and those two verbs are the only way to read a symbol in
@@ -754,7 +765,7 @@ Shape: { "schema": "plan-v1", "steps": [ ... 1..${MAX_PLAN_STEPS} steps ... ] }
754
765
  strictly in array order. Each step (no other fields exist):
755
766
  - "id": kebab-case slug, unique
756
767
  - "action": the step's task, precise enough for a worker that sees ONLY this step
757
- - "tools": non-empty unique subset of ${JSON.stringify(ceiling)} (read/grep are the worker's ONLY way to see the tree — there is no shell; write/edit change the tree; recall/get/impact/related/recent search and navigate the repository index; compress/peek read cheaply; stash/remember/forget park and record notes across steps)${readShimLaw}
768
+ - "tools": non-empty unique subset of ${JSON.stringify(ceiling)} (read/grep are the worker's ONLY way to see the tree — there is no shell; write/edit change the tree; recall/get/impact/related/recent search and navigate the repository index; compress/peek read cheaply; stash/remember/forget park and record notes across steps)${readShimLaw}${mcpLaw}
758
769
  - "rounds": integer 1..${maxStepRounds} — the step's per-attempt tool-round bound
759
770
  - "target": the step's deliverable path (REQUIRED when tools include write/edit), inside ${JSON.stringify(job.writeScope)}
760
771
  - "scope" (optional): narrow this step's WRITE fence — copy one value from the offered scopes below.
@@ -2297,6 +2308,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2297
2308
  const shrinkGuardPath = await trackedAtSeedGuard(workdir, guardListing.files);
2298
2309
 
2299
2310
  const lc = new LiteCtx({ root: workdir });
2311
+ let ctxIndexRecorded = false; // the run's ONE `ctx-index` record: the first index attempt (every later mkWorker re-indexes incrementally, unrecorded)
2300
2312
  const ceiling = Array.isArray(job.tools) ? job.tools : [...TOOL_MENU];
2301
2313
  const fencePrefixes = job.writeScope.map((/** @type {string} */ g) => resolve(workdir, globToPrefix(g)));
2302
2314
  const auditPath = join(workdir, GATE_AUDIT_FILE);
@@ -2374,7 +2386,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2374
2386
  * denied, the wallet as its budget), granted tools only (the menu IS the
2375
2387
  * grant), per-attempt round bound via loop.stop() (F20), every round metered
2376
2388
  * with a phase label (F12).
2377
- * @param {{granted: string[], phase: string, attemptRounds: number, attempts: number|null, writable: boolean, root?: ReturnType<typeof createRoot>|null, fence?: string[]|null, workerProvider?: any, truncatedBounded?: boolean}} o
2389
+ * @param {{granted: string[], phase: string, attemptRounds: number, attempts: number|null, writable: boolean, root?: ReturnType<typeof createRoot>|null, fence?: string[]|null, workerProvider?: any, truncatedBounded?: boolean, mcpRun?: Awaited<ReturnType<typeof startStepMcp>>|null}} o
2378
2390
  * `root` (Layer R): when present, the worker's write-class actions are teed
2379
2391
  * for the within-run ratchet — staged before the gate decides, discarded on
2380
2392
  * deny/halt, settled to landed-or-not after execution (the two axes, F43/F7).
@@ -2384,7 +2396,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2384
2396
  * STRIKE LADDER (src/ladder.js), where that count does not exist by design — see
2385
2397
  * the turn-allowance note below.
2386
2398
  */
2387
- async function mkWorker({ granted, phase, attemptRounds, attempts, writable, root = null, fence = null, workerProvider = null, truncatedBounded = false }) {
2399
+ async function mkWorker({ granted, phase, attemptRounds, attempts, writable, root = null, fence = null, workerProvider = null, truncatedBounded = false, mcpRun = null }) {
2388
2400
  // THE HARD RULE, ENFORCED STRUCTURALLY (PRD v1.57 §3). This is the ONE seam
2389
2401
  // that grants write-class verbs — `writeScope` is empty for every other
2390
2402
  // worker, so a read-only phase cannot reach a file whatever it intends — and
@@ -2443,7 +2455,14 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2443
2455
  // fs.writeScope/deny above (step 3's fsCheck runs first in the SAME `??`
2444
2456
  // chain, node_modules/bareguard/src/gate.js) — i.e. only the residual
2445
2457
  // case of an in-fence path that still carries one of these segments.
2446
- tools: { denyArgPatterns: { write: [FORBIDDEN_WRITE_SEGMENT_PATTERN], edit: [FORBIDDEN_WRITE_SEGMENT_PATTERN] } },
2458
+ //
2459
+ // R2c (MCP+tickets piece 6): a step that grants MCP tools ALSO gets `tools.allowlist` — and only such a step (every other step's gate is exactly as
2460
+ // before). bareguard's allowlist is exclusive for EVERY action and matches the action TYPE (`read`/`write`/`edit`/`ctx_stash`..., see toolAction), so it
2461
+ // lists the granted verbs' types plus the signed bridge names (src/stepmcp.js, proven against the real Gate): an unsigned bridge tool is denied by name.
2462
+ tools: {
2463
+ denyArgPatterns: { write: [FORBIDDEN_WRITE_SEGMENT_PATTERN], edit: [FORBIDDEN_WRITE_SEGMENT_PATTERN] },
2464
+ ...(mcpRun ? { allowlist: mcpAllowlist(granted, mcpRun.server, mcpRun.mcpTools, workdir) } : {}),
2465
+ },
2447
2466
  budget: { maxCostUsd: Math.max(remainingUsd(), 1e-4) },
2448
2467
  limits: { maxTurns },
2449
2468
  audit: { path: auditPath },
@@ -2627,7 +2646,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2627
2646
  memoryCacheCounts.bytesWithheld += bytes;
2628
2647
  },
2629
2648
  // The first-read map (experimental, off unless the spec says `readMap: true`): this worker's index, and whether it holds ctx_get.
2630
- readMap: readMapOn ? { root: workdir, hasGet: grantedNames.has(TOOL_BY_VERB.get), getNode: (/** @type {string} */ rel) => lc.getNode(rel), refresh: () => lc.index({ yield: true }), emit: emitCtx } : null,
2649
+ readMap: readMapOn ? { root: workdir, hasGet: grantedNames.has(TOOL_BY_VERB.get), getNode: (/** @type {string} */ rel) => lc.getNode(rel), indexed: () => lc.indexed, refresh: () => lc.index({ yield: true }), emit: emitCtx } : null,
2631
2650
  });
2632
2651
  const rdTool = shell.find((/** @type {{name: string}} */ t) => t.name === TOOL_BY_VERB.read);
2633
2652
  // F48: on native, bound shell_read below the CLI's tool-result display cap and hand back a
@@ -2670,16 +2689,35 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2670
2689
  // sampler all live here) for its full duration: measured 4.4s at 4.5% liveness on a
2671
2690
  // 155-file force pass. With yield:true the worst single block measured 189–252ms (n=4),
2672
2691
  // below anything a second/minute-scale timer can perceive. Store output is byte-identical.
2673
- // …and with the first-read map on the index is built at run start too, so the map never waits on a ctx tool being granted.
2674
- if (ctx.length || readMapOn) await lc.index({ yield: true });
2675
- const toolDefs = [...shell, ...ctx];
2692
+ // …and the index is built at run start for EVERY run (litectx 0.41 makes index.db lazy: nothing exists until the first index()),
2693
+ // so the carry memo's function ranges and the first-read map never wait on a ctx tool being granted. A failed pass never
2694
+ // crashes the run: it is recorded and the run goes on without ranges. One report-only record says what happened — the worker is told nothing.
2695
+ {
2696
+ const indexT0 = performance.now();
2697
+ /** @type {number|undefined} */ let indexedFiles;
2698
+ /** @type {string|undefined} */ let indexError;
2699
+ try {
2700
+ const res = await lc.index({ yield: true });
2701
+ if (typeof res?.files === 'number') indexedFiles = res.files;
2702
+ } catch (e) { indexError = String(/** @type {any} */ (e)?.message ?? e).slice(0, 300); }
2703
+ if (!ctxIndexRecorded) emitCtx('ctx-index', {
2704
+ indexed: lc.indexed === true,
2705
+ ...(indexedFiles === undefined ? {} : { files: indexedFiles }),
2706
+ ms: Math.round(performance.now() - indexT0),
2707
+ ...(indexError === undefined ? {} : { error: indexError }),
2708
+ });
2709
+ ctxIndexRecorded = true;
2710
+ }
2711
+ // R2c: the step's bridge tools sit beside its shell and ctx tools. Only the GRANTED names exist in `mcpRun.tools` (the bridge was started with `allow` = the
2712
+ // step's `mcpTools`), so an unsigned tool is not in the menu the Loop is given.
2713
+ const toolDefs = [...shell, ...ctx, ...(mcpRun ? mcpRun.tools : [])];
2676
2714
  // The carry note: records what each ask's read-class tools returned (a summary, never content) and hands the next
2677
2715
  // step/fix ask the facts. Scout and drafter asks feed the store but are never given a note.
2678
2716
  if (carry) carry.wrapTools(toolDefs);
2679
2717
  /** @param {(prompt: string, defs?: any) => Promise<any>} inner */
2680
2718
  const withCarry = (inner) => (!carry ? inner : async (/** @type {string} */ prompt, /** @type {any} */ defs) => {
2681
2719
  // The index is incremental: refreshing it here keeps the function ranges true to the files as they now are.
2682
- if (phase === 'fix' || phase.startsWith('step:')) { try { if (ctx.length) await lc.index({ yield: true }); } catch { /* ranges are left out */ } }
2720
+ if (phase === 'fix' || phase.startsWith('step:')) { try { await lc.index({ yield: true }); } catch { /* ranges are left out */ } }
2683
2721
  const text = await carry.beginAsk({ phase, iteration: roundIteration, prompt, getNode: (rel) => lc.getNode(rel) });
2684
2722
  try { return await inner(text ? `${prompt}\n\n${text}` : prompt, defs); } finally { carry.endAsk({ bounded: attemptBounded, iteration: roundIteration, rounds: attemptRounds }); }
2685
2723
  });
@@ -2703,7 +2741,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
2703
2741
  const readLines = grantedNames.has(TOOL_BY_VERB.read)
2704
2742
  ? (native && !shimArm.cap ? NATIVE_READ_STRATEGY : '') + readShimStrategy(shimArm)
2705
2743
  : '';
2706
- const system = PERSONA_TOOLS + strategyFor(granted) + readLines + anySuppressionWarning(closeStagesOf(job));
2744
+ const system = PERSONA_TOOLS + strategyFor(granted) + mcpStrategy(mcpRun ? mcpRun.names : []) + readLines + anySuppressionWarning(closeStagesOf(job));
2707
2745
  /** @param {any} u @returns {{inputTokens: number, outputTokens: number, cacheReadTokens: number, cacheCreationTokens: number}} */
2708
2746
  const usageOf = (u) => ({ inputTokens: u?.inputTokens ?? 0, outputTokens: u?.outputTokens ?? 0, cacheReadTokens: u?.cacheReadTokens ?? 0, cacheCreationTokens: u?.cacheCreationTokens ?? 0 });
2709
2747
 
@@ -3484,9 +3522,26 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
3484
3522
  * layer up. */
3485
3523
  let stepWallStop = null;
3486
3524
 
3487
- /** @param {any} step */
3525
+ /**
3526
+ * R2c (MCP+tickets piece 6): a step that grants MCP tools starts the bridge ONCE, before its worker is built, and closes it in a `finally` after the step's
3527
+ * LAST try (green, red, thrown or halted): a leaked child is an orphan process. A start refusal (server not configured, will not start, lacks a signed tool)
3528
+ * throws a plain-words `interpreter-red` from here, at $0 and before any token, which the step loop files as a step that could not be set up.
3529
+ * @param {any} step
3530
+ */
3488
3531
  const executeStep = async (step) => {
3489
- emit('step-start', { step: step.id, rounds: step.rounds, tools: step.tools });
3532
+ const wanted = Array.isArray(step.mcpTools) && step.mcpTools.length > 0;
3533
+ if (wanted && !(job.mcp && typeof job.mcp.server === 'string')) {
3534
+ const err = /** @type {CategorizedError} */ (new Error(`step "${step.id}" grants MCP tools but the job signed no MCP server`));
3535
+ err.category = 'interpreter-red';
3536
+ throw err;
3537
+ }
3538
+ const mcpRun = wanted ? await startStepMcp({ mcp: job.mcp, mcpTools: step.mcpTools }) : null;
3539
+ try { return await executeStepWith(step, mcpRun); } finally { await mcpRun?.close(); }
3540
+ };
3541
+
3542
+ /** @param {any} step @param {Awaited<ReturnType<typeof startStepMcp>>|null} mcpRun */
3543
+ const executeStepWith = async (step, mcpRun) => {
3544
+ emit('step-start', { step: step.id, rounds: step.rounds, tools: step.tools, ...(mcpRun ? { mcpTools: step.mcpTools } : {}) });
3490
3545
  // the before-side of every tree-changed exit, taken at STEP start: the
3491
3546
  // step's cumulative work is what the exit judges (outcome, never intent)
3492
3547
  const snapshot = new Map();
@@ -3525,6 +3580,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
3525
3580
  granted: step.tools, phase: `step:${step.id}`, attemptRounds: step.rounds, attempts: null, writable: true, root,
3526
3581
  fence: step.scope !== undefined ? [resolve(workdir, globToPrefix(step.scope))] : null,
3527
3582
  workerProvider: step.model !== undefined && providerFor ? providerFor(step.model) : null,
3583
+ mcpRun,
3528
3584
  });
3529
3585
  // ONE ladder per step: the seen-set and the strike count are this step's own
3530
3586
  // history, and a shared one would strike a fresh step for a gap an earlier step
@@ -0,0 +1,259 @@
1
+ // MCP + tickets piece 12 (ITEM33-BUILD addendum, "Piece 12 - check out the PR's code (head) into the run's worktree"): at RUN START, before the work branch and the seed
2
+ // read, the run's own worktree is moved to the head commit of a GitHub pull request. Plain git against the remote of the person's repo that names the PR's
3
+ // `owner/repo`; never the MCP, never a URL built from ticket text, never a push. The head sha comes from the frozen PR record through ONE accessor (`prHeadSha`).
4
+ //
5
+ // What this file is NOT: a PR reader. The frozen PR record is made by a reader that does not exist yet (its MCP tool name and toolset are an OPEN item for hamr).
6
+ // This file consumes a record that carries `head.sha` and refuses, in the spec's words, when it does not.
7
+ import { readFileSync, writeFileSync } from 'node:fs';
8
+ import { join, resolve } from 'node:path';
9
+ import { spawnClose } from './ralph.js';
10
+ import { npmEnv as credentialStrippedEnv } from './npminstall.js';
11
+ import { redactSecrets } from './validate.js';
12
+ import { prRefName, removePrRef } from './worktree.js';
13
+
14
+ export { prRefName };
15
+
16
+ /** the ONLY git subcommands this piece may run (spec item 10a): anything else throws before a process is made. Nothing that writes to a remote, to the person's config or to their index is on the list. */
17
+ export const PR_GIT_SUBCOMMANDS = Object.freeze(['fetch', 'rev-parse', 'checkout', 'merge-base', 'update-ref', 'worktree']);
18
+
19
+ /** the hard deadline of the fetch, in ms (spec item 3: 120 s; tighten-only, like the other clamps) */
20
+ export const PR_FETCH_DEADLINE_MS = 120_000;
21
+
22
+ /** none of the person's git hooks run for anything this piece does (the same spelling as src/worktree.js) */
23
+ const NO_HOOKS = Object.freeze(['-c', 'core.hooksPath=/dev/null/bareloop-no-hooks']);
24
+
25
+ /** the belt of spec item 10c: even if something tried a push through the fetching remote, its push address is a dead word */
26
+ const NO_PUSH = 'no-push-by-bareloop';
27
+
28
+ const PR_URL = /^https:\/\/github\.com\/([^/\s]+)\/([^/\s]+)\/pull\/(\d{1,10})\/?$/;
29
+ const SHA = /^[0-9a-f]{40}$/;
30
+
31
+ /**
32
+ * The PR address a ticket list gives: `https://github.com/<owner>/<repo>/pull/<n>`.
33
+ * @param {unknown} url
34
+ * @returns {{ok: true, owner: string, repo: string, number: number}|{ok: false, error: string}}
35
+ */
36
+ export function parsePrAddress(url) {
37
+ const m = typeof url === 'string' ? PR_URL.exec(url.trim()) : null;
38
+ if (!m) return { ok: false, error: 'This is not a GitHub pull request address.' };
39
+ const number = Number(m[3]);
40
+ if (!Number.isSafeInteger(number) || number < 1) return { ok: false, error: 'This is not a GitHub pull request address.' };
41
+ return { ok: true, owner: m[1], repo: m[2], number };
42
+ }
43
+
44
+ /**
45
+ * THE one accessor of the frozen PR record's head commit: GitHub's own `head.sha`. Everything in this file reads the head through here, so the day the reader's record
46
+ * names it differently there is one line to change. A record without a full 40-hex sha has no head (null).
47
+ * @param {any} record @returns {string|null}
48
+ */
49
+ export function prHeadSha(record) {
50
+ const sha = record?.head?.sha;
51
+ return typeof sha === 'string' && SHA.test(sha) ? sha : null;
52
+ }
53
+
54
+ /** the PR's base as the record gives it (`base.ref`, `base.sha`), or null when it names none @param {any} record @returns {{ref: string|null, sha: string}|null} */
55
+ export function prBaseOf(record) {
56
+ const sha = record?.base?.sha;
57
+ if (typeof sha !== 'string' || !SHA.test(sha)) return null;
58
+ return { ref: typeof record.base.ref === 'string' ? record.base.ref : null, sha };
59
+ }
60
+
61
+ /**
62
+ * The remotes a git config text declares, with their addresses AS WRITTEN (before any `insteadOf` rewrite): `[remote "name"]` sections, `url = ...` lines.
63
+ * Read from the config file instead of `git remote`, which would need a subcommand this piece is not allowed and prints the rewritten address.
64
+ * @param {string} text @returns {{name: string, url: string}[]}
65
+ */
66
+ export function remotesOfConfig(text) {
67
+ /** @type {{name: string, url: string}[]} */
68
+ const out = [];
69
+ let name = null;
70
+ for (const raw of text.split('\n')) {
71
+ const line = raw.trim();
72
+ const head = /^\[\s*([A-Za-z0-9.-]+)(?:\s+"((?:[^"\\]|\\.)*)")?\s*\]/.exec(line);
73
+ if (head) { name = head[1].toLowerCase() === 'remote' && head[2] !== undefined ? head[2].replace(/\\(.)/g, '$1') : null; continue; }
74
+ if (name === null) continue;
75
+ const kv = /^url\s*=\s*(.*)$/i.exec(line);
76
+ if (kv) out.push({ name, url: kv[1].trim().replace(/^"(.*)"$/, '$1') });
77
+ }
78
+ return out;
79
+ }
80
+
81
+ /**
82
+ * Does a remote address name `github.com/<owner>/<repo>`? https, ssh:// and the scp-like `git@github.com:owner/repo.git` forms; case-blind, `.git` optional.
83
+ * @param {string} url @param {string} owner @param {string} repo
84
+ */
85
+ export function remoteNames(url, owner, repo) {
86
+ const m = /^(?:[a-z][a-z0-9+.-]*:\/\/)?(?:[^/@\s]*@)?github\.com[:/]([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/i.exec(url.trim());
87
+ return m !== null && m[1].toLowerCase() === owner.toLowerCase() && m[2].toLowerCase() === repo.toLowerCase();
88
+ }
89
+
90
+ /** the remote to fetch from: `origin` when it names the repo, else the first that does; null = none @param {{name: string, url: string}[]} remotes @returns {{name: string, url: string}|null} */
91
+ export function matchRemote(remotes, owner, repo) {
92
+ const hits = remotes.filter((r) => remoteNames(r.url, owner, repo));
93
+ return hits.find((r) => r.name === 'origin') ?? hits[0] ?? null;
94
+ }
95
+
96
+ /** an address that carries a login: `https://user:pass@host`, `https://token@host`, or `ssh://user:pass@host` (a bare ssh user such as `git@` is not a secret) @param {string} url */
97
+ export function urlCarriesLogin(url) {
98
+ const m = /^([a-z][a-z0-9+.-]*):\/\/([^/@\s]*)@/i.exec(url.trim());
99
+ if (m === null) return false;
100
+ return /^https?$/i.test(m[1]) || m[2].includes(':');
101
+ }
102
+
103
+ /** the address with any login masked, for the words a person reads @param {string} url */
104
+ export function maskUrl(url) {
105
+ return url.trim().replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/@\s]*@/i, '$1***@');
106
+ }
107
+
108
+ /**
109
+ * The environment of every git child of this piece: the panel's env MINUS what `CLOSE_ENV_DENY` names (the one deny list, never re-spelled), KEEPING `HOME` and
110
+ * `SSH_AUTH_SOCK` (the documented exception: stripping it breaks git over ssh), with prompts off - no human is mid-run, so a credential question is a refusal, never a wait.
111
+ * @param {NodeJS.ProcessEnv} base @returns {NodeJS.ProcessEnv}
112
+ */
113
+ export function prGitEnv(base) {
114
+ const env = credentialStrippedEnv(base);
115
+ // the repo is named by the cwd; an inherited GIT_DIR would aim a child at some other repo
116
+ delete env.GIT_DIR; delete env.GIT_WORK_TREE; delete env.GIT_INDEX_FILE;
117
+ env.GIT_TERMINAL_PROMPT = '0';
118
+ env.SSH_ASKPASS_REQUIRE = 'never';
119
+ return env;
120
+ }
121
+
122
+ /**
123
+ * The argv of one git call. The subcommand is checked against `PR_GIT_SUBCOMMANDS` HERE, before any process exists.
124
+ * @param {string} sub @param {string[]} rest @param {string[]} [cfg] extra `-c key=value` words
125
+ * @returns {string[]}
126
+ */
127
+ export function prGitArgs(sub, rest, cfg = []) {
128
+ if (!PR_GIT_SUBCOMMANDS.includes(sub)) throw new Error(`git ${sub} is not one of the git calls the pull request checkout may make`);
129
+ return [...NO_HOOKS, ...cfg.flatMap((c) => ['-c', c]), sub, ...rest];
130
+ }
131
+
132
+ /**
133
+ * The fetch (spec item 3): the PR's head ref from the base repo into bareloop's private ref, so the object survives gc during the run and no branch, tag or FETCH_HEAD is touched.
134
+ * The `+` lets a Rerun move the ref when the PR was force-pushed since the last run.
135
+ * @param {string} remote @param {number} n @param {{writeFetchHead?: boolean}} [o] `false` (default) = `--no-write-fetch-head`
136
+ * @returns {string[]} the subcommand's own args (after `fetch`)
137
+ */
138
+ export function fetchRest(remote, n, { writeFetchHead = false } = {}) {
139
+ return ['--no-tags', '--no-recurse-submodules', ...(writeFetchHead ? [] : ['--no-write-fetch-head']), remote, `+refs/pull/${n}/head:${prRefName(n)}`];
140
+ }
141
+
142
+ /** git's reason, one line, with logins in addresses and secret shapes masked @param {string} stderr @param {string} [fallback] */
143
+ export function firstReason(stderr, fallback = 'no reason given') {
144
+ const line = redactSecrets(stderr).split('\n').map((l) => l.trim()).find((l) => l !== '') ?? fallback;
145
+ return line.replace(/([a-z][a-z0-9+.-]*:\/\/)[^/@\s]*@/gi, '$1***@').slice(0, 300);
146
+ }
147
+
148
+ /**
149
+ * @typedef {object} PrCheckout
150
+ * @property {string} sha the PR's head commit, now the worktree's detached HEAD @property {number} number @property {string} ownerRepo `owner/repo`
151
+ * @property {string} remote the remote the fetch used @property {string} ref the private ref @property {{ref: string|null, sha: string}|null} base @property {string|null} mergeBase
152
+ */
153
+
154
+ /**
155
+ * RUN START for a PR job: fetch the PR's head, verify it is the sha the frozen record names, and move the run's worktree there (detached). Every refusal is plain words
156
+ * that end in "Nothing spent." and leaves no private ref behind. Never pushes; the person's own tree is never touched (the worktree is the run's).
157
+ * @param {object} o
158
+ * @param {string} o.repo the person's repo root (the worktree's `repo` in source.json) @param {string} o.worktree the run's worktree
159
+ * @param {{url: string, record: any, reread?: () => Promise<any>}} o.pr `url` = the PR address; `record` = the frozen PR record; `reread` = optional: read the record again (one try, spec item 5)
160
+ * @param {NodeJS.ProcessEnv} [o.env] @param {number} [o.timeoutMs] @param {typeof spawnClose} [o.run] test seam for the child process
161
+ * @returns {Promise<{ok: true, checkout: PrCheckout}|{ok: false, error: string}>}
162
+ */
163
+ export async function checkoutPrHead({ repo, worktree, pr, env = process.env, timeoutMs = PR_FETCH_DEADLINE_MS, run = spawnClose }) {
164
+ const tail = 'Nothing spent.';
165
+ const addr = parsePrAddress(pr.url);
166
+ if (!addr.ok) return addr;
167
+ const { owner, repo: name, number: n } = addr;
168
+ const ref = prRefName(n);
169
+ const noCode = { ok: /** @type {const} */ (false), error: `Pull request #${n} has no code to fetch (GitHub did not offer its head). ${tail}` };
170
+ const want = prHeadSha(pr.record);
171
+ if (want === null) return noCode;
172
+
173
+ const childEnv = prGitEnv(env);
174
+ const git = (/** @type {string} */ cwd, /** @type {string} */ sub, /** @type {string[]} */ rest, /** @type {string[]} */ cfg = []) => run('git', prGitArgs(sub, rest, cfg), { env: childEnv, cwd, timeoutMs });
175
+ const out = (/** @type {{stdout: string}} */ r) => r.stdout.trim();
176
+
177
+ // which remote: the person's own repo config, matched by owner/repo; no address is ever built from the ticket
178
+ const common = await git(repo, 'rev-parse', ['--git-common-dir']);
179
+ if (common.error || common.status !== 0) return { ok: false, error: `Git could not fetch pull request #${n} (${firstReason(common.stderr, 'this folder is not a git repository')}). Check your git login for this repo. ${tail}` };
180
+ let configText = '';
181
+ try { configText = readFileSync(join(resolve(repo, out(common)), 'config'), 'utf8'); } catch { configText = ''; }
182
+ const remote = matchRemote(remotesOfConfig(configText), owner, name);
183
+ if (remote === null) return { ok: false, error: `No remote in this repo points at ${owner}/${name}, so the pull request's code cannot be fetched. ${tail}` };
184
+ if (urlCarriesLogin(remote.url)) return { ok: false, error: `The remote ${remote.name} (${maskUrl(remote.url)}) has a login in its address, which bareloop will not use; use an ssh address or a git credential helper. ${tail}` };
185
+
186
+ /** @param {string} message @returns {{ok: false, error: string}} */
187
+ const failed = (message) => { removePrRef(repo, n); return { ok: false, error: message }; };
188
+ const cfg = [`remote.${remote.name}.pushurl=${NO_PUSH}`];
189
+ /** one fetch + rev-parse; a git that does not know --no-write-fetch-head (before 2.29) is run again without it @param {boolean} writeFetchHead */
190
+ const fetchOnce = async (writeFetchHead = false) => {
191
+ const r = await git(repo, 'fetch', fetchRest(remote.name, n, { writeFetchHead }), cfg);
192
+ if (!writeFetchHead && r.status !== 0 && /no-write-fetch-head/.test(r.stderr) && /unknown|unrecognized/i.test(r.stderr)) return fetchOnce(true);
193
+ return r;
194
+ };
195
+ /** @returns {Promise<{ok: true, sha: string}|{ok: false, error: string}>} */
196
+ const fetchAndRead = async () => {
197
+ const f = await fetchOnce();
198
+ if (f.error) {
199
+ if (/** @type {any} */ (f.error).code === 'ETIMEDOUT') return { ok: false, error: `Fetching pull request #${n} took longer than ${Math.round(timeoutMs / 1000)} seconds. ${tail}` };
200
+ return { ok: false, error: `Git could not fetch pull request #${n} (${firstReason(String(f.error.message ?? f.error))}). Check your git login for this repo. ${tail}` };
201
+ }
202
+ if (f.status !== 0) return { ok: false, error: `Git could not fetch pull request #${n} (${firstReason(f.stderr)}). Check your git login for this repo. ${tail}` };
203
+ const rp = await git(repo, 'rev-parse', ['--verify', '--quiet', `${ref}^{commit}`]);
204
+ if (rp.error || rp.status !== 0 || !SHA.test(out(rp))) return { ok: false, error: `Git could not fetch pull request #${n} (the fetched ref could not be read). Check your git login for this repo. ${tail}` };
205
+ return { ok: true, sha: out(rp) };
206
+ };
207
+
208
+ let got = await fetchAndRead();
209
+ if (!got.ok) return failed(got.error);
210
+ let sha = want;
211
+ if (got.sha !== want) {
212
+ // the PR moved after it was read: ONE re-read of the record and ONE re-fetch; the frozen text and the checked-out code must describe the same commit
213
+ const moved = { ok: /** @type {const} */ (false), error: `The pull request changed while the run was starting. Run it again. ${tail}` };
214
+ const again = typeof pr.reread === 'function' ? await pr.reread() : null;
215
+ const wantAgain = again === null ? null : prHeadSha(again);
216
+ if (wantAgain === null) return failed(moved.error);
217
+ got = await fetchAndRead();
218
+ if (!got.ok) return failed(got.error);
219
+ if (got.sha !== wantAgain) return failed(moved.error);
220
+ sha = wantAgain;
221
+ }
222
+
223
+ // the checkout: the run's OWN worktree, detached at the head; nothing is committed
224
+ const co = await git(worktree, 'checkout', ['--detach', sha]);
225
+ if (co.error || co.status !== 0) return failed(`Git could not fetch pull request #${n} (it could not be checked out: ${firstReason(co.stderr || String(co.error?.message ?? ''))}). Check your git login for this repo. ${tail}`);
226
+
227
+ const base = prBaseOf(pr.record);
228
+ let mergeBase = null;
229
+ if (base !== null) {
230
+ const mb = await git(repo, 'merge-base', [base.sha, sha]);
231
+ mergeBase = !mb.error && mb.status === 0 && SHA.test(out(mb)) ? out(mb) : null; // a base this repo has not got is unrecorded, not a refusal
232
+ }
233
+ return { ok: true, checkout: { sha, number: n, ownerRepo: `${owner}/${name}`, remote: remote.name, ref, base, mergeBase } };
234
+ }
235
+
236
+ /**
237
+ * A RESUME's check (spec item 12): the recorded PR head is an ancestor of the worktree's HEAD, so the work branch still holds the PR's code. No fetch.
238
+ * @param {string} worktree @param {string} prHead @param {{run?: typeof spawnClose, env?: NodeJS.ProcessEnv}} [o]
239
+ * @returns {Promise<boolean>}
240
+ */
241
+ export async function prHeadIsAncestor(worktree, prHead, { run = spawnClose, env = process.env } = {}) {
242
+ if (!SHA.test(prHead)) return false;
243
+ const r = await run('git', prGitArgs('merge-base', ['--is-ancestor', prHead, 'HEAD']), { env: prGitEnv(env), cwd: worktree, timeoutMs: PR_FETCH_DEADLINE_MS });
244
+ return !r.error && r.status === 0;
245
+ }
246
+
247
+ /**
248
+ * Write the checkout into the run's `source.json` (spec item 6): `seed:<sha>`, `prHead`, `prNumber`, `prBase:{ref,sha}`. Only these fields change.
249
+ * @param {string} into the prepared copy's folder (holds source.json) @param {PrCheckout} c
250
+ */
251
+ export function recordPrOnManifest(into, c) {
252
+ const file = join(resolve(into), 'source.json');
253
+ const manifest = JSON.parse(readFileSync(file, 'utf8'));
254
+ manifest.seed = c.sha;
255
+ manifest.prHead = c.sha;
256
+ manifest.prNumber = c.number;
257
+ manifest.prBase = c.base;
258
+ writeFileSync(file, `${JSON.stringify(manifest, null, 2)}\n`);
259
+ }
package/src/readshim.js CHANGED
@@ -371,9 +371,9 @@ export function buildReadMap({ rel, lines, chunks }) {
371
371
  }
372
372
 
373
373
  /**
374
- * @typedef {{root: string, hasGet: boolean, getNode: (rel: string) => any, refresh?: (() => Promise<unknown>)|null, emit: (type: string, data: object) => void}} ReadMapOpts
374
+ * @typedef {{root: string, hasGet: boolean, getNode: (rel: string) => any, indexed?: (() => boolean)|null, refresh?: (() => Promise<unknown>)|null, emit: (type: string, data: object) => void}} ReadMapOpts
375
375
  * `root`: the job root (paths are made relative to it); `hasGet`: this worker holds `ctx_get` (a map hands out handles only that tool opens);
376
- * `getNode`: the LiteCtx index's node for a path (its `chunks`); `refresh`: re-index first so the ranges are true to the file as it now is;
376
+ * `getNode`: the LiteCtx index's node for a path (its `chunks`); `indexed`: whether the job has an index at all (`lc.indexed`; false skips with `no-index`); `refresh`: re-index first so the ranges are true to the file as it now is;
377
377
  * `emit`: the spine channel, for the report-only `read-map` / `read-map-skip` records (counts and a reason, never text).
378
378
  */
379
379
 
@@ -532,6 +532,7 @@ export function createReadShim({ cap = READ_SHIM_CAP, arm = ARM_ALL, onCount = n
532
532
  let chunks;
533
533
  try {
534
534
  if (o.refresh) await o.refresh();
535
+ if (o.indexed && !o.indexed()) return skip('no-index');
535
536
  chunks = o.getNode(rel)?.chunks;
536
537
  } catch { return skip('no-index'); }
537
538
  if (!Array.isArray(chunks)) return skip('no-index');
package/src/replay.js CHANGED
@@ -683,6 +683,9 @@ export function replayRun(spineEvents, auditEvents = [], { runId = null, auditAv
683
683
  // occurrence is never left with just a bare category word when the
684
684
  // record actually explains itself.
685
685
  detail: trimTo(e.detail, TRIP_DETAIL_MAX) ?? trimTo(e.decision, TRIP_DETAIL_MAX),
686
+ // the step ladder's own stop is ALSO category `cap-halt` (real spine u-mshcpdg4 seq 185) but carries `spend.strikes`; a money cap's
687
+ // escalation does not (u-msi0w2i5 seq 143). An ADDED field, only when the ladder ended the step.
688
+ ...(typeof e.spend?.strikes === 'number' ? { ladder: true } : {}),
686
689
  } : null);
687
690
 
688
691
  /**
@@ -1411,6 +1414,9 @@ export function replayRun(spineEvents, auditEvents = [], { runId = null, auditAv
1411
1414
  spentUsd: step.spentUsd,
1412
1415
  unpricedRounds: step.unpricedRounds,
1413
1416
  outcome: step.outcome,
1417
+ // the escalation inside the step's window (category/detail, `ladder` when its own strike limit ended it): the panel reads it to
1418
+ // tell a step the cap escalated from a step the ladder escalated (src/panel/server.js cappedLastStep)
1419
+ ...(step.tripped ? { tripped: step.tripped } : {}),
1414
1420
  // P5-R (resumed runs only): why its leg's halt cut this step off, whether it is the same step continuing
1415
1421
  // from the leg before, and its retry count not counting continuations
1416
1422
  ...(step.stopReason === undefined ? {} : { stopReason: step.stopReason, continued: step.continued, tryNumber: step.tryNumber }),
package/src/reuse.js CHANGED
@@ -1647,7 +1647,7 @@ export async function runReuse(opts) {
1647
1647
  // TERMINAL rather than on the absence of a plan. `already-green` means the
1648
1648
  // close was satisfied at the precheck — before this leg wrote a byte — so
1649
1649
  // whatever plan is on the spine did not produce it, and minting a version
1650
- // from one would be learning credit for work that did not happen.
1650
+ // from one would be reuse credit for work that did not happen.
1651
1651
  //
1652
1652
  // It used to be covered by accident: a cold already-green never drafts, so
1653
1653
  // `read.plan` was null and the branch below caught it. N4 broke that
@@ -2150,7 +2150,7 @@ export function writeGreenRow({ registryDir, bridge = null, meta, record }) {
2150
2150
  * row, and if so, write it.
2151
2151
  *
2152
2152
  * `scripts/run-u.mjs` has always kept standalone bridge FILES and never a registry,
2153
- * so its review door could describe a held learning credit it had no row to release:
2153
+ * so its review door could describe a held reuse credit it had no row to release:
2154
2154
  * `--decide accept` reached `recordDoor`, found no green row for the runid and died
2155
2155
  * `no-row-for-run`. This is the row, and STORAGE IS ALL IT IS — selection, promotion
2156
2156
  * and reuse execution stay parked (layer-3-reuse). Nothing here reads a row back.
@@ -2207,7 +2207,7 @@ export function writeRunGreenRow({ registryDir, job, name, outcome, plan, record
2207
2207
  /**
2208
2208
  * Apply a signer's door decision to the workflow a run wrote its row against:
2209
2209
  * record the disposition, and — on `accept` over a HELD judged green — release the
2210
- * learning credit that green has been carrying unspent (PRD v1.71 §3).
2210
+ * reuse credit that green has been carrying unspent (PRD v1.71 §3).
2211
2211
  *
2212
2212
  * This is the ONE seam between a person's answer and the box. It is deliberately
2213
2213
  * separate from `runReuse`: the door opens AFTER the run has ended (a green run is
package/src/revises.js ADDED
@@ -0,0 +1,56 @@
1
+ // M4e amendment 14 item 3 (fwdloop v0.29.0), the bareloop mapping: a draft has 2 revises, then the button reads Start over (a fresh draft with its own 2).
2
+ // A revise or Start over is a NEW authoring session here (the old draft is ended, the boxes reopen), so the count rides the carry link: a session folder holds
3
+ // `revises.json` ({used}); a draft that follows another by Revise has that draft's used + 1, one that follows by Start over (or follows nothing) has 0. The server is
4
+ // the only reader that decides: a refresh brings the count back from the session's own state, and a third revise is refused at $0 before anything is ended or sent.
5
+ import { readFileSync, writeFileSync } from 'node:fs';
6
+ import { join } from 'node:path';
7
+
8
+ export const MAX_REVISES = 2;
9
+ /** the count's file, inside a drafting session folder only */
10
+ export const REVISES_FILE = 'revises.json';
11
+ const SESSION_ID = /^s[a-z0-9]+$/;
12
+
13
+ /** The one spelling of the drafting sessions folder (the session and the routes both read it).
14
+ * @param {string|undefined} root */
15
+ export function sessionsRootOf(root) {
16
+ return root ?? join(process.env.HOME ?? '/tmp', '.config', 'bareloop', 'panel-sessions');
17
+ }
18
+
19
+ /** @param {string} root @param {string} id revises used by that draft; no file, or an unreadable one, is 0 (a draft from before the count existed)
20
+ * @returns {number} */
21
+ export function revisesUsedOf(root, id) {
22
+ if (!SESSION_ID.test(id)) return 0;
23
+ try {
24
+ const n = Number(JSON.parse(readFileSync(join(root, id, REVISES_FILE), 'utf8')).used);
25
+ return Number.isInteger(n) && n >= 0 ? n : 0;
26
+ } catch { return 0; }
27
+ }
28
+
29
+ /** The revises a draft will have used, given what it follows: a Revise adds one to the draft it follows; Start over, or following nothing, starts at 0.
30
+ * @param {string} root @param {unknown} carryFrom @param {unknown} carryKind
31
+ * @returns {number} */
32
+ export function nextRevisesUsed(root, carryFrom, carryKind) {
33
+ return carryKind === 'revise' && typeof carryFrom === 'string' ? revisesUsedOf(root, carryFrom) + 1 : 0;
34
+ }
35
+
36
+ /** Plain words when that revise would be a third; null when it is allowed. $0: called before anything is ended or started.
37
+ * @param {string} root @param {unknown} carryFrom @param {unknown} carryKind
38
+ * @returns {string|null} */
39
+ export function reviseRefusal(root, carryFrom, carryKind) {
40
+ if (nextRevisesUsed(root, carryFrom, carryKind) <= MAX_REVISES) return null;
41
+ return `This draft has used its ${MAX_REVISES} revises. Start over: it keeps the boxes and gives ${MAX_REVISES} new revises. Nothing was sent.`;
42
+ }
43
+
44
+ /** The words the draft record and the Audit use for a draft that follows another (fwdloop am14 item 6): `revise 1`, `revise 2`, `start over`; a first draft has none.
45
+ * @param {unknown} carryFrom @param {unknown} carryKind @param {number} used this draft's revises used
46
+ * @returns {string|null} */
47
+ export function draftLabelOf(carryFrom, carryKind, used) {
48
+ if (typeof carryFrom !== 'string') return null;
49
+ if (carryKind === 'revise') return `revise ${used}`;
50
+ return carryKind === 'startover' ? 'start over' : null;
51
+ }
52
+
53
+ /** @param {string} dir the session's folder @param {number} used */
54
+ export function writeRevisesUsed(dir, used) {
55
+ try { writeFileSync(join(dir, REVISES_FILE), `${JSON.stringify({ used })}\n`, { mode: 0o600 }); } catch { /* the count is a convenience: a disk fault only means a later Revise reads 0 */ }
56
+ }