fwdloop 0.38.0 → 0.40.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 (129) hide show
  1. package/README.md +6 -9
  2. package/bin/fwdloop +21 -19
  3. package/package.json +1 -1
  4. package/src/ask.js +70 -148
  5. package/src/audit-fold.js +6 -5
  6. package/src/auditchecks.js +6 -4
  7. package/src/authoring.js +32 -60
  8. package/src/blockasks.js +2 -1
  9. package/src/blockassemble.js +15 -3
  10. package/src/blockdraft.js +2 -2
  11. package/src/blockpick.js +42 -16
  12. package/src/books.js +237 -12
  13. package/src/checkblock.js +24 -44
  14. package/src/checklistsign.js +25 -3
  15. package/src/checklook.js +3 -1
  16. package/src/checkpick.js +6 -77
  17. package/src/cited-source.js +4 -4
  18. package/src/citedcheck.js +6 -11
  19. package/src/citedwords.js +9 -8
  20. package/src/closers.js +9 -6
  21. package/src/declaration.js +14 -49
  22. package/src/diary.js +23 -1
  23. package/src/draft-steps.js +11 -1
  24. package/src/drafter.js +18 -12
  25. package/src/draftfiles.js +127 -0
  26. package/src/draftspend.js +165 -17
  27. package/src/flow.js +42 -87
  28. package/src/flowmodel.js +1 -1
  29. package/src/index.js +3 -2
  30. package/src/inside.js +106 -0
  31. package/src/jsonl-append.js +33 -1
  32. package/src/learn.js +1 -1
  33. package/src/learnstore.js +20 -22
  34. package/src/line-checks.js +1 -1
  35. package/src/liveness.js +3 -0
  36. package/src/mcp-use.js +8 -9
  37. package/src/memo.js +13 -16
  38. package/src/model-step.js +2 -2
  39. package/src/page-words.js +8 -0
  40. package/src/pageask.js +8 -3
  41. package/src/pagebits.js +8 -1
  42. package/src/pagedropwords.js +1 -1
  43. package/src/pagerules.js +6 -3
  44. package/src/panel/author.js +99 -75
  45. package/src/panel/authorcard.js +21 -8
  46. package/src/panel/authorflows.js +3 -3
  47. package/src/panel/authorresume.js +3 -3
  48. package/src/panel/authorstart.js +15 -16
  49. package/src/panel/authortrigger.js +43 -70
  50. package/src/panel/data.js +186 -188
  51. package/src/panel/index.html +139 -115
  52. package/src/panel/jobgrid.js +3 -7
  53. package/src/panel/result.js +7 -10
  54. package/src/panel/resume.js +4 -3
  55. package/src/panel/scheduler.js +9 -9
  56. package/src/panel/server.js +8 -4
  57. package/src/panel/spawn.js +22 -11
  58. package/src/panel/tickets.js +2 -2
  59. package/src/pickrecord.js +51 -31
  60. package/src/placerule.js +3 -4
  61. package/src/plain-checks.js +1 -1
  62. package/src/planrebuild.js +19 -19
  63. package/src/primitives.js +1 -1
  64. package/src/provider.js +1 -1
  65. package/src/reasons.js +25 -0
  66. package/src/runfile.js +26 -2
  67. package/src/runner.js +57 -105
  68. package/src/runvalues.js +47 -24
  69. package/src/schedule-choices.js +41 -0
  70. package/src/schedule-shape.js +39 -0
  71. package/src/schedule.js +9 -8
  72. package/src/setup.js +20 -36
  73. package/src/shaperows.js +2 -2
  74. package/src/sheetblock.js +2 -2
  75. package/src/sheetbuild.js +5 -5
  76. package/src/sheetrun.js +4 -5
  77. package/src/summary-words.js +2 -1
  78. package/src/thinking.js +5 -2
  79. package/src/ticketrows.js +7 -28
  80. package/src/trigger-clock.js +9 -23
  81. package/src/trigger-files.js +30 -22
  82. package/src/trigger-tickets.js +15 -14
  83. package/src/try-checks.js +2 -1
  84. package/src/types.js +2 -0
  85. package/types/ask.d.ts +25 -20
  86. package/types/authoring.d.ts +7 -42
  87. package/types/blockpick.d.ts +1 -1
  88. package/types/books.d.ts +380 -4
  89. package/types/checkblock.d.ts +1 -23
  90. package/types/checklist.d.ts +3 -3
  91. package/types/checklistsign.d.ts +7 -0
  92. package/types/checkpick.d.ts +0 -21
  93. package/types/citedwords.d.ts +7 -4
  94. package/types/closers.d.ts +1 -0
  95. package/types/declaration.d.ts +4 -14
  96. package/types/diary.d.ts +14 -1
  97. package/types/draft-steps.d.ts +7 -0
  98. package/types/drafter.d.ts +1 -1
  99. package/types/draftfiles.d.ts +89 -0
  100. package/types/draftspend.d.ts +74 -0
  101. package/types/flow.d.ts +32 -54
  102. package/types/index.d.ts +3 -3
  103. package/types/inside.d.ts +71 -0
  104. package/types/jsonl-append.d.ts +20 -0
  105. package/types/learnstore.d.ts +0 -2
  106. package/types/liveness.d.ts +1 -0
  107. package/types/page-words.d.ts +6 -0
  108. package/types/pageask.d.ts +2 -0
  109. package/types/pagebits.d.ts +3 -0
  110. package/types/pagerules.d.ts +1 -0
  111. package/types/panel/author.d.ts +7 -3
  112. package/types/panel/authorcard.d.ts +0 -6
  113. package/types/panel/authorflows.d.ts +4 -4
  114. package/types/panel/authortrigger.d.ts +16 -2
  115. package/types/panel/data.d.ts +50 -16
  116. package/types/panel/spawn.d.ts +18 -2
  117. package/types/pickrecord.d.ts +29 -0
  118. package/types/reasons.d.ts +23 -0
  119. package/types/runfile.d.ts +14 -0
  120. package/types/runner.d.ts +6 -38
  121. package/types/runvalues.d.ts +17 -2
  122. package/types/schedule-choices.d.ts +9 -0
  123. package/types/schedule-shape.d.ts +15 -0
  124. package/types/sheetbuild.d.ts +1 -1
  125. package/types/thinking.d.ts +1 -0
  126. package/types/ticketrows.d.ts +0 -9
  127. package/types/trigger-clock.d.ts +3 -2
  128. package/types/trigger-files.d.ts +15 -4
  129. package/types/types.d.ts +8 -0
@@ -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
+ }
package/src/schedule.js CHANGED
@@ -13,12 +13,13 @@ import { createHash } from 'node:crypto';
13
13
  import { renameSync, rmSync, writeFileSync } from 'node:fs';
14
14
  import { isAbsolute, join } from 'node:path';
15
15
 
16
- import { readFileInside } from './flow.js';
16
+ import { readFileInside } from './inside.js';
17
17
  import { appendRow } from './jsonl-append.js';
18
- import { queueOf, readSeen, recordDropped } from './trigger-files.js';
19
- import { readRows, validateSchedule } from './trigger-clock.js';
18
+ import { isFileKind, queueOf, recordDropped } from './trigger-files.js';
19
+ import { validateSchedule } from './trigger-clock.js';
20
20
  import { triggerHash } from './trigger-line.js';
21
21
  import { WATCHABLE } from './ticket-shape.js';
22
+ import { readTriggerLedger } from './jsonl-append.js';
22
23
 
23
24
  /** @typedef {import('./trigger-line.js').Trigger} Trigger */
24
25
  /**
@@ -42,7 +43,7 @@ export const ledgerOf = (flowDir) => join(flowDir, LEDGER_FILE);
42
43
  /** @param {string} bound @param {string} signedAt */
43
44
  export const sigOf = (bound, signedAt) => createHash('sha256').update(`${bound}\n${signedAt}`).digest('hex');
44
45
 
45
- const isFile = (/** @type {any} */ t) => t?.kind === 'new-file' || t?.kind === 'file-updated';
46
+ const isFile = (/** @type {any} */ t) => isFileKind(t?.kind);
46
47
  const isTicket = (/** @type {any} */ t) => t?.kind === 'new-ticket';
47
48
  const str = (/** @type {unknown} */ v) => typeof v === 'string' && v !== '';
48
49
 
@@ -99,7 +100,7 @@ export function sameTarget(cur, next) {
99
100
  }
100
101
 
101
102
  /** Is this signing armed (its `armed` row is in the ledger)? @param {string} flowDir @param {string} sig */
102
- export const isArmed = (flowDir, sig) => readRows(ledgerOf(flowDir), sig).some((r) => r.kind === 'armed');
103
+ export const isArmed = (flowDir, sig) => readTriggerLedger(ledgerOf(flowDir), sig).some((r) => r.kind === 'armed');
103
104
 
104
105
  /**
105
106
  * Every file waiting under signing `sig` leaves its queue: one `dropped` row (under `sig`) and ONE row in the outcome file with am16's words. The drop is written
@@ -108,7 +109,7 @@ export const isArmed = (flowDir, sig) => readRows(ledgerOf(flowDir), sig).some((
108
109
  */
109
110
  export function dropQueue(flowDir, sig, nowMs, note) {
110
111
  const ledger = ledgerOf(flowDir);
111
- for (const q of queueOf(readSeen(ledger, sig))) {
112
+ for (const q of queueOf(readTriggerLedger(ledger, sig))) {
112
113
  recordDropped(ledger, q, 'schedule-changed', nowMs, sig);
113
114
  note({ outcome: 'schedule-changed', file: q.path, sha: q.sha, say: droppedSay(q.name) });
114
115
  }
@@ -121,7 +122,7 @@ export function dropQueue(flowDir, sig, nowMs, note) {
121
122
  */
122
123
  export function carryQueue(flowDir, from, to) {
123
124
  const ledger = ledgerOf(flowDir);
124
- for (const r of readSeen(ledger, from)) {
125
+ for (const r of readTriggerLedger(ledger, from)) {
125
126
  if (!['baseline', 'arrived', 'ran', 'dropped'].includes(r.kind)) continue;
126
127
  const { sig: _old, ...row } = r;
127
128
  appendRow(ledger, { ...row, sig: to });
@@ -131,7 +132,7 @@ export function carryQueue(flowDir, from, to) {
131
132
  /** The old signing's files that `carryQueue` copied are no longer its own to run. @param {string} flowDir @param {string} from @param {number} nowMs */
132
133
  export function finishCarry(flowDir, from, nowMs) {
133
134
  const ledger = ledgerOf(flowDir);
134
- for (const q of queueOf(readSeen(ledger, from))) recordDropped(ledger, q, 'carried', nowMs, from);
135
+ for (const q of queueOf(readTriggerLedger(ledger, from))) recordDropped(ledger, q, 'carried', nowMs, from);
135
136
  }
136
137
 
137
138
  /** Cancel's own row in the ledger. @param {string} flowDir @param {string} sig @param {number} nowMs */
package/src/setup.js CHANGED
@@ -8,45 +8,30 @@
8
8
  // carry `note` / `change` kinds; they are only ever READ back, from the flow's own setup.jsonl.
9
9
  // Third outcomes: a draft with no result is `stopped`; a cost nobody booked is `null` (shown "unknown", never $0).
10
10
  import { lstatSync, writeFileSync } from 'node:fs';
11
- import { triesOf } from './draft-steps.js';
11
+ import { triesOf, CARD_RE } from './draft-steps.js';
12
12
  import { join } from 'node:path';
13
13
 
14
- import { readQuestions, scrub } from './authoring.js';
14
+ import { readQuestions, scrub, draftVerdict, readNotCheckedFile, readCard, cardFileName, readRedraftMarker } from './draftfiles.js';
15
15
  import { notCheckedBlock } from './checked.js';
16
- import { readDraftSpend } from './draftspend.js';
17
- import { readFileInside, readdirInside } from './flow.js';
18
- import { readSpendRows } from './provider.js';
16
+ import { readDirSpendRows, readStartedOverFrom } from './draftspend.js';
17
+ import { readDraftLog, readJsonFile } from './flow.js';
18
+ import { readFileInside, readdirInside } from './inside.js';
19
19
  import { checkAsks } from './checkpick.js';
20
- import { RECORD_FILE, KEPT_WORDS } from './pickrecord.js';
20
+ import { readKept, KEPT_WORDS } from './pickrecord.js';
21
21
 
22
22
  export const SETUP_FILE = 'setup.jsonl';
23
- const CARD_RE = /^card-(\d+)\.json$/;
24
23
 
25
- const readJson = (dir, rel) => {
26
- const r = readFileInside(dir, rel);
27
- if (!r.ok) return null;
28
- try { return JSON.parse(r.text); } catch { return null; }
29
- };
30
24
  const mtimeIso = (dir, rel) => {
31
25
  try { return lstatSync(join(dir, rel)).mtime.toISOString(); } catch { return null; }
32
26
  };
33
27
 
34
28
  /** One plan folder's row: model, cost, verdict (green / red / stopped), plan hash, first red. @param {string} sessionDir @param {string} rel `draft` or `draft-<n>` */
35
29
  function planRow(sessionDir, rel, kind, n) {
36
- const hashFile = readFileInside(sessionDir, `${rel}/spec.hash`);
37
- const hash = hashFile.ok && hashFile.text.trim() !== '' ? hashFile.text.trim() : null;
38
- const log = readJson(sessionDir, `${rel}/log.json`);
39
- const leak = readFileInside(sessionDir, `${rel}/scrub-leak.red`);
40
- const spent = readSpendRows(join(sessionDir, rel, 'spend.jsonl')).filter((r) => r && r.kind === 'draft').pop() ?? readDraftSpend(join(sessionDir, rel));
41
- let verdict = 'stopped';
30
+ const { verdict: v, hash, log, reds } = draftVerdict(sessionDir, rel);
31
+ const spent = /** @type {any} */ (readDirSpendRows(join(sessionDir, rel)).filter(Boolean).pop());
32
+ const verdict = v === 'none' ? 'stopped' : v;
42
33
  /** @type {string|null} */
43
- let gap = 'no result was recorded';
44
- if (hash) { verdict = 'green'; gap = null; } else if (leak.ok || (log && log.ok === false)) {
45
- verdict = 'red';
46
- const reds = Array.isArray(log?.reds) ? log.reds.map(String) : [];
47
- if (leak.ok) reds.push(leak.text.trim());
48
- gap = reds.join('; ') || 'the plan did not pass the checks';
49
- }
34
+ const gap = v === 'green' ? null : v === 'red' ? (reds.join('; ') || 'the plan did not pass the checks') : 'no result was recorded';
50
35
  return {
51
36
  kind, n, at: typeof spent?.at === 'string' ? spent.at : null, model: spent?.model ?? log?.modelId ?? null,
52
37
  costUsd: typeof spent?.costUsd === 'number' ? spent.costUsd : null, spendComplete: spent ? spent.spendComplete !== false && typeof spent.costUsd === 'number' : false,
@@ -81,7 +66,7 @@ function humanRows(sessionDir, rel) {
81
66
  // a kept row's n counts the answered LOOK rows only, as before M14 am3 (a page-look row never changes)
82
67
  const lookAnswered = answered.filter((r) => r.source === 'look').length;
83
68
  // M10 am17 (6): a pick kept from the last draft is the same row, from this plan's picks record (not an answer file), its answer being the words `kept from last draft`
84
- const kept = Array.isArray(readJson(join(sessionDir, rel), RECORD_FILE)?.kept) ? readJson(join(sessionDir, rel), RECORD_FILE).kept : [];
69
+ const kept = readKept(sessionDir, rel).kept ?? [];
85
70
  const keptRows = kept.map((k, i) => {
86
71
  const [ask] = checkAsks([{ line: k.line, rule: k.rule, text: k.ruleText, check: k.check ?? null, why: null }]);
87
72
  return {
@@ -102,21 +87,20 @@ export function buildSetupRows({
102
87
  }) {
103
88
  const rows = [];
104
89
  if (sessionDir) {
105
- const card = readJson(sessionDir, 'card.json');
106
- if (card) rows.push({ kind: 'card', n: 0, at: mtimeIso(sessionDir, 'card.json'), card });
90
+ const card = readCard(sessionDir);
91
+ if (card) rows.push({ kind: 'card', n: 0, at: mtimeIso(sessionDir, cardFileName()), card });
107
92
  // amendment 14 item 6: a draft begun by Start over says so (written once by the panel's start); its row reads `start over`
108
- const so = readJson(sessionDir, 'started-over-from.json');
109
- rows.push(planRow(sessionDir, 'draft', typeof so?.startedOverFrom === 'string' ? 'startover' : 'draft', 0));
93
+ rows.push(planRow(sessionDir, 'draft', typeof readStartedOverFrom(sessionDir) === 'string' ? 'startover' : 'draft', 0));
110
94
  rows.push(...humanRows(sessionDir, 'draft'));
111
95
  // amendment 14 item 6: each revise is the card as submitted, then its plan row (model, cost, verdict, hash); there is no note row
112
96
  const ns = readdirInside(sessionDir, '.').map((f) => CARD_RE.exec(f)?.[1]).filter((x) => x !== undefined).map(Number).sort((a, b) => a - b);
113
97
  for (const n of ns) {
114
- const card = readJson(sessionDir, `card-${n}.json`);
115
- if (card) rows.push({ kind: 'card', n, at: mtimeIso(sessionDir, `card-${n}.json`), card });
98
+ const card = readCard(sessionDir, n);
99
+ if (card) rows.push({ kind: 'card', n, at: mtimeIso(sessionDir, cardFileName(n)), card });
116
100
  // M4e amendment 24 item 4: a plan drafted again after the human's answers is booked as `redraft`, not `revise` (it uses none of the 2 revises)
117
101
  // M16 item 5: a plan made by a Drop or an Add of the person is booked as that, not as a redraft; it asked nothing, and what it kept is the earlier plan's row, not its own
118
- const marker = readJson(sessionDir, `redraft-${n}.json`);
119
- const rowEdit = marker && marker.rowEdit && typeof marker.rowEdit === 'object' ? marker.rowEdit : null;
102
+ const marker = readRedraftMarker(sessionDir, n);
103
+ const rowEdit = marker?.rowEdit ?? null;
120
104
  rows.push({ ...planRow(sessionDir, `draft-${n}`, rowEdit ? 'rowedit' : marker ? 'redraft' : 'revise', n), ...(rowEdit ? { op: rowEdit.op, key: rowEdit.key } : {}) });
121
105
  if (!rowEdit) rows.push(...humanRows(sessionDir, `draft-${n}`));
122
106
  }
@@ -126,9 +110,9 @@ export function buildSetupRows({
126
110
  }
127
111
  // M4e amendment 36: the drafter's own "Not checked" list (the green plan folder's not-checked.json), kept word for word with its label. Not signed,
128
112
  // not in any hash. An unreadable or missing file is an empty list (a plan from before amendment 25 has none).
129
- const ncFile = readJson(planDir, 'not-checked.json');
113
+ const ncFile = readNotCheckedFile(planDir);
130
114
  // M16 item 5: the tag of each line that tells a list row rides the sign row (the Audit's Checks fold draws it); a plan with no list has none
131
- const notChecked = { ...notCheckedBlock(ncFile?.notChecked), ...(ncFile?.by && typeof ncFile.by === 'object' && !Array.isArray(ncFile.by) ? { by: ncFile.by } : {}) };
115
+ const notChecked = { ...notCheckedBlock(ncFile.notChecked), ...(ncFile.by ? { by: ncFile.by } : {}) };
132
116
  rows.push({
133
117
  kind: 'sign', n: 0, at: signedAt, signedBy, hash, flowHash: flowHash ?? null, notChecked,
134
118
  });
package/src/shaperows.js CHANGED
@@ -7,7 +7,7 @@
7
7
  // Rows of one shape line: a `[you]` row per `~` rule that has a field (the rule's own row, kind `rule`), an `[agent]` row per extra field (kind `shape`, key `L<n>.shape.<name>`), and the line's `[default]` row (key
8
8
  // `L<n>.$shape`): the answer is a list of items, with the item count when the person's words gave one.
9
9
  import { createRubric, rubricVocabulary } from 'bareguard';
10
- import { lineRules } from './pagebits.js';
10
+ import { lineRules, isAmountShape } from './pagebits.js';
11
11
  import { nameWhy, shapeNameRules, SHAPE_KINDS } from './shapemenu.js';
12
12
  import { countCheck } from './blockpick.js';
13
13
 
@@ -196,7 +196,7 @@ export function shapeItemCheck(part, id, factPart = null) {
196
196
  const count = facts !== null && factCounted ? {} : { ...(Number.isInteger(part.minItems) ? { minItems: part.minItems } : {}), ...(Number.isInteger(part.maxItems) ? { maxItems: part.maxItems } : {}) };
197
197
  const fields = facts === null ? own : {
198
198
  quote: { kind: 'text', required: true },
199
- values: { kind: 'object', fields: Object.fromEntries(facts.map((f) => [String(f.name), f.shape === 'money' || f.shape === 'number' ? { kind: 'number', fromText: true } : { kind: 'text' }])) },
199
+ values: { kind: 'object', fields: Object.fromEntries(facts.map((f) => [String(f.name), isAmountShape(f.shape) ? { kind: 'number', fromText: true } : { kind: 'text' }])) },
200
200
  ...own,
201
201
  };
202
202
  return { id, rule: 'itemShape', field: SHAPE_FIELD, ...count, fields };
package/src/sheetblock.js CHANGED
@@ -13,7 +13,7 @@ import { rubricVocabulary } from 'bareguard';
13
13
  import { lineRules } from './pagebits.js';
14
14
  import { sheetCheckSentence } from './sheetchecks.js';
15
15
  import { isColumnChoiceRule } from './sheetoffer.js';
16
- import { NO_VALUE_WHY } from './ticketrows.js';
16
+ import { REASON } from './reasons.js';
17
17
  import { isRec } from './isrec.js';
18
18
 
19
19
  /** the short plain name of each bareguard op (the ONE table; a test fails when bareguard gains an op this table does not name). `noDuplicates` and `noEmpty` add the column. */
@@ -131,7 +131,7 @@ export function sheetLineBlocks({ declaration, lines, csvRoles = [], record }) {
131
131
  export function uncoveredRules(declaration, lines, csvRoles, built) {
132
132
  if (csvRoles.length === 0) return [];
133
133
  return sheetLineBlocks({ declaration, lines, csvRoles }).flatMap((b) => (b.notChecked === 'none' ? [] : b.notChecked
134
- .map((r) => `line ${b.line}: "${r}" \u2014 ${built?.notChecked[`line ${b.line}: "${r}"`] ?? NO_VALUE_WHY}`)));
134
+ .map((r) => `line ${b.line}: "${r}" \u2014 ${built?.notChecked[`line ${b.line}: "${r}"`] ?? REASON.noPick}`)));
135
135
  }
136
136
 
137
137
  /** @param {any} arbiter @returns {string[]} the roles of the signed sources that are a CSV file (the sheets a check reads) */
package/src/sheetbuild.js CHANGED
@@ -9,14 +9,14 @@
9
9
  // One writer per field: `id`, `claim`, `covers` and `table` (when absent and the line reads one sheet) are assigned here. A rule row's id is `l<line>r<rules>`, an agent row's `l<line>a<k>`; the claim is the id.
10
10
  // What this throws away: a suggestion's `id`, `claim`, `text` (and its `covers`: an agent row's is only the rule no rule row holds); a refused suggestion's check (only its reason is kept, on the rules it named).
11
11
  // Third outcomes, named: a suggestion that is not an object, names no rule or op bareguard has, a table it cannot read, a column that is no header: refused with that helper's words; a rule that no
12
- // check holds is Not checked with the last refusal that named it, or the no-pick sentence (`NO_VALUE_WHY`).
12
+ // check holds is Not checked with the last refusal that named it, or the no-pick sentence (`REASON.noPick`).
13
13
  import { rubricVocabulary, claimSchema, groundedLiterals } from 'bareguard';
14
14
  import { SHEET_RULES, sheetCheckColumns, sheetCheckReds, bareguardChecks } from './sheetchecks.js';
15
15
  import { tableChecksFailingOnInput } from './sheetrun.js';
16
16
  import { isColumnChoiceRule } from './sheetoffer.js';
17
17
  import { rulesOfLine } from './sheetblock.js';
18
18
  import { wordsSaidOn } from './pagebits.js';
19
- import { NO_VALUE_WHY } from './ticketrows.js';
19
+ import { REASON } from './reasons.js';
20
20
 
21
21
  const V = /** @type {any} */ (rubricVocabulary);
22
22
  const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
@@ -101,7 +101,7 @@ export async function buildSheetLine({ line, tables, suggestions }) {
101
101
  if (isColumnChoiceRule(text)) return { rule: n, text, state: 'column', reason: null, id: null };
102
102
  if (held.has(n)) return { rule: n, text, state: 'built', reason: null, id: /** @type {string} */ (held.get(n)) };
103
103
  if (coveredByAgent.has(n)) return { rule: n, text, state: 'agent-row', reason: null, id: /** @type {string} */ (coveredByAgent.get(n)) };
104
- return { rule: n, text, state: 'not-checked', reason: refusedFor.get(n) ?? NO_VALUE_WHY, id: null };
104
+ return { rule: n, text, state: 'not-checked', reason: refusedFor.get(n) ?? REASON.noPick, id: null };
105
105
  });
106
106
  return { rows, ruleRows, agentRows, checks: [...ruleRows, ...agentRows].map((p) => p.check), refused };
107
107
  }
@@ -113,7 +113,7 @@ export async function buildSheetLine({ line, tables, suggestions }) {
113
113
  * then Not checked with the no-pick sentence, never silently nothing). A suggestion that names no sheet line, or is not an object, is refused and listed with its helper.
114
114
  * @param {{lines: {n: number, text?: string, rules?: string[], guardrail?: string, rule?: string}[], tables: Record<string, {header: string[], rows: any[]}>, suggestions: any[]}} o
115
115
  * @returns {Promise<{built: Record<number, Awaited<ReturnType<typeof buildSheetLine>>>, checks: any[], notChecked: Record<string, string>, refused: {line: number|null, helper: string, why: string}[]}>}
116
- * `notChecked`: `line N: "rule"` -> the refusal that named it (or `NO_VALUE_WHY`), for each rule of a sheet line that no check holds
116
+ * `notChecked`: `line N: "rule"` -> the refusal that named it (or `REASON.noPick`), for each rule of a sheet line that no check holds
117
117
  */
118
118
  export async function buildSheetChecks({ lines, tables, suggestions }) {
119
119
  /** @type {Record<number, Awaited<ReturnType<typeof buildSheetLine>>>} */
@@ -154,7 +154,7 @@ export function unbuiltSheetLines({ declaration, lines, roles, notChecked }) {
154
154
  const line = lines.find((l) => l.n === st.fromLine);
155
155
  const rules = line ? rulesOfLine(line).filter((r) => !isColumnChoiceRule(r)) : [];
156
156
  if (rules.length === 0) continue;
157
- unbuilt.push({ line: st.fromLine, lost: rules.map((r) => `line ${st.fromLine}: "${r}" \u2014 ${notChecked[`line ${st.fromLine}: "${r}"`] ?? NO_VALUE_WHY}`) });
157
+ unbuilt.push({ line: st.fromLine, lost: rules.map((r) => `line ${st.fromLine}: "${r}" \u2014 ${notChecked[`line ${st.fromLine}: "${r}"`] ?? REASON.noPick}`) });
158
158
  }
159
159
  return unbuilt;
160
160
  }
package/src/sheetrun.js CHANGED
@@ -5,11 +5,10 @@
5
5
  // Third outcomes, each named, never green: a sheet the run recorded no fingerprint for, a frozen copy that is missing, a table that no longer gives the recorded
6
6
  // `tableSha` (bareguard stops the check; the red names the input), any other stopped check.
7
7
  // Throws away: bareguard's `full` (expected values, evidence) is not kept - the red keeps the gaps, which name rows and counts and never a cell's text.
8
- import { basename } from 'node:path';
9
8
  import { createRubric, checkStep, runTableChecks, renderGaps, tableSha } from 'bareguard';
10
9
  import { parseCsv, sheetTable } from './csv.js';
11
- import { readFileInside } from './flow.js';
12
- import { readRunInputs } from './runfile.js';
10
+ import { readFileInside } from './inside.js';
11
+ import { readRunInputs, frozenRel } from './runfile.js';
13
12
  import { sheetCheckSentence, bareguardChecks } from './sheetchecks.js';
14
13
  import { sheetCheckName, sheetFoundWords } from './sheetblock.js';
15
14
  import { isRec } from './isrec.js';
@@ -30,7 +29,7 @@ export function sheetRolesOf(steps) {
30
29
  * @param {string} runDir @param {string} name the frozen file's name @returns {string|null}
31
30
  */
32
31
  export function tableShaOfFrozen(runDir, name) {
33
- const file = readFileInside(runDir, `inputs/${name}`);
32
+ const file = readFileInside(runDir, frozenRel(name));
34
33
  return file.ok ? tableSha(sheetTable(parseCsv(file.text))) : null;
35
34
  }
36
35
 
@@ -55,7 +54,7 @@ export function readRunSheets(runDir, checks) {
55
54
  const entry = Array.isArray(entries) ? entries.find((e) => e?.id === role) : undefined;
56
55
  if (!entry || typeof entry.frozen !== 'string') return { ok: false, red: `input "${role}": this run froze no input with that name` };
57
56
  if (typeof entry.tableSha !== 'string' || !SHA_RE.test(entry.tableSha)) return { ok: false, red: `input "${role}": this run recorded no table fingerprint for it at its start` };
58
- const file = readFileInside(runDir, `inputs/${basename(entry.frozen)}`);
57
+ const file = readFileInside(runDir, frozenRel(entry.frozen));
59
58
  if (!file.ok) return { ok: false, red: file.missing ? `input "${role}": the frozen copy is missing` : `input "${role}": ${file.red}` };
60
59
  tables[role] = sheetTable(parseCsv(file.text));
61
60
  inputs.push({ name: role, sha256: entry.tableSha });
@@ -7,6 +7,7 @@
7
7
  // The table here is fwdloop's own: it is keyed by the outcomes fwdloop's history row can hold.
8
8
  import { homedir } from 'node:os';
9
9
  import { basename } from 'node:path';
10
+ import { isFileKind } from './trigger-files.js';
10
11
 
11
12
  /** @typedef {import('./trigger-line.js').Trigger} Trigger */
12
13
 
@@ -278,7 +279,7 @@ export function scheduleBlockWords(f) {
278
279
  if (head === null || tr === null) return { line1: 'By hand', line2: null, red: false };
279
280
  if (f.waiting === true) return { line1: head, line2: SCHEDULE_WAITING_SAY, red: false, grey: true };
280
281
  if (f.lookProblem) return { line1: head, line2: `last look ${shortStamp(f.lookProblem.at)} · ${lookProblemWords(f.lookProblem)}`, red: true }; // M13 item 9b.3
281
- const file = tr.kind === 'new-file' || tr.kind === 'file-updated';
282
+ const file = isFileKind(tr.kind);
282
283
  const next = tr.kind === 'new-ticket' ? 'next: waiting for a new ticket' : file ? 'next: waiting for a new file' : (f.nextSlotMs !== null && f.armed ? `next ${dayStamp(f.nextSlotMs)}` : 'next: not armed yet');
283
284
  const p = f.problem;
284
285
  if (p) {
package/src/thinking.js CHANGED
@@ -38,6 +38,9 @@ export function worstThinkingStatus(statuses) {
38
38
  return WORST_FIRST.find((s) => statuses.includes(s)) ?? null;
39
39
  }
40
40
 
41
+ /** M20 am8: the one question "is this a thinking mode" (on or off) @param {unknown} mode @returns {boolean} */
42
+ export const isThinkingMode = (mode) => mode === 'on' || mode === 'off';
43
+
41
44
  /** The note beside the Chat "Thinking on" box, before any draft, for a model bareagent has not checked (M4d am11 item 2). */
42
45
  export const THINKING_UNVERIFIED_SAY = 'thinking off (not verified for this model)';
43
46
 
@@ -65,8 +68,8 @@ export function thinkingSay(status) {
65
68
  export function thinkingTryWords(thinking) {
66
69
  if (thinking === null || typeof thinking !== 'object') return null;
67
70
  const status = typeof thinking.status === 'string' ? thinking.status : null;
68
- if (status === null) return thinking.asked === 'on' || thinking.asked === 'off' ? `thinking ${thinking.asked} (no reply)` : null;
69
- if (status === 'applied') return thinking.asked === 'on' || thinking.asked === 'off' ? `thinking ${thinking.asked}` : null;
71
+ if (status === null) return isThinkingMode(thinking.asked) ? `thinking ${thinking.asked} (no reply)` : null;
72
+ if (status === 'applied') return isThinkingMode(thinking.asked) ? `thinking ${thinking.asked}` : null;
70
73
  return thinkingSay(status);
71
74
  }
72
75
 
package/src/ticketrows.js CHANGED
@@ -3,20 +3,17 @@
3
3
  // (src/declaration.js checkTicketFilter / checkTicketWatch) and writes the declaration's field from it, only when a rule of that kind is on the job. This file is the ONE writer of a ticket row,
4
4
  // its signed fields, its card words and its proof. A job with no ticket rows (a plan signed before M17) is not examined: its filter and watch run exactly as signed.
5
5
  // What this throws away: the filter's and watch's values (they stay in the declaration); a row keeps its line, rule number, tag, state and reason.
6
- import { checkTicketFilter, checkTicketWatch, isCountGuardrail } from './declaration.js';
6
+ import { checkTicketFilter, checkTicketWatch } from './declaration.js';
7
+ import { isCountable } from './blockpick.js';
7
8
  import { isRec } from './isrec.js';
8
-
9
- /** @type {readonly ('ticketFilter'|'ticketWatch')[]} */
10
- export const TICKET_FIELDS = Object.freeze(['ticketFilter', 'ticketWatch']);
11
- /** the Not-checked reason of a ticket rule no legal value was suggested for (the block's own noPick sentence is used by the caller's words) */
12
- export const NO_VALUE_WHY = 'No check was picked for it, so you judge it at Accept.';
9
+ import { REASON } from './reasons.js';
13
10
 
14
11
  /**
15
12
  * Which signed field a Tickets rule is the check of: `ticketWatch` (a state or labels change), `ticketFilter` (a priority P0 to P3 or a label), or null (a content rule or a count).
16
13
  * @param {string} t the rule's words @returns {'ticketFilter'|'ticketWatch'|null}
17
14
  */
18
15
  export function ticketRuleField(t) {
19
- if (isCountGuardrail(t)) return null;
16
+ if (isCountable(t)) return null;
20
17
  if (/\b(?:state|labels)\b[^;]*\bchange/i.test(t)) return 'ticketWatch';
21
18
  if (/\bp[0-3]\b/i.test(t) || /\blabel(?:l?ed|s)?\b/i.test(t)) return 'ticketFilter';
22
19
  return null;
@@ -61,9 +58,9 @@ export function ticketRowsOf({ declaration, lines }) {
61
58
  if (field === null) return;
62
59
  const key = ticketRowKey(l.n, i + 1, field);
63
60
  const has = Object.hasOwn(declaration, field);
64
- signed.push({ line: l.n, key, from: 'rule', by: 'you', kind: 'ticket', state: has ? 'built' : 'not-checked', rule: i + 1, field, ...(has ? {} : { reason: NO_VALUE_WHY }) });
65
- card.push({ key, line: l.n, by: 'you', state: has ? 'built' : 'not-checked', text: has ? `"${t}" -> ${ticketWords(field, declaration[field])}` : `"${t}"`, reason: has ? null : NO_VALUE_WHY, drop: false });
66
- if (!has) notChecked.push({ line: l.n, rule: t, reason: NO_VALUE_WHY });
61
+ signed.push({ line: l.n, key, from: 'rule', by: 'you', kind: 'ticket', state: has ? 'built' : 'not-checked', rule: i + 1, field, ...(has ? {} : { reason: REASON.noPick }) });
62
+ card.push({ key, line: l.n, by: 'you', state: has ? 'built' : 'not-checked', text: has ? `"${t}" -> ${ticketWords(field, declaration[field])}` : `"${t}"`, reason: has ? null : REASON.noPick, drop: false });
63
+ if (!has) notChecked.push({ line: l.n, rule: t, reason: REASON.noPick });
67
64
  });
68
65
  }
69
66
  return { signed, card, notChecked };
@@ -79,21 +76,3 @@ export function withTicketRows({ declaration, lines }) {
79
76
  if (tickets.signed.length === 0) return { declaration, tickets };
80
77
  return { declaration: { ...declaration, checkList: [...(base ?? []), ...tickets.signed] }, tickets };
81
78
  }
82
-
83
- /**
84
- * The proof of a plan whose list has ticket rows (a plan with none is not examined): a built ticket row needs the declaration's field, and a field the declaration holds needs a built row for it.
85
- * @param {any} declaration @returns {string[]}
86
- */
87
- export function ticketListReds(declaration) {
88
- const list = isRec(declaration) && Array.isArray(declaration.checkList) ? declaration.checkList.filter((/** @type {any} */ r) => isRec(r) && r.kind === 'ticket') : [];
89
- if (list.length === 0) return [];
90
- /** @type {string[]} */
91
- const reds = [];
92
- for (const f of TICKET_FIELDS) {
93
- const built = list.some((/** @type {any} */ r) => r.field === f && r.state === 'built');
94
- const has = Object.hasOwn(declaration, f);
95
- if (built && !has) reds.push(`declaration: checkList: a row says "${f}" is its check, but the plan has no "${f}". Nothing was signed - draft again.`);
96
- if (has && !built) reds.push(`declaration: "${f}" is not the check of any rule on the list. Nothing was signed - draft again.`);
97
- }
98
- return reds;
99
- }
@@ -11,12 +11,7 @@
11
11
  // { id:'armed:<ms>', kind:'armed', at } the trigger was set: the starting point
12
12
  // { id:'fire:<slotMs>', kind:'fire', slot, at, catchUp, missed } one run started for that slot
13
13
  // Starting a run is NOT this file; the caller does it after `recordFire`.
14
- import {
15
- mkdirSync,
16
- } from 'node:fs';
17
- import { dirname } from 'node:path';
18
-
19
- import { appendRow, ledgerText } from './jsonl-append.js';
14
+ import { appendTriggerLedger } from './jsonl-append.js';
20
15
 
21
16
  /** @typedef {{kind:'daily'|'weekdays', hour:number, minute:number} | {kind:'weekly', day:string, hour:number, minute:number}} Schedule */
22
17
  /** @typedef {{id:string, kind:'armed'|'fire', at:number, slot?:number, catchUp?:boolean, missed?:number, sig?:string, ticketN?:number}} ClockRow */
@@ -25,6 +20,11 @@ import { appendRow, ledgerText } from './jsonl-append.js';
25
20
  /** A slot seen MORE than this after its set time is a catch-up (M9 am2 item 1). Exactly this late is on time. */
26
21
  export const GRACE_MS = 120_000;
27
22
 
23
+ /** M20 am6: the one list of clock schedule kinds, and the one question "is this a clock kind" */
24
+ export const CLOCK_KINDS = Object.freeze(['daily', 'weekdays', 'weekly']);
25
+ /** @param {unknown} kind @returns {boolean} */
26
+ export const isClockKind = (kind) => CLOCK_KINDS.includes(/** @type {string} */ (kind));
27
+
28
28
  const DAYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
29
29
 
30
30
  /**
@@ -35,8 +35,7 @@ const DAYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
35
35
  export function validateSchedule(s) {
36
36
  if (!s || typeof s !== 'object' || Array.isArray(s)) throw new Error('schedule must be an object like { kind, hour, minute }, not text');
37
37
  const o = /** @type {Record<string, unknown>} */ (s);
38
- const kinds = ['daily', 'weekdays', 'weekly'];
39
- if (!kinds.includes(/** @type {string} */ (o.kind))) throw new Error(`schedule kind "${o.kind}" is not one of ${kinds.join(', ')}`);
38
+ if (!isClockKind(o.kind)) throw new Error(`schedule kind "${o.kind}" is not one of ${CLOCK_KINDS.join(', ')}`);
40
39
  const allowed = o.kind === 'weekly' ? ['kind', 'day', 'hour', 'minute'] : ['kind', 'hour', 'minute'];
41
40
  for (const k of Object.keys(o)) if (!allowed.includes(k)) throw new Error(`schedule field "${k}" is not allowed on a ${o.kind} schedule`);
42
41
  const hour = o.hour; const minute = o.minute;
@@ -116,22 +115,9 @@ export function nextSlot(schedule, afterMs) {
116
115
  return /** @type {number} */ (found);
117
116
  }
118
117
 
119
- /** @param {string} file @param {string} [sig] M9 am20: only the rows of that schedule signing (the one schedule ledger carries every signing's rows); absent = every row @returns {ClockRow[]} every row on disk that parses, oldest first; a missing file is no rows; a line a crash tore mid-append is skipped (`appendOnce` starts each append on a fresh line, so it never glues onto the next row). */
120
- export function readRows(file, sig) {
121
- const rows = ledgerText(file).split('\n').filter(Boolean).flatMap((l) => { try { return [JSON.parse(l)]; } catch { return []; } });
122
- return sig === undefined ? rows : rows.filter((r) => r.sig === sig);
123
- }
124
-
125
- /** Append one row; a row whose id is already on disk (under the same signing) is refused (write-once). @param {string} file @param {ClockRow} row @param {string} [sig] stamped on the row (M9 am20) */
126
- function appendOnce(file, row, sig) {
127
- if (readRows(file, sig).some((r) => r.id === row.id)) throw new Error(`ledger row ${row.id} already written`);
128
- mkdirSync(dirname(file), { recursive: true });
129
- appendRow(file, sig === undefined ? row : { ...row, sig });
130
- }
131
-
132
118
  /** The trigger was set at `now`: no slot before this ever fires. M13 piece 5: `ticketN` = the highest ticket number the first green run read; a ticket schedule's first look baselines only tickets up to it. @param {string} file @param {number} now @param {string} [sig] @param {number} [ticketN] */
133
119
  export function armTrigger(file, now, sig, ticketN) {
134
- appendOnce(file, { id: `armed:${now}`, kind: 'armed', at: now, ...(Number.isInteger(ticketN) ? { ticketN } : {}) }, sig);
120
+ appendTriggerLedger(file, { id: `armed:${now}`, kind: 'armed', at: now, ...(Number.isInteger(ticketN) ? { ticketN } : {}) }, sig, { throwIfWritten: true });
135
121
  }
136
122
 
137
123
  /**
@@ -140,5 +126,5 @@ export function armTrigger(file, now, sig, ticketN) {
140
126
  */
141
127
  export function recordFire(file, d, now, sig) {
142
128
  if (!d.fire || d.slot === undefined) throw new Error('recordFire needs a due result with fire true');
143
- appendOnce(file, { id: `fire:${d.slot}`, kind: 'fire', slot: d.slot, at: now, catchUp: d.catchUp, missed: d.missed }, sig);
129
+ appendTriggerLedger(file, { id: `fire:${d.slot}`, kind: 'fire', slot: d.slot, at: now, catchUp: d.catchUp, missed: d.missed }, sig, { throwIfWritten: true });
144
130
  }
@@ -14,35 +14,26 @@
14
14
  // one. 'dropped' = it was deleted / changed before its turn. A sha with a `ran` row never arrives again, whatever its name or mtime; see `arrives` for baseline / queued / dropped.
15
15
  // poll() writes nothing: it only reports finished files whose sha is new.
16
16
  import {
17
- existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync,
17
+ existsSync, lstatSync, readFileSync, readdirSync, realpathSync,
18
18
  } from 'node:fs';
19
19
  import { basename, dirname, join } from 'node:path';
20
20
  import { createHash } from 'node:crypto';
21
21
  import { compareNatural } from './natural.js';
22
22
 
23
- import { appendRow, ledgerText } from './jsonl-append.js';
23
+ import { appendTriggerLedger, readTriggerLedger } from './jsonl-append.js';
24
24
 
25
25
  /** @typedef {{id:string, kind:'baseline'|'arrived'|'ran'|'dropped', sha:string, name:string, size:number, at:number, path?:string, why?:string, of?:string, sig?:string}} SeenRow */
26
26
  /** @typedef {{path:string, sha:string, size:number}} ToRun */
27
27
  /** @typedef {{path:string, why:string}} Refused */
28
28
 
29
+ /** M20 am7: the one list of file schedule kinds, and the one question "is this a file kind" */
30
+ export const FILE_KINDS = Object.freeze(['file-updated', 'new-file']);
31
+ /** @param {unknown} kind @returns {boolean} */
32
+ export const isFileKind = (kind) => FILE_KINDS.includes(/** @type {string} */ (kind));
33
+
29
34
  /** Consecutive polls with the same size and mtime before a file is taken. (Two matches in a row = taken on the third sighting.) */
30
35
  export const STABLE_POLLS = 2;
31
36
 
32
- /** Every row that parses; a line a crash tore mid-append is skipped (it counts as not written). `appendSeen` starts each append on a fresh line, so a torn line can never glue onto the next row. @param {string} file @param {string} [sig] M9 am20: only the rows of that schedule signing (the one schedule ledger carries every signing's rows); absent = every row @returns {SeenRow[]} */
33
- export function readSeen(file, sig) {
34
- const rows = ledgerText(file).split('\n').filter(Boolean).flatMap((l) => { try { return [JSON.parse(l)]; } catch { return []; } });
35
- return sig === undefined ? rows : rows.filter((r) => r.sig === sig);
36
- }
37
-
38
- /** The ONE appender: write-once by id within a signing (a second row with the same id is not written). Starts on a fresh line when the file does not end in a newline (a torn last line). @param {string} file @param {SeenRow} row @param {string} [sig] stamped on the row @returns {boolean} written */
39
- export function appendSeen(file, row, sig) {
40
- if (readSeen(file, sig).some((r) => r.id === row.id)) return false;
41
- mkdirSync(dirname(file), { recursive: true });
42
- appendRow(file, sig === undefined ? row : { ...row, sig });
43
- return true;
44
- }
45
-
46
37
  /** Rows of one sha, file order. @param {SeenRow[]} rows @param {string} sha */
47
38
  const ofSha = (rows, sha) => rows.filter((r) => r.sha === sha);
48
39
  /** An arrived row is still waiting: neither its sha ran nor a dropped row names it. @param {SeenRow[]} rows @param {SeenRow} a */
@@ -65,17 +56,17 @@ function arrives(rows, it, mode) {
65
56
 
66
57
  /** Arrived rows are never overwritten: the 2nd arrival of a sha (after a drop) gets its own id. @param {string} ledger @param {ToRun & {name?:string}} item @param {number} at the scheduler's clock, never the file's mtime @param {string} [sig] */
67
58
  export function recordArrived(ledger, item, at, sig) {
68
- const rows = readSeen(ledger, sig);
59
+ const rows = readTriggerLedger(ledger, sig);
69
60
  if (rows.some((r) => r.sha === item.sha && (r.kind === 'ran' || waiting(rows, r)))) return false; // one writer decides: ran or already queued
70
61
  const n = rows.filter((r) => r.kind === 'arrived' && r.sha === item.sha).length;
71
- return appendSeen(ledger, { id: n ? `arrived:${item.sha}:${n}` : `arrived:${item.sha}`, kind: 'arrived', sha: item.sha, name: basename(item.path), size: item.size, path: item.path, at }, sig);
62
+ return appendTriggerLedger(ledger, { id: n ? `arrived:${item.sha}:${n}` : `arrived:${item.sha}`, kind: 'arrived', sha: item.sha, name: basename(item.path), size: item.size, path: item.path, at }, sig);
72
63
  }
73
64
  /** Call immediately before the run is started. @param {string} ledger @param {{sha:string, path:string, size:number}} item @param {number} at @param {string} [sig] */
74
- export const recordRan = (ledger, item, at, sig) => appendSeen(ledger, { id: `ran:${item.sha}`, kind: 'ran', sha: item.sha, name: basename(item.path), size: item.size, at }, sig);
65
+ export const recordRan = (ledger, item, at, sig) => appendTriggerLedger(ledger, { id: `ran:${item.sha}`, kind: 'ran', sha: item.sha, name: basename(item.path), size: item.size, at }, sig);
75
66
  /** `of` = the arrived row it cancels (item.id when a queue row is passed). @param {string} ledger @param {{sha:string, path:string, size:number, id?:string}} item @param {'deleted'|'changed'|'schedule-changed'|'carried'} why @param {number} at @param {string} [sig] */
76
67
  export function recordDropped(ledger, item, why, at, sig) {
77
68
  const of = item.id ?? `arrived:${item.sha}`;
78
- return appendSeen(ledger, { id: `dropped:${of}`, kind: 'dropped', sha: item.sha, name: basename(item.path), size: item.size, why, at, of }, sig);
69
+ return appendTriggerLedger(ledger, { id: `dropped:${of}`, kind: 'dropped', sha: item.sha, name: basename(item.path), size: item.size, why, at, of }, sig);
79
70
  }
80
71
 
81
72
  /**
@@ -124,6 +115,23 @@ export function checkTarget(mode, target) {
124
115
  }
125
116
  }
126
117
 
118
+ /**
119
+ * Is a file or folder trigger's target usable now? The words say what is wrong, without the closing "Nothing was changed."; null = fine. A file that does not exist yet may arrive
120
+ * (`checkTarget` allows it), but its folder must be there: a typo is caught now, not never.
121
+ * @param {{kind: 'file-updated', path: string}|{kind: 'new-file', folder: string}} trigger @returns {string|null}
122
+ */
123
+ export function fileTriggerWhy(trigger) {
124
+ try {
125
+ checkTarget(trigger.kind === 'new-file' ? 'new' : 'updated', trigger.kind === 'new-file' ? trigger.folder : trigger.path);
126
+ } catch (e) {
127
+ return `${/** @type {Error} */ (e).message}.`;
128
+ }
129
+ if (trigger.kind === 'file-updated') {
130
+ try { realpathSync(dirname(trigger.path)); } catch { return `The folder of ${trigger.path} does not exist.`; }
131
+ }
132
+ return null;
133
+ }
134
+
127
135
  /**
128
136
  * M9 am16: does a trigger on this target still watch this file? New: the file sits directly in the same (real) folder. Updated: it is the same (real) file. False when the target cannot be resolved.
129
137
  * @param {'new'|'updated'} mode @param {string} target @param {string} filePath a queued file's path as the watcher recorded it (a real path)
@@ -179,7 +187,7 @@ export function createFileTrigger({ mode, target, ledger, sig }) {
179
187
  for (const p of candidates().files) {
180
188
  const buf = readFileSync(p);
181
189
  const sha = sha256(buf);
182
- appendSeen(ledger, { id: `baseline:${sha}:${basename(p)}`, kind: 'baseline', sha, name: basename(p), size: buf.length, at: Date.now() }, sig); // write-once: re-arming adds nothing
190
+ appendTriggerLedger(ledger, { id: `baseline:${sha}:${basename(p)}`, kind: 'baseline', sha, name: basename(p), size: buf.length, at: Date.now() }, sig); // write-once: re-arming adds nothing
183
191
  }
184
192
  }
185
193
 
@@ -189,7 +197,7 @@ export function createFileTrigger({ mode, target, ledger, sig }) {
189
197
  const st2 = lstatSync(p);
190
198
  if (`${st2.size}:${st2.mtimeMs}` !== t.key) return 'changed'; // changed while reading: retry next poll
191
199
  const sha = sha256(buf);
192
- if (!arrives(readSeen(ledger, sig), { sha }, mode)) return null; // ran, still queued, or still the starting point
200
+ if (!arrives(readTriggerLedger(ledger, sig), { sha }, mode)) return null; // ran, still queued, or still the starting point
193
201
  return { path: p, sha, size: buf.length };
194
202
  }
195
203