fwdloop 0.26.2 → 0.27.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 (45) hide show
  1. package/bin/fwdloop +23 -3
  2. package/package.json +1 -1
  3. package/src/authoring.js +10 -0
  4. package/src/canrun.js +20 -0
  5. package/src/declaration.js +98 -2
  6. package/src/drafter.js +23 -10
  7. package/src/learnstore.js +1 -1
  8. package/src/panel/author.js +18 -2
  9. package/src/panel/authorflows.js +9 -4
  10. package/src/panel/authorstart.js +10 -6
  11. package/src/panel/authortrigger.js +34 -10
  12. package/src/panel/data.js +39 -4
  13. package/src/panel/index.html +516 -60
  14. package/src/panel/scheduler.js +42 -6
  15. package/src/panel/server.js +21 -5
  16. package/src/panel/tickets.js +113 -0
  17. package/src/runner.js +51 -10
  18. package/src/schedule.js +5 -0
  19. package/src/summary-words.js +12 -4
  20. package/src/ticket-draft.js +87 -0
  21. package/src/ticket-labels.js +65 -0
  22. package/src/ticket-mcp.js +66 -0
  23. package/src/ticket-shape.js +24 -0
  24. package/src/trigger-files.js +1 -1
  25. package/src/trigger-line.js +2 -1
  26. package/src/trigger-tickets.js +209 -0
  27. package/types/canrun.d.ts +14 -0
  28. package/types/drafter.d.ts +186 -64
  29. package/types/panel/author.d.ts +8 -0
  30. package/types/panel/authorflows.d.ts +2 -0
  31. package/types/panel/authorstart.d.ts +3 -1
  32. package/types/panel/authortrigger.d.ts +11 -1
  33. package/types/panel/data.d.ts +22 -3
  34. package/types/panel/scheduler.d.ts +7 -2
  35. package/types/panel/server.d.ts +9 -2
  36. package/types/panel/tickets.d.ts +81 -0
  37. package/types/runner.d.ts +21 -3
  38. package/types/summary-words.d.ts +2 -1
  39. package/types/ticket-draft.d.ts +96 -0
  40. package/types/ticket-labels.d.ts +36 -0
  41. package/types/ticket-mcp.d.ts +40 -0
  42. package/types/ticket-shape.d.ts +25 -0
  43. package/types/trigger-files.d.ts +2 -0
  44. package/types/trigger-line.d.ts +7 -0
  45. package/types/trigger-tickets.d.ts +91 -0
package/bin/fwdloop CHANGED
@@ -54,6 +54,7 @@ import { isInteractive, confirmTypedName, NEEDS_TTY } from '../src/sign-confirm.
54
54
  import { draftToDir, draftKeyRefusal, signDraft, SIGN_LINE, costText, questionsRefusal } from '../src/authoring.js';
55
55
  import { userInfo } from 'node:os';
56
56
  import { pageAddressesOf, pageAddressRefusal } from '../src/pagefetch.js';
57
+ import { ticketListsOf } from '../src/ticket-shape.js';
57
58
 
58
59
  // This CLI drives no fixed provider (M4d amendment 6). A job runs with the model recorded beside it as its DEFAULT (M4d am33: `run --model` picks any other ticked model for that run) (`model.json`, written when it was drafted:
59
60
  // the provider is the name of a key, its key is read from the env under that name and never printed); `draft` takes `--model` (+ `--provider`).
@@ -305,6 +306,10 @@ function reportRunResult(result, { rootArg }) {
305
306
  process.exitCode = 1;
306
307
  return;
307
308
  }
309
+ if (result.outcome === 'skipped') { // hamr 2026-10-30: a skip is a normal grey ending, not a failure
310
+ process.stdout.write(`skipped: spentUsd=${result.spentUsd}\n`);
311
+ return;
312
+ }
308
313
  process.stderr.write(`fwdloop: ${result.outcome}${result.red ? ` — ${result.red}` : ''}\n`);
309
314
  process.exitCode = 1;
310
315
  }
@@ -319,6 +324,8 @@ async function cmdRun(rest) {
319
324
  options: {
320
325
  root: { type: 'string' },
321
326
  source: { type: 'string', multiple: true, default: [] },
327
+ ticket: { type: 'string' }, // M12: the one ticket of the job's ticket list this run reads, by number
328
+ anyway: { type: 'boolean' }, // M12 p3 (hamr 2026-10-30): this ticket came by "Run it anyway"; the run does not skip it for its labels or closed
322
329
  'run-id': { type: 'string' },
323
330
  // a job drafted before its model was recorded: the model it runs with (a ticked line); --provider only if two keys tick the same id
324
331
  model: { type: 'string' }, provider: { type: 'string' },
@@ -334,6 +341,12 @@ async function cmdRun(rest) {
334
341
  const nameCheck = checkFlowName(flowName);
335
342
  if (!nameCheck.ok) fail(nameCheck.red);
336
343
 
344
+ // A refusal before the run starts must leave no run folder behind. The panel claims `run-<n>` (and may put the signed values in it) BEFORE it spawns this
345
+ // child, so EVERY exit before the run begins undoes it: registered here, at the first line that can fail, not after the checks (rmdir only ever removes an EMPTY folder).
346
+ const dropUnstartedRun = (dir) => process.on('exit', () => { dropUnstartedValues(dir); try { rmdirSync(dir); } catch { /* not empty, or gone: nothing to undo */ } });
347
+ const typedRun = typeof values['run-id'] === 'string' ? resolveRunDir(join(root, flowName), values['run-id']) : null;
348
+ if (typedRun?.ok) dropUnstartedRun(typedRun.runDir);
349
+
337
350
  const loaded = loadCatalogue();
338
351
  if (!loaded.ok) fail(`catalogue: ${loaded.reds.join('; ')}`);
339
352
  const catalogue = loaded.primitives;
@@ -368,7 +381,15 @@ async function cmdRun(rest) {
368
381
  fail(`run: --source role "${role}" is not declared by flow "${flowName}" (known roles: ${declaredRoles.join(', ') || '(none)'})`);
369
382
  }
370
383
  }
371
- const sources = declaredRoles.map((role) => ({ id: role, path: parsedSources[role] }));
384
+ // M12 piece 2 (PRD ruling 2026-10-29): a job with a ticket-list input reads ONE ticket per run, picked by number. Refused at $0, by name, before anything is claimed.
385
+ const ticketLists = ticketListsOf(read.arbiter);
386
+ const ticketRoles = Object.keys(ticketLists);
387
+ if (ticketRoles.length > 1) fail(`run: flow "${flowName}" has more than one ticket list (${ticketRoles.join(', ')}); a run reads one. Nothing started.`);
388
+ if (values.anyway && values.ticket === undefined) fail(`run: --anyway belongs with --ticket <number>. Nothing started.`);
389
+ if (values.ticket !== undefined && ticketRoles.length === 0) fail(`run: --ticket ${values.ticket}, but flow "${flowName}" has no ticket-list input. Nothing started.`);
390
+ if (ticketRoles.length === 1 && values.ticket === undefined) fail(`run: flow "${flowName}" reads tickets from "${ticketRoles[0]}" (${ticketLists[ticketRoles[0]]}); pick the ticket with --ticket <number>. Nothing started.`);
391
+ if (values.ticket !== undefined && !/^[1-9][0-9]{0,9}$/.test(values.ticket)) fail(`run: --ticket "${values.ticket}" is not a ticket number (a whole number from 1). Nothing started.`);
392
+ const sources = declaredRoles.map((role) => ({ id: role, path: parsedSources[role], ...(ticketRoles[0] === role ? { ticket: { number: Number(values.ticket), ...(values.anyway ? { anyway: true } : {}) } } : {}) }));
372
393
  for (const src of sources) {
373
394
  if (!Object.hasOwn(pages, src.id) && !existsSync(src.path)) fail(`run: source "${src.id}" is unreadable at ${src.path}`);
374
395
  }
@@ -383,6 +404,7 @@ async function cmdRun(rest) {
383
404
  if (!claimed.ok) fail(claimed.red);
384
405
  runId = claimed.runId;
385
406
  runDir = claimed.runDir;
407
+ dropUnstartedRun(runDir);
386
408
  } else {
387
409
  const runIdCheck = resolveRunDir(join(root, flowName), runId);
388
410
  if (!runIdCheck.ok) fail(runIdCheck.red);
@@ -394,8 +416,6 @@ async function cmdRun(rest) {
394
416
  const applied = applyRunValues(read.arbiter, flowName, read.signature.flow, pickRunValues(runDir));
395
417
  if (!applied.ok) fail(`run: ${applied.red}`);
396
418
  const { arbiter } = applied;
397
- // a refusal before the run starts must not leave the claimed empty folder behind (rmdir only ever removes an EMPTY folder)
398
- process.on('exit', () => { dropUnstartedValues(runDir); try { rmdirSync(runDir); } catch { /* not empty, or gone: nothing to undo */ } });
399
419
 
400
420
  // The key preflight (item A: "refuses at $0 BEFORE any book write") runs
401
421
  // here — before ANY directory for this run is created.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fwdloop",
3
- "version": "0.26.2",
3
+ "version": "0.27.0",
4
4
  "description": "Describe a job as steps and guardrails; an agent builds the workflow, pauses for humans where you said, checks every step happened, and reruns it under budgets it cannot touch.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
package/src/authoring.js CHANGED
@@ -195,12 +195,22 @@ export function buildReadout({
195
195
  const h = declaration.inputFacts?.[s.role];
196
196
  out.push(` ${s.role} = ${s.path}${h ? ` [headings: ${h.join(' | ') || 'none'}]` : ''}`);
197
197
  }
198
+ // M12 piece 3: what is signed for MCP, from the declaration's typed fields (a job without them prints none of these rows)
199
+ const mcp = declaration.mcp;
200
+ if (mcp && typeof mcp === 'object') out.push(` mcp: ${mcp.server} · tools: ${(mcp.tools ?? []).join(', ')}`);
201
+ const filter = declaration.ticketFilter;
202
+ if (filter && typeof filter === 'object') {
203
+ const parts = [...(filter.priority?.length ? [`priority ${filter.priority.join(', ')}`] : []), ...(filter.labels?.length ? [`labels ${filter.labels.join(', ')}`] : [])];
204
+ if (parts.length) out.push(` ticket filter: ${parts.join(' · ')}`);
205
+ }
206
+ if (Array.isArray(declaration.ticketWatch) && declaration.ticketWatch.length) out.push(` ticket watch: ${declaration.ticketWatch.join(', ')}`);
198
207
  out.push('', READOUT_HEADS.steps);
199
208
  const sheetBlocks = sheetLineBlocks({ declaration, lines });
200
209
  declaration.steps.forEach((st, i) => {
201
210
  out.push(` ${i + 1}. (line ${st.fromLine}) ${st.goal}`);
202
211
  out.push(` grants: ${st.primitives?.length ? st.primitives.join(', ') : 'none (pure stop)'}`
203
212
  + ` | reads: ${st.reads?.length ? st.reads.join(', ') : '-'} | emits: ${st.emits} | check: ${st.close?.class}`);
213
+ if (Array.isArray(st.mcpTools) && st.mcpTools.length) out.push(` tools: ${st.mcpTools.join(', ')}`);
204
214
  // M10 am7 item 1: the facts a cited step checks its quotes against, signed with the readout (typed fields, never model prose)
205
215
  if (st.close?.cited && typeof st.close.cited === 'object') for (const row of factRows(st.close.cited)) out.push(` ${row}`);
206
216
  // M10b piece 1: the signed sheet checks, one row each, written by code from the typed fields
package/src/canrun.js CHANGED
@@ -24,6 +24,24 @@ export function unwiredRed(found) {
24
24
  return `preflight: step "${found.step.emits}" (line ${found.step.fromLine}) grants verb "${found.verb}", which has no wired implementation`;
25
25
  }
26
26
 
27
+ /**
28
+ * M12 piece 1a (F105): the first tool the job lists (`declaration.mcp.tools`) that no step grants (`steps[].mcpTools`), or null. A job lists only the tools its
29
+ * steps use (PRD, hamr 2026-10-29); the ticket schedule's own tool lives in `schedule.json`, not here. A declaration without `mcp` has nothing to check.
30
+ * @param {Record<string, any>} declaration `readFlow`'s declaration @returns {{tool: string, server: string}|null}
31
+ */
32
+ export function findUnusedMcpTool(declaration) {
33
+ const tools = declaration.mcp?.tools;
34
+ if (!Array.isArray(tools)) return null;
35
+ const granted = new Set(declaration.steps.flatMap((s) => s.mcpTools ?? []));
36
+ const tool = tools.find((t) => !granted.has(t));
37
+ return tool === undefined ? null : { tool, server: String(declaration.mcp.server) };
38
+ }
39
+
40
+ /** The preflight refusal sentence for a job tool no step grants. @param {{tool: string, server: string}} found */
41
+ export function unusedMcpToolRed(found) {
42
+ return `preflight: job tool "${found.tool}" (server "${found.server}") is granted to no step`;
43
+ }
44
+
27
45
  /** bareguard refuses a signed name or phrase past this many characters (rubric MAX_SIGNED_LEN). */
28
46
  const MAX_ENTRY_CHARS = 1000;
29
47
  const SIGN_AGAIN = 'and sign the job again';
@@ -99,6 +117,8 @@ export function canFlowRun(read) {
99
117
  if (!read || read.ok !== true) return { ok: false, red: String(read?.reds?.[0] ?? 'the flow does not read') };
100
118
  const unwired = findUnwiredVerbStep(read.declaration);
101
119
  if (unwired) return { ok: false, red: unwiredRed(unwired) };
120
+ const unusedTool = findUnusedMcpTool(read.declaration);
121
+ if (unusedTool) return { ok: false, red: unusedMcpToolRed(unusedTool) };
102
122
  const unbuildable = findUnbuildableCheckStep(read.declaration);
103
123
  if (unbuildable) return { ok: false, red: unbuildableRed(unbuildable), detail: unbuildable.why };
104
124
  return { ok: true };
@@ -36,6 +36,7 @@
36
36
  // No `new RegExp` anywhere in this file — a test in test/signed-text.test.js
37
37
  // greps all of src/ for that, and it must keep passing with this file added.
38
38
 
39
+ import { WATCHABLE } from './ticket-shape.js';
39
40
  import { buildSoftgreenRubric, isCellsPath } from './closers.js';
40
41
  import { factPartReds } from './citedcheck.js';
41
42
  import { numberRuleReds, countReds, citedWordReds } from './citedwords.js';
@@ -58,6 +59,9 @@ export const DECLARATION_FIELDS = Object.freeze([
58
59
  'unjudgeable',
59
60
  'refused',
60
61
  'inputFacts',
62
+ 'mcp',
63
+ 'ticketFilter',
64
+ 'ticketWatch',
61
65
  // step level
62
66
  'goal',
63
67
  'primitives',
@@ -66,6 +70,7 @@ export const DECLARATION_FIELDS = Object.freeze([
66
70
  'fromLine',
67
71
  'close',
68
72
  'picks',
73
+ 'mcpTools',
69
74
  // close level
70
75
  'class',
71
76
  'shape',
@@ -82,10 +87,83 @@ const VALID_CLASSES = Object.freeze(['green', 'softgreen', 'hitl']);
82
87
  // an ask's position, an ask's TTL, the egress allow-list...").
83
88
  const ARBITER_KEYS = Object.freeze(['cap', 'ask', 'ttl', 'send', 'source', 'trigger', 'skills']);
84
89
 
85
- const TOP_LEVEL_ALLOWED = Object.freeze(['steps', 'guardrailClasses', 'unjudgeable', 'refused', 'inputFacts']);
86
- const STEP_ALLOWED = Object.freeze(['goal', 'primitives', 'reads', 'emits', 'fromLine', 'close', 'picks']);
90
+ const TOP_LEVEL_ALLOWED = Object.freeze(['steps', 'guardrailClasses', 'unjudgeable', 'refused', 'inputFacts', 'mcp', 'ticketFilter', 'ticketWatch']);
91
+ const STEP_ALLOWED = Object.freeze(['goal', 'primitives', 'reads', 'emits', 'fromLine', 'close', 'picks', 'mcpTools']);
87
92
  const CLOSE_ALLOWED = Object.freeze(['class', 'shape', 'cited', 'columns', 'sheet']);
88
93
 
94
+ /** M12 piece 1a: the ONE shape of an MCP server or tool name in a job (the bridge names a tool `<server>_<tool>`). */
95
+ const MCP_NAME = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
96
+
97
+ /** M12 piece 1a: the job's typed MCP tools, `mcp: {server, tools}`, optional (a job without it is unchanged). Returns the tool list when valid, else null.
98
+ * @param {Record<string, any>} declaration @param {string[]} reds @returns {string[]|null} */
99
+ function checkMcp(declaration, reds) {
100
+ if (!Object.hasOwn(declaration, 'mcp')) return null;
101
+ const m = declaration.mcp;
102
+ if (!isPlainObject(m)) {
103
+ reds.push('declaration: "mcp" must be an object {server, tools}');
104
+ return null;
105
+ }
106
+ const before = reds.length;
107
+ for (const key of Object.keys(m)) {
108
+ if (key !== 'server' && key !== 'tools') reds.push(`declaration: unknown key "${key}" at declaration.mcp.${key}`);
109
+ }
110
+ if (typeof m.server !== 'string' || !MCP_NAME.test(m.server)) reds.push('declaration: mcp.server must be a plain server name (letters, digits, _ or -)');
111
+ if (!Array.isArray(m.tools) || m.tools.length === 0) {
112
+ reds.push('declaration: mcp.tools must be a non-empty list of tool names');
113
+ } else {
114
+ const seen = new Set();
115
+ for (const t of m.tools) {
116
+ if (typeof t !== 'string' || !MCP_NAME.test(t)) reds.push(`declaration: mcp.tools names ${JSON.stringify(t)}, which is not a plain tool name`);
117
+ else if (seen.has(t)) reds.push(`declaration: mcp.tools names "${t}" twice`);
118
+ else seen.add(t);
119
+ }
120
+ }
121
+ return reds.length === before ? m.tools : null;
122
+ }
123
+
124
+ /** M12 piece 3 (item 4): the signed label filter, `ticketFilter: {priority?: ['P0'..'P3'], labels?: [names]}`; optional, and only on a job that lists MCP tools.
125
+ * Pure data: code decides at run (src/ticket-labels.js); the drafter may only suggest it and a human signs it.
126
+ * @param {Record<string, any>} declaration @param {string[]} reds */
127
+ function checkTicketFilter(declaration, reds) {
128
+ if (!Object.hasOwn(declaration, 'ticketFilter')) return;
129
+ const f = declaration.ticketFilter;
130
+ if (!isPlainObject(f) || Object.keys(f).length === 0) {
131
+ reds.push('declaration: "ticketFilter" must be an object with "priority" and/or "labels"');
132
+ return;
133
+ }
134
+ if (!Object.hasOwn(declaration, 'mcp')) reds.push('declaration: "ticketFilter" filters tickets read through the job\'s "mcp" tools, but the job lists no "mcp" server');
135
+ for (const key of Object.keys(f)) {
136
+ if (key !== 'priority' && key !== 'labels') reds.push(`declaration: unknown key "${key}" at declaration.ticketFilter.${key}`);
137
+ }
138
+ /** @type {Array<['priority'|'labels', (v: string) => boolean]>} */
139
+ const lists = [['priority', (v) => /^P[0-3]$/.test(v)], ['labels', (v) => v.trim() !== '' && v.length <= 100]];
140
+ for (const [key, ok] of lists) {
141
+ if (!Object.hasOwn(f, key)) continue;
142
+ if (!Array.isArray(f[key]) || f[key].length === 0) { reds.push(`declaration: ticketFilter.${key} must be a non-empty list`); continue; }
143
+ const seen = new Set();
144
+ for (const v of f[key]) {
145
+ if (typeof v !== 'string' || !ok(v)) reds.push(`declaration: ticketFilter.${key} names ${JSON.stringify(v)}, which is not ${key === 'priority' ? 'a priority from P0 to P3' : 'a label name (1 to 100 characters)'}`);
146
+ else if (seen.has(v.toLowerCase())) reds.push(`declaration: ticketFilter.${key} names "${v}" twice`);
147
+ else seen.add(v.toLowerCase());
148
+ }
149
+ }
150
+ }
151
+
152
+ /** M12 piece 3 (signed item 7): the ticket fields a schedule may watch, `ticketWatch: ['state'|'labels']`; optional, only on a job that lists MCP tools, typed values only.
153
+ * The scheduler compares (src/trigger-tickets.js); the drafter may suggest, a human signs. @param {Record<string, any>} declaration @param {string[]} reds */
154
+ function checkTicketWatch(declaration, reds) {
155
+ if (!Object.hasOwn(declaration, 'ticketWatch')) return;
156
+ const w = declaration.ticketWatch;
157
+ if (!Array.isArray(w) || w.length === 0) { reds.push(`declaration: "ticketWatch" must be a non-empty list of fields (${WATCHABLE.join(' and ')})`); return; }
158
+ if (!Object.hasOwn(declaration, 'mcp')) reds.push('declaration: "ticketWatch" watches tickets read through the job\'s "mcp" tools, but the job lists no "mcp" server');
159
+ const seen = new Set();
160
+ for (const f of w) {
161
+ if (typeof f !== 'string' || !WATCHABLE.includes(f)) reds.push(`declaration: ticketWatch names ${JSON.stringify(f)}, which is not a field that can be watched (${WATCHABLE.join(' and ')})`);
162
+ else if (seen.has(f)) reds.push(`declaration: ticketWatch names "${f}" twice`);
163
+ else seen.add(f);
164
+ }
165
+ }
166
+
89
167
  /** @returns {value is Record<string, any>} */
90
168
  function isPlainObject(value) {
91
169
  return !!value && typeof value === 'object' && !Array.isArray(value);
@@ -690,6 +768,11 @@ export function validateDeclaration(declaration, context = {}) {
690
768
  reds.push('declaration: "inputFacts" must be an object keyed by source role');
691
769
  }
692
770
 
771
+ // --- M12 piece 1a: the job's MCP tools (optional) -------------------------------
772
+ const mcpTools = checkMcp(declaration, reds);
773
+ checkTicketFilter(declaration, reds);
774
+ checkTicketWatch(declaration, reds);
775
+
693
776
  // --- steps ------------------------------------------------------------------
694
777
  const emitSeen = new Set();
695
778
  const declaredEmits = new Set();
@@ -719,6 +802,19 @@ export function validateDeclaration(declaration, context = {}) {
719
802
  }
720
803
  }
721
804
 
805
+ // M12 piece 1a: the MCP tools this step uses (optional); each must be one the job lists
806
+ if (Object.hasOwn(step, 'mcpTools')) {
807
+ if (!Array.isArray(step.mcpTools)) {
808
+ reds.push(`declaration: ${label}.mcpTools must be a list of the job's MCP tool names`);
809
+ } else if (!Object.hasOwn(declaration, 'mcp')) {
810
+ reds.push(`declaration: ${label}.mcpTools names tools, but the job lists no "mcp" server`);
811
+ } else if (mcpTools) {
812
+ for (const t of step.mcpTools) {
813
+ if (!mcpTools.includes(t)) reds.push(`declaration: ${label}.mcpTools names "${t}", which the job's mcp.tools does not list`);
814
+ }
815
+ }
816
+ }
817
+
722
818
  // primitives
723
819
  const primitives = Array.isArray(step.primitives) ? step.primitives : null;
724
820
  if (primitives === null) {
package/src/drafter.js CHANGED
@@ -21,6 +21,7 @@ import { parseSignedText, unsignedAskTtls } from './signed-text.js';
21
21
  import { validateDeclaration, SHAPE_KEYS, checkGuardrailSums, guardrailWordsPerSection } from './declaration.js';
22
22
  import { loadCatalogue } from './catalogue.js';
23
23
  import { WIRED_VERBS, wiredMenu } from './primitives.js';
24
+ import { ticketSourcesOf, ticketFactsLines, ticketSchemaParts, ticketReds, userMcpServers } from './ticket-draft.js';
24
25
  import { readInputFacts } from './input-facts.js';
25
26
  import { freezePage } from './runner.js';
26
27
  import { removeFrozenPages } from './flow.js';
@@ -129,10 +130,12 @@ const SHAPE_PROPS = Object.freeze({
129
130
  /**
130
131
  * The forced tool's parameter schema. `menu` = wiredMenu(). `sheets` (M10b piece 3, optional) = the drafting copy's table of each CSV input role: with it a step may carry
131
132
  * `close.sheet`, and every column a check names is an enum of that sheet's exact header (src/sheetoffer.js); without it (no CSV input) no sheet property exists.
132
- * @param {any[]} menu @param {{sheets?: Record<string, {header: string[]}>}} [o]
133
+ * M12 piece 3: `ticket` = `{servers}` when the job signs a ticket list; then the tool may also carry `mcp`, `ticketFilter` and a step's `mcpTools` (src/ticket-draft.js).
134
+ * @param {any[]} menu @param {{sheets?: Record<string, {header: string[]}>, ticket?: {servers: string[]}}} [o]
133
135
  */
134
- export function buildDeclarationSchema(menu, { sheets } = {}) {
136
+ export function buildDeclarationSchema(menu, { sheets, ticket } = {}) {
135
137
  const sheetProp = sheets ? sheetChecksProp(sheets) : null;
138
+ const ticketParts = ticket ? ticketSchemaParts(ticket.servers) : null;
136
139
  const shapeProps = {};
137
140
  for (const key of SHAPE_KEYS) {
138
141
  if (!SHAPE_PROPS[key]) throw new Error(`schema: SHAPE_KEYS gained "${key}" — add its type to SHAPE_PROPS`);
@@ -152,6 +155,7 @@ export function buildDeclarationSchema(menu, { sheets } = {}) {
152
155
  items: { type: 'string', enum: menu.map((e) => e.verb) },
153
156
  description: 'verbs this step is granted, from the menu only; [] for a pure stop',
154
157
  },
158
+ ...(ticketParts ? ticketParts.step : {}),
155
159
  reads: { type: 'array', items: { type: 'string' }, description: 'artifact ids emitted by EARLIER steps only (an ask step lists the earlier output to be checked FIRST), or the role of a CSV input (a step whose line has a green guardrail must list a CSV input role here)' },
156
160
  emits: { type: 'string', minLength: 1, description: 'the ONE new artifact id this step declares (unique)' },
157
161
  fromLine: { type: ['integer', 'null'], description: 'the ONE numbered job line this step serves' },
@@ -182,6 +186,7 @@ export function buildDeclarationSchema(menu, { sheets } = {}) {
182
186
  additionalProperties: false,
183
187
  },
184
188
  },
189
+ ...(ticketParts ? ticketParts.top : {}),
185
190
  guardrailClasses: {
186
191
  type: 'object',
187
192
  additionalProperties: { type: 'string', enum: [...CLASSES] },
@@ -239,9 +244,9 @@ export const QUESTIONS_PROMPT = [
239
244
  ].join('\n');
240
245
 
241
246
  /** The declaration schema plus the optional `notChecked` (every try) and, on try 3 only, `questions`. Neither is in `required`. */
242
- /** @param {any[]} menu @param {{questions?: boolean, sheets?: Record<string, {header: string[]}>|undefined}} [o] */
243
- export function buildRoundSchema(menu, { questions = false, sheets = undefined } = {}) {
244
- const s = buildDeclarationSchema(menu, { sheets });
247
+ /** @param {any[]} menu @param {{questions?: boolean, sheets?: Record<string, {header: string[]}>|undefined, ticket?: {servers: string[]}}} [o] */
248
+ export function buildRoundSchema(menu, { questions = false, sheets = undefined, ticket = undefined } = {}) {
249
+ const s = buildDeclarationSchema(menu, { sheets, ticket });
245
250
  const extra = { notChecked: { type: 'array', items: { type: 'string' }, description: 'what the job asks for that no typed check verifies' } };
246
251
  if (questions) {
247
252
  extra.questions = {
@@ -429,6 +434,7 @@ export async function draft({
429
434
  priorSpend = /** @type {((ceilingUsd: number) => number)|null} */ (null), skills = DRAFT_SKILLS, makeProviderFn = makeProvider, onBook, offerQuestions = true, draftThinking = /** @type {'on'|'off'} */ ('off'),
430
435
  draftDir = /** @type {string|null} */ (null), fetchPage = undefined, leftRules = /** @type {{line: number, rule: number}[]} */ ([]),
431
436
  learnHints = /** @type {{text: string, ids: string[]}|null} */ (null),
437
+ mcpServers = /** @type {string[]|undefined} */ (undefined),
432
438
  }) {
433
439
  // What was asked of thinking and the WORST status bareagent reported across the rounds (the page says it loudly unless 'applied'). Read from the round log, the one record.
434
440
  const thinkingOf = () => {
@@ -454,6 +460,10 @@ export async function draft({
454
460
  // The file inputs are read first, at $0, before a provider is built (a page input is fetched only after the price and cap gates, below).
455
461
  const fileFacts = readInputFacts((arbiter.sources ?? []).filter((s) => s.kind !== 'page'));
456
462
  if (!fileFacts.ok) return fail(fileFacts.reds);
463
+ // M12 piece 3: a GitHub issues list is a ticket role, not a page: never fetched at draft; the drafter is told it exists and may suggest the job's MCP tools and label filter
464
+ const ticketSources = ticketSourcesOf(arbiter.sources);
465
+ const servers = ticketSources.length ? (mcpServers ?? userMcpServers()) : [];
466
+ if (ticketSources.length && servers.length === 0) return fail([`input "${ticketSources[0].role}": a ticket list is read through an MCP server, and ~/.mcp.json names none`]);
457
467
 
458
468
  let { provider, rates, modelId } = { provider: injected, rates: injectedRates, modelId: injectedModelId };
459
469
  let prices = null; // the one price lookup's result (live provider only); the cap check below uses the SAME price
@@ -496,7 +506,7 @@ export async function draft({
496
506
 
497
507
  // M10 item 1: a web page input is fetched once and frozen into the DRAFT folder (the drafting copy). A run freezes its own copy at its own start
498
508
  // (`freezeInputs`), so a run is never checked against this one. Only now, after the $0 price and cap gates: a draft refused for money fetches nothing.
499
- const pageSources = (arbiter.sources ?? []).filter((s) => s.kind === 'page');
509
+ const pageSources = (arbiter.sources ?? []).filter((s) => s.kind === 'page' && !ticketSources.includes(s));
500
510
  /** @type {Record<string, {text: string, entry: {id: string, source: string, frozen: string, sha256: string, bytes: number}}>} */
501
511
  const pages = {};
502
512
  if (pageSources.length) {
@@ -507,7 +517,7 @@ export async function draft({
507
517
  pages[s.role] = { text: fr.text, entry: fr.entry };
508
518
  }
509
519
  }
510
- const facts = readInputFacts(arbiter.sources, { pages });
520
+ const facts = readInputFacts((arbiter.sources ?? []).filter((s) => !ticketSources.includes(s)), { pages });
511
521
  if (!facts.ok) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((pg) => pg.entry.frozen)); return fail(facts.reds); }
512
522
 
513
523
  // M10 item 3: ONE map call per page input names the page's own words; code keeps what the saved page proves. Every round goes through the
@@ -656,7 +666,8 @@ export async function draft({
656
666
  }
657
667
  }
658
668
  // The page lines go on the drafter's list of inputs: the first line of a page's block replaces the plain line readInputFacts wrote for it.
659
- const factsInfo = pageInfo.length ? [...facts.info.filter((l) => !pageSources.some((s) => l.startsWith(`- ${s.role}: a web page`))), ...pageInfo] : facts.info;
669
+ const factsBase = pageInfo.length ? [...facts.info.filter((l) => !pageSources.some((s) => l.startsWith(`- ${s.role}: a web page`))), ...pageInfo] : facts.info;
670
+ const factsInfo = [...factsBase, ...ticketSources.flatMap((s) => ticketFactsLines(s.role, servers))];
660
671
 
661
672
  // `notChecked` is offered on every try (information, not asking); `questions` only on try 3 (below).
662
673
  // M10b piece 3: the drafting copy's table of each CSV input - the header the drafter may pick from, the table bareguard's sign-time test runs over
@@ -689,7 +700,7 @@ export async function draft({
689
700
  // Amendment 25: a lock is a mechanism. Only try 3 of 3, and only when tries 1 and 2 BOTH failed validation (`revisions` counts the
690
701
  // validator's refusals fed back), gets the `questions` property; the redraft after an answer passes offerQuestions:false and never does.
691
702
  const askOpen = offerQuestions && revisions === MAX_REVISIONS;
692
- const schema = buildRoundSchema(menu, { questions: askOpen, sheets: sheetTables });
703
+ const schema = buildRoundSchema(menu, { questions: askOpen, sheets: sheetTables, ticket: ticketSources.length ? { servers } : undefined });
693
704
  const tool = {
694
705
  name: TOOL,
695
706
  description: 'Emit the flow declaration over the granted primitives, or refuse lines you cannot serve.',
@@ -780,12 +791,14 @@ export async function draft({
780
791
  });
781
792
  }
782
793
  // M10b piece 4: `covers` (which ~ rules a check verifies) stays on the check and is signed; the validator checks it, the plan card shows it
783
- const verdict = validateDeclaration(declaration, {
794
+ const verdict0 = validateDeclaration(declaration, {
784
795
  arbiter, lines, catalogue: validationCatalogue, wired: WIRED_VERBS, verbatimGoals: true, fitJobLine: true,
785
796
  // M10 am7 item 1: the words of every cited fact are proved on the drafting copy of the page, against what the page-word map kept
786
797
  sheetWords: sheetTables ? { headers: Object.fromEntries(Object.entries(sheetTables).map(([role, t]) => [role, t.header])), facts: sheetFacts.filter((f) => f.shape === 'column'), tables: sheetTables } : undefined,
787
798
  pageWords: { texts: { ...(facts.docs ?? {}), ...Object.fromEntries(Object.entries(pages).map(([role, pg]) => [role, pg.text])) }, look: pageSources.length ? { facts: look.facts, dropped: look.dropped } : null, docs: docRolesOf(arbiter.sources) },
788
799
  });
800
+ const ticketRed = ticketSources.length ? ticketReds(declaration, ticketSources, servers) : [];
801
+ const verdict = ticketRed.length ? { ok: false, reds: [...(verdict0.ok ? [] : verdict0.reds), ...ticketRed] } : verdict0;
789
802
  lastDecl = declaration;
790
803
  const asked = askOpen ? normalizeQuestions(rawQuestions, failedLines) : { kept: [], dropped: [] };
791
804
  extras = { questions: asked.kept, droppedQuestions: asked.dropped, notChecked: [...new Set([...pageNotChecked, ...cleanNotChecked(rawNotChecked), ...uncoveredRules(declaration, jobLines, Object.keys(facts.sheets ?? {}))])] };
package/src/learnstore.js CHANGED
@@ -276,7 +276,7 @@ export function learnAtRunEnd({ home, workflow, runId, runDir, specHash, now = n
276
276
  }
277
277
 
278
278
  /** M8 am4 item 2: a run waiting at an ask has not ended ('paused', or a Stop whose set-aside failed). ONE decider: the runner's run-end tally and the seed both read it. */
279
- export const NOT_A_RUN_END = new Set(['paused', 'stop-failed']);
279
+ export const NOT_A_RUN_END = new Set(['paused', 'stop-failed', 'skipped']); // M12 p3: a skipped ticket is not a job run with anything to learn from
280
280
 
281
281
  /**
282
282
  * M8 am6: seed the ledger from every run already recorded under `root` (every job, every ended run), oldest first by the run's own end time
@@ -55,6 +55,7 @@ import {
55
55
  } from '../provider.js';
56
56
  import { thinkingSupport as bareagentThinkingSupport, THINKING_FIXED_SAY, THINKING_UNVERIFIED_SAY } from '../thinking.js';
57
57
  import { parseSignedText } from '../signed-text.js';
58
+ import { ticketNumberOf, ticketRefusals, ticketSourcesOf } from '../ticket-draft.js';
58
59
  import { draftStepList, reviseStepList } from '../draft-steps.js';
59
60
  import {
60
61
  capTooSmallText, draftingSpent, EARLIER_MISSING_SAY, potSplit, STARTED_OVER_FILE, usdText,
@@ -194,6 +195,16 @@ export function createAuthor(opts) {
194
195
  return draftingSpent(dir, { ceilingUsd: capFloorFor(true, home, card) }).usd;
195
196
  }
196
197
 
198
+ /**
199
+ * M12 piece 3: the ticket-list input of a plan's signed text (the role a by-hand start picks ONE ticket of), or null. The ONE reader; the green view shows the box from it and the sign door checks it.
200
+ * @param {string} dir the draft folder @param {string} rel the plan folder @returns {string|null}
201
+ */
202
+ function ticketRoleOfPlan(dir, rel) {
203
+ const prose = readFileInside(dir, `${rel}/prose.txt`);
204
+ const parsed = prose.ok ? parseSignedText(prose.text) : null;
205
+ return parsed?.ok === true ? (ticketSourcesOf(parsed.arbiter.sources)[0]?.role ?? null) : null;
206
+ }
207
+
197
208
  /**
198
209
  * M4d am16: the split of the card's Cap $ at Sign & run, from ALL of this job's drafting (the one writer of that total, `draftingSpent`). Unpriced rounds count at their
199
210
  * worst case (the picked model's Settings ceiling). `refusal` = what is left cannot pay one run round at its worst case: refused at $0.
@@ -284,7 +295,7 @@ export function createAuthor(opts) {
284
295
  if (q.questions.length > 0) return { ...shared, phase: 'stopped', say: ANSWERS_NOT_DRAFTED_SAY };
285
296
  if (res.phase === 'green') {
286
297
  const answers = newest > 0 && redrafts.has(newest) ? answersOf(dir, newest, keys) : [];
287
- return { ...shared, phase: 'green', hash: res.hash, readout: res.readout, readoutHeads: res.readoutHeads, plan: rel, answers, ...planChecks(dir, rel) };
298
+ return { ...shared, phase: 'green', hash: res.hash, readout: res.readout, readoutHeads: res.readoutHeads, plan: rel, ticketRole: ticketRoleOfPlan(dir, rel), answers, ...planChecks(dir, rel) };
288
299
  }
289
300
  return { ...shared, phase: 'red', reds: res.reds, say: newest === 0 ? RED_SAY : cur.say };
290
301
  }
@@ -597,6 +608,11 @@ export function createAuthor(opts) {
597
608
  const run = starter.checkRun(name, runId);
598
609
  if (!run.ok) return { status: 400, body: { ok: false, refused: 'run-id', say: run.say } };
599
610
  }
611
+ // M12 piece 3 (hamr 2026-10-29): a ticket job reads ONE ticket per run, so Sign & run takes its number too; refused at $0 BEFORE signing (nothing signed, no run folder)
612
+ const ticketRole = ticketRoleOfPlan(dir, v.plan);
613
+ const ticketBad = ticketRefusals(ticketRole, b);
614
+ if (ticketBad.length > 0) return { status: 400, body: { ok: false, refused: 'ticket', refusals: ticketBad } };
615
+ const ticket = ticketNumberOf(b.ticket);
600
616
  const signedBy = userInfo().username;
601
617
  // M6 am9: a red run's redraft of an unchanged job is signed as the plan of a NEW run of the same workflow (the workflow's files are not written)
602
618
  const runOfRec = readJson(dir, RUN_OF_FILE);
@@ -625,7 +641,7 @@ export function createAuthor(opts) {
625
641
  }
626
642
  }
627
643
  const started = starter.start({
628
- kind: 'sign', flow: name, runId, sources: inputs.map((r) => ({ role: r.role, path: r.path })), values, ...(asRunOf ? { planRun: true, pick: result.modelPick ?? null } : {}),
644
+ kind: 'sign', flow: name, runId, sources: inputs.map((r) => ({ role: r.role, path: r.path, ...(r.role === ticketRole ? { ticket: /** @type {number} */ (ticket) } : {}) })), values, ...(asRunOf ? { planRun: true, pick: result.modelPick ?? null } : {}),
629
645
  }, loaded);
630
646
  if (started.status !== 202) return { status: started.status, body: { ...started.body, signed: true, flow: name, say: `${started.body.say ?? 'The run did not start.'} The flow is signed; start it from "Run a signed flow".` } };
631
647
  return { status: 202, body: { ...started.body, signed: true } };
@@ -14,6 +14,7 @@ import { lstatSync, realpathSync } from 'node:fs';
14
14
  import { join } from 'node:path';
15
15
 
16
16
  import { scrub } from '../authoring.js';
17
+ import { ticketNumberOf, ticketRefusals, ticketSourcesOf } from '../ticket-draft.js';
17
18
  import { endRow, readHistory } from '../books.js';
18
19
  import { canFlowRun, willNotRunSay } from '../canrun.js';
19
20
  import { loadCatalogue } from '../catalogue.js';
@@ -44,7 +45,7 @@ export const editBlockedSay = (runId) => `finish or stop ${runId} first`;
44
45
  export const EDIT_STARTING_SAY = 'a run is starting';
45
46
  const NO_LIMIT = 'no monthly limit set';
46
47
  /** The body keys a run start takes (amendment 5 item 2): the open boxes plus the hash of the second click. Any other key is refused by name. */
47
- const RUN_KEYS = ['flow', 'inputs', 'runId', 'destination', 'capUsd', 'askWaits', 'hash', 'provider', 'model', 'planOf'];
48
+ const RUN_KEYS = ['flow', 'inputs', 'runId', 'destination', 'capUsd', 'askWaits', 'hash', 'provider', 'model', 'planOf', 'ticket'];
48
49
 
49
50
  /**
50
51
  * What the Run / Resume forms show of a signed flow (read from its own files, never from a model): the job lines as the signed text has them
@@ -229,6 +230,10 @@ export function createFlowsDoor(opts) {
229
230
  if (Object.hasOwn(pages, r.role) && r.path !== pages[r.role]) refusals.push({ field: `inputs.${n}`, say: pageAddressRefusal(r.role, pages[r.role]) });
230
231
  });
231
232
  const declared = (read.arbiter.sources ?? []).map((s) => s.role);
233
+ // M12 piece 3 (hamr 2026-10-29): a by-hand Run on a job with a ticket list picks ONE ticket by number; any other job takes none
234
+ const ticketRole = ticketSourcesOf(read.arbiter.sources)[0]?.role ?? null;
235
+ const ticket = ticketNumberOf(body?.ticket);
236
+ refusals.push(...ticketRefusals(ticketRole, body));
232
237
  for (const role of declared) {
233
238
  if (!Object.hasOwn(pages, role) && !rows.some((r) => r.role === role)) refusals.push({ field: 'inputs', say: `This flow needs an input named "${role}". Add it.` });
234
239
  }
@@ -246,7 +251,7 @@ export function createFlowsDoor(opts) {
246
251
  flow, flowSignatureHash: read.signature.flow, runId: null, version: 0, values,
247
252
  });
248
253
  return {
249
- ok: /** @type {true} */ (true), flow, read, declared, rows: declared.map((role) => rows.find((r) => r.role === role) ?? { role, path: pages[role] }), runId, values, differs: checked.differs || runModel !== null, hash, newPick, flowDir: join(realRoot, flow), planFrom,
254
+ ok: /** @type {true} */ (true), flow, read, declared, rows: declared.map((role) => rows.find((r) => r.role === role) ?? { role, path: pages[role] }), ticketRole, ticket, runId, values, differs: checked.differs || runModel !== null, hash, newPick, flowDir: join(realRoot, flow), planFrom,
250
255
  };
251
256
  }
252
257
 
@@ -298,7 +303,7 @@ export function createFlowsDoor(opts) {
298
303
  const last = lastSources(flowDir, roles, pageAddressesOf(read.arbiter));
299
304
  const { passed, stats } = runsOf(flowDir, name, read, roles);
300
305
  return {
301
- flow: name, capUsd: read.arbiter.capUsd, roles, pages: pageAddressesOf(read.arbiter), nextRunId: nextRunId(flowDir), lastRunId: last.runId, lastSources: last.sources, leftThisMonth: left,
306
+ flow: name, capUsd: read.arbiter.capUsd, roles, pages: pageAddressesOf(read.arbiter), tickets: ticketSourcesOf(read.arbiter.sources).map((x) => x.role), nextRunId: nextRunId(flowDir), lastRunId: last.runId, lastSources: last.sources, leftThisMonth: left,
302
307
  runs: passed, stats,
303
308
  ...formFacts(read, home, flowDir),
304
309
  // M6 am5/am6: the job as the card Reuse workflow opens (`ok:true, card`), or why the card cannot hold it (`ok:false, say`). Nothing blocks it: a reuse never changes the job it is opened from.
@@ -462,7 +467,7 @@ export function createFlowsDoor(opts) {
462
467
  };
463
468
  }
464
469
  const started = starter.start({
465
- kind: 'run', flow: s.flow, runId: s.runId, sources: s.declared.map((role) => ({ role, path: /** @type {{path: string}} */ (s.rows.find((r) => r.role === role)).path })), values, pick: s.newPick, planOf: s.planFrom,
470
+ kind: 'run', flow: s.flow, runId: s.runId, sources: s.declared.map((role) => ({ role, path: /** @type {{path: string}} */ (s.rows.find((r) => r.role === role)).path, ...(role === s.ticketRole ? { ticket: /** @type {number} */ (s.ticket) } : {}) })), values, pick: s.newPick, planOf: s.planFrom,
466
471
  }, loaded);
467
472
  // M4d amendment 7b: the pick of a flow that had no record is written only once the start succeeded (a refused start leaves none), beside the signed files, never in them
468
473
  if (started.status === 202 && s.newPick !== null) {
@@ -16,7 +16,7 @@
16
16
  // starting the child is alive and the run dir has no book row yet
17
17
  // started the run dir has its first book row (`pids.jsonl`, written by the run itself before its first step); `state` is
18
18
  // working / parked / ended from `runLiveness` + `ask.json` (M4c's one "is it running?" rule), never a timer
19
- // refused the child is dead and the run dir never got a book row: `say` = the CLI's own sentence (scrubbed) + "Nothing spent."
19
+ // refused the child is dead and the run dir never got a book row (a skipped run's history row counts as one, it ended): `say` = the CLI's own sentence (scrubbed) + "Nothing spent."
20
20
  //
21
21
  // One click, one start: `start` is fully synchronous (check -> mkdir -> spawn -> write pid.json, no await), so two requests that
22
22
  // arrive together run one after the other and the second sees the first's `starting` start and is refused.
@@ -29,7 +29,7 @@ import { fileURLToPath } from 'node:url';
29
29
 
30
30
  import { loadCatalogue } from '../catalogue.js';
31
31
  import { scrub } from '../authoring.js';
32
- import { readPidRows } from '../books.js';
32
+ import { readHistory, readPidRows } from '../books.js';
33
33
  import {
34
34
  PANEL_STARTS_DIR, checkRunId, claimRunId, freeRunId, readFileInside, readdirInside, resolveRunDir, runOwnsPlan, copyRunPlan, RUN_PLAN_MARKER,
35
35
  } from '../flow.js';
@@ -77,7 +77,8 @@ export function createStarter(opts) {
77
77
  const st = readJsonFile(dir, 'start.json');
78
78
  if (!st || typeof st.flow !== 'string' || typeof st.runId !== 'string') return null;
79
79
  const base = { startId: id, kind: st.kind, flow: st.flow, runId: st.runId };
80
- const resolved = resolveRunDir(join(realpathSync(root), st.flow), st.runId);
80
+ const flowDir = join(realpathSync(root), st.flow);
81
+ const resolved = resolveRunDir(flowDir, st.runId);
81
82
  if (!resolved.ok) return null;
82
83
  // alive FIRST, then the book row: a child that writes its row and exits between the two reads as started, never refused
83
84
  const alive = childRunning(dir);
@@ -97,6 +98,8 @@ export function createStarter(opts) {
97
98
  } else if (readPidRows(resolved.runDir).length > 0) {
98
99
  return { ...base, phase: 'started', state: carriedOn() };
99
100
  } else if (alive) return { ...base, phase: 'starting' };
101
+ // a SKIPPED run (hamr 2026-10-30) ends before its first pid row, but its history row is a real ending: a grey one, never a refusal
102
+ if (readHistory(flowDir).some((h) => h.runId === st.runId && h.outcome === 'skipped')) return { ...base, phase: 'started', state: 'ended' };
100
103
  const log = readFileInside(dir, 'child.log');
101
104
  const tail = log.ok ? scrub(log.text, keys).trim().slice(-LOG_TAIL_CHARS).replace(/^fwdloop: /, '') : '';
102
105
  const say = tail === '' ? ENDED_SAY : (tail.includes(NOTHING_SPENT) ? tail : `${tail}\n${NOTHING_SPENT}`);
@@ -171,7 +174,7 @@ export function createStarter(opts) {
171
174
  * folder as `signed-values.json` BEFORE the spawn; the run then uses them (`pickRunValues`). None = the flow's own.
172
175
  * `trigger` (M9): `{kind, reason, catchUp, ...}` for a start a trigger fired (kind 'trigger'): written once into the run's own folder as `trigger.json`
173
176
  * BEFORE the spawn; `appendHistory` copies it into the run's history row (the catch-up mark, am2 item 1).
174
- * @param {{ kind: 'run'|'sign'|'trigger', flow: string, runId: string, sources: {role: string, path: string}[], planRun?: boolean, planOf?: string|null, values?: any, pick?: {slot: string, model: string}|null, trigger?: Record<string, any>|null }} a
177
+ * @param {{ kind: 'run'|'sign'|'trigger', flow: string, runId: string, sources: {role: string, path: string, ticket?: number, anyway?: boolean}[], planRun?: boolean, planOf?: string|null, values?: any, pick?: {slot: string, model: string}|null, trigger?: Record<string, any>|null }} a
175
178
  * @param {{ env: Record<string, string|undefined>, keyNames?: string[] }} loaded the keys load: its env is the child's env AND (with its key names) the scrub list
176
179
  * @returns {{ status: number, body: any }}
177
180
  */
@@ -230,7 +233,8 @@ export function createStarter(opts) {
230
233
  writeFileSync(join(dir, 'start.json'), `${JSON.stringify({
231
234
  kind, flow, runId, sources, startedAt: new Date().toISOString(),
232
235
  }, null, 2)}\n`, { mode: 0o600 });
233
- const argv = ['run', flow, '--root', realpathSync(root), ...sources.flatMap((s) => ['--source', `${s.role}=${s.path}`]), '--run-id', runId, ...(pick ? ['--model', pick.model, '--provider', pick.slot] : [])]; // M4d am7b: a flow with no record runs with the model picked in Chat
236
+ // M12: `--ticket N` (the one ticket of the list this run reads) follows the sources
237
+ const argv = ['run', flow, '--root', realpathSync(root), ...sources.flatMap((s) => ['--source', `${s.role}=${s.path}`]), ...sources.flatMap((s) => (s.ticket === undefined ? [] : ['--ticket', String(s.ticket), ...(s.anyway === true ? ['--anyway'] : [])])), '--run-id', runId, ...(pick ? ['--model', pick.model, '--provider', pick.slot] : [])]; // M4d am7b: a flow with no record runs with the model picked in Chat
234
238
  let child;
235
239
  try {
236
240
  child = spawnDetached({
@@ -290,7 +294,7 @@ export function createStarter(opts) {
290
294
  for (const id of readdirInside(sd, '.').filter((n) => ID_RE.test(n)).sort().reverse()) {
291
295
  if (readFileInside(join(sd, id), 'cleared.json').ok) continue;
292
296
  const v = readStart(join(sd, id), id, keys);
293
- if (v === null) continue;
297
+ if (v === null || v.kind === 'trigger') continue; // the Chat card never shows a start it did not make
294
298
  return v.phase === 'started' ? null : v;
295
299
  }
296
300
  return null;