bareloop 0.54.1 → 0.55.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/CHANGELOG.md +75 -0
  2. package/bareloop.context.md +65 -6
  3. package/package.json +3 -3
  4. package/src/authorflow.js +148 -46
  5. package/src/authoring.js +21 -4
  6. package/src/authorjob.js +82 -3
  7. package/src/authorreadout.js +20 -3
  8. package/src/authorrun.js +1 -1
  9. package/src/authorscout.js +9 -6
  10. package/src/cardschedule.js +42 -0
  11. package/src/checkpick.js +576 -0
  12. package/src/checksuggest.js +28 -0
  13. package/src/checkwords.js +25 -0
  14. package/src/cli.js +1 -1
  15. package/src/config.js +24 -1
  16. package/src/declaredclose.js +1 -1
  17. package/src/destpoint.js +149 -0
  18. package/src/draftspend.js +39 -0
  19. package/src/factwords.js +14 -1
  20. package/src/job.js +81 -1
  21. package/src/jobblock.js +9 -0
  22. package/src/labelscan.js +11 -0
  23. package/src/launcher.js +3 -2
  24. package/src/mcpchecks.js +52 -0
  25. package/src/mcppick.js +36 -0
  26. package/src/mcpsources.js +77 -0
  27. package/src/mcpuse.js +97 -0
  28. package/src/natural.js +23 -0
  29. package/src/pagemap.js +5 -2
  30. package/src/panel/authorroutes.js +90 -15
  31. package/src/panel/authorsession.js +183 -21
  32. package/src/panel/index.html +686 -26
  33. package/src/panel/jobgrid.js +117 -0
  34. package/src/panel/jobplan.js +31 -15
  35. package/src/panel/scheduler.js +80 -13
  36. package/src/panel/schedules.js +189 -28
  37. package/src/panel/schedulestart.js +44 -13
  38. package/src/panel/server.js +419 -32
  39. package/src/panel/settingsroutes.js +133 -3
  40. package/src/panel/status.js +19 -1
  41. package/src/panel/tickets.js +44 -0
  42. package/src/pickrecord.js +145 -0
  43. package/src/plan.js +31 -2
  44. package/src/planrun.js +71 -15
  45. package/src/prcheckout.js +259 -0
  46. package/src/readshim.js +3 -2
  47. package/src/revises.js +56 -0
  48. package/src/rubricstep.js +62 -16
  49. package/src/run.js +10 -1
  50. package/src/runexport.js +2 -0
  51. package/src/runlist.js +3 -2
  52. package/src/schedulewords.js +46 -4
  53. package/src/source.js +81 -7
  54. package/src/stepmcp.js +86 -0
  55. package/src/ticket.js +113 -0
  56. package/src/ticketfilter.js +76 -0
  57. package/src/ticketlabels.js +79 -0
  58. package/src/ticketmcp.js +111 -0
  59. package/src/ticketnext.js +35 -0
  60. package/src/ticketrepo.js +98 -0
  61. package/src/ticketschedule.js +32 -0
  62. package/src/ticketshape.js +45 -0
  63. package/src/tools.js +9 -0
  64. package/src/trigger.js +14 -2
  65. package/src/triggerclock.js +7 -3
  66. package/src/triggerfiles.js +19 -11
  67. package/src/triggertickets.js +244 -0
  68. package/src/userrun.js +145 -9
  69. package/src/validate.js +3 -1
  70. package/src/worktree.js +43 -1
  71. package/types/authorflow.d.ts +128 -28
  72. package/types/authorjob.d.ts +16 -3
  73. package/types/authorreadout.d.ts +9 -2
  74. package/types/authorscout.d.ts +4 -2
  75. package/types/cardschedule.d.ts +24 -0
  76. package/types/checkpick.d.ts +297 -0
  77. package/types/checksuggest.d.ts +30 -0
  78. package/types/checkwords.d.ts +14 -0
  79. package/types/config.d.ts +7 -0
  80. package/types/destpoint.d.ts +87 -0
  81. package/types/draftspend.d.ts +16 -0
  82. package/types/factwords.d.ts +7 -0
  83. package/types/job.d.ts +13 -0
  84. package/types/jobblock.d.ts +9 -0
  85. package/types/labelscan.d.ts +7 -0
  86. package/types/launcher.d.ts +2 -2
  87. package/types/mcpchecks.d.ts +8 -0
  88. package/types/mcppick.d.ts +33 -0
  89. package/types/mcpsources.d.ts +51 -0
  90. package/types/mcpuse.d.ts +15 -0
  91. package/types/natural.d.ts +2 -0
  92. package/types/pagemap.d.ts +2 -1
  93. package/types/panel/authorroutes.d.ts +11 -2
  94. package/types/panel/authorsession.d.ts +58 -3
  95. package/types/panel/jobgrid.d.ts +405 -0
  96. package/types/panel/jobplan.d.ts +10 -4
  97. package/types/panel/scheduler.d.ts +7 -2
  98. package/types/panel/schedules.d.ts +124 -4
  99. package/types/panel/schedulestart.d.ts +21 -3
  100. package/types/panel/server.d.ts +427 -6
  101. package/types/panel/settingsroutes.d.ts +4 -2
  102. package/types/panel/status.d.ts +16 -2
  103. package/types/panel/tickets.d.ts +61 -0
  104. package/types/pickrecord.d.ts +88 -0
  105. package/types/plan.d.ts +1 -0
  106. package/types/prcheckout.d.ts +151 -0
  107. package/types/readshim.d.ts +4 -3
  108. package/types/revises.d.ts +23 -0
  109. package/types/rubricstep.d.ts +14 -5
  110. package/types/run.d.ts +18 -1
  111. package/types/runlist.d.ts +6 -3
  112. package/types/schedulewords.d.ts +29 -2
  113. package/types/source.d.ts +40 -4
  114. package/types/stepmcp.d.ts +40 -0
  115. package/types/ticket.d.ts +114 -0
  116. package/types/ticketfilter.d.ts +34 -0
  117. package/types/ticketlabels.d.ts +44 -0
  118. package/types/ticketmcp.d.ts +84 -0
  119. package/types/ticketnext.d.ts +33 -0
  120. package/types/ticketrepo.d.ts +118 -0
  121. package/types/ticketschedule.d.ts +21 -0
  122. package/types/ticketshape.d.ts +37 -0
  123. package/types/tools.d.ts +1 -0
  124. package/types/trigger.d.ts +9 -1
  125. package/types/triggerclock.d.ts +6 -2
  126. package/types/triggerfiles.d.ts +13 -5
  127. package/types/triggertickets.d.ts +110 -0
  128. package/types/userrun.d.ts +50 -0
  129. package/types/validate.d.ts +1 -0
  130. package/types/worktree.d.ts +19 -0
@@ -0,0 +1,77 @@
1
+ // borrowed-from: fwdloop src/mcp-sources.js@6cdc01e (CONFIG-LOOKUP core only: no routes, no UI, no `check tools` - the Settings > MCP tab and its routes come in R3)
2
+ // Where bareloop's MCP servers come from, decided in ONE place. Sources, in order: the 4 places bare-agent reads, then the paths the person added
3
+ // (config.json `mcpPaths`, absolute, in the order added). A project folder's `.mcp.json` is never read: every path here is explicit, bare-agent's default
4
+ // discovery is never called. bare-agent's `discoverServers` is called once PER PATH (it merges silently and keeps no file of origin); the merge, "first
5
+ // wins" and the shadow mark are done here. A server with no `command` (a remote one) is listed and marked `remote`: it is never started. This file only
6
+ // READS config files and returns names, flags and file paths; a command, its args and its env are never copied out of `discoverServers`' result.
7
+ import { discoverServers } from 'bare-agent/mcp';
8
+ import { existsSync, readFileSync } from 'node:fs';
9
+ import { homedir } from 'node:os';
10
+ import { join } from 'node:path';
11
+ import { readConfig } from './config.js';
12
+
13
+ export { mcpPathProblem } from './config.js';
14
+
15
+ /** the 4 places bare-agent reads, in its order (absolute) @returns {string[]} */
16
+ export const DEFAULT_MCP_PLACES = (home = homedir()) => {
17
+ const h = home;
18
+ return [join(h, '.mcp.json'), join(h, '.claude', 'mcp_servers.json'), join(h, '.config', 'Claude', 'claude_desktop_config.json'), join(h, '.cursor', 'mcp.json')];
19
+ };
20
+
21
+ /** a path as the person sees it: the home folder written `~` @param {string} p @param {string} [home] the person's home folder (tests inject a fixture one) */
22
+ export const showMcpPath = (p, home = homedir()) => { const h = home; return p === h ? '~' : p.startsWith(`${h}/`) ? `~${p.slice(h.length)}` : p; };
23
+
24
+ /** a typed path with a leading `~` or `~/` written out (the config stores absolute paths only) @param {string} p @param {string} [home] */
25
+ export const expandMcpPath = (p, home = homedir()) => (p === '~' ? home : p.startsWith('~/') ? join(home, p.slice(2)) : p);
26
+
27
+ /**
28
+ * The added paths in config.json; none when the file is missing, and a plain-words `problem` when it cannot be read (never papered over).
29
+ * @param {string} [home] the config home (tests); undefined = `~/.config/bareloop`
30
+ * @returns {{ paths: string[], problem: string|null }}
31
+ */
32
+ export function addedMcpPaths(home) {
33
+ const r = readConfig(home === undefined ? {} : { home });
34
+ if (r.problem) return { paths: [], problem: 'Your settings file (config.json) cannot be read, so added MCP paths are not used.' };
35
+ return { paths: Array.isArray(r.config.mcpPaths) ? /** @type {string[]} */ (r.config.mcpPaths) : [], problem: null };
36
+ }
37
+
38
+ /**
39
+ * Every place, in order, with the servers found in it.
40
+ * `status`: 'found' (a readable file), 'missing' (no file) or 'not-json' (a file that is not JSON; bare-agent skips it silently).
41
+ * A server: `{name, remote, shadowedBy}`; `shadowedBy` is the shown path of the earlier place that has the same name (the earlier one wins), or null.
42
+ * @param {{ home?: string, mcpHome?: string }} [o] `home` the config home (tests); `mcpHome` the person's home folder the four places live under
43
+ * (tests inject a fixture one so discovery never reads the real `~`; undefined = `os.homedir()`)
44
+ * @returns {{ places: Array<{ path: string, file: string, added: boolean, status: 'found'|'missing'|'not-json', servers: Array<{name: string, remote: boolean, shadowedBy: string|null}> }>, problem: string|null }}
45
+ */
46
+ export function mcpSources(o = {}) {
47
+ const added = addedMcpPaths(o.home);
48
+ const typed = [...DEFAULT_MCP_PLACES(o.mcpHome).map((p) => ({ path: showMcpPath(p, o.mcpHome), file: p, added: false })), ...added.paths.map((p) => ({ path: showMcpPath(p, o.mcpHome), file: p, added: true }))];
49
+ /** @type {Map<string, string>} */
50
+ const first = new Map();
51
+ const places = typed.map(({ path, file, added: isAdded }) => {
52
+ if (!existsSync(file)) return { path, file, added: isAdded, status: /** @type {const} */ ('missing'), servers: [] };
53
+ try { JSON.parse(readFileSync(file, 'utf8')); } catch { return { path, file, added: isAdded, status: /** @type {const} */ ('not-json'), servers: [] }; }
54
+ const found = discoverServers([file]);
55
+ const servers = [...found].map(([name, def]) => {
56
+ const shadowedBy = first.get(name) ?? null;
57
+ if (shadowedBy === null) first.set(name, path);
58
+ return { name, remote: typeof def?.command !== 'string' || def.command === '', shadowedBy };
59
+ });
60
+ return { path, file, added: isAdded, status: /** @type {const} */ ('found'), servers };
61
+ });
62
+ return { places, problem: added.problem };
63
+ }
64
+
65
+ /**
66
+ * The file that holds the WINNING `server` (the first place in the list that has the name), whether it is remote, or null when no place has it.
67
+ * Every place bareloop starts an MCP from takes its config file from here.
68
+ * @param {string} server @param {{ home?: string, mcpHome?: string }} [o]
69
+ * @returns {{ file: string, remote: boolean } | null}
70
+ */
71
+ export function mcpConfigFor(server, o = {}) {
72
+ for (const p of mcpSources(o).places) {
73
+ const s = p.servers.find((x) => x.name === server);
74
+ if (s) return { file: p.file, remote: s.remote };
75
+ }
76
+ return null;
77
+ }
package/src/mcpuse.js ADDED
@@ -0,0 +1,97 @@
1
+ // borrowed-from: fwdloop src/mcp-use.js@105f81a (re-shaped: fwd scans its run folders; bareloop reads the run list's spines. fwd's post-tag 4a06ae7 `hasOwnProperty` fix is NOT copied: tool counts are read with Object.hasOwn from the start)
2
+ // How often each MCP server's tools were used, read from what runs already record. Nothing new is written, nothing is started.
3
+ // - a ticket read: `source.json` (beside the run's prepared copy) `mcp.calls` (a plain-folder / rubric job) or `inputs[].mcp.calls`; for a CODE-REPO job the
4
+ // frozen ticket's `mcp.calls` ride on the spine's FIRST `job-start` record (`ticket.mcp`), and only that one (a resumed leg repeats it). The file holds no time,
5
+ // so `last` is the file's mtime (the job-start's `ts` for a repo job);
6
+ // - a step's tool call: a gate-audit row (`phase:"gate"`) in the run's work folder whose action type is `<server>_<tool>` (the step bridge names a tool so);
7
+ // `decision:"deny"` is a denied call, counted apart and not as a use.
8
+ // A torn or unreadable file is skipped, row by row (its rows go missing from the count; it never breaks the page). A run whose spine is not under a `source-<seed>`
9
+ // folder (a bundle run) has no source.json and no work folder to find: it is not counted, never guessed.
10
+ import { readFileSync, statSync } from 'node:fs';
11
+ import { dirname, join } from 'node:path';
12
+ import { sourceNearSpine } from './runfiles.js';
13
+ import { GATE_AUDIT_FILE } from './kinds.js';
14
+
15
+ /** @param {string} p */
16
+ const readJson = (p) => { try { return JSON.parse(readFileSync(p, 'utf8')); } catch { return null; } };
17
+
18
+ /** the ticket-read records of one run: `[{server, tool, at}]` @param {string} spine @returns {Array<{server: string, tool: string, at: string}>} */
19
+ function ticketCalls(spine) {
20
+ /** @type {Array<{server: string, tool: string, at: string}>} */
21
+ const out = [];
22
+ const near = sourceNearSpine(spine);
23
+ const add = (/** @type {any} */ m, /** @type {string} */ at) => {
24
+ if (!m || typeof m.server !== 'string') return;
25
+ for (const c of Array.isArray(m.calls) ? m.calls : []) if (c && typeof c === 'object' && Object.hasOwn(c, 'tool') && typeof c.tool === 'string') out.push({ server: m.server, tool: c.tool, at });
26
+ };
27
+ if (near.sourceJsonPath) {
28
+ const j = readJson(near.sourceJsonPath);
29
+ let at = '';
30
+ try { at = statSync(near.sourceJsonPath).mtime.toISOString(); } catch { /* no time */ }
31
+ if (j && typeof j === 'object') {
32
+ add(j.mcp, at);
33
+ for (const i of Array.isArray(j.inputs) ? j.inputs : []) add(i?.mcp, at);
34
+ }
35
+ }
36
+ let text = '';
37
+ try { text = readFileSync(spine, 'utf8'); } catch { return out; }
38
+ for (const line of text.split('\n')) {
39
+ if (!line.includes('"type":"job-start"')) continue;
40
+ let r;
41
+ try { r = JSON.parse(line); } catch { continue; }
42
+ if (r?.type !== 'job-start') continue;
43
+ if (r.ticket?.mcp) add(r.ticket.mcp, typeof r.ts === 'string' ? r.ts : '');
44
+ break; // the first leg's job-start only
45
+ }
46
+ return out;
47
+ }
48
+
49
+ /** the gate-audit files of one run's work folder(s) @param {string} spine @returns {string[]} */
50
+ function auditFiles(spine) {
51
+ const near = sourceNearSpine(spine);
52
+ if (!near.sourceJsonPath) return [];
53
+ const files = [join(dirname(near.sourceJsonPath), 'tree', GATE_AUDIT_FILE)];
54
+ const wt = readJson(near.sourceJsonPath)?.worktree;
55
+ if (typeof wt === 'string' && wt !== '') files.push(join(wt, GATE_AUDIT_FILE));
56
+ return files;
57
+ }
58
+
59
+ /**
60
+ * @param {Array<{ spine?: string, runid?: string }>} rows the run list's rows (`readRunList().rows`)
61
+ * @param {string[]} servers the server names to count for; a step tool row belongs to the LONGEST name that prefixes it with `_`
62
+ * @returns {Map<string, { calls: number, runs: number, last: string|null, denied: number, tools: Map<string, number> }>}
63
+ */
64
+ export function countMcpUse(rows, servers) {
65
+ const byLength = [...servers].sort((a, b) => b.length - a.length);
66
+ /** @type {Map<string, { calls: number, runSet: Set<string>, last: string, denied: number, tools: Map<string, number> }>} */
67
+ const acc = new Map(servers.map((s) => [s, { calls: 0, runSet: new Set(), last: '', denied: 0, tools: new Map() }]));
68
+ const use = (/** @type {string} */ server, /** @type {string} */ tool, /** @type {string} */ run, /** @type {string} */ at, /** @type {boolean} */ denied) => {
69
+ const a = acc.get(server);
70
+ if (!a) return;
71
+ if (denied) { a.denied++; return; }
72
+ a.calls++; a.runSet.add(run); a.tools.set(tool, (a.tools.get(tool) ?? 0) + 1);
73
+ if (at && at > a.last) a.last = at;
74
+ };
75
+ const seenRuns = new Set();
76
+ for (const row of rows) {
77
+ if (typeof row?.spine !== 'string') continue;
78
+ const key = String(row.runid ?? row.spine);
79
+ if (seenRuns.has(key)) continue;
80
+ seenRuns.add(key);
81
+ for (const c of ticketCalls(row.spine)) use(c.server, c.tool, key, c.at, false);
82
+ for (const file of auditFiles(row.spine)) {
83
+ let text;
84
+ try { text = readFileSync(file, 'utf8'); } catch { continue; }
85
+ for (const line of text.split('\n')) {
86
+ if (!line.includes('"phase":"gate"')) continue;
87
+ let r;
88
+ try { r = JSON.parse(line); } catch { continue; }
89
+ const type = r?.action?.type;
90
+ if (r?.phase !== 'gate' || typeof type !== 'string') continue;
91
+ const server = byLength.find((s) => type.startsWith(`${s}_`) && type.length > s.length + 1);
92
+ if (server) use(server, type.slice(server.length + 1), key, typeof r.ts === 'string' ? r.ts : '', r.decision === 'deny');
93
+ }
94
+ }
95
+ }
96
+ return new Map([...acc].map(([s, a]) => [s, { calls: a.calls, runs: a.runSet.size, last: a.last || null, denied: a.denied, tools: a.tools }]));
97
+ }
package/src/natural.js ADDED
@@ -0,0 +1,23 @@
1
+ // The ONE place that orders names with numbers in them (`#9` before `#10`). Digit runs compare as numbers (by length after leading zeros, then by text,
2
+ // so a long number never loses digits); everything else compares as text.
3
+
4
+ /** @param {string} a @param {string} b digit strings */
5
+ const digits = (a, b) => {
6
+ const x = a.replace(/^0+/, '');
7
+ const y = b.replace(/^0+/, '');
8
+ return x.length - y.length || (x < y ? -1 : x > y ? 1 : 0);
9
+ };
10
+
11
+ /** @param {unknown} x @param {unknown} y @returns {number} negative, 0 or positive, like a sort callback */
12
+ export function compareNatural(x, y) {
13
+ const tx = String(x).match(/\d+|\D+/g) ?? [];
14
+ const ty = String(y).match(/\d+|\D+/g) ?? [];
15
+ for (let i = 0; i < Math.min(tx.length, ty.length); i++) {
16
+ const a = tx[i];
17
+ const b = ty[i];
18
+ if (a === b) continue;
19
+ const c = /^\d/.test(a) && /^\d/.test(b) ? digits(a, b) : (a < b ? -1 : 1);
20
+ if (c !== 0) return c;
21
+ }
22
+ return tx.length - ty.length;
23
+ }
package/src/pagemap.js CHANGED
@@ -14,6 +14,7 @@ import { isRateLimited, rateLimitWaitMs } from './ratelimit.js';
14
14
  import { isOutputCutOff } from './authorflow.js';
15
15
  import { AUTHOR_CALL_TIMEOUT_MS, AUTHOR_SCOUT_MAX_TOKENS, SURVEY_CAUSES } from './authorscout.js';
16
16
  import { lineRules, boundInWords, wordsSaidOn } from './rubricstep.js';
17
+ import { isCountable } from './checkpick.js';
17
18
  import { applyPageRules, validReading } from './pagerules.js';
18
19
  import { dryReadMoney, dryReadTimes, dryReadPhrases } from './pagedry.js';
19
20
  import { ruleWords, FACT_LANGS } from './facts.js';
@@ -215,7 +216,7 @@ export const stripAgreeLead = (text) => {
215
216
  return m ? m[1].trim() : String(text ?? '');
216
217
  };
217
218
 
218
- /** @typedef {{line: number, rule: number, source: 'look', question: string, ask: 'reading'|'cant-check', ruleText: string, reading?: string}} LookAsk
219
+ /** @typedef {{line: number, rule: number, source: 'look', question: string, ask: 'reading'|'cant-check'|'check'|'no-check', ruleText: string, reading?: string}} LookAsk
219
220
  * `reading` = the plain words an `agree` writes as a `~` rule (a reading ask only) */
220
221
 
221
222
  /** the words of a reading ask: the ONE spelling, and {@link readingOfQuestion} reads it back (the Result tab's "(you confirmed)") */
@@ -240,6 +241,7 @@ export function readingOfQuestion(q) {
240
241
  * bound they wrote themselves is theirs and nothing is asked. `agree` writes the reading as a `~` rule in plain words (the answer text is
241
242
  * `reading`), so the drafter is told it and the fact signs plain.
242
243
  * - CAN'T CHECK: no kept fact carries it (PRD v1.106 Part 5 Q3 T2). `drop it` leaves it Not checked.
244
+ * A COUNT rule (`isCountable`: words, list items or lines, sections) is none of these: it is asked once, as a pick (R10, fwd am24); the look's facts about it stay.
243
245
  * One ask per rule text on a line; readings first, then can't-check asks, each in line order. The caller applies the machine's cap and the answer gate.
244
246
  * @param {{facts?: {line: number, forRule?: number, name?: string, shape?: string, unit?: string[], currency?: string[], reading?: import('./pagerules.js').Reading}[]}|null|undefined} look
245
247
  * @param {{n: number, text?: string, rule?: string, rules?: string[]}[]|null|undefined} jobLines
@@ -256,6 +258,7 @@ export function askableFromLook(look, jobLines) {
256
258
  for (const l of Array.isArray(jobLines) ? jobLines : []) {
257
259
  lineRules(l).forEach((rule, k) => {
258
260
  const n = k + 1;
261
+ if (isCountable(rule)) return; // R10 (fwd am24): a count rule is asked ONCE, as a pick (src/checkpick.js), never as a page question ("I can't check this on the page" / "I read it as"); its look facts stay
259
262
  const key = `${l.n}\u0000${rule.trim().toLowerCase()}`;
260
263
  const tied = facts.filter((f) => f.line === l.n && f.forRule === n);
261
264
  if (tied.length > 0) {
@@ -290,6 +293,6 @@ const ruleBounds = (r) => (r.op === 'between' ? [r.lo, r.hi] : [r.value]);
290
293
  * @param {LookAsk[]} asks @returns {string}
291
294
  */
292
295
  export function tooManyAsksText(asks) {
293
- const list = asks.map((a) => `line ${a.line} "${a.ruleText}" → ${a.reading ?? "I can't check this on the page"}`).join('; ');
296
+ const list = asks.map((a) => `line ${a.line} "${a.ruleText}" → ${a.ask === 'no-check' ? "I can't check this" : (a.reading ?? "I can't check this on the page")}`).join('; ');
294
297
  return redactSecrets(`Your job has ${asks.length} rules I can't check or had to guess. Please rewrite it so each one says what to look for. My readings: ${list}.`);
295
298
  }
@@ -23,11 +23,16 @@ import { openSync, existsSync } from 'node:fs';
23
23
  import { join } from 'node:path';
24
24
  import { readFileSync } from 'node:fs';
25
25
  import { planMatchesClose } from '../rubricstep.js';
26
- import { createSession, validateJobCard, validateReuseCard, jobBoxesChanged, buildReuseSpec, cardFields, nextFreeJobName, startDestinationProblem, STEP_LABELS } from './authorsession.js';
26
+ import { ticketNumberOf } from '../ticketshape.js';
27
+ import { newestUnrunTicket } from '../ticketnext.js';
28
+ import { readRunList } from '../runlist.js';
29
+ import { createSession, validateJobCard, validateReuseCard, jobBoxesChanged, buildReuseSpec, cardFields, nextFreeJobName, startDestinationProblem, resolveFlowCard, ticketBoxProblem, STEP_LABELS } from './authorsession.js';
27
30
  import { parseInputs } from '../jobblock.js';
28
31
  import { isReusableGreen } from './status.js';
29
32
  import { proveInputFiles, looksLikeRubricInput, webFetchState } from '../source.js';
30
- import { validateJob } from '../job.js';
33
+ import { validateJob, flowTypeOf } from '../job.js';
34
+ import { ticketAnyway } from './tickets.js';
35
+ import { cardScheduleOf } from '../cardschedule.js';
31
36
 
32
37
  /** plain words for a run whose saved job no longer passes today's `validateJob` (RULED 2026-10-15): never the raw red codes */
33
38
  export const OLD_JOB_REUSE_WORDS = "This run was made by an older bareloop. Its saved job doesn't pass today's checks, so it can't be reused. Start a new job instead.";
@@ -42,6 +47,7 @@ import { endpointOf, judgePick, keyValueOf, rowsForHome, tickedLines } from '../
42
47
  import { thinkingForLine } from '../thinking.js';
43
48
  import { panelMoney2 } from '../panelmoney.js';
44
49
  import { apiKeyProblem, checkProviderReachable } from '../providers.js';
50
+ import { reviseRefusal, sessionsRootOf } from '../revises.js';
45
51
 
46
52
  /** @returns {string} a fresh per-process token — never persisted, never logged */
47
53
  export function mintToken() {
@@ -115,8 +121,9 @@ const TERMINAL_PHASES = new Set(['refused', 'abandoned', 'error', 'signed', 'sig
115
121
  * deliberately has none of).
116
122
  * @param {{ port: number, token: string, env?: Record<string,string|undefined>,
117
123
  * sessionsRoot?: string, spawnFn?: typeof realSpawn, bareloopBin?: string,
118
- * jobsDir?: string, fetchImpl?: typeof fetch, home?: string,
124
+ * jobsDir?: string, fetchImpl?: typeof fetch, home?: string, mcpHome?: string, newestUnrunTicket?: typeof newestUnrunTicket,
119
125
  * schedules?: ReturnType<typeof import('./schedules.js').createScheduleDoor>,
126
+ * isSkippedTicket?: (job: string, number: number) => boolean, skippedRunOf?: (job: string, number: number) => string|null,
120
127
  * sessionDeps?: Record<string, any>,
121
128
  * runJobNames?: () => string[],
122
129
  * startFrom?: {get: (runid: string, o?: {model?: string}) => any, getImport: (id: string, o?: {model?: string}) => any, listJobs?: (o?: {model?: string}) => any[]} }} opts
@@ -151,23 +158,50 @@ export function createAuthorRoutes(opts) {
151
158
  * @returns {Promise<{ok: true, session: ReturnType<typeof createSession>}|{ok: false, status: number, error: string}>}
152
159
  */
153
160
  function startSession(card, reuse, inputs, o = {}) {
161
+ // fwd M4e am14 item 3: a third revise of one draft is refused at $0, before any input proof, session or model call
162
+ const tooMany = o.headless ? null : reviseRefusal(sessionsRootOf(opts.sessionsRoot), card?.carryFrom, card?.carryKind);
163
+ if (tooMany !== null) return Promise.resolve({ ok: /** @type {false} */ (false), status: 409, error: tooMany });
154
164
  // ONE owner of "is this a rubric job on files": a reuse (and so a scheduled fire) reads it from the signed spec's verdict type,
155
165
  // never from the card; a fresh job reads the card. A rubric job whose line 1 is a file or URL has no repo to prove inputs against;
156
166
  // the session proves every line itself (`proveRubricInputs`), at $0, before any model call.
157
167
  const rubric = reuse ? reuse.spec?.verdictType === 'soft-green' : card?.checkType === 'rubric';
158
168
  if (reuse) card = { ...card, checkType: rubric ? 'rubric' : 'deterministic' };
159
169
  const filesJob = rubric && inputs.length > 0 && looksLikeRubricInput(inputs[0].value);
160
- return (filesJob ? Promise.resolve(/** @type {{ok: true}} */ ({ ok: true })) : proveInputFiles(inputs)).then((proof) => {
170
+ // piece 8: the card's Flow type and MCP pick, decided at $0 before any session (a reuse keeps the signed spec's own MCP). Nothing is started: the pick reads the check log.
171
+ /** @type {ReturnType<typeof resolveFlowCard>} */
172
+ const flow = reuse
173
+ ? { ok: true, flowType: flowTypeOf(reuse.spec), pick: reuse.spec?.mcp ? { server: reuse.spec.mcp.server, tools: reuse.spec.mcp.tools } : null }
174
+ : resolveFlowCard(card, { ...(opts.home !== undefined ? { home: opts.home } : {}), ...(opts.mcpHome !== undefined ? { mcpHome: opts.mcpHome } : {}) });
175
+ if (!flow.ok) return Promise.resolve({ ok: /** @type {false} */ (false), status: 400, error: flow.error });
176
+ const ticketProblem = ticketBoxProblem(card, flow.flowType);
177
+ if (ticketProblem !== null) return Promise.resolve({ ok: /** @type {false} */ (false), status: 400, error: ticketProblem });
178
+ // piece 9 (R7): the card's Schedule row, decided at $0 before any session exists. A scheduled fire is a headless start with no Schedule row, so it never reaches this.
179
+ const sch = o.headless ? { ok: /** @type {const} */ (true), trigger: null } : cardScheduleOf(card, {
180
+ flowType: flow.flowType, pick: flow.pick, inputs, hasSchedule: (job) => { try { return !!opts.schedules?.readSchedule(job); } catch { return false; } },
181
+ });
182
+ if (!sch.ok) return Promise.resolve({ ok: /** @type {false} */ (false), status: 400, error: sch.error });
183
+ return (filesJob ? Promise.resolve(/** @type {{ok: true}} */ ({ ok: true })) : proveInputFiles(inputs, flow.pick ? { mcp: flow.pick } : {})).then((proof) => {
161
184
  if (!proof.ok) return { ok: /** @type {false} */ (false), status: 400, error: proof.error };
162
185
  if (!o.headless && hasLiveSession()) return { ok: /** @type {false} */ (false), status: 409, error: 'an authoring session is already live — one at a time' };
163
186
  // the SAME Destination check the session runs, at $0, BEFORE the session (and its folder) exists
164
187
  const destProblem = startDestinationProblem(card);
165
188
  if (destProblem !== null) return { ok: /** @type {false} */ (false), status: 400, error: destProblem };
166
- const session = createSession(cardFields(card), {
167
- env: envNow(), sessionsRoot: opts.sessionsRoot, ...(opts.home !== undefined ? { home: opts.home } : {}), ...(reuse ? { reuse } : {}), ...(opts.sessionDeps ?? {}),
189
+ // R7b rulings (live runs mw6skdyk, mw6u5794): a by-hand Tickets session looks for a new ticket NOW, at $0, before any session, copy, draft or model call, through the ONE reader
190
+ // (`run-u` calls the same one at run start). Nothing new, or a look that cannot read, refuses in the card's own error line. A scheduled fire (headless) carries its ticket and never looks.
191
+ const lookJob = reuse ? String(reuse.spec?.job ?? card.jobName) : card.jobName;
192
+ return (!o.headless && flow.flowType === 'tickets' && flow.pick
193
+ ? (opts.newestUnrunTicket ?? newestUnrunTicket)({
194
+ job: lookJob, rows: (() => { try { return readRunList({ ...(opts.home !== undefined ? { home: opts.home } : {}) }).rows; } catch { return []; } })(), inputs, mcp: flow.pick,
195
+ })
196
+ : Promise.resolve({ ok: /** @type {true} */ (true) })
197
+ ).then((picked) => {
198
+ if (!picked.ok) return { ok: /** @type {false} */ (false), status: 400, error: `${/** @type {any} */ (picked).say} Nothing spent.` };
199
+ const session = createSession(cardFields(card), {
200
+ env: envNow(), sessionsRoot: opts.sessionsRoot, ...(opts.home !== undefined ? { home: opts.home } : {}), ...(reuse ? { reuse } : {}), flow: { flowType: flow.flowType, pick: flow.pick }, ...(typeof card.carryFrom === 'string' ? { carryFrom: card.carryFrom, carryKind: card.carryKind } : {}), ...(sch.trigger ? { schedule: sch.trigger } : {}), ...(opts.sessionDeps ?? {}),
201
+ });
202
+ (o.headless ? headless : sessions).set(session.id, session);
203
+ return { ok: /** @type {true} */ (true), session };
168
204
  });
169
- (o.headless ? headless : sessions).set(session.id, session);
170
- return { ok: /** @type {true} */ (true), session };
171
205
  }).catch((e) => ({ ok: /** @type {false} */ (false), status: 500, error: `could not check the inputs: ${/** @type {Error} */ (e)?.message ?? e}` }));
172
206
  }
173
207
 
@@ -283,7 +317,7 @@ export function createAuthorRoutes(opts) {
283
317
  ok: true, origin: pre.origin, card, from: pre.from, note: pre.note,
284
318
  // ONE door (v1.101): `green` = the origin earned a real green (an imported job counts), so an unchanged job reuses the signed plan;
285
319
  // `nextName` = the Job name box once a job box changes (the box shows the origin's name until then). Nothing is locked.
286
- green: pre.origin.importId !== undefined || isReusableGreen(pre.outcome),
320
+ green: pre.origin.importId !== undefined || isReusableGreen(pre.outcome) || pre.neverRan === true,
287
321
  nextName: nextFreeJobName(pre.origin.job, opts.runJobNames ? opts.runJobNames() : [], { jobsDir: opts.jobsDir }),
288
322
  specHash: pre.specHash, workflowKey: pre.workflowKey, trackRecord: pre.trackRecord,
289
323
  line: pre.line, specNamesModel: pre.specNamesModel, specWorker: pre.specWorker,
@@ -316,6 +350,17 @@ export function createAuthorRoutes(opts) {
316
350
  return true;
317
351
  }
318
352
 
353
+ // ── R8 (piece 4): "Run it anyway" on a skipped ticket, after the person's reason. A click route behind the token + Origin/Host guard above (the authoring session can reach no route here by
354
+ // itself); with no schedule on it starts that ticket's run at once, else it queues ONE `arrived` row. Placed with the other exact matches, before the session regex below.
355
+ if (pathname === '/api/author/ticket-anyway') {
356
+ if (!opts.schedules || !opts.isSkippedTicket) { send(404, { ok: false, error: 'not found' }); return true; }
357
+ if (req.method !== 'POST') { send(405, { ok: false, error: 'POST only' }); return true; }
358
+ ticketAnyway({ body, isSkipped: opts.isSkippedTicket, door: opts.schedules, ...(opts.skippedRunOf ? { skippedRunOf: opts.skippedRunOf } : {}) })
359
+ .then((r) => send(r.status, r.body))
360
+ .catch((e) => send(500, { ok: false, error: `could not run it anyway: ${/** @type {Error} */ (e).message}. Nothing started.` }));
361
+ return true;
362
+ }
363
+
319
364
  // A refreshed page re-attaches to the one live (non-terminal) session: its id and state (card, messages, steps),
320
365
  // or `null`. The server's session map is the only truth; nothing is stored page-side.
321
366
  if (pathname === '/api/author/live') {
@@ -358,7 +403,7 @@ export function createAuthorRoutes(opts) {
358
403
  // a scheduled run's green waits for the person's Accept (quarantine): its plan is neither reused nor re-drafted until then
359
404
  if (pre.outcome === 'green-held') { send(409, { ok: false, error: 'This run was started by a schedule and is waiting for your Accept. Accept it first, then it can be reused.' }); return true; }
360
405
  card.jobName = pre.origin.job; // an unchanged job keeps its name; a typed one is ignored
361
- if (fromImport !== null || isReusableGreen(pre.outcome)) {
406
+ if (fromImport !== null || isReusableGreen(pre.outcome) || pre.neverRan === true) {
362
407
  const rv = validateReuseCard(card, { rows });
363
408
  if (!rv.ok) { send(400, { ok: false, error: rv.error }); return true; }
364
409
  const spec = buildReuseSpec(pre.spec, card, rows);
@@ -407,6 +452,9 @@ export function createAuthorRoutes(opts) {
407
452
  return true;
408
453
  }
409
454
  if (sub === 'abandon') {
455
+ // a Revise ends this draft: the third one is refused here, so the plan the person is looking at is not thrown away for nothing
456
+ const tooMany = body?.kind === 'revise' ? reviseRefusal(sessionsRootOf(opts.sessionsRoot), session.id, 'revise') : null;
457
+ if (tooMany !== null) { send(409, { ok: false, error: tooMany, state: session.state }); return true; }
410
458
  const r = session.abandon();
411
459
  send(r.ok ? 200 : 400, { ...r, state: session.state });
412
460
  return true;
@@ -423,7 +471,7 @@ export function createAuthorRoutes(opts) {
423
471
  }
424
472
  if (sub === 'sign') {
425
473
  const claimedHash = String(body?.specHash ?? '');
426
- const r = signRun(session, claimedHash, { env: envNow(), spawnFn, bareloopBin, sessionsRoot: opts.sessionsRoot, home: opts.home });
474
+ const r = signRun(session, claimedHash, { env: envNow(), spawnFn, bareloopBin, sessionsRoot: opts.sessionsRoot, home: opts.home, ...(opts.schedules ? { schedules: opts.schedules } : {}) });
427
475
  send(r.ok ? 200 : 400, r);
428
476
  return true;
429
477
  }
@@ -448,7 +496,8 @@ export { panelMoney2 };
448
496
  * it to sign"), and this is where it is checked, not trusted.
449
497
  * @param {ReturnType<typeof createSession>} session
450
498
  * @param {string} claimedHash
451
- * @param {{env: any, spawnFn: typeof realSpawn, bareloopBin: string, sessionsRoot?: string, home?: string, reviewDoor?: boolean, onSpawnError?: (e: Error) => void, onExit?: (code: number|null) => void}} o
499
+ * @param {{env: any, spawnFn: typeof realSpawn, bareloopBin: string, sessionsRoot?: string, home?: string, reviewDoor?: boolean, onSpawnError?: (e: Error) => void, onExit?: (code: number|null) => void, anyway?: boolean, schedules?: ReturnType<typeof import('./schedules.js').createScheduleDoor>}} o
500
+ * `schedules` (R7, piece 9): the schedule door. A session whose card picked a Schedule has it signed WITH the job here, written OFF, before the run is spawned; a refusal spawns nothing.
452
501
  * @returns {{ok: boolean, error?: string, job?: string}}
453
502
  */
454
503
  export function signRun(session, claimedHash, o) {
@@ -476,6 +525,20 @@ export function signRun(session, claimedHash, o) {
476
525
  if (!m.ok) return { ok: false, error: m.error };
477
526
  } catch { return { ok: false, error: 'could not read the signed spec to compare it with the plan you were shown — refusing to sign' }; }
478
527
  }
528
+ // PIECE 9 (R7): the Schedule the card picked is signed WITH the job it is a field of (`spec.trigger`), written OFF beside the run about to start; the first green run turns it on. Before the
529
+ // spawn, so a refusal starts nothing and a run is never left without the schedule the person signed it with.
530
+ /** @type {string|null} the job whose waiting schedule this sign wrote */
531
+ let scheduledJob = null;
532
+ if (session.state.schedule) {
533
+ if (!o.schedules) return { ok: false, error: 'this panel cannot keep a schedule, so the job was not signed' };
534
+ try {
535
+ const spec = JSON.parse(readFileSync(session.state.resolvedSpecPath, 'utf8'));
536
+ const dest = typeof session.state.card?.destination === 'string' ? session.state.card.destination.trim() : '';
537
+ const made = o.schedules.signWithJob({ spec, specHash: session.state.specHash, trigger: spec.trigger, inputsText: typeof session.state.card?.inputs === 'string' ? session.state.card.inputs : '', destination: /^(\/|[a-zA-Z]:[\\/])/.test(dest) ? dest : null });
538
+ if (!made.ok) return { ok: false, error: made.say };
539
+ scheduledJob = spec.job;
540
+ } catch { return { ok: false, error: 'could not read the signed spec to sign its schedule — refusing to sign' }; }
541
+ }
479
542
  const logFile = join(session.state.outDir, 'run.log');
480
543
  // array argv, never a shell string — `--approve <hash>` is a literal
481
544
  // element, checkable byte-for-byte by a test stubbing `spawnFn`, and there
@@ -496,20 +559,32 @@ export function signRun(session, claimedHash, o) {
496
559
  // EXACT. Meaningless without a drafting spend, so only ever passed
497
560
  // alongside --draft-spent-usd, matching run-u's own guard.
498
561
  const draftIncomplete = draftSpentUsd !== null && session.state.draftSpendComplete === false;
562
+ const ticketArg = ticketNumberOf(session.state.card?.ticket);
499
563
  const args = [
500
564
  'systemd-inhibit', '--why=bareloop panel run',
501
565
  process.execPath, o.bareloopBin,
502
566
  'run-u', '--spec', session.state.resolvedSpecPath, '--approve', session.state.specHash,
503
567
  // T (F.1): a scheduled run opens the review door even when deterministic, so its green waits for the person's Accept
504
568
  ...(o.reviewDoor === true ? ['--review-door'] : []),
569
+ // piece 8: a Tickets MCP run reads the ticket number typed on the card (per run, never signed): the same number `--ticket` takes, read by the same function
570
+ ...(ticketArg !== undefined ? ['--ticket', String(ticketArg)] : []),
571
+ // R7 (am3): the person's own "Run it anyway" on a ticket - `run-u` reads `--anyway` as "start it even if the job's filter skipped it". Never set by a card or a scheduled fire.
572
+ ...(o.anyway === true && ticketArg !== undefined ? ['--anyway'] : []),
505
573
  ...(draftSpentUsd !== null ? ['--draft-spent-usd', String(draftSpentUsd), ...(draftIncomplete ? ['--draft-spend-incomplete'] : [])] : []),
506
574
  ];
507
575
  /** @type {number|null} */
508
576
  let logFd = null;
509
577
  try { logFd = openSync(logFile, 'a'); } catch { logFd = null; }
510
- const child = o.spawnFn('setsid', args, {
511
- detached: true, stdio: ['ignore', logFd ?? 'ignore', logFd ?? 'ignore'], env: o.env,
512
- });
578
+ /** a run that never started takes its waiting schedule back (cancel is never refused; it writes its own plain row) */
579
+ const dropSchedule = () => { if (scheduledJob !== null) { try { o.schedules?.cancel(scheduledJob); } catch { /* the schedule file is already gone */ } } };
580
+ /** @type {ReturnType<typeof realSpawn>} */
581
+ let child;
582
+ try {
583
+ child = o.spawnFn('setsid', args, {
584
+ detached: true, stdio: ['ignore', logFd ?? 'ignore', logFd ?? 'ignore'], env: o.env,
585
+ });
586
+ } catch (e) { dropSchedule(); throw e; }
587
+ if (scheduledJob !== null && typeof child?.once === 'function') child.once('error', dropSchedule);
513
588
  if (typeof child?.unref === 'function') child.unref();
514
589
  if (o.onSpawnError && typeof child?.once === 'function') child.once('error', o.onSpawnError);
515
590
  if (o.onExit && typeof child?.once === 'function') child.once('exit', o.onExit);