fwdloop 0.22.0 → 0.23.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 +2 -2
- package/src/ask.js +20 -4
- package/src/authoring.js +4 -0
- package/src/canrun.js +5 -0
- package/src/checked.js +14 -3
- package/src/citedcheck.js +16 -1
- package/src/closers.js +13 -223
- package/src/csv.js +69 -12
- package/src/declaration.js +64 -6
- package/src/drafter.js +37 -15
- package/src/model-step.js +13 -21
- package/src/panel/author.js +2 -1
- package/src/panel/authorcard.js +9 -2
- package/src/panel/data.js +20 -5
- package/src/panel/index.html +43 -1
- package/src/panel/result.js +6 -0
- package/src/runner.js +24 -7
- package/src/sheet-record.js +57 -0
- package/src/sheetblock.js +170 -0
- package/src/sheetchecks.js +206 -0
- package/src/sheetclaims.js +78 -0
- package/src/sheetoffer.js +125 -0
- package/src/sheetrun.js +105 -0
- package/src/try-checks.js +6 -0
- package/src/types.js +1 -9
- package/types/ask.d.ts +2 -1
- package/types/checked.d.ts +9 -3
- package/types/closers.d.ts +6 -31
- package/types/csv.d.ts +25 -4
- package/types/declaration.d.ts +6 -1
- package/types/drafter.d.ts +22 -8
- package/types/model-step.d.ts +19 -30
- package/types/panel/authorcard.d.ts +2 -1
- package/types/runner.d.ts +8 -4
- package/types/sheet-record.d.ts +24 -0
- package/types/sheetblock.d.ts +116 -0
- package/types/sheetchecks.d.ts +70 -0
- package/types/sheetclaims.d.ts +26 -0
- package/types/sheetoffer.d.ts +25 -0
- package/types/sheetrun.d.ts +35 -0
- package/types/types.d.ts +16 -11
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "fwdloop",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.23.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",
|
|
@@ -51,7 +51,7 @@
|
|
|
51
51
|
"dependencies": {
|
|
52
52
|
"bare-agent": "^0.52.0",
|
|
53
53
|
"barebrowse": "^0.21.0",
|
|
54
|
-
"bareguard": "^0.
|
|
54
|
+
"bareguard": "^0.26.0",
|
|
55
55
|
"litectx": "^0.32.0"
|
|
56
56
|
},
|
|
57
57
|
"devDependencies": {
|
package/src/ask.js
CHANGED
|
@@ -184,7 +184,7 @@ export function makeFileAskStep({
|
|
|
184
184
|
* @param {any} ask the parsed ask.json object (or its `evidence` field's
|
|
185
185
|
* container — pass the whole ask so a missing `evidence` key is itself a
|
|
186
186
|
* handled case, not the caller's problem).
|
|
187
|
-
* @returns {{ draft: {step?: string, text: string} | null, unjudged: Array<{step: string, emits?: string, text: string}>, why?: string }}
|
|
187
|
+
* @returns {{ draft: {step?: string, text: string} | null, unjudged: Array<{step: string, emits?: string, text: string}>, why?: string, claims?: Record<string, any> }}
|
|
188
188
|
*/
|
|
189
189
|
export function readAskEvidence(ask) {
|
|
190
190
|
const evidence = ask && typeof ask === 'object' ? ask.evidence : undefined;
|
|
@@ -205,8 +205,8 @@ export function readAskEvidence(ask) {
|
|
|
205
205
|
};
|
|
206
206
|
}
|
|
207
207
|
|
|
208
|
-
//
|
|
209
|
-
|
|
208
|
+
// The earlier steps' text carried into the ask (the same for every shape that has an `artifact`).
|
|
209
|
+
const readUnjudged = () => {
|
|
210
210
|
const rawUnjudged = Array.isArray(evidence.unjudged) ? evidence.unjudged : [];
|
|
211
211
|
const unjudged = [];
|
|
212
212
|
for (const item of rawUnjudged) {
|
|
@@ -230,7 +230,12 @@ export function readAskEvidence(ask) {
|
|
|
230
230
|
// dropped rather than shown as a blank row — the draft itself is
|
|
231
231
|
// never lost by a malformed sibling entry.
|
|
232
232
|
}
|
|
233
|
-
return
|
|
233
|
+
return unjudged;
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
// M3 shape: evidence.artifact.text (+ evidence.unjudged[]).
|
|
237
|
+
if (evidence.artifact && typeof evidence.artifact === 'object' && typeof evidence.artifact.text === 'string') {
|
|
238
|
+
return { draft: { text: evidence.artifact.text }, unjudged: readUnjudged() };
|
|
234
239
|
}
|
|
235
240
|
|
|
236
241
|
// M2 shape: evidence.text (+ evidence.lines) — no unjudged concept.
|
|
@@ -238,6 +243,17 @@ export function readAskEvidence(ask) {
|
|
|
238
243
|
return { draft: { text: evidence.text }, unjudged: [] };
|
|
239
244
|
}
|
|
240
245
|
|
|
246
|
+
// M10b am4: a step with sheet checks answers in claim boxes, an object with no text. They are handed on as `claims` (the panel matches them to the step's checks);
|
|
247
|
+
// the `why` stays, for the caller that finds no sheet step for them.
|
|
248
|
+
if (evidence.artifact && typeof evidence.artifact === 'object' && !Array.isArray(evidence.artifact)) {
|
|
249
|
+
return {
|
|
250
|
+
draft: null,
|
|
251
|
+
unjudged: readUnjudged(),
|
|
252
|
+
claims: evidence.artifact,
|
|
253
|
+
why: `ask.json "evidence" has neither ".artifact.text" (M3) nor ".text" (M2) — unrecognised shape: keys ${JSON.stringify(Object.keys(evidence))}`,
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
|
|
241
257
|
// Present but neither recognised shape — never fall through to
|
|
242
258
|
// `undefined`/`JSON.stringify(undefined)` ("undefined" the string).
|
|
243
259
|
return {
|
package/src/authoring.js
CHANGED
|
@@ -23,6 +23,7 @@ import { draft } from './drafter.js';
|
|
|
23
23
|
import { parseSignedText, unsignedAskTtls } from './signed-text.js';
|
|
24
24
|
import { validateDeclaration } from './declaration.js';
|
|
25
25
|
import { factRows } from './citedcheck.js';
|
|
26
|
+
import { sheetLineBlocks } from './sheetblock.js';
|
|
26
27
|
import { loadCatalogue } from './catalogue.js';
|
|
27
28
|
import { WIRED_VERBS } from './primitives.js';
|
|
28
29
|
import { canonicalBytes } from './signature.js';
|
|
@@ -192,12 +193,15 @@ export function buildReadout({
|
|
|
192
193
|
out.push(` ${s.role} = ${s.path}${h ? ` [headings: ${h.join(' | ') || 'none'}]` : ''}`);
|
|
193
194
|
}
|
|
194
195
|
out.push('', READOUT_HEADS.steps);
|
|
196
|
+
const sheetBlocks = sheetLineBlocks({ declaration, lines });
|
|
195
197
|
declaration.steps.forEach((st, i) => {
|
|
196
198
|
out.push(` ${i + 1}. (line ${st.fromLine}) ${st.goal}`);
|
|
197
199
|
out.push(` grants: ${st.primitives?.length ? st.primitives.join(', ') : 'none (pure stop)'}`
|
|
198
200
|
+ ` | reads: ${st.reads?.length ? st.reads.join(', ') : '-'} | emits: ${st.emits} | check: ${st.close?.class}`);
|
|
199
201
|
// M10 am7 item 1: the facts a cited step checks its quotes against, signed with the readout (typed fields, never model prose)
|
|
200
202
|
if (st.close?.cited && typeof st.close.cited === 'object') for (const row of factRows(st.close.cited)) out.push(` ${row}`);
|
|
203
|
+
// M10b piece 1: the signed sheet checks, one row each, written by code from the typed fields
|
|
204
|
+
if (Array.isArray(st.close?.sheet)) for (const row of sheetBlocks.find((b) => b.line === st.fromLine)?.checked ?? []) out.push(` sheet check: ${row.text}`);
|
|
201
205
|
// M10 am8 item 2: the column lock, signed with the readout (typed fields)
|
|
202
206
|
if (Array.isArray(st.close?.columns)) for (const c of st.close.columns) if (typeof c?.column === 'string' && typeof c?.source === 'string') out.push(` cells only from column '${c.column}' of ${c.source}`);
|
|
203
207
|
// M4e amendment 14 item 5: the check's sections in its order (+ word limit); fixed text from typed fields, never model prose.
|
package/src/canrun.js
CHANGED
|
@@ -70,6 +70,11 @@ export function unbuildableSay(n, shape) {
|
|
|
70
70
|
*/
|
|
71
71
|
export function findUnbuildableCheckStep(declaration) {
|
|
72
72
|
for (const step of declaration.steps) {
|
|
73
|
+
// M10b piece 5 (item 8, hamr's ruling): a green step with neither close.sheet nor close.cited is the old cell cite, which no longer runs. A job signed that
|
|
74
|
+
// way is kept for reference (it still reads and displays) and is refused here, at $0, before any spend.
|
|
75
|
+
if (step.close?.class === 'green' && !step.close.cited && !Array.isArray(step.close.sheet)) {
|
|
76
|
+
return { step, why: 'a green step with no close.sheet or close.cited is the retired cell cite', say: `This flow will not run: Line ${step.fromLine}'s check cannot cite cells any more. Draft it again to run it.` };
|
|
77
|
+
}
|
|
73
78
|
if (step.close?.class !== 'softgreen') continue;
|
|
74
79
|
try {
|
|
75
80
|
buildSoftgreenRubric(step.close.shape ?? {});
|
package/src/checked.js
CHANGED
|
@@ -12,28 +12,38 @@
|
|
|
12
12
|
export const NOT_CHECKED_LABEL = "not checked (the AI's own reading)";
|
|
13
13
|
|
|
14
14
|
import { factRows } from './citedcheck.js';
|
|
15
|
+
import { sheetCheckRows } from './sheetchecks.js';
|
|
16
|
+
import { sheetLineBlocks } from './sheetblock.js';
|
|
15
17
|
import { splitReadNotes, signedFactNames } from './pagedropwords.js';
|
|
16
18
|
|
|
17
19
|
const list = (xs) => xs.join(', ');
|
|
18
20
|
|
|
19
21
|
/**
|
|
20
22
|
* One entry per step, in plan order: the plain sentences for what its typed close checks.
|
|
21
|
-
*
|
|
23
|
+
* M10b piece 4: with `lines` (the signed job lines) a step that reads a sheet also carries `sheet`, its line's block (src/sheetblock.js `sheetLineBlocks`: guardrails,
|
|
24
|
+
* Checked with `covers`, Not checked), and its sentences are only the lead sentence; the surfaces draw the block. Without `lines` the older one-row-per-check sentences.
|
|
25
|
+
* @param {{ steps?: any[] }} declaration @param {{ hasAsk?: boolean, askLines?: number[], lines?: any[], csvRoles?: string[] }} [opts] hasAsk = the job has a signed ask line (so "you check it at the ask" is true);
|
|
22
26
|
* askLines = the job lines of the signed asks, which also lets a step after the LAST ask read "you check it after you accept" (am41 item 2, am42: the ONE place for these words)
|
|
23
|
-
* @returns {{ step: number, line: number|null, goal: string, class: string, sentences: string[] }[]}
|
|
27
|
+
* @returns {{ step: number, line: number|null, goal: string, class: string, sentences: string[], sheet?: ReturnType<typeof sheetLineBlocks>[number] }[]}
|
|
24
28
|
*/
|
|
25
|
-
export function checkedLines(declaration, { hasAsk = true, askLines } = {}) {
|
|
29
|
+
export function checkedLines(declaration, { hasAsk = true, askLines, lines, csvRoles = [] } = {}) {
|
|
30
|
+
const blocks = Array.isArray(lines) ? sheetLineBlocks({ declaration, lines, csvRoles }) : [];
|
|
26
31
|
const steps = Array.isArray(declaration?.steps) ? declaration.steps : [];
|
|
27
32
|
if (Array.isArray(askLines)) hasAsk = askLines.length > 0;
|
|
28
33
|
const lastAsk = Array.isArray(askLines) ? steps.reduce((m, st, i) => (askLines.includes(st?.fromLine) ? i : m), -1) : -1;
|
|
29
34
|
return steps.map((st, i) => {
|
|
30
35
|
const cls = st?.close?.class;
|
|
36
|
+
const firstGreen = steps.findIndex((x) => x?.fromLine === st?.fromLine && x?.close?.class === 'green') === i;
|
|
37
|
+
const sheet = firstGreen ? (blocks.find((b) => b.line === st?.fromLine) ?? null) : null;
|
|
31
38
|
const shape = st?.close?.shape && typeof st.close.shape === 'object' ? st.close.shape : {};
|
|
32
39
|
/** @type {string[]} */
|
|
33
40
|
const out = [];
|
|
34
41
|
if (cls === 'green' && st.close.cited && typeof st.close.cited === 'object') {
|
|
35
42
|
// M10 am7 item 1: the facts the drafter wrote, as plain rows written by code from the typed fields
|
|
36
43
|
out.push(`Each result must be quoted word for word from the saved page "${st.close.cited.source}", and the machine checks every quote, every value and the count against that copy.`, ...factRows(st.close.cited));
|
|
44
|
+
} else if (cls === 'green' && Array.isArray(st.close.sheet)) {
|
|
45
|
+
// M10b piece 1: the signed sheet checks, one row each, written by code from the typed fields
|
|
46
|
+
out.push('The machine recomputes each of these from the saved sheet and compares it with what the step gave:', ...(sheet ? [] : sheetCheckRows(st.close.sheet)));
|
|
37
47
|
} else if (cls === 'green') {
|
|
38
48
|
out.push('Every figure must cite its source cell, or a formula over cells, and the machine recomputes it and compares it with its source.');
|
|
39
49
|
} else if (cls === 'softgreen') {
|
|
@@ -49,6 +59,7 @@ export function checkedLines(declaration, { hasAsk = true, askLines } = {}) {
|
|
|
49
59
|
}
|
|
50
60
|
return {
|
|
51
61
|
step: i + 1, line: Number.isInteger(st?.fromLine) ? st.fromLine : null, goal: typeof st?.goal === 'string' ? st.goal : '', class: String(cls), sentences: out,
|
|
62
|
+
...(sheet && cls === 'green' ? { sheet } : {}),
|
|
52
63
|
};
|
|
53
64
|
});
|
|
54
65
|
}
|
package/src/citedcheck.js
CHANGED
|
@@ -36,6 +36,21 @@ const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object'
|
|
|
36
36
|
/** @param {string} t @returns {string} the sha256 of the text, hex */
|
|
37
37
|
export const sha256Text = (t) => createHash('sha256').update(t, 'utf8').digest('hex');
|
|
38
38
|
|
|
39
|
+
/**
|
|
40
|
+
* A money unit list with an entry listed twice, equal after the whitespace normalization bareguard's quote matcher applies (bareguard 0.26.0: its
|
|
41
|
+
* rubric refuses such a list), keeps the first of them. The one place a unit list is built into a signed fact.
|
|
42
|
+
* @param {string[]} units @returns {string[]}
|
|
43
|
+
*/
|
|
44
|
+
function unitsOnce(units) {
|
|
45
|
+
const seen = new Set();
|
|
46
|
+
return units.filter((u) => {
|
|
47
|
+
const key = String(u).split('**').join('').split('__').join('').replace(/\s+/g, ' ').trim();
|
|
48
|
+
if (seen.has(key)) return false;
|
|
49
|
+
seen.add(key);
|
|
50
|
+
return true;
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
|
|
39
54
|
/**
|
|
40
55
|
* A kept look fact as signed facts. The label that comes first becomes the anchor and the limit the look read (`reading`) becomes the number rule. A PLACE
|
|
41
56
|
* fact (the look gave it `phrases`, src/pageplace.js: R2, R2a, R2b) becomes one phrase fact per phrase, because every one of them must be in the quote
|
|
@@ -53,7 +68,7 @@ export function factsOfLook(k) {
|
|
|
53
68
|
const anchor = k.labels?.[0] ?? k.label ?? k.words?.[0];
|
|
54
69
|
if (anchor !== undefined) f.anchor = String(anchor);
|
|
55
70
|
if (f.shape === 'money') {
|
|
56
|
-
if (k.unit !== undefined) f.unit =
|
|
71
|
+
if (k.unit !== undefined) f.unit = unitsOnce(k.unit);
|
|
57
72
|
if (k.currency !== undefined) f.currency = [...k.currency];
|
|
58
73
|
}
|
|
59
74
|
if (isRec(k.reading)) f.rule = { ...k.reading };
|
package/src/closers.js
CHANGED
|
@@ -2,40 +2,21 @@
|
|
|
2
2
|
// SIGNED", scope item 4): `closeByClass(step, artifact, ctx)` — the
|
|
3
3
|
// deterministic, $0 close, dispatched on the step's declared `close.class`.
|
|
4
4
|
//
|
|
5
|
-
// borrowed-from: fwdloop poc/m0/
|
|
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
|
|
5
|
+
// borrowed-from: fwdloop poc/m0/shape.mjs@29caa83
|
|
9
6
|
// (`closeWordsAndSections`, F38 version — every failing check reported, not
|
|
10
7
|
// just the first). Rewritten against M2's own typed artifact contract below
|
|
11
8
|
// — src/ never imports from poc/ (CLAUDE.md: "borrow, never import").
|
|
9
|
+
// (The M0 cell-cite grammar - sum/count/min/max/sub/daysBetween over `<input>!C3` cites - retired in M10b piece 5, item 8.)
|
|
12
10
|
//
|
|
13
11
|
// ---------------------------------------------------------------------------
|
|
14
12
|
// Artifact contracts (M2 scope item 4's own docblock requirement).
|
|
15
13
|
// ---------------------------------------------------------------------------
|
|
16
14
|
//
|
|
17
|
-
// GREEN step artifact:
|
|
18
|
-
// -
|
|
19
|
-
//
|
|
20
|
-
//
|
|
21
|
-
//
|
|
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`.
|
|
15
|
+
// GREEN step artifact: one of two forms, each with its own closer.
|
|
16
|
+
// - a page or document quote: `{ results: [...] }` (`closeCited`, bareguard's `cited` check);
|
|
17
|
+
// - a sheet: one typed claim box per `cells` check (`closeSheet`, src/sheetrun.js, bareguard's `cells` / `table` checks).
|
|
18
|
+
// A green step with neither `close.cited` nor `close.sheet` is the retired cell cite: `closeByClass` answers `crash`, and a job signed that way is refused
|
|
19
|
+
// at start (src/canrun.js `findUnbuildableCheckStep`) before it can get here.
|
|
39
20
|
//
|
|
40
21
|
// SOFTGREEN (compose) step artifact: `{ text: string }`
|
|
41
22
|
// - `text` is the whole composed text; `maxWords`/`sections`/`wordsPerSection` run over it directly. Since M4e amendment 18 these
|
|
@@ -64,208 +45,15 @@
|
|
|
64
45
|
|
|
65
46
|
import { createRubric, checkStep } from 'bareguard';
|
|
66
47
|
import { checkCited } from './citedcheck.js';
|
|
48
|
+
import { closeSheet } from './sheetrun.js';
|
|
67
49
|
|
|
68
50
|
/** @typedef {import('./types.js').CloseVerdict} CloseVerdict */
|
|
69
51
|
|
|
70
|
-
export const FORMULAS = Object.freeze({
|
|
71
|
-
sum: (vals) => vals.reduce((a, b) => a + b, 0),
|
|
72
|
-
count: (vals) => vals.length,
|
|
73
|
-
min: (vals) => Math.min(...vals),
|
|
74
|
-
max: (vals) => Math.max(...vals),
|
|
75
|
-
sub: (vals) => vals[0] - vals[1],
|
|
76
|
-
});
|
|
77
|
-
|
|
78
|
-
/**
|
|
79
|
-
* M10 am10: the one description of the cite forms, told to a step whose check cites cells and named in the red when a cite fits none.
|
|
80
|
-
* Built from the checker's own formula list (FORMULAS keys + daysBetween, which is handled apart), so the text cannot drift from what is accepted.
|
|
81
|
-
*/
|
|
82
|
-
export function citeForms(names = [...Object.keys(FORMULAS), 'daysBetween']) {
|
|
83
|
-
return `one cell (\`<input>!C3\`), a field above it (\`#name\`), or ${names.join(', ')} over those`;
|
|
84
|
-
}
|
|
85
|
-
|
|
86
52
|
/** An input with cells (M4d amendment 8): a file whose name ends `.csv`. The one decider for "this input can be cited". */
|
|
87
53
|
export function isCellsPath(p) {
|
|
88
54
|
return typeof p === 'string' && p.toLowerCase().endsWith('.csv');
|
|
89
55
|
}
|
|
90
56
|
|
|
91
|
-
const CELL_RE = /^([a-zA-Z0-9_-]+)!([A-Za-z]+)(\d+)$/;
|
|
92
|
-
const FORMULA_RE = /^(sum|count|min|max|sub|daysBetween)\((.*)\)$/;
|
|
93
|
-
const FIELD_REF_RE = /^#([A-Za-z0-9_]+)$/;
|
|
94
|
-
const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
|
|
95
|
-
|
|
96
|
-
function colIndexOf(col) {
|
|
97
|
-
let n = 0;
|
|
98
|
-
for (const ch of col.toUpperCase()) n = n * 26 + (ch.charCodeAt(0) - 64);
|
|
99
|
-
return n - 1;
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
/** Strip thousands separators / currency symbols; report the value and the source's own decimal precision. */
|
|
103
|
-
function parseNumeric(raw) {
|
|
104
|
-
const cleaned = String(raw).replace(/[$,]/g, '').trim();
|
|
105
|
-
const value = Number(cleaned);
|
|
106
|
-
const dot = cleaned.indexOf('.');
|
|
107
|
-
const decimals = dot === -1 ? 0 : cleaned.length - dot - 1;
|
|
108
|
-
return { value, decimals };
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
function roundTo(n, decimals) {
|
|
112
|
-
const f = 10 ** decimals;
|
|
113
|
-
return Math.round(n * f) / f;
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
function getCellRaw(artifact, col, row) {
|
|
117
|
-
const found = (artifact.rows ?? []).find((r) => r.rowNumber === row);
|
|
118
|
-
if (!found) return null;
|
|
119
|
-
return found.cells?.[col.toUpperCase()] ?? null;
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
/**
|
|
123
|
-
* Resolve one `cite` string against `ctx.reads` (artifacts already read by
|
|
124
|
-
* this step) and `fieldsSoFar` (fields of THIS artifact already resolved, in
|
|
125
|
-
* declared order). Returns `{ ok:true, raw }` (a raw cell value still to be
|
|
126
|
-
* type-compared) or `{ ok:true, computed }` (a formula's already-numeric
|
|
127
|
-
* result) or `{ ok:false, red }`. Never throws on a malformed cite — that is
|
|
128
|
-
* a red the caller renders, not an exception.
|
|
129
|
-
*/
|
|
130
|
-
function resolveCite(cite, ctx) {
|
|
131
|
-
if (typeof cite !== 'string' || cite.length === 0) {
|
|
132
|
-
return { ok: false, red: `cite must be a non-empty string, got ${JSON.stringify(cite)}` };
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
const cellMatch = CELL_RE.exec(cite);
|
|
136
|
-
if (cellMatch) {
|
|
137
|
-
const [, artifactId, col, rowStr] = cellMatch;
|
|
138
|
-
const artifact = ctx.reads?.[artifactId];
|
|
139
|
-
if (!artifact) return { ok: false, red: `cite "${cite}": unknown artifact "${artifactId}"` };
|
|
140
|
-
if (artifact.kind !== 'cells' && artifact.kind !== 'csv') {
|
|
141
|
-
return { ok: false, red: `cite "${cite}": artifact "${artifactId}" is not a cells/csv-kind read` };
|
|
142
|
-
}
|
|
143
|
-
if (colIndexOf(col) < 0) return { ok: false, red: `cite "${cite}": "${col}" is not a valid column` };
|
|
144
|
-
const row = Number(rowStr);
|
|
145
|
-
const raw = getCellRaw(artifact, col, row);
|
|
146
|
-
if (raw === null) return { ok: false, red: `cite "${cite}": cell ${col}${row} does not exist in "${artifactId}"` };
|
|
147
|
-
// M10 am8 item 2: the step's check names the column(s) its facts come from; a cell from any other column is red, naming it
|
|
148
|
-
const locked = (Array.isArray(ctx.lock) ? ctx.lock : []).filter((l) => l?.source === artifactId).map((l) => l.column);
|
|
149
|
-
if (locked.length > 0) {
|
|
150
|
-
const name = artifact.header?.[colIndexOf(col)];
|
|
151
|
-
if (!locked.includes(name)) return { ok: false, red: `cite "${cite}": the cell ${col}${row} is in column '${name ?? col}', but this step is locked to column ${locked.map((c) => `'${c}'`).join(' and ')}` };
|
|
152
|
-
}
|
|
153
|
-
return { ok: true, raw };
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
const fieldMatch = FIELD_REF_RE.exec(cite);
|
|
157
|
-
if (fieldMatch) {
|
|
158
|
-
const name = fieldMatch[1];
|
|
159
|
-
if (!Object.prototype.hasOwnProperty.call(ctx.fieldsSoFar ?? {}, name)) {
|
|
160
|
-
return { ok: false, red: `cite "${cite}": field "${name}" is not resolved yet (fields resolve top to bottom, never forward)` };
|
|
161
|
-
}
|
|
162
|
-
return { ok: true, raw: ctx.fieldsSoFar[name].value };
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
const formulaMatch = FORMULA_RE.exec(cite);
|
|
166
|
-
if (formulaMatch) {
|
|
167
|
-
const [, op, argsRaw] = formulaMatch;
|
|
168
|
-
const argCites = argsRaw.split(',').map((s) => s.trim()).filter((s) => s.length > 0);
|
|
169
|
-
|
|
170
|
-
if (op === 'daysBetween') {
|
|
171
|
-
if (argCites.length < 1 || argCites.length > 2) {
|
|
172
|
-
return { ok: false, red: `cite "${cite}": daysBetween takes 1 or 2 args, got ${argCites.length}` };
|
|
173
|
-
}
|
|
174
|
-
const resolved = [];
|
|
175
|
-
for (const arg of argCites) {
|
|
176
|
-
const r = resolveCite(arg, ctx);
|
|
177
|
-
if (!r.ok) return r;
|
|
178
|
-
resolved.push(r.raw);
|
|
179
|
-
}
|
|
180
|
-
const fromDate = resolved[0];
|
|
181
|
-
const toDate = argCites.length === 2 ? resolved[1] : ctx.businessDate;
|
|
182
|
-
if (!ISO_DATE_RE.test(String(fromDate)) || !ISO_DATE_RE.test(String(toDate))) {
|
|
183
|
-
return { ok: false, red: `cite "${cite}": daysBetween needs ISO (YYYY-MM-DD) dates, got "${fromDate}"/"${toDate}"` };
|
|
184
|
-
}
|
|
185
|
-
const days = Math.round((Date.parse(`${toDate}T00:00:00Z`) - Date.parse(`${fromDate}T00:00:00Z`)) / 86400000);
|
|
186
|
-
return { ok: true, computed: days };
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
const fn = FORMULAS[op];
|
|
190
|
-
if (!fn) return { ok: false, red: `cite "${cite}": unknown formula "${op}" (closed grammar: sum,count,min,max,sub,daysBetween)` };
|
|
191
|
-
const vals = [];
|
|
192
|
-
for (const arg of argCites) {
|
|
193
|
-
const r = resolveCite(arg, ctx);
|
|
194
|
-
if (!r.ok) return r;
|
|
195
|
-
const num = r.computed !== undefined ? r.computed : parseNumeric(r.raw).value;
|
|
196
|
-
if (Number.isNaN(num)) return { ok: false, red: `cite "${cite}": arg "${arg}" does not resolve to a number` };
|
|
197
|
-
vals.push(num);
|
|
198
|
-
}
|
|
199
|
-
return { ok: true, computed: fn(vals) };
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
return { ok: false, red: `cite "${cite}" does not match the cell or formula grammar - the forms are: ${citeForms()}` };
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
function checkField(name, field, ctx) {
|
|
206
|
-
if (!field || typeof field !== 'object' || field.value === undefined || typeof field.cite !== 'string') {
|
|
207
|
-
return { verdict: 'red', red: `field "${name}" must be an object {value, cite:string}, got ${JSON.stringify(field)}` };
|
|
208
|
-
}
|
|
209
|
-
const resolved = resolveCite(field.cite, ctx);
|
|
210
|
-
if (!resolved.ok) return { verdict: 'red', red: `field "${name}": ${resolved.red}` };
|
|
211
|
-
|
|
212
|
-
if (resolved.computed !== undefined) {
|
|
213
|
-
if (Number(field.value) !== resolved.computed) {
|
|
214
|
-
return { verdict: 'red', red: `field "${name}" ${field.value} ≠ ${field.cite} = ${resolved.computed}` };
|
|
215
|
-
}
|
|
216
|
-
return { verdict: 'green' };
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
const raw = resolved.raw;
|
|
220
|
-
if (ISO_DATE_RE.test(String(field.value))) {
|
|
221
|
-
if (String(field.value) !== String(raw)) {
|
|
222
|
-
return { verdict: 'red', red: `field "${name}" ${field.value} ≠ cite ${field.cite} = ${raw}` };
|
|
223
|
-
}
|
|
224
|
-
return { verdict: 'green' };
|
|
225
|
-
}
|
|
226
|
-
const { value: numVal, decimals } = parseNumeric(raw);
|
|
227
|
-
if (Number.isNaN(numVal)) {
|
|
228
|
-
if (String(field.value).trim() !== String(raw).trim()) {
|
|
229
|
-
return { verdict: 'red', red: `field "${name}" ${field.value} ≠ cite ${field.cite} = ${raw}` };
|
|
230
|
-
}
|
|
231
|
-
return { verdict: 'green' };
|
|
232
|
-
}
|
|
233
|
-
if (roundTo(Number(field.value), decimals) !== roundTo(numVal, decimals)) {
|
|
234
|
-
return { verdict: 'red', red: `field "${name}" ${field.value} ≠ cite ${field.cite} = ${numVal}` };
|
|
235
|
-
}
|
|
236
|
-
return { verdict: 'green' };
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
/**
|
|
240
|
-
* `green` close: every field in `artifact.fields`, in declared order,
|
|
241
|
-
* resolves and matches its cite. First red wins.
|
|
242
|
-
*
|
|
243
|
-
* @param {any} artifact
|
|
244
|
-
* @param {{ reads: Record<string, any>, businessDate: string, lock?: {source: string, column: string}[] }} ctx `lock` (M10 am8): the columns the step's check names
|
|
245
|
-
* @returns {CloseVerdict}
|
|
246
|
-
*/
|
|
247
|
-
export function closeGreen(artifact, ctx) {
|
|
248
|
-
try {
|
|
249
|
-
if (!artifact || typeof artifact !== 'object' || !artifact.fields || typeof artifact.fields !== 'object') {
|
|
250
|
-
return /** @type {CloseVerdict} */ ({ verdict: 'unparseable', red: 'green artifact must be an object shaped {fields: {...}}' });
|
|
251
|
-
}
|
|
252
|
-
const names = Object.keys(artifact.fields);
|
|
253
|
-
if (names.length === 0) {
|
|
254
|
-
return /** @type {CloseVerdict} */ ({ verdict: 'unparseable', red: 'green artifact has no fields' });
|
|
255
|
-
}
|
|
256
|
-
/** @type {Record<string, any>} */
|
|
257
|
-
const fieldsSoFar = {};
|
|
258
|
-
for (const name of names) {
|
|
259
|
-
const result = checkField(name, artifact.fields[name], { reads: ctx.reads, fieldsSoFar, businessDate: ctx.businessDate, lock: ctx.lock });
|
|
260
|
-
if (result.verdict === 'red') return /** @type {CloseVerdict} */ (result);
|
|
261
|
-
fieldsSoFar[name] = artifact.fields[name];
|
|
262
|
-
}
|
|
263
|
-
return { verdict: 'green', red: null };
|
|
264
|
-
} catch (err) {
|
|
265
|
-
return { verdict: 'crash', red: `green close crashed: ${err.message}` };
|
|
266
|
-
}
|
|
267
|
-
}
|
|
268
|
-
|
|
269
57
|
/**
|
|
270
58
|
* M10 piece 4 (item 2, "green grows"): the green close of a step that cites quotes instead of cells. `part` is the step's fact part (`close.cited`, set by
|
|
271
59
|
* code from the page look's kept facts, never by the model); `source` is the run's OWN frozen copy of the page or doc (`readRunSource`); the artifact is
|
|
@@ -476,16 +264,18 @@ export async function closeSoftgreen(artifact, shape) {
|
|
|
476
264
|
/**
|
|
477
265
|
* The one dispatcher — `close by declared class` (M2 scope item 4).
|
|
478
266
|
*
|
|
479
|
-
* @param {{ close?: { class?: string, shape?: Record<string, any>, cited?: any, columns?: {source: string, column: string}[] } }} step
|
|
267
|
+
* @param {{ close?: { class?: string, shape?: Record<string, any>, cited?: any, columns?: {source: string, column: string}[], sheet?: any[] } }} step
|
|
480
268
|
* @param {unknown} artifact
|
|
481
|
-
* @param {{ reads: Record<string, any>, businessDate: string, source?: {ok: true, text: string, sha256: string}|{ok: false, red: string}|null }} ctx
|
|
269
|
+
* @param {{ reads: Record<string, any>, businessDate: string, source?: {ok: true, text: string, sha256: string}|{ok: false, red: string}|null, sheet?: any }} ctx
|
|
482
270
|
* `source` (M10 piece 4) = the run's own frozen copy a cited step reads, from `readRunSource`; only a step whose close carries `cited` reads it
|
|
271
|
+
* `sheet` (M10b piece 2) = the run's own tables and recorded `tableSha`s a step with `close.sheet` is checked on, from `readRunSheets`
|
|
483
272
|
* @returns {Promise<CloseVerdict>}
|
|
484
273
|
*/
|
|
485
274
|
export async function closeByClass(step, artifact, ctx) {
|
|
486
275
|
const cls = step?.close?.class;
|
|
487
276
|
if (cls === 'green' && step?.close?.cited) return await closeCited(step.close.cited, artifact, ctx.source);
|
|
488
|
-
if (cls === 'green') return
|
|
277
|
+
if (cls === 'green' && Array.isArray(step?.close?.sheet)) return await closeSheet(step.close.sheet, artifact, ctx.sheet);
|
|
278
|
+
if (cls === 'green') return { verdict: 'crash', red: 'closeByClass: a green step with no close.sheet or close.cited is the retired cell cite' };
|
|
489
279
|
if (cls === 'softgreen') return await closeSoftgreen(artifact, step?.close?.shape ?? {});
|
|
490
280
|
if (cls === 'hitl') return { verdict: 'hitl', red: null };
|
|
491
281
|
return { verdict: 'crash', red: `closeByClass: unknown close class ${JSON.stringify(cls)}` };
|
package/src/csv.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
// borrowed-from: fwdloop poc/m0/csv.mjs@76a3607 (
|
|
2
|
-
// parser
|
|
3
|
-
// doesn't need (dependency hierarchy: stdlib/vanilla first). The addressable
|
|
1
|
+
// borrowed-from: fwdloop poc/m0/csv.mjs@76a3607 (the first reader; M10b item 2 rewrote it to RFC 4180 quoting). Tiny CSV
|
|
2
|
+
// parser (dependency hierarchy: stdlib/vanilla first). The addressable
|
|
4
3
|
// -cells contract (`parseCellRef`/`colLetter`) is fwdloop's own citation
|
|
5
4
|
// grammar (F13, ruled 2026-09-09 — not a baresuite primitive), so it lives
|
|
6
5
|
// with the reader that produces those addresses.
|
|
@@ -32,17 +31,61 @@ export function parseCellRef(cell) {
|
|
|
32
31
|
}
|
|
33
32
|
|
|
34
33
|
/**
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
34
|
+
* Split CSV text into records (RFC 4180): a cell may be quoted ("1,200.50" is one cell, "" inside quotes is one quote, a comma or a line break inside quotes
|
|
35
|
+
* stays in the cell); LF and CRLF both end a record. Each record carries `line`, the 1-based line of the text it starts on, so a line break inside a quoted
|
|
36
|
+
* cell still counts. A blank line (nothing, not even quotes) is no record, but its line is counted. A quote inside an unquoted cell is just a character.
|
|
37
|
+
* @param {string} text @returns {{line: number, fields: string[]}[]}
|
|
38
|
+
*/
|
|
39
|
+
function records(text) {
|
|
40
|
+
/** @type {{line: number, fields: string[]}[]} */
|
|
41
|
+
const out = [];
|
|
42
|
+
let line = 1;
|
|
43
|
+
let startLine = 1;
|
|
44
|
+
/** @type {string[]} */ let fields = [];
|
|
45
|
+
let cell = '';
|
|
46
|
+
let inQuotes = false;
|
|
47
|
+
let quoted = false; // the current record used a quote: an empty cell then is a real cell, not a blank line
|
|
48
|
+
const endCell = () => { fields.push(cell); cell = ''; };
|
|
49
|
+
const endRecord = () => {
|
|
50
|
+
endCell();
|
|
51
|
+
if (!(fields.length === 1 && fields[0] === '' && !quoted)) out.push({ line: startLine, fields });
|
|
52
|
+
fields = [];
|
|
53
|
+
quoted = false;
|
|
54
|
+
};
|
|
55
|
+
for (let i = 0; i < text.length; i += 1) {
|
|
56
|
+
const ch = text[i];
|
|
57
|
+
if (inQuotes) {
|
|
58
|
+
if (ch === '"') {
|
|
59
|
+
if (text[i + 1] === '"') { cell += '"'; i += 1; } else inQuotes = false;
|
|
60
|
+
} else {
|
|
61
|
+
if (ch === '\n') line += 1;
|
|
62
|
+
cell += ch;
|
|
63
|
+
}
|
|
64
|
+
} else if (ch === '"' && cell === '') { inQuotes = true; quoted = true; }
|
|
65
|
+
else if (ch === ',') endCell();
|
|
66
|
+
else if (ch === '\n' || (ch === '\r' && text[i + 1] === '\n')) {
|
|
67
|
+
if (ch === '\r') i += 1;
|
|
68
|
+
endRecord();
|
|
69
|
+
line += 1;
|
|
70
|
+
startLine = line;
|
|
71
|
+
} else cell += ch;
|
|
72
|
+
}
|
|
73
|
+
if (cell !== '' || fields.length > 0 || quoted) endRecord();
|
|
74
|
+
return out;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Parse CSV text into { header, rows } (RFC 4180 quoting, see `records`).
|
|
79
|
+
* `rows[i]` is `{ rowNumber, cells: { A: '...', B: '...' }, byName: { Customer: '...' }, raw: ['...', '...'] }` (`raw` is the row's cells exactly as the file has them: no padding, nothing cut)
|
|
80
|
+
* where `rowNumber` is the real sheet line the row starts on (header is row 1; a blank line is skipped but still counted, so it never shifts the rows below).
|
|
38
81
|
*/
|
|
39
82
|
export function parseCsv(text) {
|
|
40
|
-
const
|
|
41
|
-
if (
|
|
42
|
-
const header =
|
|
83
|
+
const recs = records(text);
|
|
84
|
+
if (recs.length === 0) return { header: [], rows: [] };
|
|
85
|
+
const header = recs[0].fields;
|
|
43
86
|
const rows = [];
|
|
44
|
-
for (let i = 1; i <
|
|
45
|
-
const fields =
|
|
87
|
+
for (let i = 1; i < recs.length; i += 1) {
|
|
88
|
+
const fields = recs[i].fields;
|
|
46
89
|
const cells = {};
|
|
47
90
|
const byName = {};
|
|
48
91
|
header.forEach((name, col) => {
|
|
@@ -51,7 +94,21 @@ export function parseCsv(text) {
|
|
|
51
94
|
cells[letter] = val;
|
|
52
95
|
byName[name] = val;
|
|
53
96
|
});
|
|
54
|
-
rows.push({ rowNumber: i
|
|
97
|
+
rows.push({ rowNumber: recs[i].line, cells, byName, raw: [...fields] });
|
|
55
98
|
}
|
|
56
99
|
return { header, rows };
|
|
57
100
|
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* A parsed sheet as bareguard's table shape: `{ header: string[], rows: [{ rowNumber, cells: string[] }] }`. Each row's cells are the row exactly as the file
|
|
104
|
+
* has it (`raw`): a short or a long row is NOT padded or cut here, so bareguard itself stops it (`tableSha` gives null for a ragged row, and the table is
|
|
105
|
+
* refused). The header strings are exactly as the file has them. The one writer of this shape (M10b item 2).
|
|
106
|
+
* @param {{header: string[], rows: {rowNumber: number, raw: string[]}[]}} sheet from `parseCsv`
|
|
107
|
+
* @returns {{header: string[], rows: {rowNumber: number, cells: string[]}[]}}
|
|
108
|
+
*/
|
|
109
|
+
export function sheetTable(sheet) {
|
|
110
|
+
return {
|
|
111
|
+
header: [...sheet.header],
|
|
112
|
+
rows: sheet.rows.map((r) => ({ rowNumber: r.rowNumber, cells: [...r.raw] })),
|
|
113
|
+
};
|
|
114
|
+
}
|