fwdloop 0.38.0 → 0.39.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 (127) hide show
  1. package/bin/fwdloop +21 -19
  2. package/package.json +1 -1
  3. package/src/ask.js +70 -148
  4. package/src/audit-fold.js +5 -4
  5. package/src/auditchecks.js +6 -4
  6. package/src/authoring.js +32 -60
  7. package/src/blockasks.js +2 -1
  8. package/src/blockassemble.js +3 -2
  9. package/src/blockdraft.js +2 -2
  10. package/src/blockpick.js +5 -5
  11. package/src/books.js +217 -12
  12. package/src/checkblock.js +20 -41
  13. package/src/checklistsign.js +25 -3
  14. package/src/checklook.js +3 -1
  15. package/src/checkpick.js +5 -76
  16. package/src/cited-source.js +4 -4
  17. package/src/citedcheck.js +6 -11
  18. package/src/citedwords.js +9 -8
  19. package/src/closers.js +9 -6
  20. package/src/declaration.js +14 -49
  21. package/src/diary.js +23 -1
  22. package/src/draft-steps.js +11 -1
  23. package/src/drafter.js +13 -9
  24. package/src/draftfiles.js +127 -0
  25. package/src/draftspend.js +165 -17
  26. package/src/flow.js +42 -87
  27. package/src/flowmodel.js +1 -1
  28. package/src/index.js +3 -2
  29. package/src/inside.js +86 -0
  30. package/src/jsonl-append.js +33 -1
  31. package/src/learn.js +1 -1
  32. package/src/learnstore.js +20 -22
  33. package/src/line-checks.js +1 -1
  34. package/src/liveness.js +3 -0
  35. package/src/mcp-use.js +8 -9
  36. package/src/memo.js +13 -16
  37. package/src/model-step.js +2 -2
  38. package/src/page-words.js +8 -0
  39. package/src/pageask.js +8 -3
  40. package/src/pagebits.js +8 -1
  41. package/src/pagedropwords.js +1 -1
  42. package/src/pagerules.js +6 -3
  43. package/src/panel/author.js +99 -75
  44. package/src/panel/authorcard.js +21 -8
  45. package/src/panel/authorflows.js +3 -3
  46. package/src/panel/authorresume.js +3 -3
  47. package/src/panel/authorstart.js +15 -16
  48. package/src/panel/authortrigger.js +43 -70
  49. package/src/panel/data.js +125 -168
  50. package/src/panel/index.html +122 -61
  51. package/src/panel/jobgrid.js +3 -7
  52. package/src/panel/result.js +7 -10
  53. package/src/panel/resume.js +4 -3
  54. package/src/panel/scheduler.js +9 -9
  55. package/src/panel/server.js +8 -4
  56. package/src/panel/spawn.js +22 -11
  57. package/src/panel/tickets.js +2 -2
  58. package/src/pickrecord.js +51 -31
  59. package/src/placerule.js +3 -4
  60. package/src/planrebuild.js +19 -19
  61. package/src/primitives.js +1 -1
  62. package/src/provider.js +1 -1
  63. package/src/reasons.js +25 -0
  64. package/src/runfile.js +26 -2
  65. package/src/runner.js +57 -105
  66. package/src/runvalues.js +47 -24
  67. package/src/schedule-choices.js +41 -0
  68. package/src/schedule-shape.js +39 -0
  69. package/src/schedule.js +9 -8
  70. package/src/setup.js +20 -36
  71. package/src/shaperows.js +2 -2
  72. package/src/sheetblock.js +2 -2
  73. package/src/sheetbuild.js +5 -5
  74. package/src/sheetrun.js +4 -5
  75. package/src/summary-words.js +2 -1
  76. package/src/thinking.js +5 -2
  77. package/src/ticketrows.js +7 -28
  78. package/src/trigger-clock.js +9 -23
  79. package/src/trigger-files.js +30 -22
  80. package/src/trigger-tickets.js +15 -14
  81. package/src/try-checks.js +2 -1
  82. package/src/types.js +2 -0
  83. package/types/ask.d.ts +25 -20
  84. package/types/authoring.d.ts +7 -42
  85. package/types/blockpick.d.ts +1 -1
  86. package/types/books.d.ts +256 -4
  87. package/types/checkblock.d.ts +1 -23
  88. package/types/checklist.d.ts +3 -3
  89. package/types/checklistsign.d.ts +7 -0
  90. package/types/checkpick.d.ts +0 -21
  91. package/types/citedwords.d.ts +7 -4
  92. package/types/closers.d.ts +1 -0
  93. package/types/declaration.d.ts +4 -14
  94. package/types/diary.d.ts +14 -1
  95. package/types/draft-steps.d.ts +7 -0
  96. package/types/drafter.d.ts +1 -1
  97. package/types/draftfiles.d.ts +89 -0
  98. package/types/draftspend.d.ts +74 -0
  99. package/types/flow.d.ts +32 -54
  100. package/types/index.d.ts +3 -3
  101. package/types/inside.d.ts +58 -0
  102. package/types/jsonl-append.d.ts +20 -0
  103. package/types/learnstore.d.ts +0 -2
  104. package/types/liveness.d.ts +1 -0
  105. package/types/page-words.d.ts +6 -0
  106. package/types/pageask.d.ts +2 -0
  107. package/types/pagebits.d.ts +3 -0
  108. package/types/pagerules.d.ts +1 -0
  109. package/types/panel/author.d.ts +7 -3
  110. package/types/panel/authorcard.d.ts +0 -6
  111. package/types/panel/authorflows.d.ts +4 -4
  112. package/types/panel/authortrigger.d.ts +16 -2
  113. package/types/panel/data.d.ts +36 -11
  114. package/types/panel/spawn.d.ts +18 -2
  115. package/types/pickrecord.d.ts +29 -0
  116. package/types/reasons.d.ts +23 -0
  117. package/types/runfile.d.ts +14 -0
  118. package/types/runner.d.ts +6 -38
  119. package/types/runvalues.d.ts +17 -2
  120. package/types/schedule-choices.d.ts +9 -0
  121. package/types/schedule-shape.d.ts +15 -0
  122. package/types/sheetbuild.d.ts +1 -1
  123. package/types/thinking.d.ts +1 -0
  124. package/types/ticketrows.d.ts +0 -9
  125. package/types/trigger-clock.d.ts +3 -2
  126. package/types/trigger-files.d.ts +15 -4
  127. package/types/types.d.ts +8 -0
package/src/runner.js CHANGED
@@ -47,11 +47,10 @@ import { parseCsv } from './csv.js';
47
47
  import { resetRunStore } from './run-store.js';
48
48
  import { fileURLToPath } from 'node:url';
49
49
 
50
+ import { readPlan, readRunPlan, runOwnsPlan, resolveRunDir, FLOW_FILES, PANEL_STARTS_DIR, writeRunJobCopy } from './flow.js';
51
+ import { readFileInside, readdirInside, resolveInside } from './inside.js';
50
52
  import {
51
- readPlan, readRunPlan, runOwnsPlan, resolveRunDir, readFileInside, readdirInside, resolveInside, FLOW_FILES, PANEL_STARTS_DIR, writeRunJobCopy,
52
- } from './flow.js';
53
- import {
54
- writeAskArchive, readAcceptedHashesByEmits, serializeArtifact, normalizeDecision, answerTiming, effectiveExpiresAt, withReopen, setAsideAnswer,
53
+ writeAskArchive, readAcceptedHashesByEmits, serializeArtifact, normalizeDecision, answerTiming, effectiveExpiresAt, withReopen, setAsideAnswer, readAskFile, needsReason,
55
54
  } from './ask.js';
56
55
  import {
57
56
  findUnwiredVerbStep, unwiredRed, findUnbuildableCheckStep, unbuildableRed, findMcpPlanRed,
@@ -63,19 +62,20 @@ import { citedLineOf, writeCitedLine, quotesOfLines } from './cited-record.js';
63
62
  import { sheetRolesOf, tableShaOfFrozen, readRunSheets } from './sheetrun.js';
64
63
  import { writeSheetLine } from './sheet-record.js';
65
64
  import {
66
- appendAudit, appendHistory, readAudit, readHistory, endRow, HALT_OUTCOMES,
65
+ appendAudit, appendHistory, readAudit, readHistory, endRow,
66
+ readHaltRecord, readLog, readRunState, readSavedAnswer, consumedAnswerName, nextHaltConsumedName, HALT_FILE, isNotRunEnd, isSpendFloorEnding, isResumableEnding, isGoodEnding, isStopNote,
67
67
  } from './books.js';
68
- import { learnAtRunEnd, NOT_A_RUN_END, hintsForRun, placeSpecOf } from './learnstore.js';
68
+ import { learnAtRunEnd, hintsForRun, placeSpecOf } from './learnstore.js';
69
69
  import { redactSecrets } from './redact.js';
70
70
  import { appendRow } from './jsonl-append.js';
71
71
  import { applyRunValues, pickRunValues } from './runvalues.js';
72
72
  import { stepThinkingMode, stepHintsWanted } from './thinking.js';
73
- import { appendChecks, nextRound } from './diary.js';
73
+ import { appendChecks, appendTryStart, nextRound } from './diary.js';
74
74
  import {
75
75
  doneRecord, happenedRecord, outputRecord, closeRecords,
76
76
  } from './try-checks.js';
77
77
  import { readJobThinking, readModelRecord, takeLearningsRecord } from './flowmodel.js';
78
- import { readRunInputs, readRunRecord, writeRunStart } from './runfile.js';
78
+ import { readRunInputs, readPlaceRows, writeRunStart, INPUTS_DIR, frozenRel } from './runfile.js';
79
79
  // borrowed-from: bareloop src/userrun.js@v0.56.0 (3383cce) (the place-rule read at run start and its stop words; fwd keeps the read value in run.json, not a spine)
80
80
  import { citedPlaceFactsOf, bindCitedPlaceValues, readPlaceRules, valueInWords, stopWords, placeValuesOfEvents, lastRunPlaceRead, PLACE_EVENT, NO_PLACE_RECORD_WORDS } from './placerule.js';
81
81
  import { buildMemo } from './memo.js';
@@ -88,7 +88,7 @@ import { createMCPBridge, discoverServers } from 'bare-agent/mcp';
88
88
  import { mcpToolName } from './primitives.js';
89
89
  import { decideTicket, readTicketFields } from './ticket-labels.js';
90
90
  import {
91
- readResumeLock, recordPid, writeLockHolder, procStartOf, LOCK_NO_HOLDER,
91
+ readResumeLock, lockMayBeHeld, recordPid, writeLockHolder, procStartOf, LOCK_NO_HOLDER,
92
92
  } from './liveness.js';
93
93
 
94
94
  const __dirname = dirname(fileURLToPath(import.meta.url));
@@ -130,7 +130,7 @@ export const SPEND_TOLERANCE_USD = 1e-9;
130
130
  // ---------------------------------------------------------------------------
131
131
 
132
132
  export const STOP_FILE = 'stop.request';
133
- export const HALT_FILE = 'halt.json';
133
+ export { HALT_FILE };
134
134
 
135
135
  /** The panel's one write of a stop request. `'exists'` = already asked, nothing more to do. @param {string} runDir */
136
136
  export function requestStop(runDir) {
@@ -207,13 +207,6 @@ function clearStop(runDir) {
207
207
  try { unlinkSync(join(runDir, STOP_FILE)); } catch { /* none pending */ }
208
208
  }
209
209
 
210
- /** The one reader of halt.json: `{ok:true, halt}`, `{ok:false, missing:true}` (not resumable), or `{ok:false, red}`. @param {string} runDir */
211
- export function readHaltRecord(runDir) {
212
- const r = readFileInside(runDir, HALT_FILE);
213
- if (!r.ok) return r.missing ? { ok: false, missing: true } : { ok: false, red: `halt.json — ${r.red}` };
214
- try { return { ok: true, halt: JSON.parse(r.text) }; } catch (err) { return { ok: false, red: `halt.json is not valid JSON — ${err.message}` }; }
215
- }
216
-
217
210
  // ---------------------------------------------------------------------------
218
211
  // Money - the per-attempt hold is injected data: the caller works it out from the
219
212
  // picked model's own Settings prices (`ceilingCostUsd(rates)`, src/provider.js) and passes
@@ -438,7 +431,7 @@ export async function freezePage(dir, id, url, { fetchPage = fetchPageText } = {
438
431
  * `ticketRead` and frozen like a page; its manifest entry also carries `mcp`, the record of what the server exposed and each call made (kept in `run.json`, no new file).
439
432
  * @param {{fetchPage?: (url: string) => Promise<{ok: true, text: string, url: string}|{ok: false, error: string}>, tableRoles?: string[], mcp?: {server: string, tools: string[]}, ticketRead?: typeof readTicketMcp, ticketFilter?: {priority?: string[], labels?: string[]}}} [o] */
440
433
  export async function freezeInputs(runDir, sources, { fetchPage, tableRoles = [], mcp, ticketRead = readTicketMcp, ticketFilter } = {}) {
441
- const inputsDir = join(runDir, 'inputs');
434
+ const inputsDir = join(runDir, INPUTS_DIR);
442
435
  mkdirSync(inputsDir, { recursive: true });
443
436
  const manifest = [];
444
437
  /** M12 piece 3: the first ticket the signed labels (or its state) skip: its reason; the run ends `skipped` after its start record is written */
@@ -497,7 +490,7 @@ export function readRunPlaceRules(runDir, steps, manifest, earlier = {}) {
497
490
  if (facts.length === 0) return { ok: /** @type {true} */ (true), rows: null, values: {} };
498
491
  const read = readPlaceRules(facts.map((fact) => {
499
492
  const entry = manifest.find((e) => e?.id === fact.source);
500
- const file = entry && typeof entry.frozen === 'string' ? readFileInside(runDir, `inputs/${basename(entry.frozen)}`) : null;
493
+ const file = entry && typeof entry.frozen === 'string' ? readFileInside(runDir, frozenRel(entry.frozen)) : null;
501
494
  return { fact, text: file && file.ok ? file.text : null, was: earlier[fact.key] ?? valueInWords(fact.place, fact.phrase) };
502
495
  }));
503
496
  if (!read.proceed) return { ok: /** @type {false} */ (false), words: stopWords(read.rows) };
@@ -511,8 +504,8 @@ export function readRunPlaceRules(runDir, steps, manifest, earlier = {}) {
511
504
  */
512
505
  export function stepsWithRecordedPlaces(runDir, steps) {
513
506
  if (citedPlaceFactsOf(steps).length === 0) return { ok: /** @type {true} */ (true), steps };
514
- const got = readRunRecord(runDir);
515
- const values = got.ok && Array.isArray(got.rec.placeRules?.rows) ? placeValuesOfEvents([{ type: PLACE_EVENT, rows: got.rec.placeRules.rows }]) : null;
507
+ const placed = readPlaceRows(runDir);
508
+ const values = placed !== null ? placeValuesOfEvents([{ type: PLACE_EVENT, rows: placed }]) : null;
516
509
  if (values === null) return { ok: /** @type {false} */ (false), words: NO_PLACE_RECORD_WORDS };
517
510
  return { ok: /** @type {true} */ (true), steps: bindCitedPlaceValues(steps, values) };
518
511
  }
@@ -721,7 +714,7 @@ function readInputCells(runDir, id) {
721
714
  if (!manifest.ok) return manifest.code === 'missing' ? { ok: false, missing: true } : { ok: false, missing: false, red: manifest.red };
722
715
  const entry = manifest.entries.find((e) => e?.id === id);
723
716
  if (!entry || !isCellsPath(entry.frozen)) return { ok: false, missing: true };
724
- const file = readFileInside(runDir, `inputs/${basename(entry.frozen)}`);
717
+ const file = readFileInside(runDir, frozenRel(entry.frozen));
725
718
  if (!file.ok) return file.missing ? { ok: false, missing: false, red: 'the frozen copy is missing' } : { ok: false, missing: false, red: file.red };
726
719
  if (createHash('sha256').update(file.text).digest('hex') !== entry.sha256) return { ok: false, missing: false, red: 'the frozen copy changed since it was frozen' };
727
720
  return { ok: true, value: { kind: 'cells', ...parseCsv(file.text) } };
@@ -780,7 +773,7 @@ export const LEARN_ERROR_FILE = 'learn-error.jsonl';
780
773
  function recordRunNotes({
781
774
  flowName, runId, runDir, outcome, now,
782
775
  }) {
783
- if (NOT_A_RUN_END.has(outcome)) return;
776
+ if (isNotRunEnd(outcome)) return; // M8 am4 item 2 / M12 p3: a pause, a failed stop and a skipped ticket are not a run end (src/books.js ENDINGS)
784
777
  const door = configDoorHome();
785
778
  if (door.skip) return;
786
779
  try {
@@ -1055,6 +1048,8 @@ async function runStepTries({
1055
1048
  const stopSeam = readStop ? Object.freeze({ stopRequested: readStop }) : undefined;
1056
1049
 
1057
1050
  const startedAt = Date.now();
1051
+ // M20 am1 item 8: the try begins - one report-only diary row, so the Run tab can say "AI working" and since when
1052
+ if (runDir !== null) appendTryStart(runDir, { step: stepMeta.step, try: attempt, at: now() });
1058
1053
  // eslint-disable-next-line no-await-in-loop
1059
1054
  let result = await modelStep(executorContext, grantedTools, stepMeta, stopSeam);
1060
1055
  if (result && result.ok === false && result.transport === true) {
@@ -1216,7 +1211,7 @@ async function runStepTries({
1216
1211
  tryChecks.push(...closeRecords(step, artifact, closed, checkList, jobLines));
1217
1212
  saveTry();
1218
1213
 
1219
- if (closed.verdict === 'green' || closed.verdict === 'hitl') {
1214
+ if (isGoodEnding(closed.verdict)) {
1220
1215
  recordAudit(rowOf({
1221
1216
  step, attempt, verdict: closed.verdict, gap: null, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false, at: now(), tokens: result.tokens ?? null, tools: result.tools ?? null, ungranted: result.ungranted, refused: result.refused, thinking: result.thinking,
1222
1217
  }), result.artifact);
@@ -1596,8 +1591,7 @@ export async function runFlow({
1596
1591
  // ---------------------------------------------------------------------------
1597
1592
 
1598
1593
  /** An ask step that never waits — it immediately tells the fold to park.
1599
- * The counterpart to `makeFileAskStep`'s in-process poll (M2 scope item 6);
1600
- * a caller wanting park-and-exit behaviour from a FRESH `runFlow` call
1594
+ * A caller wanting park-and-exit behaviour from a FRESH `runFlow` call
1601
1595
  * passes this (or an equivalent) as `askStep`.
1602
1596
  * @returns {(opts?: any) => Promise<{decision: 'park'}>} */
1603
1597
  export function makeParkingAskStep() {
@@ -1631,11 +1625,14 @@ function makeOneShotThenParkAskStep({ decision, reason, artifactSha256 }) {
1631
1625
  function lastTryNumber(runDir, stepId) {
1632
1626
  let last = 0;
1633
1627
  for (const r of readAudit(runDir)) {
1634
- if (r.step === stepId && Number.isInteger(r.attempt) && r.verdict !== 'cap-halt' && r.verdict !== 'stop-asked' && r.verdict !== 'stop-not-honoured' && r.attempt > last) last = r.attempt;
1628
+ if (r.step === stepId && Number.isInteger(r.attempt) && r.verdict !== 'cap-halt' && !isStopNote(r.verdict) && r.attempt > last) last = r.attempt;
1635
1629
  }
1636
1630
  return last;
1637
1631
  }
1638
1632
 
1633
+ /** M20 am8: the one question "did the ask slot's loop already end the run" (it returned `paused` or `stopped`: its `result` is the run's own return value) @param {{type?: unknown}} r a loop's return @returns {boolean} */
1634
+ export const endsRun = (r) => r.type === 'paused' || r.type === 'stopped';
1635
+
1639
1636
  /**
1640
1637
  * One signed ask slot's own loop (M2's ask branch, unchanged in spirit,
1641
1638
  * extracted so `resumeRun` can re-enter the SAME logic mid-ask instead of
@@ -1699,7 +1696,7 @@ async function runAskSlot({
1699
1696
  const askedAt = now();
1700
1697
  const expiresAt = new Date(Date.parse(askedAt) + askSlot.ttlMs).toISOString();
1701
1698
  // F45 finding 2: a parked ask.json must carry the SAME evidence a
1702
- // human sees in-process (`makeFileAskStep`'s `{ artifact, unjudged }`)
1699
+ // human sees (`{ artifact, unjudged }`)
1703
1700
  // — the draft under review and the unjudged evidence, never just the
1704
1701
  // question. `evidence` above is already recomputed at the top of every
1705
1702
  // loop iteration (including a re-park after a redo, where
@@ -1801,7 +1798,7 @@ async function runAskSlot({
1801
1798
  const isRedo = answer.decision === 'redo' || answer.decision === 'rerun';
1802
1799
  const reason = typeof answer.reason === 'string' ? answer.reason.trim() : '';
1803
1800
 
1804
- if (isRedo && reason.length === 0) {
1801
+ if (needsReason(answer.decision) && reason.length === 0) {
1805
1802
  recordAudit(makeAuditRow({
1806
1803
  step, attempt: redone + 1, verdict: 'refused', gap: 'a redo/rerun needs a reason', usd: 0, spendComplete: true, wallMs: 0, strike: false, at: now(),
1807
1804
  }), undefined, unjudgedCount);
@@ -2033,7 +2030,7 @@ async function foldFromStep({
2033
2030
  startedAt,
2034
2031
  runStartedAt,
2035
2032
  });
2036
- if (stop.type === 'paused' || stop.type === 'stopped') return stop.result;
2033
+ if (endsRun(stop)) return stop.result;
2037
2034
  if (stop.type === 'halted') {
2038
2035
  return haltRun({
2039
2036
  flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts, outcome: stop.outcome, red: stop.red,
@@ -2153,7 +2150,7 @@ async function foldFromStep({
2153
2150
  runStartedAt,
2154
2151
  });
2155
2152
 
2156
- if (askResult.type === 'paused' || askResult.type === 'stopped') return askResult.result;
2153
+ if (endsRun(askResult)) return askResult.result;
2157
2154
  if (askResult.type === 'halted') {
2158
2155
  return haltRun({
2159
2156
  flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value && askResult.stop?.book?.spendComplete !== false, attempts: attemptsLog, artifacts, outcome: askResult.outcome, red: askResult.red,
@@ -2253,18 +2250,11 @@ function sumAuditUsd(runDir, { skipVerdicts = /** @type {string[]} */ ([]) } = {
2253
2250
  // raw `readFileSync` — a symlinked `audit.jsonl` (or a symlinked ancestor
2254
2251
  // directory) reads as "missing" (total 0), never as some outside file's
2255
2252
  // content summed into a cap check.
2256
- const result = readFileInside(runDir, 'audit.jsonl');
2257
- if (!result.ok) return { ok: true, total: 0, complete: true };
2258
- const lines = result.text.split('\n').filter((line) => line.trim().length > 0);
2253
+ const read = readAudit(runDir, { strict: true });
2254
+ if (!read.ok) return read;
2259
2255
  let total = 0;
2260
2256
  let complete = true;
2261
- for (const line of lines) {
2262
- let row;
2263
- try {
2264
- row = JSON.parse(line);
2265
- } catch (err) {
2266
- return { ok: false, red: `audit.jsonl line is not valid JSON — ${err.message}` };
2267
- }
2257
+ for (const row of read.rows) {
2268
2258
  // a row of a verdict the caller names cost nothing and carries `usd: null` on purpose (a cap-halt: the round was never bought)
2269
2259
  if (skipVerdicts.includes(row.verdict)) continue;
2270
2260
  if (row.spendComplete === false) complete = false;
@@ -2315,7 +2305,7 @@ async function takeResumeLock(runDir, runId, lockPath) {
2315
2305
  await new Promise((r) => { setTimeout(r, 150); });
2316
2306
  lock = readResumeLock(runDir);
2317
2307
  }
2318
- if (lock.state === 'live' || lock.state === 'unknown') {
2308
+ if (lockMayBeHeld(lock.state)) {
2319
2309
  return { ok: false, red: `resume: run "${runId}" is locked by another resumer (pid ${lock.pid}, ${lockPath})` };
2320
2310
  }
2321
2311
  if (lock.state === 'empty') {
@@ -2430,19 +2420,14 @@ export async function resumeRun({
2430
2420
  // symlinked run dir ancestor) is refused by name here, never read
2431
2421
  // through to an outside file's content (the same class `answer.json`
2432
2422
  // and `audit.jsonl` above already close).
2433
- const stateResult = readFileInside(runDir, 'state.json');
2423
+ const stateResult = readRunState(runDir, { strict: true });
2434
2424
  if (!stateResult.ok) {
2435
2425
  if (stateResult.missing) {
2436
2426
  return { outcome: 'refused', red: `resume: no parked state for run "${runId}" (${statePath})` };
2437
2427
  }
2438
2428
  return { outcome: 'refused', red: `resume: state.json for run "${runId}" — ${stateResult.red}` };
2439
2429
  }
2440
- let state;
2441
- try {
2442
- state = JSON.parse(stateResult.text);
2443
- } catch (err) {
2444
- return { outcome: 'refused', red: `resume: state.json for run "${runId}" is not valid JSON — ${err.message}` };
2445
- }
2430
+ const state = stateResult.state;
2446
2431
 
2447
2432
  // F45 finding 3: the run's TRUE wall-clock start, restored from the
2448
2433
  // parked state rather than this process's own `startedAt` — otherwise
@@ -2571,26 +2556,21 @@ export async function resumeRun({
2571
2556
  };
2572
2557
  }
2573
2558
 
2574
- const answerPath = join(runDir, 'answer.json');
2575
- // F48 round 3: `answer.json` goes through `resolveInside` too — a
2576
- // symlinked answer file (or a symlinked run dir ancestor) is refused by
2577
- // name here, the same as "no answer yet", never read through to an
2578
- // outside file's content.
2579
- const answerResolved = resolveInside(runDir, 'answer.json');
2580
- if (!answerResolved.ok) {
2581
- if (answerResolved.missing) {
2559
+ // F48 round 3: `answer.json` goes through the gateway (`readSavedAnswer`) — a symlinked answer file (or a symlinked run dir ancestor) is refused by
2560
+ // name here, the same as "no answer yet", never read through to an outside file's content.
2561
+ const savedAnswer = readSavedAnswer(runDir);
2562
+ if (!savedAnswer.ok) {
2563
+ if (savedAnswer.missing) {
2582
2564
  return { outcome: 'refused', red: `resume: no answer yet for run "${runId}"` };
2583
2565
  }
2584
- return { outcome: 'refused', red: `resume: answer.json for run "${runId}" — ${answerResolved.red}` };
2566
+ return { outcome: 'refused', red: `resume: answer.json for run "${runId}" — ${savedAnswer.red}` };
2585
2567
  }
2586
- let answer;
2587
- try {
2588
- answer = JSON.parse(readFileSync(answerPath, 'utf8'));
2589
- } catch (err) {
2590
- return { outcome: 'refused', red: `resume: answer.json for run "${runId}" is not valid JSON — ${err.message}` };
2568
+ if (savedAnswer.parseError !== null) {
2569
+ return { outcome: 'refused', red: `resume: answer.json for run "${runId}" is not valid JSON — ${savedAnswer.parseError}` };
2591
2570
  }
2571
+ let answer = savedAnswer.value;
2592
2572
  // Valid JSON that is not an object (`null`, a number, a string, an array) has no askId to read: refused by name.
2593
- if (answer === null || typeof answer !== 'object' || Array.isArray(answer)) {
2573
+ if (!savedAnswer.isObject) {
2594
2574
  return { outcome: 'refused', red: `resume: answer.json for run "${runId}" is not a JSON object (it holds ${answer === null ? 'null' : Array.isArray(answer) ? 'an array' : `a ${typeof answer}`})` };
2595
2575
  }
2596
2576
  // M4b amendment 3: a consumed/saved answer that says `reject` (an older
@@ -2602,7 +2582,7 @@ export async function resumeRun({
2602
2582
 
2603
2583
  // M4c amendment 3: an answer's saved time, never the restart's clock, says whether it was on time. A missing or
2604
2584
  // unreadable one is refused by name here, before the consume, so the answer stays replayable.
2605
- const timing = answerTiming(answer.answeredAt, effectiveExpiresAt(runDir, state.askId, state.expiresAt));
2585
+ const timing = savedAnswer.broken ? 'unreadable' : answerTiming(answer.answeredAt, effectiveExpiresAt(runDir, state.askId, state.expiresAt));
2606
2586
  if (timing === 'unreadable') {
2607
2587
  return { outcome: 'refused', red: `resume: answer.json for run "${runId}" has a missing or unreadable answeredAt ("${answer.answeredAt}") — refusing rather than treating it as on time` };
2608
2588
  }
@@ -2632,8 +2612,8 @@ export async function resumeRun({
2632
2612
 
2633
2613
  // Consume-once, BEFORE acting on the decision (F44) — the rename is
2634
2614
  // itself a one-winner gate, on top of the lock above.
2635
- const consumedPath = join(runDir, `answer.${answer.askId}.consumed.json`);
2636
- renameSync(answerPath, consumedPath);
2615
+ const consumedPath = join(runDir, consumedAnswerName(answer.askId));
2616
+ renameSync(join(runDir, 'answer.json'), consumedPath);
2637
2617
  // M4c: the answer is ours and every guard has passed — record this resume process before its first step.
2638
2618
  recordPid(runDir, 'resume', now());
2639
2619
 
@@ -2860,7 +2840,7 @@ export async function resumeRun({
2860
2840
  runStartedAt,
2861
2841
  });
2862
2842
 
2863
- if (askResult.type === 'paused' || askResult.type === 'stopped') return askResult.result;
2843
+ if (endsRun(askResult)) return askResult.result;
2864
2844
  if (askResult.type === 'halted') {
2865
2845
  return haltRun({
2866
2846
  flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs: getNowMs, signatureHash: state.signatureHash, spent, priorSpendComplete: spendComplete.value && askResult.stop?.book?.spendComplete !== false, attempts: attemptsLog, artifacts, outcome: askResult.outcome, red: askResult.red,
@@ -3049,8 +3029,7 @@ export async function continueRun({
3049
3029
  if (!recordedHashes.ok) return { outcome: 'refused', red: recordedHashes.red };
3050
3030
 
3051
3031
  // Consume-once BEFORE acting (the answer's own rule, F44): the rename is a one-winner gate on top of the lock.
3052
- const taken = readdirInside(runDir, '.').filter((n) => /^halt\.\d+\.consumed\.json$/.test(n)).length;
3053
- renameSync(join(runDir, HALT_FILE), join(runDir, `halt.${taken + 1}.consumed.json`));
3032
+ renameSync(join(runDir, HALT_FILE), join(runDir, nextHaltConsumedName(runDir)));
3054
3033
  settleStop({ runDir, now, outcome: halt.outcome ?? 'halted' }); // a request left over from before the halt is not this continue's
3055
3034
  recordPid(runDir, 'continue', now());
3056
3035
 
@@ -3083,8 +3062,9 @@ export async function continueRun({
3083
3062
 
3084
3063
  // Amendment 7 item 8: a Stop that cut the step short leaves its tries in the books; Resume re-enters it as a NEW try, numbered after them.
3085
3064
  // A try the Stop cut mid-way (its `stopped` row) wears a number but is replaced, not counted against the step's limit. Read from the
3086
- // books (the source of truth), never a second record. A cap-halt re-entry keeps its own, earlier behaviour.
3065
+ // books (the source of truth), never a second record. A cap-halt re-entry (M4d am30, F275) only numbers its tries after the step's last; its limit is the step's own, as before.
3087
3066
  const resumeTries = { numbered: 0, done: 0 };
3067
+ if (halt.outcome === 'cap-halt' && steps[halt.stepIndex]) resumeTries.numbered = lastTryNumber(runDir, steps[halt.stepIndex].emits ?? null);
3088
3068
  if (halt.outcome === 'stopped' && steps[halt.stepIndex]) {
3089
3069
  const tries = readAudit(runDir).filter((r) => r.step === steps[halt.stepIndex].emits && Number.isInteger(r.attempt) && r.verdict !== 'cap-halt');
3090
3070
  resumeTries.numbered = tries.length;
@@ -3209,7 +3189,7 @@ export async function stopParkedRun({
3209
3189
  const ask = readAsk(runDir);
3210
3190
  const state = readRunState(runDir);
3211
3191
  if (!ask || typeof ask.askId !== 'string' || !state || state.askId !== ask.askId) return refused(`run "${runId}" is not waiting at an ask`);
3212
- if (existsSync(join(runDir, `answer.${ask.askId}.consumed.json`))) return refused(`run "${runId}" already took its answer`);
3192
+ if (existsSync(join(runDir, consumedAnswerName(ask.askId)))) return refused(`run "${runId}" already took its answer`);
3213
3193
  if (endRow(readHistory(flowDir), runDir, runId) !== null) return refused(`run "${runId}" has ended`);
3214
3194
  if (!Number.isInteger(state.stepIndex) || state.stepIndex < 0) return refused(`run "${runId}" state.json field "stepIndex" is not a step number`);
3215
3195
  const audit = auditSpend(runDir);
@@ -3260,33 +3240,6 @@ function writeLog(runDir, payload) {
3260
3240
  writeFileSync(join(runDir, 'log.json'), JSON.stringify(payload, null, 2));
3261
3241
  }
3262
3242
 
3263
- /**
3264
- * `writeLog`'s own sibling reader (M4a piece 2, docs/wiki/the-module-
3265
- * ladder.md M4a scope item 2: "one reader per book") — `null` when the run
3266
- * hasn't reached an exit path yet (still running, or parked before any
3267
- * halt/complete), or the file is present but not valid JSON (a torn write),
3268
- * never a thrown error.
3269
- * @param {string} runDir
3270
- * @returns {any|null}
3271
- */
3272
- export function readLog(runDir) {
3273
- const result = readFileInside(runDir, 'log.json');
3274
- if (!result.ok) return null;
3275
- try { return JSON.parse(result.text); } catch { return null; }
3276
- }
3277
-
3278
- /**
3279
- * `state.json`'s own sibling reader (same rule as {@link readLog}) — `null`
3280
- * when the run has never parked, or the file is present but not valid JSON.
3281
- * @param {string} runDir
3282
- * @returns {any|null}
3283
- */
3284
- export function readRunState(runDir) {
3285
- const result = readFileInside(runDir, 'state.json');
3286
- if (!result.ok) return null;
3287
- try { return JSON.parse(result.text); } catch { return null; }
3288
- }
3289
-
3290
3243
  /**
3291
3244
  * `ask.json`'s own sibling reader (same rule as {@link readLog}) — the
3292
3245
  * parking ask protocol's own writer lives in {@link runAskSlot} above.
@@ -3296,10 +3249,10 @@ export function readRunState(runDir) {
3296
3249
  * @returns {any|null}
3297
3250
  */
3298
3251
  export function readAsk(runDir) {
3299
- const result = readFileInside(runDir, 'ask.json');
3300
- if (!result.ok) return null;
3252
+ const result = readAskFile(runDir);
3253
+ if (!result.ok || result.parseError !== null) return null;
3301
3254
  // The deadline every reader sees is the effective one (`withReopen`: a reopened ask's new deadline).
3302
- try { return withReopen(runDir, JSON.parse(result.text)); } catch { return null; }
3255
+ try { return withReopen(runDir, result.value); } catch { return null; }
3303
3256
  }
3304
3257
 
3305
3258
  /**
@@ -3341,8 +3294,7 @@ function haltRun({
3341
3294
  // now passes `runStartedAt` under this key — see call sites), so `wallMs`
3342
3295
  // times the whole run, pauses included, never just the halting process.
3343
3296
  const wallMs = nowMs() - startedAt;
3344
- const spendComplete = priorSpendComplete
3345
- && outcome !== 'provider-red' && outcome !== 'pricing-red' && outcome !== 'cap-halt';
3297
+ const spendComplete = priorSpendComplete && !isSpendFloorEnding(outcome);
3346
3298
  mkdirSync(flowDir, { recursive: true });
3347
3299
  try {
3348
3300
  if (existsSync(runDir)) {
@@ -3351,7 +3303,7 @@ function haltRun({
3351
3303
  runId, outcome, red, ...(detail ? { detail } : {}), ...(skip ? { skipReason: skip } : {}), attempts, artifacts,
3352
3304
  });
3353
3305
  // M4e amendment 4 item 4: a cap-halted or stopped run leaves the one record Resume continues from (its only writer).
3354
- if (resumeAt && HALT_OUTCOMES.includes(outcome)) {
3306
+ if (resumeAt && isResumableEnding(outcome)) {
3355
3307
  writeFileSync(join(runDir, HALT_FILE), `${JSON.stringify({
3356
3308
  runId, outcome, at: now(), flow: { root: resumeAt.flowRoot, name: resumeAt.flowName }, signatureHash, inputsManifest: resumeAt.inputsManifest,
3357
3309
  stepIndex: resumeAt.stepIndex, startedAt, unjudged: resumeAt.unjudged ?? [],
package/src/runvalues.js CHANGED
@@ -17,11 +17,11 @@ import { createHash } from 'node:crypto';
17
17
  import { unlinkSync, writeFileSync } from 'node:fs';
18
18
  import { join } from 'node:path';
19
19
 
20
- import { readFileInside, readdirInside } from './flow.js';
20
+ import { readFileInside, readdirInside } from './inside.js';
21
21
  import { TRIGGER_RECORD_FILE } from './trigger-line.js';
22
22
  import { DEFAULT_ACTION_WAIT_MS } from './action-stop.js';
23
23
 
24
- export const VALUES_FILE_RE = /^signed-values(?:-r(\d+))?\.json$/;
24
+ const VALUES_FILE_RE = /^signed-values(?:-r(\d+))?\.json$/;
25
25
 
26
26
  const WAIT_RE = /^(\d+)\s*([smh])$/i;
27
27
  const UNIT_MS = { s: 1000, m: 60_000, h: 3_600_000 };
@@ -113,37 +113,60 @@ export function writeRunValues(runDir, record) {
113
113
  }
114
114
 
115
115
  /**
116
- * The ONE decision "which signed version does this run use": the highest version file in the run folder.
117
- * `{ok:true, none:true}` = the flow's own values; `{ok:true, version, record}`; `{ok:false, red}` = a file that cannot be trusted
118
- * (unreadable, not JSON, wrong shape, a hash that does not match its fields, a name that disagrees with its version).
119
- * @param {string} runDir
120
- * @returns {{ok: true, none: true} | {ok: true, none?: false, version: number, record: any} | {ok: false, red: string}}
116
+ * The ONE reader of one signed values file: trusted or refused. A refusal is a file that cannot be trusted (unreadable, not JSON,
117
+ * wrong shape, a hash that does not match its fields, a name that disagrees with its version).
118
+ * @param {string} runDir @param {string} name the file's name @param {number} version the version its name says
119
+ * @returns {{ok: true, version: number, record: any} | {ok: false, red: string}}
121
120
  */
122
- export function pickRunValues(runDir) {
123
- let best = null;
124
- for (const name of readdirInside(runDir, '.')) {
125
- const m = VALUES_FILE_RE.exec(name);
126
- if (m === null) continue;
127
- const version = m[1] === undefined ? 0 : Number(m[1]);
128
- if (best === null || version > best.version) best = { version, name };
129
- }
130
- if (best === null) return { ok: true, none: true };
131
- const f = readFileInside(runDir, best.name);
132
- if (!f.ok) return { ok: false, red: `signed values: ${best.name} — ${f.missing ? 'unreadable' : f.red}` };
121
+ function readValuesFile(runDir, name, version) {
122
+ const f = readFileInside(runDir, name);
123
+ if (!f.ok) return { ok: false, red: `signed values: ${name} — ${f.missing ? 'unreadable' : f.red}` };
133
124
  let record;
134
- try { record = JSON.parse(f.text); } catch (err) { return { ok: false, red: `signed values: ${best.name} is not valid JSON — ${err.message}` }; }
125
+ try { record = JSON.parse(f.text); } catch (err) { return { ok: false, red: `signed values: ${name} is not valid JSON — ${err.message}` }; }
135
126
  const v = record?.values;
136
- const shaped = record && typeof record === 'object' && record.version === best.version && typeof record.flow === 'string' && typeof record.flowSignatureHash === 'string'
127
+ const shaped = record && typeof record === 'object' && record.version === version && typeof record.flow === 'string' && typeof record.flowSignatureHash === 'string'
137
128
  && typeof record.hash === 'string' && v && typeof v === 'object' && Number.isFinite(v.capUsd) && v.capUsd > 0
138
129
  && (v.destination === null || (typeof v.destination === 'string' && v.destination !== ''))
139
130
  && v.askWaits && typeof v.askWaits === 'object' && Object.values(v.askWaits).every((w) => parseWaitMs(w) !== null)
140
131
  && (v.model === undefined || (v.model && typeof v.model.slot === 'string' && v.model.slot !== '' && typeof v.model.model === 'string' && v.model.model !== ''));
141
- if (!shaped) return { ok: false, red: `signed values: ${best.name} does not have the shape of a signed values record` };
132
+ if (!shaped) return { ok: false, red: `signed values: ${name} does not have the shape of a signed values record` };
142
133
  const want = valuesHash({
143
- flow: record.flow, flowSignatureHash: record.flowSignatureHash, runId: best.version === 0 ? null : (record.runId ?? null), version: best.version, values: v,
134
+ flow: record.flow, flowSignatureHash: record.flowSignatureHash, runId: version === 0 ? null : (record.runId ?? null), version, values: v,
144
135
  });
145
- if (want !== record.hash) return { ok: false, red: `signed values: ${best.name} does not match its own hash — it was changed after it was signed` };
146
- return { ok: true, version: best.version, record };
136
+ if (want !== record.hash) return { ok: false, red: `signed values: ${name} does not match its own hash — it was changed after it was signed` };
137
+ return { ok: true, version, record };
138
+ }
139
+
140
+ /**
141
+ * Every signed values file in the run folder, oldest version first, each read by `readValuesFile` (the Audit lists them; a refused one
142
+ * shows as refused).
143
+ * @param {string} runDir
144
+ * @returns {Array<{file: string, version: number} & ({ok: true, record: any} | {ok: false, red: string})>}
145
+ */
146
+ export function listRunValues(runDir) {
147
+ const out = [];
148
+ for (const file of readdirInside(runDir, '.')) {
149
+ const m = VALUES_FILE_RE.exec(file);
150
+ if (m === null) continue;
151
+ out.push({ file, version: m[1] === undefined ? 0 : Number(m[1]) });
152
+ }
153
+ out.sort((a, b) => a.version - b.version);
154
+ return out.map((e) => { const r = readValuesFile(runDir, e.file, e.version); return r.ok ? { file: e.file, version: e.version, ok: true, record: r.record } : { file: e.file, version: e.version, ok: false, red: r.red }; });
155
+ }
156
+
157
+ /**
158
+ * The ONE decision "which signed version does this run use": the highest version file in the run folder.
159
+ * `{ok:true, none:true}` = the flow's own values; `{ok:true, version, record}`; `{ok:false, red}` = a file that cannot be trusted
160
+ * (see `readValuesFile`).
161
+ * @param {string} runDir
162
+ * @returns {{ok: true, none: true} | {ok: true, none?: false, version: number, record: any} | {ok: false, red: string}}
163
+ */
164
+ export function pickRunValues(runDir) {
165
+ const all = listRunValues(runDir);
166
+ if (all.length === 0) return { ok: true, none: true };
167
+ const top = all[all.length - 1].version;
168
+ const best = all.find((e) => e.version === top) ?? all[0]; // the first file of the top version, as before
169
+ return best.ok ? { ok: true, version: best.version, record: best.record } : { ok: false, red: best.red };
147
170
  }
148
171
 
149
172
  /**
@@ -0,0 +1,41 @@
1
+ import { isClockKind } from './trigger-clock.js';
2
+ import { isFileKind } from './trigger-files.js';
3
+ import { isFlowType } from './declaration.js';
4
+
5
+ // M20 am5 item 1: the ONE list of schedule choices per flow type. The Run card's When and the New job card's Schedule both ask it (the page gets it from the server,
6
+ // `__FWDLOOP_SCHEDULE_CHOICES__`; the server's own card check asks `scheduleKindsOf`). The words are the Run card's.
7
+ // What a choice needs from the job (a file input for the two file kinds, a ticket list for a new ticket) is the card's own availability rule, not this list's.
8
+
9
+ /** @type {Record<string, string>} the Run card's words, one per kind */
10
+ const LABELS = Object.freeze({
11
+ hand: 'By hand',
12
+ daily: 'Every day at HH:MM',
13
+ weekdays: 'Weekdays at HH:MM',
14
+ weekly: 'Every <day> at HH:MM',
15
+ 'file-updated': 'When <file> is updated',
16
+ 'new-file': 'When a new file arrives in <folder>',
17
+ 'new-ticket': 'When a new ticket arrives in <input name>',
18
+ });
19
+
20
+ /** the New job card has no input box for a ticket list (the plan names the one list), so its word for that choice is the signed M13 item 7 one */
21
+ const NEW_CARD_LABELS = Object.freeze({ 'new-ticket': 'When a new ticket arrives' });
22
+
23
+ const PLAIN = Object.freeze(['hand', 'daily', 'weekdays', 'weekly', 'file-updated', 'new-file']);
24
+ const BY_TYPE = Object.freeze({
25
+ plain: PLAIN,
26
+ // a generic MCP job: By hand and every day only
27
+ mcp: Object.freeze(['hand', 'daily']),
28
+ // a Tickets MCP job: today's plain choices and a new ticket
29
+ tickets: Object.freeze([...PLAIN, 'new-ticket']),
30
+ });
31
+
32
+ /** @param {unknown} flowType @returns {'plain'|'mcp'|'tickets'} */
33
+ const typeOf = (flowType) => (isFlowType(flowType) ? /** @type {'plain'|'mcp'|'tickets'} */ (flowType) : 'plain');
34
+
35
+ /** the kinds a flow type offers, in the Run card's order @param {unknown} flowType @returns {string[]} */
36
+ export const scheduleKindsOf = (flowType) => [...BY_TYPE[typeOf(flowType)]];
37
+
38
+ /** the whole list as the page takes it: per flow type, `{kind, clock, file, label, newCardLabel}` (clock, file: the one answers of isClockKind and isFileKind) @returns {Record<string, {kind: string, clock: boolean, file: boolean, label: string, newCardLabel: string}[]>} */
39
+ export function scheduleChoices() {
40
+ return Object.fromEntries(Object.entries(BY_TYPE).map(([type, kinds]) => [type, kinds.map((kind) => ({ kind, clock: isClockKind(kind), file: isFileKind(kind), label: LABELS[kind], newCardLabel: NEW_CARD_LABELS[kind] ?? LABELS[kind] }))]));
41
+ }
@@ -0,0 +1,39 @@
1
+ // M20 am5 item 1: what a typed schedule is and whether its file or folder is there, ONE place for the Run card's door (src/panel/authortrigger.js `inspect`) and the New job card
2
+ // (its card check and its sign). `shapeOf` moved verbatim out of src/panel/authortrigger.js; the file/folder check is `fileTriggerWhy` in src/trigger-files.js. Reads and writes no file.
3
+ import { isAbsolute } from 'node:path';
4
+ import { validateSchedule } from './trigger-clock.js';
5
+ import { isFileKind } from './trigger-files.js';
6
+ import { WATCHABLE } from './ticket-shape.js';
7
+
8
+ /** @typedef {import('./trigger-line.js').Trigger} Trigger */
9
+
10
+ /**
11
+ * The trigger a body asks for, checked as data: null (By hand) or exactly one of the five shapes, the role one of the job's inputs, a full
12
+ * path. Returns the typed trigger or the sentence that says what to fix.
13
+ * @param {unknown} t @param {string[]} roles
14
+ * @returns {{ok: true, trigger: Trigger|null} | {ok: false, say: string}}
15
+ */
16
+ export function shapeOf(t, roles) {
17
+ if (t === null) return { ok: true, trigger: null };
18
+ if (!t || typeof t !== 'object' || Array.isArray(t)) return { ok: false, say: 'Pick when it runs from the choices. A schedule is not typed as text. Nothing was changed.' };
19
+ const o = /** @type {Record<string, unknown>} */ (t);
20
+ if (isFileKind(o.kind)) {
21
+ const where = o.kind === 'new-file' ? 'folder' : 'path';
22
+ const extra = Object.keys(o).filter((k) => !['kind', 'role', where].includes(k));
23
+ if (extra.length > 0) return { ok: false, say: `A "${o.kind}" trigger takes a kind, a role and a ${where}, not "${extra[0]}". Nothing was changed.` };
24
+ if (typeof o.role !== 'string' || !roles.includes(o.role)) return { ok: false, say: `This job has no input named "${String(o.role)}" (it takes: ${roles.join(', ') || 'none'}). Pick one of those. Nothing was changed.` };
25
+ const p = o[where];
26
+ // eslint-disable-next-line no-control-regex
27
+ if (typeof p !== 'string' || p === '' || !isAbsolute(p) || /[\x00-\x1f\x7f]/.test(p)) return { ok: false, say: `The ${where} must be a full path on one line, like /home/you/inbox. Nothing was changed.` };
28
+ return { ok: true, trigger: /** @type {Trigger} */ (o.kind === 'new-file' ? { kind: 'new-file', role: o.role, folder: p } : { kind: 'file-updated', role: o.role, path: p }) };
29
+ }
30
+ if (o.kind === 'new-ticket') {
31
+ // M12 piece 2: the person picks the input; the list address, the job's server and the look's tool are filled from the signed job (inspect), never typed here
32
+ const extra = Object.keys(o).filter((k) => !['kind', 'role', 'watch'].includes(k));
33
+ if (extra.length > 0) return { ok: false, say: `A "new-ticket" trigger takes a kind and a role, not "${extra[0]}". Nothing was changed.` };
34
+ if (typeof o.role !== 'string' || !roles.includes(o.role)) return { ok: false, say: `This job has no input named "${String(o.role)}" (it takes: ${roles.join(', ') || 'none'}). Pick one of those. Nothing was changed.` };
35
+ if (o.watch !== undefined && !(Array.isArray(o.watch) && o.watch.every((w) => WATCHABLE.includes(w)))) return { ok: false, say: `A ticket schedule can watch only ${WATCHABLE.join(' and ')}. Nothing was changed.` };
36
+ return { ok: true, trigger: /** @type {Trigger} */ ({ kind: 'new-ticket', role: o.role, list: '', server: '', tool: '', ...(o.watch ? { watch: o.watch } : {}) }) };
37
+ }
38
+ try { return { ok: true, trigger: validateSchedule(t) }; } catch (e) { return { ok: false, say: `${/** @type {Error} */ (e).message}. Nothing was changed.` }; }
39
+ }