fwdloop 0.4.0 → 0.5.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fwdloop",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Describe a job as steps and guardrails; an agent builds the workflow, pauses for humans where you said, checks every step happened, and reruns it under budgets it cannot touch.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
package/src/ask.js ADDED
@@ -0,0 +1,97 @@
1
+ // M2 piece 2 (docs/wiki/the-module-ladder.md, "M2 — scope, exit, negative —
2
+ // SIGNED", scope item 6): the file-checkpoint ask, in-process. Writes
3
+ // `ask.json` (question + evidence + askedAt + attempt) into the run dir and
4
+ // polls for `answer.json` (`{ decision: accept|reject|rerun, reason?,
5
+ // answeredAt }`). Consumed exactly once (renamed away on read); a stale
6
+ // answer — `answeredAt` older than THIS ask's `askedAt` — is quarantined
7
+ // (renamed to `answer.stale.<n>.json`, audited `stale-answer-ignored`) and
8
+ // never applied; a timeout returns `{ decision: 'timeout' }`, which
9
+ // `src/runner.js` must treat as a halt (a pause spends nothing).
10
+ //
11
+ // borrowed-from: fwdloop poc/m0/runner.mjs@76a3607 (`checkpointAsk`'s file
12
+ // protocol: `ask.json` out / poll `answer.json`, and the "ASK OPEN" stderr
13
+ // line so a human watching knows a run is waiting on them) and
14
+ // fwdloop poc/m0/answer.mjs@76a3607 (the answer file's own shape). Rewritten
15
+ // off bare-agent's `Checkpoint` (M0's dependency) onto a plain poll loop —
16
+ // M2's signed scope (item 6) calls for "M0's file checkpoint, in-process",
17
+ // not a second Checkpoint instance layered on top of the same file protocol.
18
+
19
+ import {
20
+ existsSync, mkdirSync, readFileSync, renameSync, writeFileSync,
21
+ } from 'node:fs';
22
+ import { join } from 'node:path';
23
+
24
+ import { appendAudit } from './books.js';
25
+
26
+ function sleep(ms) {
27
+ return new Promise((resolve) => { setTimeout(resolve, ms); });
28
+ }
29
+
30
+ function safeStamp(iso) {
31
+ return String(iso).replace(/[^0-9A-Za-z]/g, '-');
32
+ }
33
+
34
+ /**
35
+ * @param {{ timeoutMs?: number, pollMs?: number, clock?: () => string, writeLine?: (line:string) => void }} [opts]
36
+ * @returns {(opts:{question:string, evidence:unknown, runDir:string}) => Promise<{decision:string, reason?:string}>}
37
+ */
38
+ export function makeFileAskStep({
39
+ timeoutMs = 120_000,
40
+ pollMs = 500,
41
+ clock = () => new Date().toISOString(),
42
+ writeLine = (line) => { process.stderr.write(`${line}\n`); },
43
+ } = {}) {
44
+ let attemptCounter = 0;
45
+
46
+ return async function fileAskStep({ question, evidence, runDir }) {
47
+ attemptCounter += 1;
48
+ const attempt = attemptCounter;
49
+
50
+ mkdirSync(runDir, { recursive: true });
51
+ const askPath = join(runDir, 'ask.json');
52
+ const answerPath = join(runDir, 'answer.json');
53
+ const askedAt = clock();
54
+
55
+ writeFileSync(askPath, JSON.stringify({
56
+ question, evidence, askedAt, attempt,
57
+ }, null, 2));
58
+ writeLine(`ASK OPEN (expires in ${Math.round(timeoutMs / 1000)}s): ${question} — answer by writing ${answerPath}`);
59
+
60
+ const deadline = Date.now() + timeoutMs;
61
+ let staleCount = 0;
62
+
63
+ for (;;) {
64
+ if (existsSync(answerPath)) {
65
+ let raw = null;
66
+ try { raw = readFileSync(answerPath, 'utf8'); } catch { raw = null; }
67
+ let parsed = null;
68
+ if (raw !== null) { try { parsed = JSON.parse(raw); } catch { parsed = null; } }
69
+
70
+ if (parsed) {
71
+ const { answeredAt } = parsed;
72
+ const isStale = typeof answeredAt === 'string' && typeof askedAt === 'string' && answeredAt < askedAt;
73
+ if (isStale) {
74
+ staleCount += 1;
75
+ let staleName = join(runDir, `answer.stale.${staleCount}.json`);
76
+ while (existsSync(staleName)) { staleCount += 1; staleName = join(runDir, `answer.stale.${staleCount}.json`); }
77
+ renameSync(answerPath, staleName);
78
+ appendAudit(runDir, {
79
+ step: 'ask', attempt, class: null, verdict: 'stale-answer-ignored', gap: `answeredAt ${answeredAt} predates this ask's askedAt ${askedAt}`, usd: 0, spendComplete: true, wallMs: 0, model: null, modelMatch: null, strike: false,
80
+ });
81
+ // Keep polling — a stale file quarantined does not mean THIS
82
+ // ask has been answered.
83
+ } else {
84
+ renameSync(answerPath, join(runDir, `answer.${safeStamp(askedAt)}.consumed.json`));
85
+ return { decision: parsed.decision, reason: parsed.reason };
86
+ }
87
+ }
88
+ }
89
+
90
+ if (Date.now() >= deadline) {
91
+ return { decision: 'timeout' };
92
+ }
93
+ // eslint-disable-next-line no-await-in-loop
94
+ await sleep(pollMs);
95
+ }
96
+ };
97
+ }
package/src/books.js ADDED
@@ -0,0 +1,76 @@
1
+ // M2 piece 1 (docs/wiki/the-module-ladder.md, "M2 — scope, exit, negative —
2
+ // SIGNED", scope item 9): the two append-only books. `runs/<run-id>/audit.jsonl`
3
+ // gets one row per attempt (plus one per ask and one per send); `flows/<name>/
4
+ // history.jsonl` gets one row per run. Each has exactly one writer — this
5
+ // module — so nothing else in src/ ever calls `appendFileSync` on either
6
+ // path a second time.
7
+ //
8
+ // borrowed-from: fwdloop poc/m0/redo.mjs@29caa83 (the `appendAudit` shape:
9
+ // `mkdirSync` the parent then `appendFileSync`, one JSON line) — generalised
10
+ // to the two typed rows M2 signs, never the `redo.mjs`-specific fields.
11
+ //
12
+ // Money honesty (M2 scope item 7, project rule "unknown cost is never
13
+ // rendered as 0"): a row's cost field must never be `undefined` (that would
14
+ // mean a caller silently did `cost ?? 0` upstream and this module can't tell
15
+ // the difference from a real zero any more) and a `null` cost — "unknown" —
16
+ // is only ever allowed alongside `spendComplete: false`. Both books apply
17
+ // this same rule to their own cost field (`usd` for audit, `spentUsd` for
18
+ // history); both throw (never silently coerce) on a violation, so a bad
19
+ // caller fails loudly at the one place that would otherwise hide it.
20
+
21
+ import { appendFileSync, mkdirSync } from 'node:fs';
22
+ import { dirname, join } from 'node:path';
23
+
24
+ function appendLine(filePath, row) {
25
+ mkdirSync(dirname(filePath), { recursive: true });
26
+ appendFileSync(filePath, `${JSON.stringify(row)}\n`);
27
+ }
28
+
29
+ /**
30
+ * Refuse (throw) a row whose cost field is `undefined` (never `?? 0` — the
31
+ * caller must say `null` on purpose for "unknown"), or whose cost field is
32
+ * `null` while `spendComplete` is not `false` (a `null` cost is only ever
33
+ * allowed alongside an explicit `spendComplete: false`). A numeric cost is
34
+ * allowed regardless of `spendComplete`.
35
+ */
36
+ function checkCostField(row, field, label) {
37
+ const value = row[field];
38
+ if (value === undefined) {
39
+ throw new Error(`${label}: "${field}" must not be undefined — never "?? 0"`);
40
+ }
41
+ if (value === null) {
42
+ if (row.spendComplete !== false) {
43
+ throw new Error(`${label}: "${field}" is null but spendComplete is not false — a null ${field} is only allowed with spendComplete:false`);
44
+ }
45
+ return;
46
+ }
47
+ if (typeof value !== 'number' || Number.isNaN(value)) {
48
+ throw new Error(`${label}: "${field}" must be a number or null, got ${JSON.stringify(value)}`);
49
+ }
50
+ }
51
+
52
+ /**
53
+ * One row per attempt (also used for one row per ask and one row per send —
54
+ * M2 scope item 9). `row` shape: `{ step, attempt, class, verdict, gap, usd,
55
+ * spendComplete, wallMs, model, modelMatch, strike }`. Append-only, one
56
+ * writer.
57
+ *
58
+ * @param {string} runDir
59
+ * @param {Record<string, any>} row
60
+ */
61
+ export function appendAudit(runDir, row) {
62
+ checkCostField(row, 'usd', 'appendAudit');
63
+ appendLine(join(runDir, 'audit.jsonl'), row);
64
+ }
65
+
66
+ /**
67
+ * One row per run. `row` shape: `{ runId, at, outcome, spentUsd,
68
+ * spendComplete, capUsd, wallMs, signatureHash }`. Append-only, one writer.
69
+ *
70
+ * @param {string} flowDir
71
+ * @param {Record<string, any>} row
72
+ */
73
+ export function appendHistory(flowDir, row) {
74
+ checkCostField(row, 'spentUsd', 'appendHistory');
75
+ appendLine(join(flowDir, 'history.jsonl'), row);
76
+ }
package/src/closers.js ADDED
@@ -0,0 +1,370 @@
1
+ // M2 piece 1 (docs/wiki/the-module-ladder.md, "M2 — scope, exit, negative —
2
+ // SIGNED", scope item 4): `closeByClass(step, artifact, ctx)` — the
3
+ // deterministic, $0 close, dispatched on the step's declared `close.class`.
4
+ //
5
+ // borrowed-from: fwdloop poc/m0/close.mjs@29caa83 (the closed formula
6
+ // grammar sum/count/min/max/sub/daysBetween; `parseNumeric`/`roundTo` —
7
+ // compare a stated figure to its source at the SOURCE's own decimal
8
+ // precision, never the stated figure's) and fwdloop poc/m0/shape.mjs@29caa83
9
+ // (`closeWordsAndSections`, F38 version — every failing check reported, not
10
+ // just the first). Rewritten against M2's own typed artifact contract below
11
+ // — src/ never imports from poc/ (CLAUDE.md: "borrow, never import").
12
+ //
13
+ // ---------------------------------------------------------------------------
14
+ // Artifact contracts (M2 scope item 4's own docblock requirement).
15
+ // ---------------------------------------------------------------------------
16
+ //
17
+ // GREEN step artifact: `{ fields: { <name>: { value, cite } } }`
18
+ // - `value`: the number, ISO date (`YYYY-MM-DD`) string, or exact text the
19
+ // step claims for this field.
20
+ // - `cite`: a string in one of two forms:
21
+ // "<artifactId>!<COL><ROW>" a cell in a 'cells'/'csv'-kind
22
+ // artifact already in `ctx.reads`
23
+ // (e.g. "aging_cells!E2").
24
+ // "<formula>(<arg>[,<arg>...])" formula ∈ {sum,count,min,max,sub,
25
+ // daysBetween}; each <arg> is a cell
26
+ // cite OR "#<fieldName>" naming an
27
+ // EARLIER field of this SAME
28
+ // artifact (fields resolve in
29
+ // declared order, never forward —
30
+ // same flat shape M0's citation-id
31
+ // inputs used; formulas never
32
+ // nest inside one string).
33
+ // `daysBetween(cite)` (one arg) computes days between that date and
34
+ // `ctx.businessDate`; `daysBetween(cite,cite)` (two args) computes days
35
+ // between the two — never a third form.
36
+ // A malformed field or an artifact shaped wrong is `unparseable` (a
37
+ // casualty, never a red — bareloop F17); an internal error while
38
+ // resolving is `crash`.
39
+ //
40
+ // SOFTGREEN (compose) step artifact: `{ text: string, lines?: string[] }`
41
+ // - `text` is the whole composed text; `maxWords`/`sections` (F38's
42
+ // `closeWordsAndSections`) run over it directly.
43
+ // - `linesPerInvoice`/`mustCarry` (new here, M0 had no equivalent —
44
+ // M0's own `closeCompose` checked citations+brackets, which M2's
45
+ // `green` class already covers; this piece's `mustCarry` check is
46
+ // the text-shape half only) group `text`'s own non-empty lines into
47
+ // blocks of `linesPerInvoice` lines and require every `mustCarry`
48
+ // string to appear (case-insensitive substring) in each block.
49
+ // - What this LEAVES OUT (named, not silently assumed): the optional
50
+ // `lines` field is never cross-checked against `text` itself, and
51
+ // `mustCarry` is a substring match on the block's own words, never a
52
+ // citation-level check that the carried figure is the RIGHT figure —
53
+ // that grounding is `green`'s job, on a different step, per the
54
+ // signed scope ("close by declared class, one closer per class").
55
+ //
56
+ // hitl: no mechanical close is possible — `closeByClass` returns
57
+ // `{ verdict: 'hitl', red: null }` and the runner decides what that means
58
+ // (the signed ask slot, or — for a hitl-classed step with no ask binding,
59
+ // e.g. a plain "silence" default with no guardrail proposal — a pass-through
60
+ // once its happened check clears; see src/runner.js's own docblock for this
61
+ // reading, flagged there as an interpretation call, not a rule from the
62
+ // signed text).
63
+
64
+ /** @typedef {import('./types.js').CloseVerdict} CloseVerdict */
65
+
66
+ const FORMULAS = Object.freeze({
67
+ sum: (vals) => vals.reduce((a, b) => a + b, 0),
68
+ count: (vals) => vals.length,
69
+ min: (vals) => Math.min(...vals),
70
+ max: (vals) => Math.max(...vals),
71
+ sub: (vals) => vals[0] - vals[1],
72
+ });
73
+
74
+ const CELL_RE = /^([a-zA-Z0-9_-]+)!([A-Za-z]+)(\d+)$/;
75
+ const FORMULA_RE = /^(sum|count|min|max|sub|daysBetween)\((.*)\)$/;
76
+ const FIELD_REF_RE = /^#([A-Za-z0-9_]+)$/;
77
+ const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
78
+
79
+ function colIndexOf(col) {
80
+ let n = 0;
81
+ for (const ch of col.toUpperCase()) n = n * 26 + (ch.charCodeAt(0) - 64);
82
+ return n - 1;
83
+ }
84
+
85
+ /** Strip thousands separators / currency symbols; report the value and the source's own decimal precision. */
86
+ function parseNumeric(raw) {
87
+ const cleaned = String(raw).replace(/[$,]/g, '').trim();
88
+ const value = Number(cleaned);
89
+ const dot = cleaned.indexOf('.');
90
+ const decimals = dot === -1 ? 0 : cleaned.length - dot - 1;
91
+ return { value, decimals };
92
+ }
93
+
94
+ function roundTo(n, decimals) {
95
+ const f = 10 ** decimals;
96
+ return Math.round(n * f) / f;
97
+ }
98
+
99
+ function getCellRaw(artifact, col, row) {
100
+ const found = (artifact.rows ?? []).find((r) => r.rowNumber === row);
101
+ if (!found) return null;
102
+ return found.cells?.[col.toUpperCase()] ?? null;
103
+ }
104
+
105
+ /**
106
+ * Resolve one `cite` string against `ctx.reads` (artifacts already read by
107
+ * this step) and `fieldsSoFar` (fields of THIS artifact already resolved, in
108
+ * declared order). Returns `{ ok:true, raw }` (a raw cell value still to be
109
+ * type-compared) or `{ ok:true, computed }` (a formula's already-numeric
110
+ * result) or `{ ok:false, red }`. Never throws on a malformed cite — that is
111
+ * a red the caller renders, not an exception.
112
+ */
113
+ function resolveCite(cite, ctx) {
114
+ if (typeof cite !== 'string' || cite.length === 0) {
115
+ return { ok: false, red: `cite must be a non-empty string, got ${JSON.stringify(cite)}` };
116
+ }
117
+
118
+ const cellMatch = CELL_RE.exec(cite);
119
+ if (cellMatch) {
120
+ const [, artifactId, col, rowStr] = cellMatch;
121
+ const artifact = ctx.reads?.[artifactId];
122
+ if (!artifact) return { ok: false, red: `cite "${cite}": unknown artifact "${artifactId}"` };
123
+ if (artifact.kind !== 'cells' && artifact.kind !== 'csv') {
124
+ return { ok: false, red: `cite "${cite}": artifact "${artifactId}" is not a cells/csv-kind read` };
125
+ }
126
+ if (colIndexOf(col) < 0) return { ok: false, red: `cite "${cite}": "${col}" is not a valid column` };
127
+ const row = Number(rowStr);
128
+ const raw = getCellRaw(artifact, col, row);
129
+ if (raw === null) return { ok: false, red: `cite "${cite}": cell ${col}${row} does not exist in "${artifactId}"` };
130
+ return { ok: true, raw };
131
+ }
132
+
133
+ const fieldMatch = FIELD_REF_RE.exec(cite);
134
+ if (fieldMatch) {
135
+ const name = fieldMatch[1];
136
+ if (!Object.prototype.hasOwnProperty.call(ctx.fieldsSoFar ?? {}, name)) {
137
+ return { ok: false, red: `cite "${cite}": field "${name}" is not resolved yet (fields resolve top to bottom, never forward)` };
138
+ }
139
+ return { ok: true, raw: ctx.fieldsSoFar[name].value };
140
+ }
141
+
142
+ const formulaMatch = FORMULA_RE.exec(cite);
143
+ if (formulaMatch) {
144
+ const [, op, argsRaw] = formulaMatch;
145
+ const argCites = argsRaw.split(',').map((s) => s.trim()).filter((s) => s.length > 0);
146
+
147
+ if (op === 'daysBetween') {
148
+ if (argCites.length < 1 || argCites.length > 2) {
149
+ return { ok: false, red: `cite "${cite}": daysBetween takes 1 or 2 args, got ${argCites.length}` };
150
+ }
151
+ const resolved = [];
152
+ for (const arg of argCites) {
153
+ const r = resolveCite(arg, ctx);
154
+ if (!r.ok) return r;
155
+ resolved.push(r.raw);
156
+ }
157
+ const fromDate = resolved[0];
158
+ const toDate = argCites.length === 2 ? resolved[1] : ctx.businessDate;
159
+ if (!ISO_DATE_RE.test(String(fromDate)) || !ISO_DATE_RE.test(String(toDate))) {
160
+ return { ok: false, red: `cite "${cite}": daysBetween needs ISO (YYYY-MM-DD) dates, got "${fromDate}"/"${toDate}"` };
161
+ }
162
+ const days = Math.round((Date.parse(`${toDate}T00:00:00Z`) - Date.parse(`${fromDate}T00:00:00Z`)) / 86400000);
163
+ return { ok: true, computed: days };
164
+ }
165
+
166
+ const fn = FORMULAS[op];
167
+ if (!fn) return { ok: false, red: `cite "${cite}": unknown formula "${op}" (closed grammar: sum,count,min,max,sub,daysBetween)` };
168
+ const vals = [];
169
+ for (const arg of argCites) {
170
+ const r = resolveCite(arg, ctx);
171
+ if (!r.ok) return r;
172
+ const num = r.computed !== undefined ? r.computed : parseNumeric(r.raw).value;
173
+ if (Number.isNaN(num)) return { ok: false, red: `cite "${cite}": arg "${arg}" does not resolve to a number` };
174
+ vals.push(num);
175
+ }
176
+ return { ok: true, computed: fn(vals) };
177
+ }
178
+
179
+ return { ok: false, red: `cite "${cite}" does not match the cell or formula grammar` };
180
+ }
181
+
182
+ function checkField(name, field, ctx) {
183
+ if (!field || typeof field !== 'object' || field.value === undefined || typeof field.cite !== 'string') {
184
+ return { verdict: 'red', red: `field "${name}" must be an object {value, cite:string}, got ${JSON.stringify(field)}` };
185
+ }
186
+ const resolved = resolveCite(field.cite, ctx);
187
+ if (!resolved.ok) return { verdict: 'red', red: `field "${name}": ${resolved.red}` };
188
+
189
+ if (resolved.computed !== undefined) {
190
+ if (Number(field.value) !== resolved.computed) {
191
+ return { verdict: 'red', red: `field "${name}" ${field.value} ≠ ${field.cite} = ${resolved.computed}` };
192
+ }
193
+ return { verdict: 'green' };
194
+ }
195
+
196
+ const raw = resolved.raw;
197
+ if (ISO_DATE_RE.test(String(field.value))) {
198
+ if (String(field.value) !== String(raw)) {
199
+ return { verdict: 'red', red: `field "${name}" ${field.value} ≠ cite ${field.cite} = ${raw}` };
200
+ }
201
+ return { verdict: 'green' };
202
+ }
203
+ const { value: numVal, decimals } = parseNumeric(raw);
204
+ if (Number.isNaN(numVal)) {
205
+ if (String(field.value).trim() !== String(raw).trim()) {
206
+ return { verdict: 'red', red: `field "${name}" ${field.value} ≠ cite ${field.cite} = ${raw}` };
207
+ }
208
+ return { verdict: 'green' };
209
+ }
210
+ if (roundTo(Number(field.value), decimals) !== roundTo(numVal, decimals)) {
211
+ return { verdict: 'red', red: `field "${name}" ${field.value} ≠ cite ${field.cite} = ${numVal}` };
212
+ }
213
+ return { verdict: 'green' };
214
+ }
215
+
216
+ /**
217
+ * `green` close: every field in `artifact.fields`, in declared order,
218
+ * resolves and matches its cite. First red wins.
219
+ *
220
+ * @param {any} artifact
221
+ * @param {{ reads: Record<string, any>, businessDate: string }} ctx
222
+ * @returns {CloseVerdict}
223
+ */
224
+ export function closeGreen(artifact, ctx) {
225
+ try {
226
+ if (!artifact || typeof artifact !== 'object' || !artifact.fields || typeof artifact.fields !== 'object') {
227
+ return /** @type {CloseVerdict} */ ({ verdict: 'unparseable', red: 'green artifact must be an object shaped {fields: {...}}' });
228
+ }
229
+ const names = Object.keys(artifact.fields);
230
+ if (names.length === 0) {
231
+ return /** @type {CloseVerdict} */ ({ verdict: 'unparseable', red: 'green artifact has no fields' });
232
+ }
233
+ /** @type {Record<string, any>} */
234
+ const fieldsSoFar = {};
235
+ for (const name of names) {
236
+ const result = checkField(name, artifact.fields[name], { reads: ctx.reads, fieldsSoFar, businessDate: ctx.businessDate });
237
+ if (result.verdict === 'red') return /** @type {CloseVerdict} */ (result);
238
+ fieldsSoFar[name] = artifact.fields[name];
239
+ }
240
+ return { verdict: 'green', red: null };
241
+ } catch (err) {
242
+ return { verdict: 'crash', red: `green close crashed: ${err.message}` };
243
+ }
244
+ }
245
+
246
+ /**
247
+ * The declared-shape word-cap + ordered-sections check, F38 version (every
248
+ * failing check reported, not just the first). Identical rules to
249
+ * poc/m0/shape.mjs's own `closeWordsAndSections`.
250
+ *
251
+ * @param {unknown} text
252
+ * @param {{ maxWords: number, sections: string[] }} declared
253
+ * @returns {CloseVerdict}
254
+ */
255
+ export function closeWordsAndSections(text, { maxWords, sections }) {
256
+ if (typeof text !== 'string') {
257
+ return { verdict: 'unparseable', red: `expected string text, got ${text === null ? 'null' : typeof text}` };
258
+ }
259
+
260
+ const lines = text.split(/\r?\n/);
261
+ const reds = /** @type {string[]} */ ([]);
262
+
263
+ let wordCount = 0;
264
+ for (const line of lines) {
265
+ const stripped = line.replace(/^#+\s*/, '');
266
+ const words = stripped.split(/\s+/).filter((w) => w.length > 0);
267
+ wordCount += words.length;
268
+ }
269
+ if (Number.isFinite(maxWords) && wordCount > maxWords) {
270
+ reds.push(`${wordCount} words, limit ${maxWords}`);
271
+ }
272
+
273
+ const headingLines = lines
274
+ .map((line) => line.replace(/^#+\s*/, '').replace(/:\s*$/, '').trim().toLowerCase())
275
+ .filter((l) => l.length > 0);
276
+
277
+ let searchFrom = 0;
278
+ for (const section of sections ?? []) {
279
+ const want = section.trim().toLowerCase();
280
+ const foundAt = headingLines.indexOf(want, searchFrom);
281
+ if (foundAt === -1) {
282
+ const anywhere = headingLines.indexOf(want);
283
+ if (anywhere === -1) {
284
+ reds.push(`no line is exactly the heading "${section}" (a heading is a line that is only that text, optionally after #)`);
285
+ } else {
286
+ reds.push(`section heading "${section}" is out of order`);
287
+ }
288
+ } else {
289
+ searchFrom = foundAt + 1;
290
+ }
291
+ }
292
+
293
+ if (reds.length > 0) return { verdict: 'red', red: reds.join('; '), reds };
294
+ return { verdict: 'green', reds: [] };
295
+ }
296
+
297
+ /**
298
+ * `linesPerInvoice`/`mustCarry`: group `text`'s own non-empty lines into
299
+ * blocks of `linesPerInvoice` lines; every `mustCarry` string must appear
300
+ * (case-insensitive substring) somewhere in each block. Returns an array of
301
+ * red strings (empty when clean) — the caller folds these into its own
302
+ * `reds` list alongside `closeWordsAndSections`'s.
303
+ */
304
+ export function closeLinesAndCarry(text, { linesPerInvoice, mustCarry }) {
305
+ const lines = text.split(/\r?\n/).filter((l) => l.trim().length > 0);
306
+ const reds = [];
307
+ if (lines.length === 0) {
308
+ reds.push('text has no non-empty lines to check against linesPerInvoice');
309
+ return reds;
310
+ }
311
+ if (lines.length % linesPerInvoice !== 0) {
312
+ reds.push(`text has ${lines.length} non-empty line(s), not a multiple of linesPerInvoice ${linesPerInvoice}`);
313
+ }
314
+ for (let i = 0; i < lines.length; i += linesPerInvoice) {
315
+ const block = lines.slice(i, i + linesPerInvoice).join(' ');
316
+ for (const must of mustCarry ?? []) {
317
+ if (!block.toLowerCase().includes(String(must).toLowerCase())) {
318
+ reds.push(`invoice block starting at line ${i + 1} is missing "${must}"`);
319
+ }
320
+ }
321
+ }
322
+ return reds;
323
+ }
324
+
325
+ /**
326
+ * `softgreen` close: dispatches to `closeWordsAndSections` (when the shape
327
+ * declares `maxWords`/`sections`) and/or `closeLinesAndCarry` (when it
328
+ * declares `linesPerInvoice`/`mustCarry`) and reports every failing check
329
+ * from both, one sentence each (F38's rule, never widened to first-red-only).
330
+ *
331
+ * @param {any} artifact
332
+ * @param {{ maxWords?: number, sections?: string[], linesPerInvoice?: number, mustCarry?: string[] }} shape
333
+ * @returns {CloseVerdict}
334
+ */
335
+ export function closeSoftgreen(artifact, shape) {
336
+ if (!artifact || typeof artifact !== 'object' || typeof artifact.text !== 'string') {
337
+ return /** @type {CloseVerdict} */ ({ verdict: 'unparseable', red: `softgreen artifact must be an object shaped {text: string}, got ${JSON.stringify(artifact)}` });
338
+ }
339
+ try {
340
+ const reds = /** @type {string[]} */ ([]);
341
+ if (shape.maxWords !== undefined || shape.sections !== undefined) {
342
+ const wc = closeWordsAndSections(artifact.text, { maxWords: shape.maxWords ?? Infinity, sections: shape.sections ?? [] });
343
+ if (wc.verdict === 'unparseable') return /** @type {CloseVerdict} */ (wc);
344
+ reds.push(...(wc.reds ?? []));
345
+ }
346
+ if (shape.linesPerInvoice !== undefined && shape.mustCarry !== undefined) {
347
+ reds.push(...closeLinesAndCarry(artifact.text, { linesPerInvoice: shape.linesPerInvoice, mustCarry: shape.mustCarry }));
348
+ }
349
+ if (reds.length > 0) return { verdict: 'red', red: reds.join('; '), reds };
350
+ return { verdict: 'green', red: null, reds: [] };
351
+ } catch (err) {
352
+ return { verdict: 'crash', red: `softgreen close crashed: ${err.message}` };
353
+ }
354
+ }
355
+
356
+ /**
357
+ * The one dispatcher — `close by declared class` (M2 scope item 4).
358
+ *
359
+ * @param {{ close?: { class?: string, shape?: Record<string, any> } }} step
360
+ * @param {unknown} artifact
361
+ * @param {{ reads: Record<string, any>, businessDate: string }} ctx
362
+ * @returns {CloseVerdict}
363
+ */
364
+ export function closeByClass(step, artifact, ctx) {
365
+ const cls = step?.close?.class;
366
+ if (cls === 'green') return closeGreen(artifact, ctx);
367
+ if (cls === 'softgreen') return closeSoftgreen(artifact, step?.close?.shape ?? {});
368
+ if (cls === 'hitl') return { verdict: 'hitl', red: null };
369
+ return { verdict: 'crash', red: `closeByClass: unknown close class ${JSON.stringify(cls)}` };
370
+ }
package/src/csv.js ADDED
@@ -0,0 +1,57 @@
1
+ // borrowed-from: fwdloop poc/m0/csv.mjs@76a3607 (verbatim logic). Tiny CSV
2
+ // parser — never quoted-field aware, which every fixture this project reads
3
+ // doesn't need (dependency hierarchy: stdlib/vanilla first). The addressable
4
+ // -cells contract (`parseCellRef`/`colLetter`) is fwdloop's own citation
5
+ // grammar (F13, ruled 2026-09-09 — not a baresuite primitive), so it lives
6
+ // with the reader that produces those addresses.
7
+
8
+ /** Column letter for a 0-based column index: 0 -> 'A', 1 -> 'B', ... */
9
+ export function colLetter(i) {
10
+ let n = i + 1;
11
+ let s = '';
12
+ while (n > 0) {
13
+ const rem = (n - 1) % 26;
14
+ s = String.fromCharCode(65 + rem) + s;
15
+ n = Math.floor((n - 1) / 26);
16
+ }
17
+ return s;
18
+ }
19
+
20
+ /** Column index (0-based) for a column letter: 'A' -> 0, 'B' -> 1, ... */
21
+ export function colIndex(letter) {
22
+ let n = 0;
23
+ for (const ch of letter) n = n * 26 + (ch.charCodeAt(0) - 64);
24
+ return n - 1;
25
+ }
26
+
27
+ /** Parse a cell ref like "E2" into { col: 'E', row: 2 }. */
28
+ export function parseCellRef(cell) {
29
+ const m = /^([A-Z]+)(\d+)$/.exec(cell);
30
+ if (!m) throw new Error(`bad cell ref "${cell}"`);
31
+ return { col: m[1], row: Number(m[2]) };
32
+ }
33
+
34
+ /**
35
+ * Parse CSV text with no quoted fields into { header, rows }.
36
+ * `rows[i]` is `{ rowNumber, cells: { A: '...', B: '...' }, byName: { Customer: '...' } }`
37
+ * where `rowNumber` is the 1-based sheet row (header is row 1, first data row is row 2).
38
+ */
39
+ export function parseCsv(text) {
40
+ const lines = text.split(/\r?\n/).filter((l) => l.length > 0);
41
+ if (lines.length === 0) return { header: [], rows: [] };
42
+ const header = lines[0].split(',');
43
+ const rows = [];
44
+ for (let i = 1; i < lines.length; i += 1) {
45
+ const fields = lines[i].split(',');
46
+ const cells = {};
47
+ const byName = {};
48
+ header.forEach((name, col) => {
49
+ const letter = colLetter(col);
50
+ const val = fields[col] ?? '';
51
+ cells[letter] = val;
52
+ byName[name] = val;
53
+ });
54
+ rows.push({ rowNumber: i + 1, cells, byName });
55
+ }
56
+ return { header, rows };
57
+ }