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
@@ -0,0 +1,151 @@
1
+ // R7b (3), hamr 2026-11-07 (option A): "the AI points, the person decides". Before a repo job is drafted, ONE small paid call reads the job lines and names, for a line that
2
+ // names a file to change, the line, the file (copied from that line) and the folder that holds it. Plain code then checks every claim (the line is a job line, the path
3
+ // stands in that line's own words, the file is in the repo's committed tree, the folder is a real parent of it) and that the file lies OUTSIDE the Destination. Only then is
4
+ // there ONE question, worded by code, answered yes or no like the fit check's "go on". A made-up file, a path the line does not hold or a malformed reply is no question.
5
+ // Failure is OPEN (a wrong question is the costly mistake): a call that does not finish asks nothing and drafting goes on. The call/book/retry pattern is src/fitcheck.js's.
6
+
7
+ import { createRequire } from 'node:module';
8
+ import { priceOf, scrubRaw, tallyCalls, capStop, callCasualty } from './text.js';
9
+ import { redactSecrets } from './validate.js';
10
+ import { isTransportFailure } from './transport.js';
11
+ import { isRateLimited, rateLimitWaitMs } from './ratelimit.js';
12
+ import { isOutputCutOff } from './authorflow.js';
13
+ import { AUTHOR_CALL_TIMEOUT_MS, AUTHOR_SCOUT_MAX_TOKENS } from './authorscout.js';
14
+
15
+ const require = createRequire(import.meta.url);
16
+ const { Loop } = require('bare-agent');
17
+
18
+ /** the label of the one paid call, as the drafting book sees it */
19
+ export const DEST_CALL_LABEL = 'dest-point';
20
+
21
+ export const DEST_SYSTEM = 'You read the numbered lines of a code job. You never invent words: every file path you name must be copied, character for character, from the job line that holds it.';
22
+
23
+ /**
24
+ * What the AI is told (the numbered job text only, no `~` rules) and the one rule, with a legal example.
25
+ * @param {{jobLines: {n: number, text: string}[], destination: string}} o @returns {string}
26
+ */
27
+ export function destPrompt({ jobLines, destination }) {
28
+ const job = jobLines.map((l) => `LINE ${l.n}: ${l.text}`).join('\n');
29
+ return `THE JOB:\n${job}\n\nDestination (the only place the job may change files): ${destination}\n\n`
30
+ + 'Name ONLY a file the line asks to CHANGE (to fix, edit, write, add or remove). A file the line only says must pass, be read, be run or be checked (for example the tests it must make pass) is NOT a change: never name it. '
31
+ + 'For EACH job line, for each file it asks to change, give the line number, the file path copied exactly from that line, and the folder that holds that file (the folder part of the path, ending with /). '
32
+ + 'A line that names no file path to change is left out; never guess a path the line does not contain. '
33
+ + 'Reply with JSON only, no prose, no code fence: {"points":[{"line":<line number>,"file":"<path copied from the line>","folder":"<its folder>"}]}. '
34
+ + 'Example: for the line "LINE 1: Fix the bug in src/sum.js so the tests in test/sum.test.js pass" the reply is {"points":[{"line":1,"file":"src/sum.js","folder":"src/"}]}, and test/sum.test.js is not named because the line only needs those tests to pass; for "LINE 2: make npm test pass" it is {"points":[]}.';
35
+ }
36
+
37
+ /** @typedef {{line: number, file: string, folder: string}} DestPoint */
38
+
39
+ /** does `file` lie under the Destination (a folder, a file, a glob, or `.`)? @param {string} file @param {string} destination @returns {boolean} */
40
+ export function destinationCovers(file, destination) {
41
+ for (const raw of destination.split(/[,\n]/)) {
42
+ const t = raw.trim().replace(/^(\.\/)+/, '').replace(/\/+$/, '');
43
+ if (raw.trim() === '') continue;
44
+ if (t === '' || t === '.') return true;
45
+ if (/[*?]/.test(t)) {
46
+ const re = new RegExp(`^${t.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*\*/g, '\u0000').replace(/\*/g, '[^/]*').replace(/\?/g, '[^/]').replace(/\u0000/g, '.*')}$`);
47
+ if (re.test(file)) return true;
48
+ } else if (file === t || file.startsWith(`${t}/`)) return true;
49
+ }
50
+ return false;
51
+ }
52
+
53
+ /**
54
+ * Read the AI's reply and decide, all in code. Malformed (no repair): not JSON, not `{points:[...]}`, a point that is not an object with a whole line, a string file and a string folder.
55
+ * A point survives only when its line is a job line, the file path is written in that line's own text, the file is in the repo's committed tree, the folder is a real parent folder
56
+ * of that file, and the file is NOT under the Destination. The survivors are ordered by line.
57
+ * @param {unknown} text @param {{jobLines: {n: number, text: string}[], files: readonly string[], destination: string}} o
58
+ * @returns {{status: 'malformed'}|{status: 'ok', points: DestPoint[], dropped: number}}
59
+ */
60
+ export function decideDestPoint(text, { jobLines, files, destination }) {
61
+ /** @type {any} */
62
+ let j;
63
+ try { j = JSON.parse(String(text ?? '').trim()); } catch { return { status: 'malformed' }; }
64
+ if (j === null || typeof j !== 'object' || Array.isArray(j) || !Array.isArray(j.points)) return { status: 'malformed' };
65
+ const lines = new Map(jobLines.map((l) => [l.n, l.text]));
66
+ const tree = new Set(files);
67
+ /** @type {DestPoint[]} */
68
+ const points = [];
69
+ let dropped = 0;
70
+ for (const p of j.points) {
71
+ if (p === null || typeof p !== 'object' || Array.isArray(p) || !Number.isInteger(p.line) || typeof p.file !== 'string' || typeof p.folder !== 'string') return { status: 'malformed' };
72
+ const file = p.file.replace(/^(\.\/)+/, '');
73
+ const folder = p.folder.replace(/^(\.\/)+/, '').replace(/\/+$/, '');
74
+ const lineText = lines.get(p.line);
75
+ const ok = lineText !== undefined && file !== '' && lineText.includes(p.file) && tree.has(file) && folder !== '' && file.startsWith(`${folder}/`) && !destinationCovers(file, destination);
76
+ if (ok) points.push({ line: p.line, file, folder: `${folder}/` }); else dropped += 1;
77
+ }
78
+ points.sort((a, b) => a.line - b.line);
79
+ return { status: 'ok', points, dropped };
80
+ }
81
+
82
+ /** the one question, worded by code @param {DestPoint} p @param {string} destination @returns {string} */
83
+ export const destQuestionText = (p, destination) => redactSecrets(
84
+ `Line ${p.line} needs ${p.file} changed, but Destination is ${destination.trim().replace(/\s*\n\s*/g, ', ')}, so the job could not change it. Set Destination to ${p.folder}?${DEST_ANSWER}`,
85
+ );
86
+ /** the answer words the question ends with (said once, here; the panel's question box shows the question without them and has the buttons instead) */
87
+ export const DEST_ANSWER = ' Type yes to set it, or no to keep it as it is.';
88
+ /** the answers (any case, a closing full stop allowed) @param {unknown} text @returns {'yes'|'no'|null} */
89
+ export const yesNoOf = (text) => {
90
+ const t = String(text ?? '').trim().replace(/\.$/, '').toLowerCase();
91
+ return t === 'yes' || t === 'y' ? 'yes' : (t === 'no' || t === 'n' ? 'no' : null);
92
+ };
93
+
94
+ const defaultLoop = (/** @type {any} */ { system, onLlmResult, provider, rates }) =>
95
+ new Loop({ provider, system, onLlmResult, ...(rates ? { rates } : {}) });
96
+
97
+ /**
98
+ * Run the pointing call: one call (one retry on a malformed reply, a transport failure or a 429). Never throws on a call casualty; every failure is `absent` (no question).
99
+ * @param {{jobLines: {n: number, text: string}[], files: readonly string[], destination: string, provider?: any, maxTokens?: number, ceilingUsd?: number|null,
100
+ * callTimeoutMs?: number, onCall?: (call: {label: string, costUsd: number|null, unpricedRounds: number, thinkingStatus?: string, raw?: string}) => void,
101
+ * createLoop?: Function, rates?: {in: number, out: number}|null, callOptions?: Record<string, any>, sleep?: (ms: number) => Promise<void>}} o
102
+ * @returns {Promise<{state: 'point'|'none'|'absent', point: DestPoint|null, reason: string|null, calls: {label: string, costUsd: number|null, unpricedRounds: number}[]}>}
103
+ */
104
+ export async function runDestPoint({
105
+ jobLines, files, destination, provider = null, maxTokens = AUTHOR_SCOUT_MAX_TOKENS, ceilingUsd = null, callTimeoutMs = AUTHOR_CALL_TIMEOUT_MS,
106
+ onCall = () => {}, createLoop = defaultLoop, rates = null, callOptions = {}, sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
107
+ }) {
108
+ const callTimeout = Number.isFinite(Number(callTimeoutMs)) && Number(callTimeoutMs) > 0 ? Math.min(Math.trunc(Number(callTimeoutMs)), AUTHOR_CALL_TIMEOUT_MS) : AUTHOR_CALL_TIMEOUT_MS;
109
+ const priced = rates ? { rates } : {};
110
+ /** @type {{label: string, costUsd: number|null, unpricedRounds: number}[]} */
111
+ const calls = [];
112
+ let attempts = 0;
113
+ const record = (/** @type {any} */ r) => {
114
+ const call = { label: DEST_CALL_LABEL, ...priceOf(r) };
115
+ calls.push(call);
116
+ const raw = scrubRaw({ label: DEST_CALL_LABEL, attempt: attempts, text: r?.text });
117
+ onCall({ ...call, raw: raw.text, ...(r?.thinkingStatus === undefined ? {} : { thinkingStatus: r.thinkingStatus }) });
118
+ };
119
+ const absent = (/** @type {string} */ reason) => ({ state: /** @type {'absent'} */ ('absent'), point: null, reason, calls });
120
+ const content = destPrompt({ jobLines, destination });
121
+ let malformed = 0;
122
+ let transportRetried = false;
123
+ let rateRetried = false;
124
+ for (;;) {
125
+ if (capStop({ ceilingUsd, ...tallyCalls(calls) })) return absent('the folder check was not made: the spend ceiling was reached');
126
+ attempts += 1;
127
+ const loop = createLoop({ system: DEST_SYSTEM, onLlmResult: undefined, provider, ...priced });
128
+ /** @type {any} */
129
+ let r;
130
+ try {
131
+ r = await loop.run([{ role: 'user', content }], [], { cacheMessages: true, maxTokens, timeoutMs: callTimeout, ...callOptions });
132
+ } catch (e) {
133
+ if (isRateLimited(e) && !rateRetried) {
134
+ const wait = rateLimitWaitMs(e);
135
+ if (wait !== null) { rateRetried = true; await sleep(wait); continue; }
136
+ }
137
+ const casualty = callCasualty(e) ?? (isTransportFailure(e) ? String(/** @type {any} */ (e)?.message ?? e) : null);
138
+ if (casualty === null) throw e;
139
+ record({ error: casualty });
140
+ if (!transportRetried) { transportRetried = true; continue; }
141
+ return absent(`the folder check call failed: ${redactSecrets(casualty)}`);
142
+ }
143
+ record(r);
144
+ if (isOutputCutOff(r)) return absent('the folder check answer was cut off');
145
+ if (r?.error) return absent(`the folder check call failed: ${redactSecrets(String(r.error))}`);
146
+ const d = decideDestPoint(r?.text, { jobLines, files, destination });
147
+ if (d.status === 'ok') return { state: d.points.length > 0 ? 'point' : 'none', point: d.points[0] ?? null, reason: null, calls };
148
+ malformed += 1;
149
+ if (malformed >= 2) return absent('the folder check answer was not readable twice');
150
+ }
151
+ }
package/src/draftspend.js CHANGED
@@ -243,6 +243,88 @@ export function readDraftSteps(dir) {
243
243
  return steps;
244
244
  }
245
245
 
246
+ /**
247
+ * fwd am14 item 6: the label this draft's record carries (`revise 1`, `revise 2`, `start over`; src/revises.js `draftLabelOf` owns the words), or null for a first draft.
248
+ * @param {string} dir
249
+ * @returns {string|null}
250
+ */
251
+ export function readDraftLabel(dir) {
252
+ /** @type {string} */
253
+ let text;
254
+ try { text = readFileSync(join(dir, DRAFT_LOG_FILE), 'utf8'); } catch { return null; }
255
+ for (const line of text.split('\n')) {
256
+ if (!line.includes('"draft-label"')) continue;
257
+ try { const ev = JSON.parse(line); if (ev?.kind === 'draft-label' && typeof ev.label === 'string') return ev.label; } catch { /* a torn line */ }
258
+ }
259
+ return null;
260
+ }
261
+
262
+ /**
263
+ * The checks the draft ended with, each marked who added it (`agent` = the drafter, `you` = the person's own pick): the last `draft-checks` line of the log, or `[]` (a draft from before it, or a job that has none).
264
+ * @param {string} dir
265
+ * @returns {{line: number, text: string, by: 'agent'|'you'}[]}
266
+ */
267
+ export function readDraftChecks(dir) {
268
+ /** @type {string} */
269
+ let text;
270
+ try { text = readFileSync(join(dir, DRAFT_LOG_FILE), 'utf8'); } catch { return []; }
271
+ /** @type {{line: number, text: string, by: 'agent'|'you'}[]} */
272
+ let out = [];
273
+ for (const line of text.split('\n')) {
274
+ if (!line.includes('"draft-checks"')) continue;
275
+ try {
276
+ const ev = JSON.parse(line);
277
+ if (ev?.kind === 'draft-checks' && Array.isArray(ev.checks)) out = ev.checks.filter((/** @type {any} */ c) => c && Number.isInteger(c.line) && typeof c.text === 'string' && (c.by === 'agent' || c.by === 'you'));
278
+ } catch { /* a torn line */ }
279
+ }
280
+ return out;
281
+ }
282
+
283
+ /**
284
+ * The suggested checks code could not build, one plain sentence each (the last `draft-notbuilt` line of the log): the Audit's draft lines. `[]` when there are none.
285
+ * @param {string} dir
286
+ * @returns {{line: number, text: string}[]}
287
+ */
288
+ export function readDraftNotBuilt(dir) {
289
+ /** @type {string} */
290
+ let text;
291
+ try { text = readFileSync(join(dir, DRAFT_LOG_FILE), 'utf8'); } catch { return []; }
292
+ /** @type {{line: number, text: string}[]} */
293
+ let out = [];
294
+ for (const line of text.split('\n')) {
295
+ if (!line.includes('"draft-notbuilt"')) continue;
296
+ try {
297
+ const ev = JSON.parse(line);
298
+ if (ev?.kind === 'draft-notbuilt' && Array.isArray(ev.rows)) out = ev.rows.filter((/** @type {any} */ c) => c && Number.isInteger(c.line) && typeof c.text === 'string');
299
+ } catch { /* a torn line */ }
300
+ }
301
+ return out;
302
+ }
303
+
304
+ /**
305
+ * The check list's rows as the drafting ended (draft log `ledger` rows of phase `final`, the last one per key): each row's own words, so the Job tab can name a
306
+ * Not checked row in the person's words. `null` when the session has no readable log or no final row (a CLI run, an imported run, a deleted session). Never throws.
307
+ * @param {string} dir
308
+ * @returns {{key: string, rowKind: string, words: string[], state: string}[]|null}
309
+ */
310
+ export function readDraftLedger(dir) {
311
+ /** @type {string} */
312
+ let text;
313
+ try { text = readFileSync(join(dir, DRAFT_LOG_FILE), 'utf8'); } catch { return null; }
314
+ /** @type {Map<string, {key: string, rowKind: string, words: string[], state: string}>} */
315
+ const byKey = new Map();
316
+ for (const line of text.split('\n')) {
317
+ if (!line.includes('"ledger"')) continue;
318
+ try {
319
+ const ev = JSON.parse(line);
320
+ if (ev?.kind === 'ledger' && ev.phase === 'final' && typeof ev.key === 'string') {
321
+ byKey.set(ev.key, { key: ev.key, rowKind: String(ev.rowKind), words: Array.isArray(ev.words) ? ev.words.filter((/** @type {any} */ w) => typeof w === 'string' && w) : [], state: String(ev.state) });
322
+ }
323
+ } catch { /* a torn line */ }
324
+ }
325
+ return byKey.size ? [...byKey.values()] : null;
326
+ }
327
+
246
328
  /**
247
329
  * The DRAFTING PART of a run (hamr 2026-10-06, option A): the first part of the run's views, built from the session's
248
330
  * drafting log. `null` when the run did not come out of a panel session, or the log carries no metered call (a Reuse
@@ -268,5 +350,8 @@ export function draftingPartFor(row, spine, opts = {}) {
268
350
  wallMs: starts.length && ends.length ? Math.max(0, Math.max(...ends) - Math.min(...starts)) : null,
269
351
  spentUsd: spine.draftSpentUsd, spendComplete: spine.draftSpendComplete !== false, unpricedRounds: 0,
270
352
  draftSteps: steps,
353
+ draftLabel: readDraftLabel(dir),
354
+ draftChecks: readDraftChecks(dir),
355
+ draftNotBuilt: readDraftNotBuilt(dir),
271
356
  };
272
357
  }
package/src/facts.js CHANGED
@@ -10,6 +10,7 @@
10
10
  // the check. The claim TEXT that bareguard's number scan reads is written by code from the values, never by the worker.
11
11
 
12
12
  import { rubricVocabulary } from 'bareguard';
13
+ import { placeRuleProblem } from './placerule.js';
13
14
 
14
15
  /** the shapes a fact may have (bareguard's value kinds, plus `phrase` = a presence decide) */
15
16
  export const FACT_SHAPES = Object.freeze(['money', 'number', 'date', 'time', 'phrase', 'text']);
@@ -18,7 +19,7 @@ export const FACT_OPS = Object.freeze(['lt', 'lte', 'gt', 'gte', 'between']);
18
19
  /** bareguard signs at most this many decides on one `cited` check */
19
20
  export const MAX_FACTS = 10;
20
21
  /** every field a fact may carry */
21
- const FACT_FIELDS = Object.freeze(['name', 'shape', 'unit', 'currency', 'phrase', 'anchor', 'until', 'rule', 'aiProposal', 'lang', 'decimal']);
22
+ const FACT_FIELDS = Object.freeze(['name', 'shape', 'unit', 'currency', 'phrase', 'anchor', 'until', 'rule', 'aiProposal', 'lang', 'decimal', 'place']);
22
23
  /** the languages whose month names bareguard 0.27 reads on a `date` fact (its `lang`), each with the name a person reads; absent `lang` = ISO YYYY-MM-DD only */
23
24
  export const FACT_LANGS = Object.freeze({ en: 'English', de: 'German', fr: 'French', es: 'Spanish', it: 'Italian', pt: 'Portuguese', nl: 'Dutch' });
24
25
  /** the decimal marks a number or money fact may sign (bareguard 0.27 `decimal`); absent = "." */
@@ -124,6 +125,10 @@ export function factShapeReds(part, w, red) {
124
125
  if (!nonEmpty(f.phrase)) red('invalid-value', `${fw}.phrase`, 'the fixed words the quote must contain, copied from the input');
125
126
  for (const k of ['anchor', 'until', 'rule']) if (has(k)) red('invalid-value', `${fw}.${k}`, 'a phrase is fixed words the quote must contain; it has no anchor, until or rule');
126
127
  } else if (has('phrase')) red('invalid-value', `${fw}.phrase`, 'only a phrase fact carries phrase');
128
+ if (has('place')) {
129
+ const bad = f.shape === 'phrase' ? placeRuleProblem(f.place) : 'only a phrase fact carries a place rule';
130
+ if (bad !== null) red('invalid-value', `${fw}.place`, bad);
131
+ }
127
132
  if (has('anchor') && !nonEmpty(f.anchor)) red('invalid-value', `${fw}.anchor`, 'a label copied VERBATIM from the input');
128
133
  if (has('until') && !nonEmpty(f.until)) red('invalid-value', `${fw}.until`, 'a label copied VERBATIM from the input');
129
134
  if (has('until') && !has('anchor') && f.shape !== 'phrase') red('invalid-value', `${fw}.until`, 'until needs an anchor');
@@ -257,6 +262,8 @@ export function ruleWords(f) {
257
262
  * @returns {string}
258
263
  */
259
264
  export function factSentence(f, source) {
265
+ // PLACE RULES: a check that reads WHERE the newest value sits, not what it is; the phrase shown is the signed drafting example (the value a run read is in its Audit)
266
+ if (f.shape === 'phrase' && isRec(f.place)) return `${f.place.kind === 'headingDateAfter' ? 'date' : 'version'} in the newest "${f.place.prefix}" heading (last read ${f.phrase})`;
260
267
  /** @type {string[]} */
261
268
  const bits = [];
262
269
  if (f.shape === 'phrase') bits.push('phrase', `must say "${f.phrase}"`);
package/src/factwords.js CHANGED
@@ -6,7 +6,7 @@
6
6
  // Compared WHITE-SPACE BLIND: any run of white space (U+202F and U+00A0 included - Google writes U+202F before AM/PM, 259 times in one
7
7
  // page) is one space on both sides.
8
8
 
9
- import { labelOnList, normLabel, scanLabels } from './labelscan.js';
9
+ import { labelOnList, normLabel, scanLabels, renderLabelList, renderKeptLabelList } from './labelscan.js';
10
10
  import { asList } from './facts.js';
11
11
  import { dropSentence } from './pagedropwords.js';
12
12
 
@@ -73,6 +73,19 @@ export function keptSetOf(look, source) {
73
73
  };
74
74
  }
75
75
 
76
+ /**
77
+ * The label lists the drafter is told, one per input: ONE owner with the proof above. An input the page-word map read (a look with a
78
+ * `dropped` list) is offered the labels `keptSetOf` accepts, nothing else; any other input keeps the code-made list the proof reads.
79
+ * @param {Record<string, string>} texts @param {Parameters<typeof keptSetOf>[0]} look
80
+ * @returns {string[]}
81
+ */
82
+ export function labelListsFor(texts, look) {
83
+ return Object.entries(texts).map(([label, text]) => {
84
+ const kept = keptSetOf(look, label);
85
+ return kept ? renderKeptLabelList(label, [...kept.labels]) : renderLabelList(label, scanLabels(text));
86
+ });
87
+ }
88
+
76
89
  /**
77
90
  * The reds for ONE fact part against its frozen source text.
78
91
  * @param {{part: any, text: string, line: number|string, scan?: import('./labelscan.js').LabelScan, kept?: ReturnType<typeof keptSetOf>}} o
package/src/fitcheck.js CHANGED
@@ -91,12 +91,14 @@ export const notFoundList = (notFound) => notFound.map((x) => `${x.ask} (line ${
91
91
 
92
92
  /**
93
93
  * The one question, worded by code.
94
- * @param {{found: number, total: number, notFound: {line: number, ask: string}[]}} o
94
+ * @param {{found: number, total: number, notFound: {line: number, ask: string}[], foundAsks?: {line: number, ask: string}[]}} o
95
95
  * @returns {string}
96
96
  */
97
- export const fitQuestionText = ({ found, total, notFound }) => redactSecrets(
98
- `I found ${found} of ${total} of your asks on this page. Not found: ${notFoundList(notFound)}. Type go on to keep drafting, or anything else to stop and change the job or the page.`,
97
+ export const fitQuestionText = ({ found, total, notFound, foundAsks = [] }) => redactSecrets(
98
+ `I found ${found} of ${total} of your asks on this page${found > 0 && foundAsks.length ? `: ${notFoundList(foundAsks)}` : ''}. Not found: ${notFoundList(notFound)}.${FIT_ANSWER}`,
99
99
  );
100
+ /** the answer words the question ends with (said once, here; the panel's question box shows the question without them and has the buttons instead) */
101
+ export const FIT_ANSWER = ' Type go on to keep drafting, or anything else to stop and change the job or the page.';
100
102
 
101
103
  /** the default loop seam - one spelling of how this repo drives a model */
102
104
  const defaultLoop = (/** @type {any} */ { system, onLlmResult, provider, rates }) =>
package/src/job.js CHANGED
@@ -19,7 +19,9 @@ import { validateCloseDecl, DECLARED_CLOSE_CLASSES } from './declaredclose.js';
19
19
  import { inputLabelsOf } from './rubricstep.js';
20
20
  import { CLOSE_TIMEOUT_FLOOR_MS } from './closetimeout.js';
21
21
  import { validateTrigger } from './trigger.js';
22
+ import { WATCHABLE } from './ticketshape.js';
22
23
  import { resolveJobJudge } from './judged.js';
24
+ import { ticketFilterReds } from './ticketfilter.js';
23
25
 
24
26
  // The menus below ARE the close-authoring hierarchy (PRD §7) and ship frozen:
25
27
  // they are read at call time, so a mutable export would let adopter code
@@ -170,7 +172,7 @@ export const CONDITION_KEYS = Object.freeze(['providerPath', 'closeVerbosity', '
170
172
  // `steps` stays in the field list ONLY so a retired spec reds by name
171
173
  // (`shape-retired`) instead of falling through to a generic unknown-field —
172
174
  // the operator gets told what happened, not just that something is wrong.
173
- const JOB_FIELDS = ['schema', 'job', 'description', 'provider', 'baseUrl', 'conditions', 'cadence', 'trigger', 'budgetUsd', 'maxWallMs', 'closeTimeoutMs', 'model', 'thinking', 'handoffNote', 'seedNote', 'readMap', 'judge', 'writeScope', 'steps', 'escalation', 'goal', 'verdictType', 'close', 'closeDecl', 'checks', 'tools', 'jobLines', 'inputs'];
175
+ const JOB_FIELDS = ['schema', 'job', 'description', 'provider', 'baseUrl', 'conditions', 'cadence', 'trigger', 'budgetUsd', 'maxWallMs', 'closeTimeoutMs', 'model', 'thinking', 'handoffNote', 'seedNote', 'mcp', 'flowType', 'ticketFilter', 'ticketWatch', 'readMap', 'judge', 'writeScope', 'steps', 'escalation', 'goal', 'verdictType', 'close', 'closeDecl', 'checks', 'tools', 'jobLines', 'inputs'];
174
176
  /** the exact fields of a signed `judge` override — nested objects red unknown
175
177
  * keys too, because no smuggling level exists in a signed spec */
176
178
  const JUDGE_FIELDS = ['provider', 'model'];
@@ -231,6 +233,79 @@ export function validateBaseUrl(value) {
231
233
  return 'https:// required (http:// admitted only to 127.0.0.1/localhost/::1)';
232
234
  }
233
235
 
236
+ /** the job's flow types; `flowType` is set by code from the job card and signed with the job (fwdloop M13 piece 4) */
237
+ export const FLOW_TYPES = Object.freeze(['plain', 'mcp', 'tickets']);
238
+
239
+ /** the words the card's Flow type menu and the Job tab use for each flow type (fwd's am2 names) */
240
+ export const FLOW_TYPE_LABELS = Object.freeze({ plain: 'plain', mcp: 'MCP', tickets: 'Tickets MCP' });
241
+
242
+ /**
243
+ * The ONE reader of a job's flow type: the field when present; an `mcp` block with no `flowType` is a Tickets job; no `mcp` block is plain.
244
+ * @param {Record<string, any>} spec @returns {'plain'|'mcp'|'tickets'}
245
+ */
246
+ export function flowTypeOf(spec) {
247
+ if (typeof spec?.flowType === 'string' && FLOW_TYPES.includes(spec.flowType)) return /** @type {any} */ (spec.flowType);
248
+ return spec?.mcp ? 'tickets' : 'plain';
249
+ }
250
+
251
+ /** the shape of an MCP server or tool name in a job (the bridge names a tool `<server>_<tool>`) */
252
+ const MCP_NAME = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
253
+
254
+ /**
255
+ * Validate `mcp`, `flowType`, `ticketFilter`, `ticketWatch` (all optional; a spec without them is unchanged). Reds name the field and the legal shape.
256
+ * @param {Record<string, any>} spec @param {(code: string, path: string, detail?: string) => void} red
257
+ */
258
+ function checkMcpFields(spec, red) {
259
+ const has = (/** @type {string} */ k) => spec[k] !== undefined;
260
+ const hasMcp = has('mcp');
261
+ if (hasMcp) {
262
+ const m = spec.mcp;
263
+ if (!isObj(m)) red('invalid-value', 'mcp', 'an object {server, tools}');
264
+ else {
265
+ for (const key of Object.keys(m)) if (key !== 'server' && key !== 'tools') red('unknown-field', `mcp.${key}`, 'declared keys only: server|tools');
266
+ if (typeof m.server !== 'string' || !MCP_NAME.test(m.server)) red('invalid-value', 'mcp.server', 'a plain server name (letters, digits, _ or -)');
267
+ if (!Array.isArray(m.tools) || m.tools.length === 0) red('invalid-value', 'mcp.tools', 'a non-empty list of tool names');
268
+ else {
269
+ const seen = new Set();
270
+ for (const t of m.tools) {
271
+ if (typeof t !== 'string' || !MCP_NAME.test(t)) red('invalid-value', 'mcp.tools', `names ${JSON.stringify(t)}, which is not a plain tool name`);
272
+ else if (seen.has(t)) red('invalid-value', 'mcp.tools', `names "${t}" twice`);
273
+ else seen.add(t);
274
+ }
275
+ }
276
+ }
277
+ }
278
+ if (has('flowType')) {
279
+ const t = spec.flowType;
280
+ if (typeof t !== 'string' || !FLOW_TYPES.includes(t)) red('invalid-value', 'flowType', `one of ${FLOW_TYPES.join(', ')}`);
281
+ else {
282
+ if (t === 'plain' && hasMcp) red('invalid-value', 'flowType', 'a "plain" job takes no "mcp" server');
283
+ if (t !== 'plain' && !hasMcp) red('invalid-value', 'flowType', `a "${t}" job needs an "mcp" server`);
284
+ if (t !== 'tickets') {
285
+ if (has('ticketFilter')) red('invalid-value', 'ticketFilter', 'belongs to a Tickets MCP job');
286
+ if (has('ticketWatch')) red('invalid-value', 'ticketWatch', 'belongs to a Tickets MCP job');
287
+ }
288
+ }
289
+ }
290
+ if (has('ticketFilter')) {
291
+ // ONE reader of a legal filter (src/ticketfilter.js), shared with the drafter's proposal
292
+ for (const r of ticketFilterReds(spec.ticketFilter, { hasMcp })) red(r.code, r.path, r.detail);
293
+ }
294
+ if (has('ticketWatch')) {
295
+ const w = spec.ticketWatch;
296
+ if (!Array.isArray(w) || w.length === 0) red('invalid-value', 'ticketWatch', `a non-empty list of fields (${WATCHABLE.join(' and ')})`);
297
+ else {
298
+ if (!hasMcp) red('invalid-value', 'ticketWatch', 'watches tickets read through the job\'s "mcp" tools, but the job lists no "mcp" server');
299
+ const seen = new Set();
300
+ for (const f of w) {
301
+ if (typeof f !== 'string' || !WATCHABLE.includes(f)) red('invalid-value', 'ticketWatch', `names ${JSON.stringify(f)}, which is not a field that can be watched (${WATCHABLE.join(' and ')})`);
302
+ else if (seen.has(f)) red('invalid-value', 'ticketWatch', `names "${f}" twice`);
303
+ else seen.add(f);
304
+ }
305
+ }
306
+ }
307
+ }
308
+
234
309
  /**
235
310
  * Validate an operator-owned job spec (`schema: "job-v1"`). Never throws on
236
311
  * JSON text or plain parsed data — the ingest contract; a live object with a
@@ -361,6 +436,11 @@ export function validateJob(input, { shellCapUsd = 2 } = {}) {
361
436
  red('invalid-value', 'seedNote', 'true or false (absent = on): whether the planner and the first worker are told what the job\'s own count check said on the untouched tree');
362
437
  }
363
438
 
439
+ // THE MCP SOURCE AND TICKET FIELDS (ITEM33-BUILD, MCP+tickets piece 1): `mcp {server, tools}`, `flowType`, `ticketFilter`, `ticketWatch`.
440
+ // Signed like `seedNote`: ABSENT keeps every old spec's bytes, so its hash. Set by CODE from the person's card pick, never by the drafter
441
+ // (assembleSpec refuses a draft carrying them). Validated here; the run-start reader is src/ticketmcp.js.
442
+ checkMcpFields(spec, red);
443
+
364
444
  // THE FIRST-READ MAP (src/readshim.js, EXPERIMENTAL): a declared job condition, signed like `thinking`. A boolean; ABSENT = off (an old spec keeps
365
445
  // its bytes, so its hash), `true` makes the first shell_read of a big non-test file in an ask return a map of its parts. The switch is hashed.
366
446
  if (spec.readMap !== undefined && typeof spec.readMap !== 'boolean') {
package/src/jobblock.js CHANGED
@@ -90,6 +90,15 @@ export function renderJobLines(lines) {
90
90
  return lines.map((l) => `${l.n}. ${l.text}${l.rule ? `\n rule: ${l.rule}` : ''}`).join('\n');
91
91
  }
92
92
 
93
+ /**
94
+ * The job lines as the job BOX reads them (R10): each line's text, then one `~` line per rule. The inverse of {@link parseJobBlock}, so a card reopened by a Revise holds
95
+ * the `~` lines the person's answers added.
96
+ * @param {{text: string, rules: string[]}[]} lines @returns {string}
97
+ */
98
+ export function jobBoxText(lines) {
99
+ return lines.map((l) => [l.text, ...l.rules.map((r) => `~ ${r}`)].join('\n')).join('\n');
100
+ }
101
+
93
102
  /**
94
103
  * The PASS:/FAIL: examples the person wrote, each kept with its line number (answer 2 of a rubric interview — what the
95
104
  * calibration compile reads). Empty string when there are none.
package/src/labelscan.js CHANGED
@@ -177,3 +177,14 @@ export function renderLabelList(inputLabel, scan) {
177
177
  });
178
178
  return `LABELS IN THE INPUT "${inputLabel}" - pick a label ONLY from this list (by its id or its exact words); a label that is not here is refused:\n\n${blocks.length ? blocks.join('\n\n') : '(no repeated label was found before a value)'}`;
179
179
  }
180
+
181
+ /**
182
+ * The list a page-word map input is shown: ONLY the labels the map kept (what the draft gate's `keptSetOf` accepts), so the prompt and the
183
+ * proof read the same words. Empty = no label was kept, so the drafter leaves the label out.
184
+ * @param {string} inputLabel @param {string[]} labels
185
+ * @returns {string}
186
+ */
187
+ export function renderKeptLabelList(inputLabel, labels) {
188
+ return `LABELS IN THE INPUT "${inputLabel}" - pick a label ONLY from this list (its exact words); a label that is not here is refused:\n\n`
189
+ + (labels.length ? labels.map((l) => ` ${JSON.stringify(l)}`).join('\n') : '(the page words kept no label for this input - leave the label out of every fact)');
190
+ }
package/src/launcher.js CHANGED
@@ -13,6 +13,7 @@ import { createServer } from 'node:net';
13
13
  import { spawn as realSpawn } from 'node:child_process';
14
14
  import { dirname, join } from 'node:path';
15
15
  import { fileURLToPath } from 'node:url';
16
+ import { npmEnv } from './npminstall.js';
16
17
  import { readConfig, updateConfig, ConfigError } from './config.js';
17
18
  import { keysHome, keysFilePath, ensureKeysFile } from './keysfile.js';
18
19
  import { openInOs } from './opener.js';
@@ -67,7 +68,7 @@ const RULE_WIDTH = 56;
67
68
  * @property {import('./tty-colour.js').Paint} [paintErr] colour for stderr lines (default: `paint`)
68
69
  * @property {number} [now] ms clock for the run list's age rules (default: real time); tests pass their own
69
70
  * @property {string} [platform]
70
- * @property {Record<string, string|undefined>} [env] raw env handed to the panel child (default process.env)
71
+ * @property {Record<string, string|undefined>} [env] raw env: handed whole to the panel child, stripped by npmEnv for the update npm child (default process.env)
71
72
  */
72
73
 
73
74
  /**
@@ -349,7 +350,7 @@ export async function updateCmd(io, d, shown) {
349
350
  let timer;
350
351
  const end = (/** @type {boolean} */ v) => { clearTimeout(timer); resolve(v); };
351
352
  try {
352
- const child = (d.npmSpawn ?? realSpawn)('npm', ['install', '-g', 'bareloop@latest'], { stdio: 'inherit' });
353
+ const child = (d.npmSpawn ?? realSpawn)('npm', ['install', '-g', 'bareloop@latest'], { stdio: 'inherit', env: npmEnv(d.env ?? process.env) });
353
354
  // not in the signed text: npm may run this long, then its own child is ended (aligned with fwdloop)
354
355
  timer = setTimeout(() => { try { child.kill('SIGTERM'); } catch { /* already gone */ } end(false); }, d.npmDeadlineMs ?? NPM_DEADLINE_MS);
355
356
  child.once('error', () => end(false));
@@ -0,0 +1,52 @@
1
+ // borrowed-from: fwdloop src/mcp-checks.js@6f9bd72 (the config home is bareloop's `keysHome`; the "newest OK tools" reader is kept for the New job card, R4)
2
+ // The log of `check tools` presses: `mcp-checks.jsonl` beside config.json in the config home. APPEND-ONLY: each press appends one line, nothing is ever rewritten or
3
+ // removed. A line is `{server, path, at, ok, tools:[{name, hint}]}` or `{server, path, at, ok:false, error}`. A tool row is a NAME and a hint (`read-only` or null),
4
+ // an error is a fixed plain sentence: no env value, no command line and no key is ever written here. The page shows the newest line per path and server.
5
+ // A torn or foreign line is skipped when reading, so a half-written last line never hides the earlier ones.
6
+ import { appendFileSync, mkdirSync, readFileSync } from 'node:fs';
7
+ import { join } from 'node:path';
8
+ import { keysHome } from './keysfile.js';
9
+
10
+ export const MCP_CHECKS_FILE = 'mcp-checks.jsonl';
11
+
12
+ /** @param {string|undefined} home the config home (undefined = `~/.config/bareloop`) */
13
+ export const mcpChecksFile = (home) => join(keysHome(home), MCP_CHECKS_FILE);
14
+
15
+ /** append ONE line; throws when it cannot be written @param {string|undefined} home @param {Record<string, any>} entry */
16
+ export function appendMcpCheck(home, entry) {
17
+ mkdirSync(keysHome(home), { recursive: true, mode: 0o700 });
18
+ appendFileSync(mcpChecksFile(home), `${JSON.stringify(entry)}\n`, { mode: 0o600 });
19
+ }
20
+
21
+ /** every well-formed line, oldest first; none when the file is missing @param {string|undefined} home @returns {any[]} */
22
+ function checkLines(home) {
23
+ let text = '';
24
+ try { text = readFileSync(mcpChecksFile(home), 'utf8'); } catch { return []; }
25
+ const out = [];
26
+ for (const line of text.split('\n')) {
27
+ let r;
28
+ try { r = JSON.parse(line); } catch { continue; }
29
+ if (typeof r?.server !== 'string' || typeof r?.path !== 'string' || typeof r?.at !== 'string') continue;
30
+ out.push(r);
31
+ }
32
+ return out;
33
+ }
34
+
35
+ /** the newest line per `path\tserver` @param {string|undefined} home @returns {Map<string, any>} */
36
+ export function newestMcpChecks(home) {
37
+ const out = new Map();
38
+ for (const r of checkLines(home)) out.set(`${r.path}\t${r.server}`, r);
39
+ return out;
40
+ }
41
+
42
+ /** the tool names of the newest OK line (with at least one tool) for this server at this path, or null @param {string|undefined} home @param {string} server @param {string} path @returns {string[]|null} */
43
+ export function newestOkMcpTools(home, server, path) {
44
+ /** @type {string[]|null} */
45
+ let tools = null;
46
+ for (const r of checkLines(home)) {
47
+ if (r.server !== server || r.path !== path || r.ok !== true || !Array.isArray(r.tools)) continue;
48
+ const names = r.tools.map((/** @type {any} */ x) => x?.name).filter((/** @type {unknown} */ n) => typeof n === 'string' && n !== '');
49
+ if (names.length > 0) tools = [...new Set(names)];
50
+ }
51
+ return tools;
52
+ }
package/src/mcppick.js ADDED
@@ -0,0 +1,36 @@
1
+ // borrowed-from: fwdloop src/mcp-pick.js@d18d65b (imports are bareloop's: the config home is `keysHome`, the person's home folder is `mcpHome`)
2
+ // The ONE place that decides the tools a job gets from its MCP. A job with an MCP gets ALL the tools of that MCP's newest OK line in `mcp-checks.jsonl` (src/mcpchecks.js),
3
+ // set by code: never chosen by the drafter, never reviewed by the person, and no server is ever started here (a server starts only on a press of `check tools`).
4
+ // A tool the server gains later is not in the job. Read-only; writes nothing.
5
+ import { newestOkMcpTools } from './mcpchecks.js';
6
+ import { mcpSources, mcpConfigFor } from './mcpsources.js';
7
+ import { remoteRefusal } from './ticketmcp.js';
8
+
9
+ /** the one refusal for an MCP nobody has checked (or whose check never succeeded) */
10
+ export const NEVER_CHECKED_SAY = 'press check tools in Settings > MCP first';
11
+
12
+ /**
13
+ * @param {string} server
14
+ * @param {{ home?: string, mcpHome?: string }} [o] `home` the config home (undefined = `~/.config/bareloop`); `mcpHome` the person's home folder the MCP config places live under (tests inject one)
15
+ * @returns {{ ok: true, server: string, tools: string[] } | { ok: false, say: string }}
16
+ */
17
+ export function mcpPickFor(server, o = {}) {
18
+ const place = mcpSources(o).places.find((p) => p.servers.some((s) => s.name === server));
19
+ if (!place) return { ok: false, say: `${server} is not in any MCP config (Settings > MCP lists the ones found)` };
20
+ if (mcpConfigFor(server, o)?.remote) return { ok: false, say: remoteRefusal(server) };
21
+ const tools = newestOkMcpTools(o.home, server, place.path);
22
+ return tools === null ? { ok: false, say: NEVER_CHECKED_SAY } : { ok: true, server, tools };
23
+ }
24
+
25
+ /**
26
+ * The spec with the card's flow type and MCP pick signed into it. A `plain` pick writes NOTHING (no `flowType` key, no `mcp`), so every plain job keeps the hash it had before
27
+ * the card had these controls. The `mcp` block is the pick's server and EVERY tool of its newest check; the agent never sets it (`assembleSpec` refuses a draft that carries it).
28
+ * @template {Record<string, any>} T
29
+ * R5: a Tickets job also signs the drafter's PROPOSED `ticketFilter` (already read by `ticketFilterReds`), if it made one: the person signs the whole hash. Never on an `mcp` job.
30
+ * @param {T} spec @param {'plain'|'mcp'|'tickets'} flowType @param {{ server: string, tools: string[] }|null} pick @param {{priority?: string[], labels?: string[]}|undefined} [ticketFilter]
31
+ * @returns {T}
32
+ */
33
+ export function signFlow(spec, flowType, pick, ticketFilter = undefined) {
34
+ if (flowType === 'plain' || pick === null) return spec;
35
+ return { ...spec, flowType, mcp: { server: pick.server, tools: [...pick.tools] }, ...(flowType === 'tickets' && ticketFilter !== undefined ? { ticketFilter } : {}) };
36
+ }