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
@@ -27,14 +27,24 @@ import { SHAPES } from '../providershapes.js';
27
27
  import { keyRows, effectiveModels, usableKey, rowNamesOf } from '../providerrows.js';
28
28
  import { apiKeyProblem } from '../providers.js';
29
29
  import { listModels } from '../modellist.js';
30
+ import { homedir } from 'node:os';
31
+ import { listServerTools } from 'bare-agent/mcp';
32
+ import { mcpPathProblem } from '../config.js';
33
+ import { mcpSources, expandMcpPath, DEFAULT_MCP_PLACES } from '../mcpsources.js';
34
+ import { appendMcpCheck, newestMcpChecks } from '../mcpchecks.js';
35
+ import { countMcpUse } from '../mcpuse.js';
36
+ import { MCP_PASS_ENV } from '../ticketmcp.js';
37
+ import { readRunList } from '../runlist.js';
30
38
 
31
39
  const BROKEN_CONFIG = 'Your settings file (config.json) cannot be read. Fix or remove it, then look again.';
40
+ const MCP_CHECK_MS = 15000;
32
41
  const BAD_KEY = 'The key has a space or a line break in it. Fix it in your keys file, then reload keys.';
33
42
 
34
43
  /**
35
44
  * `openFolderSpawn` / `platform` are test seams for the Open keys folder button (a real caller passes
36
- * neither: `child_process.spawn` and `process.platform`).
37
- * @param {{ port: number, token: string, home?: string, env?: Record<string,string|undefined>,
45
+ * neither: `child_process.spawn` and `process.platform`). `mcpHome` is the test seam for the person's home folder the four MCP config places
46
+ * live under and where `check tools` starts a server (a real caller passes none: `os.homedir()`), so a test reads a fixture home, never the real `~`.
47
+ * @param {{ port: number, token: string, home?: string, mcpHome?: string, env?: Record<string,string|undefined>,
38
48
  * fetchImpl?: typeof fetch, now?: () => number, openFolderSpawn?: (cmd: string, args: string[], o: object) => any,
39
49
  * platform?: string }} opts
40
50
  */
@@ -214,6 +224,117 @@ export function createSettingsRoutes(opts) {
214
224
  .then((opened) => (opened ? reply(200, { ok: true, opened: true, path: dir }) : cannot()));
215
225
  }
216
226
 
227
+
228
+ // ---- Settings > MCP (piece 7). Reads the MCP config files (never writes them) and shows names, flags and counts only: no command, args, env or key.
229
+ /** @type {Set<string>} */
230
+ const checking = new Set();
231
+ /** a tool hint as the page shows it: only `readOnlyHint: true` is a hint; anything else is "no hint" (null) @param {any} a */
232
+ const hintOf = (a) => (a?.readOnlyHint === true ? 'read-only' : null);
233
+ const sources = () => mcpSources({ ...(opts.home === undefined ? {} : { home: opts.home }), ...(opts.mcpHome === undefined ? {} : { mcpHome: opts.mcpHome }) });
234
+
235
+ function mcpGet() {
236
+ const src = sources();
237
+ const names = [...new Set(src.places.flatMap((p) => p.servers.map((x) => x.name)))];
238
+ const use = countMcpUse(readRunList({ home: opts.home }).rows, names);
239
+ const checks = newestMcpChecks(opts.home);
240
+ const places = src.places.map((p) => ({
241
+ path: p.path,
242
+ added: p.added,
243
+ status: p.status,
244
+ servers: p.servers.map((x) => {
245
+ const u = use.get(x.name);
246
+ const c = x.remote || x.shadowedBy !== null ? null : checks.get(`${p.path}\t${x.name}`) ?? null;
247
+ return {
248
+ name: x.name,
249
+ remote: x.remote,
250
+ shadowedBy: x.shadowedBy,
251
+ check: c === null ? null : (c.ok === true && Array.isArray(c.tools)
252
+ ? { at: c.at, ok: true, tools: c.tools.map((/** @type {any} */ t) => ({ name: String(t?.name), hint: t?.hint === 'read-only' ? 'read-only' : null })) }
253
+ : { at: c.at, ok: false, error: typeof c.error === 'string' ? c.error : 'The check failed.' }),
254
+ use: x.remote || x.shadowedBy !== null || !u ? null : { calls: u.calls, runs: u.runs, last: u.last, denied: u.denied, tools: Object.fromEntries(u.tools) },
255
+ };
256
+ }),
257
+ }));
258
+ return reply(200, { ok: true, problem: src.problem, places });
259
+ }
260
+
261
+ /** the plain sentence for a failed `check tools`; the library's own message can hold the start command, so it is never passed on @param {any} e */
262
+ function checkFailure(e) {
263
+ if (e?.context?.timeout === true) return 'The server did not answer in time.';
264
+ if (e?.context?.spawnError === true) return 'The server did not start.';
265
+ if (e?.context?.notFound === true) return 'The server is not in the list any more.';
266
+ return 'The check failed.';
267
+ }
268
+
269
+ /** The one place a press starts a server: ONLY from this POST (never a page load or a GET), that one server, once, with the same start options as a run. @param {any} body */
270
+ async function mcpCheck(body) {
271
+ const server = body?.server;
272
+ if (typeof server !== 'string' || server === '') return refuse('bad-server', 'Pick an MCP to check. Nothing was started.');
273
+ const place = sources().places.find((p) => p.servers.some((x) => x.name === server));
274
+ const row = place?.servers.find((x) => x.name === server);
275
+ if (!place || !row) return refuse('unknown-mcp', 'That MCP is not in the list. Nothing was started.');
276
+ if (row.remote) return refuse('remote-mcp', 'A remote server is not supported yet. Nothing was started.');
277
+ if (row.shadowedBy !== null) return refuse('shadowed-mcp', 'An earlier path has an MCP with this name, so this one is not used. Nothing was started.');
278
+ if (checking.has(server)) return refuse('already-checking', 'That MCP is being checked right now.', 409);
279
+ checking.add(server);
280
+ const line = { server, path: place.path, at: new Date(opts.now ? opts.now() : Date.now()).toISOString() };
281
+ try {
282
+ let entry;
283
+ try {
284
+ // confirmServer vets ONLY the named server (bare-agent needs exactly `true`); the start options are a run's: PATH and HOME, the home folder as cwd
285
+ const tools = await listServerTools({ server, configPaths: [place.file], passEnv: MCP_PASS_ENV, cwd: opts.mcpHome ?? homedir(), confirmServer: (/** @type {string} */ n) => n === server, timeout: MCP_CHECK_MS });
286
+ entry = { ...line, ok: true, tools: tools.map((t) => ({ name: t.name, hint: hintOf(t.annotations) })) };
287
+ } catch (e) {
288
+ entry = { ...line, ok: false, error: checkFailure(e) };
289
+ }
290
+ try {
291
+ appendMcpCheck(opts.home, entry);
292
+ } catch {
293
+ return refuse('log-failed', 'The check ran but its result could not be saved.', 500);
294
+ }
295
+ return reply(200, { ok: true, checked: entry.ok });
296
+ } finally {
297
+ checking.delete(server);
298
+ }
299
+ }
300
+
301
+ /** @param {any} body */
302
+ function mcpPathAdd(body) {
303
+ const raw = typeof body?.path === 'string' ? body.path.trim() : body?.path;
304
+ // the person may type `~/x`; the config keeps absolute paths only (`mcpPathProblem`), so it is written out first
305
+ const typed = typeof raw === 'string' ? expandMcpPath(raw, opts.mcpHome) : raw;
306
+ const why = mcpPathProblem([typed]);
307
+ if (why) return refuse('bad-path', `${why} Nothing was saved.`);
308
+ const c = config();
309
+ if (c.problem) return refuse('config-broken', `${BROKEN_CONFIG} Nothing was saved.`);
310
+ const list = Array.isArray(c.config.mcpPaths) ? c.config.mcpPaths : [];
311
+ if (DEFAULT_MCP_PLACES(opts.mcpHome).includes(typed) || list.includes(typed)) return refuse('path-listed', 'That path is already in the list. Nothing was saved.');
312
+ try {
313
+ updateConfig({ mcpPaths: [...list, typed] }, { home: opts.home });
314
+ } catch (e) {
315
+ if (!(e instanceof ConfigError)) throw e;
316
+ return refuse('config-broken', `${BROKEN_CONFIG} Nothing was saved.`);
317
+ }
318
+ return reply(200, { ok: true, path: typed });
319
+ }
320
+
321
+ /** @param {any} body */
322
+ function mcpPathRemove(body) {
323
+ const c = config();
324
+ if (c.problem) return refuse('config-broken', `${BROKEN_CONFIG} Nothing was saved.`);
325
+ const list = Array.isArray(c.config.mcpPaths) ? c.config.mcpPaths : [];
326
+ const typed = typeof body?.path === 'string' ? expandMcpPath(body.path, opts.mcpHome) : null;
327
+ if (typed === null || !list.includes(typed)) return refuse('path-unknown', 'That path is not one you added. Nothing was changed.');
328
+ const next = list.filter((/** @type {string} */ p) => p !== typed);
329
+ try {
330
+ updateConfig({ mcpPaths: next.length ? next : null }, { home: opts.home });
331
+ } catch (e) {
332
+ if (!(e instanceof ConfigError)) throw e;
333
+ return refuse('config-broken', `${BROKEN_CONFIG} Nothing was saved.`);
334
+ }
335
+ return reply(200, { ok: true });
336
+ }
337
+
217
338
  /**
218
339
  * The POST routes that answer asynchronously.
219
340
  * @param {string} pathname
@@ -224,6 +345,9 @@ export function createSettingsRoutes(opts) {
224
345
  if (pathname === '/api/settings/provider') return providerRoute(body);
225
346
  if (pathname === '/api/settings/model') return modelRoute(body);
226
347
  if (pathname === '/api/settings/open-keys-folder') return openKeysFolder(body);
348
+ if (pathname === '/api/settings/mcp-check') return mcpCheck(body);
349
+ if (pathname === '/api/settings/mcp-path') return mcpPathAdd(body);
350
+ if (pathname === '/api/settings/mcp-path-remove') return mcpPathRemove(body);
227
351
  return listFor(body?.slot).then((r) => {
228
352
  if ('unknown' in r) return refuse('unknown-provider', 'That provider is not known.');
229
353
  if (pathname === '/api/settings/test') return reply(200, r.ok ? { ok: true, ms: r.ms } : r);
@@ -311,7 +435,13 @@ export function createSettingsRoutes(opts) {
311
435
  send(r.status, r.body);
312
436
  return true;
313
437
  }
314
- const postPaths = ['/api/settings/provider', '/api/settings/model', '/api/settings/models', '/api/settings/test', '/api/settings/open-keys-folder'];
438
+ if (pathname === '/api/settings/mcp' && req.method === 'GET') {
439
+ const r = mcpGet();
440
+ send(r.status, r.body);
441
+ return true;
442
+ }
443
+ const postPaths = ['/api/settings/provider', '/api/settings/model', '/api/settings/models', '/api/settings/test', '/api/settings/open-keys-folder',
444
+ '/api/settings/mcp-check', '/api/settings/mcp-path', '/api/settings/mcp-path-remove'];
315
445
  if (req.method === 'POST' && postPaths.includes(pathname)) {
316
446
  Promise.resolve(postRoute(pathname, body)).then((r) => send(r.status, r.body));
317
447
  return true;
@@ -11,6 +11,7 @@
11
11
  // cap-halt, wall-halt -> capped (money cap / time cap)
12
12
  // escalated + money-halt record, escalated + wall-halt -> capped
13
13
  // stopped (the person pressed Stop) -> stopped
14
+ // skipped (a Tickets job's signed filter let the ticket by) -> skipped (a quiet end: not a failure, not a pass, never reusable or Needs you)
14
15
  // plan-red, check-red, step-red, escalated (strikes / provider / other), close-red, provider-red, step-stalled,
15
16
  // and every other outcome (refusals, instrument stops) -> failed
16
17
  // `waiting` is the step-level sign for a step that has not started; no run outcome maps to it.
@@ -31,7 +32,7 @@ export function isReusableGreen(outcome) {
31
32
  return outcome === 'green' || outcome === 'already-green';
32
33
  }
33
34
 
34
- /** @typedef {'running'|'waiting'|'passed'|'failed'|'capped'|'stopped'|'died'} StatusKey */
35
+ /** @typedef {'running'|'waiting'|'passed'|'failed'|'capped'|'stopped'|'died'|'skipped'} StatusKey */
35
36
 
36
37
  /** the table: key -> sign + word */
37
38
  export const STATUS = Object.freeze({
@@ -42,8 +43,24 @@ export const STATUS = Object.freeze({
42
43
  capped: Object.freeze({ sign: '✗', word: 'capped' }),
43
44
  stopped: Object.freeze({ sign: '■', word: 'stopped' }),
44
45
  died: Object.freeze({ sign: '?', word: 'died' }),
46
+ // a ticket the job's signed filter did not let through (piece 2): grey, rests, ends at run start at $0
47
+ skipped: Object.freeze({ sign: '–', word: 'skipped' }),
45
48
  });
46
49
 
50
+ /**
51
+ * The plain words a skipped run carries (the `settled` event's `words`, the Ended line), from CODE. They do NOT repeat the status word: every surface prints `skipped — <words>` from the table's word (the CLI line adds its own `skipped:`): the filter decision's own reason, never model-written.
52
+ * `reason` is `decideTicket`'s ('closed' | 'priority P3, not P1' | 'no P1 label' | 'no bug label'); `filter` is the job's signed `ticketFilter`, which tells a missing
53
+ * priority label from a missing type label (the two share the `no X label` spelling).
54
+ * @param {string} reason @param {{priority?: string[], labels?: string[]}|undefined} filter @returns {string}
55
+ */
56
+ export function skipWords(reason, filter) {
57
+ if (reason === 'closed') return 'the ticket is closed';
58
+ const m = /^no (.+) label$/.exec(reason);
59
+ if (m && filter?.priority?.length && m[1] === filter.priority.join(' or ')) return `no ${m[1]} label on the ticket`;
60
+ if (m) return `label ${m[1]} not on the ticket`;
61
+ return reason;
62
+ }
63
+
47
64
  /**
48
65
  * The status of one run.
49
66
  * @param {{outcome: string|null|undefined, died?: boolean, category?: string|null, moneyHalt?: boolean}} o
@@ -57,6 +74,7 @@ export function statusFor(o) {
57
74
  if (o.died) key = 'died';
58
75
  else if (out === null || out === undefined) key = 'running';
59
76
  else if (out === 'green' || out === 'already-green' || out === 'satisfied') key = 'passed';
77
+ else if (out === 'skipped') key = 'skipped';
60
78
  else if (capKindOf(o) !== null) key = 'capped';
61
79
  else if (out === 'stopped') key = 'stopped';
62
80
  return { key, ...STATUS[key] };
@@ -0,0 +1,44 @@
1
+ // borrowed-from: fwdloop src/panel/tickets.js@v0.29.0 (adapted: GROUP_OF is keyed by bareloop's STATUS keys (src/panel/status.js), the one table; the ticket list itself is NOT taken, the grid
2
+ // (src/panel/jobgrid.js) is the one view; the queue seam is the schedule door's `arriveAnyway`, which writes the ledger row (src/triggertickets.js `recordAnyway`) or, while the schedule is off, starts at once)
3
+ // ITEM33-BUILD piece 4 (R8): the four buckets of a ticket job's grid and `POST /api/author/ticket-anyway`.
4
+ import { isTicketNumber, TICKET_NUMBER_WORDS } from '../ticketshape.js';
5
+
6
+ /** the four buckets, in the mockup's order: key, label, open at first. The page draws them; it types none of these words. */
7
+ export const TICKET_GROUPS = Object.freeze([
8
+ Object.freeze({ key: 'wait', label: 'Needs you', open: true }),
9
+ Object.freeze({ key: 'stop', label: 'Stopped', open: true }),
10
+ Object.freeze({ key: 'done', label: 'Passed', open: false }),
11
+ Object.freeze({ key: 'skip', label: 'Skipped', open: false }),
12
+ ]);
13
+
14
+ /**
15
+ * A run's STATUS KEY (src/panel/status.js, the one table) -> its bucket. A running run still needs a person or is still going: Needs you. A run waiting at its review door is `passed` in the table
16
+ * but needs the person's Accept: the grid moves it to Needs you from the run list's own `needs` tag (`bucketOf`, src/panel/jobgrid.js), never from a second outcome reader.
17
+ */
18
+ export const GROUP_OF = Object.freeze({
19
+ running: 'wait', waiting: 'wait', passed: 'done', failed: 'stop', capped: 'stop', stopped: 'stop', died: 'stop', skipped: 'skip',
20
+ });
21
+
22
+ /** a "Run it anyway" reason: short, never blank. The same bar as a rerun's. */
23
+ export const ANYWAY_REASON_MAX = 500;
24
+
25
+ /**
26
+ * `POST /api/author/ticket-anyway {job, ticket, reason}`: a SKIPPED ticket is run anyway, after a short reason. Without a reason nothing starts. `isSkipped(job, number)` says whether the
27
+ * job's grid holds that ticket as a skipped row nobody has run since; `door.arriveAnyway({job, number, reason})` is the ONE seam (production: the schedule door's).
28
+ * @param {{body: any, isSkipped: (job: string, number: number) => boolean, door: {arriveAnyway: (a: {job: string, number: number, reason: string, runid?: string}) => Promise<{ok: boolean, say: string, started?: boolean}>},
29
+ * skippedRunOf?: (job: string, number: number) => string|null}} a
30
+ * @returns {Promise<{status: number, body: Record<string, any>}>}
31
+ */
32
+ export async function ticketAnyway({ body, isSkipped, door, skippedRunOf }) {
33
+ const b = body !== null && typeof body === 'object' ? body : {};
34
+ const reason = typeof b.reason === 'string' ? b.reason.trim() : '';
35
+ if (reason === '') return { status: 400, body: { ok: false, refused: 'reason-required', say: 'Please write a reason to run it anyway. Nothing started.' } };
36
+ if (reason.length > ANYWAY_REASON_MAX) return { status: 400, body: { ok: false, refused: 'reason-too-long', say: `Keep the reason under ${ANYWAY_REASON_MAX} characters. Nothing started.` } };
37
+ if (typeof b.job !== 'string' || b.job === '' || !isTicketNumber(b.ticket)) return { status: 400, body: { ok: false, refused: 'bad-request', say: `Name the job and the ticket number (${TICKET_NUMBER_WORDS}). Nothing started.` } };
38
+ if (!isSkipped(b.job, b.ticket)) return { status: 409, body: { ok: false, refused: 'not-skipped', say: `Ticket #${b.ticket} is not a skipped ticket of this job. Nothing started.` } };
39
+ const r = await door.arriveAnyway({ job: b.job, number: b.ticket, reason, ...(skippedRunOf ? { runid: skippedRunOf(b.job, b.ticket) ?? undefined } : {}) });
40
+ if (!r.ok) return { status: 409, body: { ok: false, refused: 'queue', say: r.say } };
41
+ return r.started === true
42
+ ? { status: 202, body: { ok: true, started: true, number: b.ticket, say: r.say } }
43
+ : { status: 202, body: { ok: true, queued: true, number: b.ticket, say: r.say } };
44
+ }
@@ -0,0 +1,163 @@
1
+ // borrowed-from: fwdloop src/pickrecord.js@v0.29.0
2
+ // M10 am17 + am18: the ONE record of check picks, carried from plan to plan. A pick is tied to its job line's WORDS (plus its order among lines with the same words)
3
+ // and to its guardrail's exact words, never to a line or rule number: both are recomputed on the new card. This file is the only writer of a record's entries
4
+ // (`entriesFromAnswers`) and the only reader that decides keep-or-ask (`matchRecord`); the logic is the one F146 / F146b proved (poc/m10-am17/keep-picks-am18.mjs).
5
+ // Throws away: line and rule numbers (recomputed), the model's words (it never sees a pick), a pick whose line or guardrail words no longer match.
6
+ import { readFileSync, writeFileSync } from 'node:fs';
7
+ import path from 'node:path';
8
+
9
+ /** the record's file, inside a drafting session folder only (never a run folder) */
10
+ export const RECORD_FILE = 'picks-record.json';
11
+ /** the exact words a kept pick is marked with in the draft log, the Audit and the plan card (M10 am17 (6)) */
12
+ export const KEPT_WORDS = 'kept from last draft';
13
+
14
+ /** @typedef {{lineWords: string, occurrence: number, ruleText: string, added: string|null, check: Record<string, any>|null, own: boolean, left: boolean}} Entry */
15
+ /** @typedef {{line: number, rule: number, text: string}} Rule */
16
+
17
+ const norm = (/** @type {unknown} */ t) => String(t).toLowerCase().replace(/\s+/g, ' ').trim();
18
+ /** @param {unknown} a @param {unknown} b the two texts are the same words (case and spacing aside) */
19
+ export const sameWords = (a, b) => norm(a) === norm(b);
20
+ const id = (/** @type {Rule} */ r) => `${r.line}:${r.rule}`;
21
+
22
+ /**
23
+ * The key of every job line: its own words, plus how many lines before it have the same words (equal lines match in their order).
24
+ * @param {{n: number, text: string}[]} lines @returns {Map<number, {lineWords: string, occurrence: number}>}
25
+ */
26
+ export function lineKeys(lines) {
27
+ /** @type {Map<string, number>} */
28
+ const seen = new Map();
29
+ return new Map(lines.map((l) => {
30
+ const w = norm(l.text);
31
+ const occurrence = seen.get(w) ?? 0;
32
+ seen.set(w, occurrence + 1);
33
+ return [l.n, { lineWords: w, occurrence }];
34
+ }));
35
+ }
36
+
37
+ /**
38
+ * The entries for answers just given, numbered on THIS card (the answer redraft's card: its line and rule numbers are the ones the asks carried).
39
+ * @param {{n: number, text: string}[]} lines @param {Rule[]} rules
40
+ * @param {{line: number, rule: number, check?: Record<string, any>|null, added?: string|null, own?: boolean}[]} picks @param {{line: number, rule: number}[]} left
41
+ * @returns {Entry[]}
42
+ */
43
+ export function entriesFromAnswers(lines, rules, picks, left) {
44
+ const keys = lineKeys(lines);
45
+ /** @param {number} line @param {number} rule */
46
+ const base = (line, rule) => {
47
+ const r = rules.find((x) => x.line === line && x.rule === rule);
48
+ const k = keys.get(line);
49
+ return r === undefined || k === undefined ? null : { ...k, ruleText: r.text };
50
+ };
51
+ /** @type {Entry[]} */
52
+ const out = [];
53
+ for (const p of picks) {
54
+ const b = base(p.line, p.rule);
55
+ if (b) out.push({ ...b, added: typeof p.added === 'string' ? p.added : null, check: p.check ?? null, own: p.own === true, left: false });
56
+ }
57
+ for (const l of left) {
58
+ const b = base(l.line, l.rule);
59
+ if (b) out.push({ ...b, added: null, check: null, own: false, left: true });
60
+ }
61
+ return out;
62
+ }
63
+
64
+ /**
65
+ * Decide, for the card in hand, which stored picks are kept and which guardrails must be asked.
66
+ * A pick is KEPT when the job line with its words (same order among equal lines) still has its source guardrail with the exact words and, if the pick wrote a `~` line,
67
+ * that line with its exact words too. Otherwise the pick is dropped (never partly kept) and its guardrails are asked: a pair broken on one side is ONE ask, so the
68
+ * partner left on the card is folded (neither asked nor given the old check) - except an EDITED added line (M10 am21): that one is asked (`pairRule` = its source's number) and the source is folded. Pure.
69
+ * @param {Entry[]} entries @param {{n: number, text: string}[]} lines @param {Rule[]} rules every guardrail the call settles
70
+ * @returns {{picks: {line: number, rule: number, check: Record<string, any>|null, added?: string, own?: boolean}[], left: {line: number, rule: number}[],
71
+ * kept: {line: number, rule: number, entry: Entry}[], askRules: (Rule & {pairRule?: number})[]}}
72
+ */
73
+ export function matchRecord(entries, lines, rules) {
74
+ const byKey = new Map([...lineKeys(lines)].map(([n, k]) => [`${k.lineWords}#${k.occurrence}`, n]));
75
+ /** @type {Set<string>} */
76
+ const claimed = new Set();
77
+ /** @type {Set<string>} */
78
+ const folded = new Set();
79
+ /** @type {Map<string, number>} an edited added line (by id) -> the rule number of the source it was paired with (M10 am21) */
80
+ const edited = new Map();
81
+ const free = (/** @type {number} */ n, /** @type {string} */ text) => rules.find((r) => r.line === n && !claimed.has(id(r)) && !folded.has(id(r)) && norm(r.text) === norm(text));
82
+ const kept = [];
83
+ /** @type {{e: Entry, n: number|undefined}[]} */
84
+ const broken = [];
85
+ for (const e of Array.isArray(entries) ? entries : []) {
86
+ const n = byKey.get(`${e.lineWords}#${e.occurrence}`);
87
+ const src = n === undefined ? undefined : free(n, e.ruleText);
88
+ if (src) claimed.add(id(src)); // held while the partner is looked for, so a pair never takes one rule twice
89
+ const add = n === undefined || !src || e.added === null ? undefined : free(n, e.added);
90
+ if (n !== undefined && src && (e.added === null || add)) {
91
+ if (add) claimed.add(id(add));
92
+ kept.push({ line: n, rule: src.rule, entry: e });
93
+ } else {
94
+ if (src) claimed.delete(id(src));
95
+ broken.push({ e, n });
96
+ }
97
+ }
98
+ // a pair broken on one side is ONE pick, so ONE ask: the partner that is left folds into it (it keeps no old check and is not asked on its own)
99
+ for (const { e, n } of broken) {
100
+ if (e.added === null) continue;
101
+ if (n === undefined) {
102
+ // the line's own words changed: it is a new line, all its guardrails are asked; its old `~` line with its source still there rides the source's ask
103
+ for (const l of lines) {
104
+ const s = free(l.n, e.ruleText);
105
+ const a = s ? rules.find((r) => r.line === l.n && r !== s && !claimed.has(id(r)) && !folded.has(id(r)) && norm(r.text) === norm(e.added ?? '')) : undefined;
106
+ if (a) { folded.add(id(a)); break; }
107
+ }
108
+ continue;
109
+ }
110
+ const src = free(n, e.ruleText);
111
+ const add = free(n, e.added);
112
+ if (src && !add) {
113
+ // the added line was edited (or deleted): the unclaimed rule right after the source on that line is it. M10 am21: the ONE ask is about THAT line's words
114
+ // (it carries the source's number as `pairRule`, the rule its pick is kept under); the source rides it and is not asked on its own
115
+ const p = rules.find((r) => r.line === n && r.rule > src.rule && !claimed.has(id(r)) && !folded.has(id(r)));
116
+ if (p) { folded.add(id(src)); edited.set(id(p), src.rule); }
117
+ } else if (add && !src) {
118
+ // the source was edited: the unclaimed rule right before the added line is it; the old added line rides that ask
119
+ const p = [...rules].reverse().find((r) => r.line === n && r.rule < add.rule && !claimed.has(id(r)) && !folded.has(id(r)));
120
+ if (p) folded.add(id(add));
121
+ }
122
+ }
123
+ const picks = [];
124
+ const left = [];
125
+ for (const k of kept) {
126
+ const e = k.entry;
127
+ if (e.left) left.push({ line: k.line, rule: k.rule });
128
+ else picks.push({ line: k.line, rule: k.rule, check: e.check, ...(e.added === null ? {} : { added: e.added }), ...(e.own ? { own: true } : {}) });
129
+ }
130
+ return { picks, left, kept, askRules: rules.filter((r) => !claimed.has(id(r)) && !folded.has(id(r))).map((r) => (edited.has(id(r)) ? { ...r, pairRule: edited.get(id(r)) } : r)) };
131
+ }
132
+
133
+ /**
134
+ * Read a carried record (the session folder's file). A missing or unreadable file is no record (a draft from before R10 has none).
135
+ * @param {string} file @returns {Entry[]|null}
136
+ */
137
+ export function readRecordFile(file) {
138
+ try {
139
+ const j = JSON.parse(readFileSync(file, 'utf8'));
140
+ return Array.isArray(j?.picks) ? j.picks.filter((/** @type {any} */ e) => e && typeof e.lineWords === 'string' && Number.isInteger(e.occurrence) && typeof e.ruleText === 'string') : null;
141
+ } catch { return null; }
142
+ }
143
+
144
+ /** where a drafting session folder keeps its record @param {string} planDir */
145
+ export const recordPath = (planDir) => path.join(planDir, RECORD_FILE);
146
+
147
+ /**
148
+ * The Drop/Add choices a draft's person made on the confirm card (hamr 2026-11-13, N-2), carried the same way as the picks: tied to the line's words and the row's own name, never to a number.
149
+ * @param {string} file @returns {{lineWords: string, occurrence: number, tail: string, choice: string}[]|null}
150
+ */
151
+ export function readRowChoices(file) {
152
+ try {
153
+ const j = JSON.parse(readFileSync(file, 'utf8'));
154
+ return Array.isArray(j?.rowChoices) ? j.rowChoices.filter((/** @type {any} */ e) => e && typeof e.lineWords === 'string' && Number.isInteger(e.occurrence) && typeof e.tail === 'string' && (e.choice === 'drop' || e.choice === 'add')) : null;
155
+ } catch { return null; }
156
+ }
157
+
158
+ /** write a part of the record without losing the other: `patch` is `{picks}` or `{rowChoices}` @param {string} file @param {Record<string, any>} patch */
159
+ export function writeRecordPart(file, patch) {
160
+ let cur = {};
161
+ try { const j = JSON.parse(readFileSync(file, 'utf8')); if (j && typeof j === 'object' && !Array.isArray(j)) cur = j; } catch { /* no record yet */ }
162
+ writeFileSync(file, `${JSON.stringify({ ...cur, ...patch })}\n`, { mode: 0o600 });
163
+ }