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/src/runner.js
CHANGED
|
@@ -60,6 +60,8 @@ import { configHome, configDoorHome } from './config.js';
|
|
|
60
60
|
import { closeByClass, isCellsPath } from './closers.js';
|
|
61
61
|
import { readRunSource } from './cited-source.js';
|
|
62
62
|
import { citedLineOf, writeCitedLine } from './cited-record.js';
|
|
63
|
+
import { sheetRolesOf, tableShaOfFrozen, readRunSheets } from './sheetrun.js';
|
|
64
|
+
import { writeSheetLine } from './sheet-record.js';
|
|
63
65
|
import {
|
|
64
66
|
appendAudit, appendHistory, readAudit, readHistory, endRow, HALT_OUTCOMES,
|
|
65
67
|
} from './books.js';
|
|
@@ -413,8 +415,11 @@ export async function freezePage(dir, id, url, { fetchPage = fetchPageText } = {
|
|
|
413
415
|
* unreadable source refuses by name. A source that is a web address
|
|
414
416
|
* (M10 item 1) is fetched and frozen by `freezePage`, in the same manifest.
|
|
415
417
|
* @param {string} runDir @param {Array<{id: string, path: string}>} sources
|
|
416
|
-
*
|
|
417
|
-
|
|
418
|
+
* M10b amendment 1: a CSV input named in `tableRoles` (the sheets a step's `close.sheet` reads) also gets its `tableSha` (bareguard's fingerprint of the table made
|
|
419
|
+
* from the FROZEN copy) in its manifest entry - the ONE place it is written, once, with the run's inputs; every sheet check of the run uses this recorded value.
|
|
420
|
+
* A sheet bareguard cannot read as a table refuses the run here, naming the input.
|
|
421
|
+
* @param {{fetchPage?: (url: string) => Promise<{ok: true, text: string, url: string}|{ok: false, error: string}>, tableRoles?: string[]}} [o] */
|
|
422
|
+
export async function freezeInputs(runDir, sources, { fetchPage, tableRoles = [] } = {}) {
|
|
418
423
|
const inputsDir = join(runDir, 'inputs');
|
|
419
424
|
mkdirSync(inputsDir, { recursive: true });
|
|
420
425
|
const manifest = [];
|
|
@@ -432,9 +437,16 @@ export async function freezeInputs(runDir, sources, { fetchPage } = {}) {
|
|
|
432
437
|
copyFileSync(sourcePath, frozenPath);
|
|
433
438
|
const sha256 = hashFile(frozenPath);
|
|
434
439
|
const { size: bytes } = statSync(frozenPath);
|
|
435
|
-
|
|
440
|
+
/** @type {Record<string, any>} */
|
|
441
|
+
const entry = {
|
|
436
442
|
id, source: sourcePath, frozen: frozenPath, sha256, bytes,
|
|
437
|
-
}
|
|
443
|
+
};
|
|
444
|
+
if (tableRoles.includes(id)) {
|
|
445
|
+
const tsha = isCellsPath(frozenPath) ? tableShaOfFrozen(runDir, basename(frozenPath)) : null;
|
|
446
|
+
if (tsha === null) return { ok: false, red: `freeze: input "${id}" cannot be read as a table (a row with more or fewer cells than the header, or a repeated column name); fix the sheet` };
|
|
447
|
+
entry.tableSha = tsha;
|
|
448
|
+
}
|
|
449
|
+
manifest.push(entry);
|
|
438
450
|
}
|
|
439
451
|
writeFileSync(join(runDir, 'inputs.json'), JSON.stringify(manifest, null, 2));
|
|
440
452
|
return { ok: true, manifest };
|
|
@@ -836,7 +848,7 @@ export async function runStepRalph({
|
|
|
836
848
|
// M4d am25: `thinkingMode` is the ONE decision of what this try asks of thinking (`stepThinkingMode`); the model step only passes it on.
|
|
837
849
|
// M10 am7 item 3: `cited` is the fact part of a green step that quotes a saved page - the form of its ANSWER ({results: [{quote, values}]}) and the facts it must hold,
|
|
838
850
|
// told to the step in plain words by the model step. It is not the check: the quotes are checked by `closeCited` against the run's own copy.
|
|
839
|
-
const stepMeta = Object.freeze({ class: step.close?.class ?? null, cited: step.close?.class === 'green' && step.close.cited ? step.close.cited : null, attempt, step: step?.emits ?? step?.goal ?? null, thinkingMode: stepThinkingMode({ boxOn: thinkingBox, attempt }) });
|
|
851
|
+
const stepMeta = Object.freeze({ class: step.close?.class ?? null, cited: step.close?.class === 'green' && step.close.cited ? step.close.cited : null, sheet: step.close?.class === 'green' && Array.isArray(step.close.sheet) ? step.close.sheet : null, attempt, step: step?.emits ?? step?.goal ?? null, thinkingMode: stepThinkingMode({ boxOn: thinkingBox, attempt }) });
|
|
840
852
|
|
|
841
853
|
const stopSeam = readStop ? Object.freeze({ stopRequested: readStop }) : undefined;
|
|
842
854
|
|
|
@@ -979,7 +991,12 @@ export async function runStepRalph({
|
|
|
979
991
|
// written by the one writer, `writeCitedLine`, whatever the verdict - the Result tab says why a line did not pass.
|
|
980
992
|
const citedPart = step?.close?.class === 'green' ? step?.close?.cited : undefined;
|
|
981
993
|
const source = citedPart && runDir !== null ? readRunSource(runDir, citedPart.source, { docx: true }) : undefined;
|
|
982
|
-
|
|
994
|
+
// M10b piece 2: a step with `close.sheet` is checked by bareguard on the run's own frozen copy and the `tableSha` recorded at its start; the record of what it
|
|
995
|
+
// said is written by the one writer, `writeSheetLine`, whatever the verdict.
|
|
996
|
+
const sheetPart = step?.close?.class === 'green' && Array.isArray(step?.close?.sheet) ? step.close.sheet : undefined;
|
|
997
|
+
const sheet = sheetPart && runDir !== null ? readRunSheets(runDir, sheetPart) : undefined;
|
|
998
|
+
const closed = await closeByClass(step, artifact, { reads: readsMap, businessDate, source, sheet });
|
|
999
|
+
if (sheetPart && runDir !== null && closed.sheetRecord) writeSheetLine(runDir, { n: step.fromLine, try: attempt, checks: sheetPart, closed });
|
|
983
1000
|
if (citedPart && runDir !== null && closed.cited) {
|
|
984
1001
|
writeCitedLine(runDir, citedLineOf({
|
|
985
1002
|
n: step.fromLine, part: closed.cited.part, results: closed.cited.results, check: closed.cited.check,
|
|
@@ -1163,7 +1180,7 @@ export async function runFlow({
|
|
|
1163
1180
|
writeRunThinking(flowDir, runDir);
|
|
1164
1181
|
if (runModel) writeRunModel(runDir, runModel); // M4d am33: the one record of the model this run started on
|
|
1165
1182
|
|
|
1166
|
-
const frozen = await freezeInputs(runDir, sources ?? [], { fetchPage });
|
|
1183
|
+
const frozen = await freezeInputs(runDir, sources ?? [], { fetchPage, tableRoles: sheetRolesOf(declaration.steps) });
|
|
1167
1184
|
if (!frozen.ok) {
|
|
1168
1185
|
return haltRun({
|
|
1169
1186
|
flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: frozen.red, spent: { value: 0 },
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// M10b piece 2: the ONE writer of `<run>/sheet-checks.json`, the record of what each sheet check said in this run, for the separate checker that re-runs a run's
|
|
2
|
+
// signed checks against its saved sheet (M10b "Done when"). Append-only: one entry per (job line, try), written the moment that try's check has run, never replaced.
|
|
3
|
+
// Shape: { lines: [ { n, try, passed, tables: [{name, tableSha}], checks: [the signed check objects], claims: <the step's answer>, results: [{id, text, ok, result}], red } ] }.
|
|
4
|
+
// `tables[].tableSha` is the one recorded at the run's start (inputs.json), the one the check used. Throws away: nothing the check saw; no cell text is kept here.
|
|
5
|
+
import { writeFileSync, renameSync } from 'node:fs';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
import { readFileInside } from './flow.js';
|
|
8
|
+
|
|
9
|
+
/** the record's name in the run's own folder */
|
|
10
|
+
export const SHEET_CHECKS_FILE = 'sheet-checks.json';
|
|
11
|
+
|
|
12
|
+
const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* @param {string} runDir @param {{n: number, try: number, checks: any[], closed: {verdict: string, red?: string|null, sheetRecord?: any}}} o
|
|
16
|
+
* @returns {void}
|
|
17
|
+
*/
|
|
18
|
+
export function writeSheetLine(runDir, { n, try: attempt, checks, closed }) {
|
|
19
|
+
const rec = closed.sheetRecord;
|
|
20
|
+
if (!rec) return;
|
|
21
|
+
/** @type {any[]} */
|
|
22
|
+
let lines = [];
|
|
23
|
+
const had = readFileInside(runDir, SHEET_CHECKS_FILE);
|
|
24
|
+
if (had.ok) {
|
|
25
|
+
try {
|
|
26
|
+
const parsed = JSON.parse(had.text);
|
|
27
|
+
if (isRec(parsed) && Array.isArray(parsed.lines)) lines = parsed.lines;
|
|
28
|
+
} catch { lines = []; }
|
|
29
|
+
}
|
|
30
|
+
if (lines.some((l) => isRec(l) && l.n === n && l.try === attempt)) return;
|
|
31
|
+
lines.push({
|
|
32
|
+
n, try: attempt, passed: closed.verdict === 'green',
|
|
33
|
+
tables: rec.inputs.map((/** @type {any} */ i) => ({ name: i.name, tableSha: i.sha256 })),
|
|
34
|
+
checks: JSON.parse(JSON.stringify(checks)),
|
|
35
|
+
claims: rec.claims,
|
|
36
|
+
results: rec.checks,
|
|
37
|
+
red: closed.verdict === 'green' ? null : (closed.red ?? null),
|
|
38
|
+
});
|
|
39
|
+
const file = join(runDir, SHEET_CHECKS_FILE);
|
|
40
|
+
const tmp = `${file}.tmp`;
|
|
41
|
+
writeFileSync(tmp, `${JSON.stringify({ lines }, null, 2)}\n`);
|
|
42
|
+
renameSync(tmp, file);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The reader of the record, for the Result tab and the separate checker: `{lines: [...]}`, or null when the file is missing or is not that shape (the page then
|
|
47
|
+
* shows no verdicts, never a half-read record). Read through the safe gateway.
|
|
48
|
+
* @param {string} runDir @returns {{lines: any[]}|null}
|
|
49
|
+
*/
|
|
50
|
+
export function readSheetChecks(runDir) {
|
|
51
|
+
const got = readFileInside(runDir, SHEET_CHECKS_FILE);
|
|
52
|
+
if (!got.ok) return null;
|
|
53
|
+
try {
|
|
54
|
+
const parsed = JSON.parse(got.text);
|
|
55
|
+
return isRec(parsed) && Array.isArray(parsed.lines) ? { lines: parsed.lines } : null;
|
|
56
|
+
} catch { return null; }
|
|
57
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
// M10b piece 4 (docs/wiki/the-module-ladder.md "M10b amendment 2", items 4 and 7): the ONE builder of what a job line that reads a sheet shows -
|
|
2
|
+
// { guardrails, checked: [{id, name, words, covers, text}], notChecked: [guardrail, ...] | 'none' }
|
|
3
|
+
// from the signed declaration (the step's `close.sheet`, each check's `covers` tag) and the job line's own `~` rules. After a run, `record` (the
|
|
4
|
+
// `sheet-checks.json` lines, src/sheet-record.js) adds to each check its verdict and what was found: `{ok, found}`. Every surface (the Chat plan card, the Job tab, the
|
|
5
|
+
// Result tab, the Audit's check rows) shows this block's strings; none of them words a check itself.
|
|
6
|
+
// Throws away: the check's id, claim, range and the other typed fields that do not change what it says (src/sheetchecks.js `sheetCheckSentence` drops them too).
|
|
7
|
+
// A green "found" is the step's OWN claimed value in plain words (a number, or a count of rows / days / bands / groups); a string claim (a looked-up cell) is never
|
|
8
|
+
// repeated, because it is cell text. A red "found" is bareguard's gap words (row numbers and counts), never a cell's text.
|
|
9
|
+
// Third outcomes, named: a line the run never reached (no record) carries no verdict; a check the record lacks carries none (the page shows no mark).
|
|
10
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
11
|
+
import { rubricVocabulary } from 'bareguard';
|
|
12
|
+
import { lineRules } from './pagebits.js';
|
|
13
|
+
import { sheetCheckSentence } from './sheetchecks.js';
|
|
14
|
+
import { isColumnChoiceRule } from './sheetoffer.js';
|
|
15
|
+
|
|
16
|
+
const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
17
|
+
|
|
18
|
+
/** 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. */
|
|
19
|
+
export const SHEET_OP_NAMES = Object.freeze({
|
|
20
|
+
count: 'count', countEmpty: 'empty count', countIf: 'count', uniqueCount: 'unique count',
|
|
21
|
+
sum: 'sum', sumIf: 'sum', average: 'average', averageIf: 'average', median: 'median', min: 'min', max: 'max',
|
|
22
|
+
found: 'found', lookup: 'lookup', rows: 'rows', topN: 'top', duplicates: 'duplicates', groupTotals: 'group totals', percentOfTotal: 'percent of total',
|
|
23
|
+
band: 'bucket', daysBetween: 'days between', daysSince: 'date', earliest: 'earliest date', latest: 'latest date',
|
|
24
|
+
allNumbers: 'all numbers', allDates: 'all dates', noEmpty: 'no empty', noDuplicates: 'no duplicate', rowCount: 'row count', rowMath: 'row math',
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
/** the ops of bareguard that a name is needed for @returns {string[]} */
|
|
28
|
+
export function vocabularyOps() {
|
|
29
|
+
const V = /** @type {any} */ (rubricVocabulary);
|
|
30
|
+
return [...new Set(['cells', 'table'].flatMap((r) => Object.keys(V.rules[r].ops)))];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** @param {any} check a bareguard cells / table check @returns {string} the short name: `rows`, `count`, `sum`, `no duplicate Invoice #` ... */
|
|
34
|
+
export function sheetCheckName(check) {
|
|
35
|
+
if (!isRec(check)) return 'a check';
|
|
36
|
+
const base = Object.hasOwn(SHEET_OP_NAMES, check.op) ? /** @type {Record<string, string>} */ (SHEET_OP_NAMES)[check.op] : String(check.op);
|
|
37
|
+
return (check.op === 'noDuplicates' || check.op === 'noEmpty') && typeof check.column === 'string' ? `${base} ${check.column}` : base;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* What the step claimed for one check, in plain words (a green check's "found"). Null when the claim has nothing to say (a `table` check, a missing box, a string).
|
|
42
|
+
* @param {any} check @param {unknown} claims the step's answer @returns {string|null}
|
|
43
|
+
*/
|
|
44
|
+
export function sheetFoundWords(check, claims) {
|
|
45
|
+
if (!isRec(check) || typeof check.claim !== 'string' || !isRec(claims) || !isRec(/** @type {any} */ (claims)[check.claim])) return null;
|
|
46
|
+
const box = /** @type {Record<string, any>} */ (/** @type {any} */ (claims)[check.claim]);
|
|
47
|
+
const plural = (/** @type {number} */ n, /** @type {string} */ one, /** @type {string} */ many) => `${n} ${n === 1 ? one : many}`;
|
|
48
|
+
if (typeof box.value === 'number' || typeof box.value === 'boolean') return typeof box.value === 'boolean' ? (box.value ? 'yes' : 'no') : String(box.value);
|
|
49
|
+
if (Array.isArray(box.rows)) return plural(box.rows.length, 'row', 'rows');
|
|
50
|
+
if (Array.isArray(box.keys)) return plural(box.keys.length, 'row', 'rows');
|
|
51
|
+
if (Array.isArray(box.values)) return plural(box.values.length, 'value', 'values');
|
|
52
|
+
if (Array.isArray(box.totals)) return plural(box.totals.length, 'group', 'groups');
|
|
53
|
+
if (isRec(box.days)) return plural(Object.keys(box.days).length, 'row', 'rows');
|
|
54
|
+
if (isRec(box.bands)) return plural(Object.keys(box.bands).length, 'row', 'rows');
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** @param {any} l a job line `{rules?, guardrail?, rule?}` @returns {string[]} its `~` rules, numbered from 1 by position */
|
|
59
|
+
export const rulesOfLine = (l) => lineRules({ ...(Array.isArray(l?.rules) ? { rules: l.rules } : {}), rule: l?.guardrail ?? l?.rule });
|
|
60
|
+
|
|
61
|
+
/** the "covers ..." words of one check @param {string[]} rules @returns {string} "" when it covers none */
|
|
62
|
+
export const coversWords = (rules) => rules.map((r) => `covers "${r}"`).join(' · ');
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* The block of every job line whose step reads a sheet. A line qualifies when its green step carries `close.sheet`, or (with `csvRoles`) reads a CSV input and carries no
|
|
66
|
+
* older `close.columns` / `close.cited` check (then every guardrail is Not checked).
|
|
67
|
+
* @param {{declaration: any, lines: Array<{n: number, rules?: string[], guardrail?: string, rule?: string}>, csvRoles?: string[], record?: any}} o
|
|
68
|
+
* `record` = the parsed `sheet-checks.json` (`{lines: [...]}`), only after a run
|
|
69
|
+
* @returns {Array<{line: number, guardrails: string[], checked: Array<{id: string, name: string, words: string, covers: string[], coversWords: string, text: string, ok?: boolean, found?: string}>, notChecked: string[]|'none'}>}
|
|
70
|
+
*/
|
|
71
|
+
export function sheetLineBlocks({ declaration, lines, csvRoles = [], record }) {
|
|
72
|
+
const out = [];
|
|
73
|
+
if (!isRec(declaration) || !Array.isArray(declaration.steps)) return out;
|
|
74
|
+
const seen = new Set();
|
|
75
|
+
for (const st of declaration.steps) {
|
|
76
|
+
if (!isRec(st) || !isRec(st.close) || st.close.class !== 'green' || !Number.isInteger(st.fromLine) || seen.has(st.fromLine)) continue;
|
|
77
|
+
const hasSheet = Array.isArray(st.close.sheet) && st.close.sheet.length > 0;
|
|
78
|
+
const readsCsv = Array.isArray(st.reads) && st.reads.some((/** @type {string} */ r) => csvRoles.includes(r));
|
|
79
|
+
if (!hasSheet && (!readsCsv || st.close.columns !== undefined || st.close.cited !== undefined)) continue;
|
|
80
|
+
seen.add(st.fromLine);
|
|
81
|
+
const guardrails = rulesOfLine((Array.isArray(lines) ? lines : []).find((l) => l.n === st.fromLine));
|
|
82
|
+
const covered = new Set();
|
|
83
|
+
const tried = Array.isArray(record?.lines) ? record.lines.filter((/** @type {any} */ l) => isRec(l) && l.n === st.fromLine && Number.isInteger(l.try)) : [];
|
|
84
|
+
const newest = tried.reduce((/** @type {any} */ m, /** @type {any} */ l) => (m === null || l.try >= m.try ? l : m), null);
|
|
85
|
+
const checked = (hasSheet ? st.close.sheet : []).map((/** @type {any} */ c) => {
|
|
86
|
+
const nums = Array.isArray(c.covers) ? c.covers.filter((/** @type {unknown} */ x) => Number.isInteger(x) && /** @type {number} */ (x) >= 1 && /** @type {number} */ (x) <= guardrails.length) : [];
|
|
87
|
+
for (const x of nums) covered.add(x);
|
|
88
|
+
const rules = [...new Set(nums)].sort((a, b) => a - b).map((x) => guardrails[x - 1]);
|
|
89
|
+
const name = sheetCheckName(c);
|
|
90
|
+
const words = sheetCheckSentence(c);
|
|
91
|
+
const cw = coversWords(rules);
|
|
92
|
+
/** @type {any} */
|
|
93
|
+
const e = { id: typeof c.id === 'string' ? c.id : '', name, words, covers: rules, coversWords: cw, text: [name, ...(words === name ? [] : [words]), ...(cw ? [cw] : [])].join(' — ') };
|
|
94
|
+
const res = newest && Array.isArray(newest.results) ? newest.results.find((/** @type {any} */ r) => isRec(r) && r.id === c.id) : undefined;
|
|
95
|
+
if (isRec(res) && typeof res.ok === 'boolean') {
|
|
96
|
+
e.ok = res.ok;
|
|
97
|
+
if (res.ok) {
|
|
98
|
+
const f = sheetFoundWords(c, newest.claims);
|
|
99
|
+
e.found = f === null ? `${name} checked` : `${name} checked — ${f}`;
|
|
100
|
+
} else {
|
|
101
|
+
const gap = typeof res.result === 'string' ? res.result.split('\n').map((/** @type {string} */ x) => x.trim().replace(`${e.id}: `, '')).filter(Boolean).join('; ') : '';
|
|
102
|
+
e.found = `${name} — ${gap || 'did not pass'}`;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return e;
|
|
106
|
+
});
|
|
107
|
+
const notChecked = guardrails.filter((r, i) => !isColumnChoiceRule(r) && !covered.has(i + 1));
|
|
108
|
+
out.push({ line: st.fromLine, guardrails, checked, notChecked: notChecked.length === 0 ? /** @type {'none'} */ ('none') : notChecked });
|
|
109
|
+
}
|
|
110
|
+
return out;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* The guardrail rules of a sheet step that no check covers, as the drafter's Not-checked lines (`line N: "rule" - no sheet check covers it`): the block's own
|
|
115
|
+
* `notChecked`, one list for the plan card and the drafter's saved record.
|
|
116
|
+
* @param {any} declaration @param {Array<{n: number, rules?: string[], guardrail?: string, rule?: string}>} lines @param {string[]} csvRoles @returns {string[]}
|
|
117
|
+
*/
|
|
118
|
+
export function uncoveredRules(declaration, lines, csvRoles) {
|
|
119
|
+
if (csvRoles.length === 0) return [];
|
|
120
|
+
return sheetLineBlocks({ declaration, lines, csvRoles }).flatMap((b) => (b.notChecked === 'none' ? [] : b.notChecked.map((r) => `line ${b.line}: "${r}" \u2014 no sheet check covers it`)));
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** @param {any} arbiter @returns {string[]} the roles of the signed sources that are a CSV file (the sheets a check reads) */
|
|
124
|
+
export function csvRolesOf(arbiter) {
|
|
125
|
+
return (Array.isArray(arbiter?.sources) ? arbiter.sources : [])
|
|
126
|
+
.filter((/** @type {any} */ s) => isRec(s) && s.kind !== 'page' && typeof s.path === 'string' && s.path.toLowerCase().endsWith('.csv') && typeof s.role === 'string')
|
|
127
|
+
.map((/** @type {any} */ s) => s.role);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** one value of a claim in the words of a line: text as it is, anything else as JSON */
|
|
131
|
+
const claimShow = (/** @type {unknown} */ v) => (typeof v === 'string' ? v : JSON.stringify(v));
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* M10b am4: the step's answer (its claim boxes) value by value, one line each: `invoiceCount: 8`, `daysPastDue: row 2 -> 124`. A list is one line per entry (a list of row
|
|
135
|
+
* numbers reads `row N`); a map is one line per key (`row <key> -> <value>`). An empty list or map reads `<name>: none`, never no line.
|
|
136
|
+
* Throws away: nothing but the box's own key (`value`, `rows`, `days`...), which the line's words already say.
|
|
137
|
+
* @param {unknown} claims the step's answer @returns {string[]}
|
|
138
|
+
*/
|
|
139
|
+
export function claimLines(claims) {
|
|
140
|
+
const out = [];
|
|
141
|
+
if (!isRec(claims)) return out;
|
|
142
|
+
for (const [name, box] of Object.entries(/** @type {Record<string, any>} */ (claims))) {
|
|
143
|
+
if (!isRec(box)) { out.push(`${name}: ${claimShow(box)}`); continue; }
|
|
144
|
+
for (const [key, v] of Object.entries(box)) {
|
|
145
|
+
if (Array.isArray(v)) {
|
|
146
|
+
if (v.length === 0) out.push(`${name}: none`);
|
|
147
|
+
for (const e of v) out.push(`${name}: ${key === 'rows' || key === 'keys' ? 'row ' : ''}${claimShow(e)}`);
|
|
148
|
+
} else if (isRec(v)) {
|
|
149
|
+
if (Object.keys(v).length === 0) out.push(`${name}: none`);
|
|
150
|
+
for (const [k, e] of Object.entries(v)) out.push(`${name}: row ${k} \u2192 ${claimShow(e)}`);
|
|
151
|
+
} else out.push(`${name}: ${claimShow(v)}`);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return out;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* M10b am4: what an ask card shows for the claim boxes it was given. The step is the sheet step whose saved try (`sheet-checks.json`) holds exactly these claims; its block is
|
|
159
|
+
* the Result tab's own (`sheetLineBlocks`, that try's verdicts), and `answer` is the claims value by value. Null when no saved try matches: the caller then keeps the old line.
|
|
160
|
+
* @param {{claims: unknown, declaration: any, lines: Array<{n: number, rules?: string[], guardrail?: string, rule?: string}>, csvRoles?: string[], record?: any}} o
|
|
161
|
+
* @returns {{block: ReturnType<typeof sheetLineBlocks>[number], answer: string[]}|null}
|
|
162
|
+
*/
|
|
163
|
+
export function askSheetCard({ claims, declaration, lines, csvRoles = [], record }) {
|
|
164
|
+
if (!isRec(claims) || !Array.isArray(record?.lines)) return null;
|
|
165
|
+
const same = record.lines.filter((/** @type {any} */ l) => isRec(l) && Number.isInteger(l.try) && Number.isInteger(l.n) && isDeepStrictEqual(l.claims, claims));
|
|
166
|
+
const newest = same.reduce((/** @type {any} */ m, /** @type {any} */ l) => (m === null || l.try >= m.try ? l : m), null);
|
|
167
|
+
if (newest === null) return null;
|
|
168
|
+
const block = sheetLineBlocks({ declaration, lines, csvRoles, record: { lines: [newest] } }).find((b) => b.line === newest.n);
|
|
169
|
+
return block ? { block, answer: claimLines(claims) } : null;
|
|
170
|
+
}
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
// M10b piece 1 (docs/wiki/the-module-ladder.md "M10b scope" item 4 and amendment 1): the signed checks of a sheet live in the job, in the step's close
|
|
2
|
+
// (`close.sheet`). Each entry is a bareguard `cells` / `table` check object, kept as DATA exactly as bareguard defines it (src/primitives/rubric.js
|
|
3
|
+
// `rubricVocabulary`); fwdloop has no check language of its own. Three things live here, each once:
|
|
4
|
+
// - `sheetCheckColumns` every column name a check holds, wherever bareguard puts one (the code proves each is an exact header of the sheet);
|
|
5
|
+
// - `sheetCheckReds` the $0 sign-time test: the checks are built into a bareguard rubric over the drafting copy's table (its `tableSha`), and a
|
|
6
|
+
// refusal comes back as a red naming the job line;
|
|
7
|
+
// - `sheetCheckSentence` the plain words of one check, written from its typed fields, for the plan card and the readout.
|
|
8
|
+
// Throws away: nothing is stored here; the sentence leaves out fields that do not change what the check says (id, claim, range, tolerance, valueKind).
|
|
9
|
+
// Third outcomes, each named, never silently fine: a sheet bareguard cannot read as a table (`tableSha` null: a row with another cell count than the header,
|
|
10
|
+
// a repeated header), a role with no drafting copy, a refusal by `createRubric`.
|
|
11
|
+
|
|
12
|
+
import { createRubric, tableSha } from 'bareguard';
|
|
13
|
+
import { numbersSaid } from './citedwords.js';
|
|
14
|
+
import { wordsSaidOn, lineRules } from './pagebits.js';
|
|
15
|
+
|
|
16
|
+
/** the bareguard rules a sheet check may use (`diff` is out of scope for M10b) */
|
|
17
|
+
export const SHEET_RULES = Object.freeze(['cells', 'table']);
|
|
18
|
+
/** most checks one step may carry */
|
|
19
|
+
export const MAX_SHEET_CHECKS = 20;
|
|
20
|
+
|
|
21
|
+
const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
22
|
+
|
|
23
|
+
/** the fields of a check that hold a column name as a plain string (the ONE list: {@link sheetCheckColumns} reads it, the drafter's tool schema offers a header enum on each) */
|
|
24
|
+
export const COLUMN_STRING_FIELDS = Object.freeze(['column', 'keyColumn', 'groupColumn', 'result']);
|
|
25
|
+
/** the row-math operands: a column name, or (for `b`) `{const}` */
|
|
26
|
+
export const COLUMN_OPERAND_FIELDS = Object.freeze(['a', 'b']);
|
|
27
|
+
/** the date-cell fields: `{column, row}` */
|
|
28
|
+
export const COLUMN_CELL_FIELDS = Object.freeze(['from', 'to', 'cell']);
|
|
29
|
+
/** the list fields whose entries hold a `column` */
|
|
30
|
+
export const COLUMN_LIST_FIELDS = Object.freeze(['where', 'dateFormats']);
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Every column name one check holds: its own `column`, `keyColumn`, `groupColumn`, `result`, a row-math operand `a` / `b` (a name; `{const}` is no column), the
|
|
34
|
+
* date cells `from` / `to` / `cell`, and the column of each `where` condition and `dateFormats` entry.
|
|
35
|
+
* @param {any} check @returns {string[]}
|
|
36
|
+
*/
|
|
37
|
+
export function sheetCheckColumns(check) {
|
|
38
|
+
if (!isRec(check)) return [];
|
|
39
|
+
const out = [];
|
|
40
|
+
for (const k of [...COLUMN_STRING_FIELDS, ...COLUMN_OPERAND_FIELDS]) if (typeof check[k] === 'string') out.push(check[k]);
|
|
41
|
+
for (const k of COLUMN_CELL_FIELDS) if (isRec(check[k]) && typeof check[k].column === 'string') out.push(check[k].column);
|
|
42
|
+
for (const k of COLUMN_LIST_FIELDS) if (Array.isArray(check[k])) for (const e of check[k]) if (isRec(e) && typeof e.column === 'string') out.push(e.column);
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const CMP_WORDS = Object.freeze({
|
|
47
|
+
gt: '>', gte: '>=', lt: '<', lte: '<=', eq: '=', before: 'before', after: 'after', dateOn: 'on', equals: 'is',
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
/** @param {any} w one `where` condition @returns {string} */
|
|
51
|
+
function conditionWords(w) {
|
|
52
|
+
if (!isRec(w)) return '?';
|
|
53
|
+
const col = String(w.column);
|
|
54
|
+
const v = (/** @type {unknown} */ x) => (typeof x === 'string' ? `"${x}"` : String(x));
|
|
55
|
+
if (w.cmp === 'between' || w.cmp === 'dateBetween') return `${col} between ${v(w.lo)} and ${v(w.hi)}`;
|
|
56
|
+
if (w.cmp === 'empty') return `${col} is empty`;
|
|
57
|
+
if (w.cmp === 'notEmpty') return `${col} is not empty`;
|
|
58
|
+
const sym = /** @type {Record<string, string>} */ (CMP_WORDS)[w.cmp];
|
|
59
|
+
return `${col} ${sym ?? String(w.cmp)} ${v(w.value)}`;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** @param {any} check @returns {string} " where A > 1 and B is empty", or "" */
|
|
63
|
+
const whereWords = (check) => (Array.isArray(check.where) && check.where.length > 0 ? ` where ${check.where.map(conditionWords).join(' and ')}` : '');
|
|
64
|
+
|
|
65
|
+
/** @param {any} b one band @returns {string} */
|
|
66
|
+
const bandName = (b) => (isRec(b) ? String(b.name) : '?');
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* The plain words of ONE sheet check, written from its typed fields (never from model text). The ONE function; the plan card, the readout and the Checked
|
|
70
|
+
* list all call it. An op with no sentence of its own reads `<rule> <op> on <column>` plus its conditions, so a check can never be shown as nothing.
|
|
71
|
+
* @param {any} check a bareguard cells / table check object @returns {string}
|
|
72
|
+
*/
|
|
73
|
+
export function sheetCheckSentence(check) {
|
|
74
|
+
if (!isRec(check)) return 'a check that is not readable';
|
|
75
|
+
const col = typeof check.column === 'string' ? check.column : '';
|
|
76
|
+
const asOf = typeof check.asOf === 'string' ? ` as of ${check.asOf}` : '';
|
|
77
|
+
switch (check.op) {
|
|
78
|
+
case 'rows': return `rows${whereWords(check)}`;
|
|
79
|
+
case 'countIf': return `count of rows${whereWords(check)}`;
|
|
80
|
+
case 'count': return `count of ${col}`;
|
|
81
|
+
case 'sumIf': return `sum of ${col}${whereWords(check)}`;
|
|
82
|
+
case 'sum': return `sum of ${col}`;
|
|
83
|
+
case 'averageIf': return `average of ${col}${whereWords(check)}`;
|
|
84
|
+
case 'average': return `average of ${col}`;
|
|
85
|
+
case 'band': return `band on ${col}${asOf}: ${(Array.isArray(check.bands) ? check.bands : []).map(bandName).join(', ')}${whereWords(check)}`;
|
|
86
|
+
case 'daysSince': return `days since ${col || 'a date cell'}${asOf}${whereWords(check)}`;
|
|
87
|
+
case 'noDuplicates': return `no duplicate ${col}`;
|
|
88
|
+
case 'noEmpty': return `no empty ${col}`;
|
|
89
|
+
case 'allNumbers': return `every ${col} is a number`;
|
|
90
|
+
case 'allDates': return `every ${col} is a date`;
|
|
91
|
+
case 'rowCount': return `the sheet has ${check.n} rows`;
|
|
92
|
+
default: return `${check.rule} ${check.op}${col ? ` on ${col}` : ''}${whereWords(check)}`;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* M10b piece 4: a signed check may carry fwdloop's own `covers` (the numbers of the job line's `~` rules the drafter tagged it to; signed, so the person sees it).
|
|
98
|
+
* bareguard does not know it, so the checks are cleaned HERE, the ONE place, on the way into bareguard (`createRubric` at sign time and at run time).
|
|
99
|
+
* @param {any[]} checks @returns {any[]} a copy without `covers`
|
|
100
|
+
*/
|
|
101
|
+
export function bareguardChecks(checks) {
|
|
102
|
+
return checks.map((c) => { if (!isRec(c) || !('covers' in c)) return c; const { covers: _kept, ...rest } = c; return rest; });
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* M10b piece 4: `covers`, when a check has it, is a list of rule numbers of its job line (counted from 1 over the line's `~` rules). A check without it is fine (an old draft).
|
|
107
|
+
* @param {any[]} checks @param {{n: number, rule?: string, rules?: string[]}} jobLine @returns {string[]} reds, each naming the line and the check
|
|
108
|
+
*/
|
|
109
|
+
export function sheetCoversReds(checks, jobLine) {
|
|
110
|
+
const reds = [];
|
|
111
|
+
const nRules = lineRules(jobLine).length;
|
|
112
|
+
for (const c of checks) {
|
|
113
|
+
if (!isRec(c) || c.covers === undefined) continue;
|
|
114
|
+
if (!Array.isArray(c.covers) || c.covers.some((x) => !Number.isInteger(x) || x < 1 || x > nRules)) {
|
|
115
|
+
reds.push(`declaration: line ${jobLine.n}: the sheet check${typeof c.id === 'string' ? ` '${c.id}'` : ''} "covers" must list rule numbers of line ${jobLine.n}'s guardrail (it has ${nRules} rule${nRules === 1 ? '' : 's'}, counted from 1)`);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return reds;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** The rows for a step's `close.sheet`, one per check, in order. @param {unknown} sheet @returns {string[]} */
|
|
122
|
+
export function sheetCheckRows(sheet) {
|
|
123
|
+
return Array.isArray(sheet) ? sheet.map(sheetCheckSentence) : [];
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* The $0 sign-time test of one step's sheet checks (M10b item 4): bareguard's `createRubric` is given the checks and the signed fingerprint of each sheet
|
|
128
|
+
* they read (`tableSha` of the drafting copy's table). A refusal is a red that names the job line (and the check). A column that is no header of its sheet is
|
|
129
|
+
* a red naming the line and the column. Never throws.
|
|
130
|
+
* @param {any[]} checks the step's `close.sheet` (already known to be a list of objects) @param {number} line the job line the step comes from
|
|
131
|
+
* @param {Record<string, {header: string[], rows: any[]}>} tables the drafting copy's table of each sheet role @returns {string[]} reds, each naming the line
|
|
132
|
+
*/
|
|
133
|
+
export function sheetCheckReds(checks, line, tables) {
|
|
134
|
+
const reds = [];
|
|
135
|
+
const at = `declaration: line ${line}:`;
|
|
136
|
+
/** @type {Map<string, string|null>} */
|
|
137
|
+
const shas = new Map();
|
|
138
|
+
for (const c of checks) {
|
|
139
|
+
if (!isRec(c) || typeof c.table !== 'string' || shas.has(c.table)) continue;
|
|
140
|
+
const t = tables[c.table];
|
|
141
|
+
if (!t) { shas.set(c.table, null); reds.push(`${at} the sheet check reads "${c.table}", which has no saved copy to test against`); continue; }
|
|
142
|
+
shas.set(c.table, tableSha(t));
|
|
143
|
+
if (shas.get(c.table) === null) reds.push(`${at} bareguard cannot read "${c.table}" as a table (a row with more or fewer cells than the header, or a repeated column name); fix the sheet`);
|
|
144
|
+
}
|
|
145
|
+
for (const c of checks) {
|
|
146
|
+
const t = isRec(c) && typeof c.table === 'string' ? tables[c.table] : undefined;
|
|
147
|
+
if (!t) continue;
|
|
148
|
+
for (const name of sheetCheckColumns(c)) {
|
|
149
|
+
if (!t.header.includes(name)) reds.push(`${at} '${name}' is not a real column of "${c.table}" (its columns: ${t.header.map((h) => `'${h}'`).join(', ')}). Copy a column name exactly.`);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
if (reds.length > 0) return reds;
|
|
153
|
+
const inputs = [...shas].map(([name, sha256]) => ({ name, sha256 }));
|
|
154
|
+
try {
|
|
155
|
+
createRubric({ schema: 1, goal: `line ${line}`, inputs, checkpoints: { sheet: { gating: true, checks: bareguardChecks(checks) } }, maxReds: 3 });
|
|
156
|
+
} catch (err) {
|
|
157
|
+
const msg = String(/** @type {any} */ (err).message).replace(/^invalid rubric: /, '');
|
|
158
|
+
const idx = /checks\[(\d+)\]/.exec(String(/** @type {any} */ (err).path ?? msg));
|
|
159
|
+
const who = idx && isRec(checks[Number(idx[1])]) && typeof checks[Number(idx[1])].id === 'string' ? ` '${checks[Number(idx[1])].id}'` : '';
|
|
160
|
+
reds.push(`${at} bareguard refuses the sheet check${who}: ${msg}`);
|
|
161
|
+
}
|
|
162
|
+
return reds;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const NUMBER_CMPS = Object.freeze(['gt', 'gte', 'lt', 'lte', 'eq', 'between']);
|
|
166
|
+
const DATE_CMPS = Object.freeze(['before', 'after', 'dateOn', 'dateBetween']);
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* M10b piece 3: a number or a date in a check comes from the job, never from the model. Every number in a `where` condition (gt gte lt lte eq between) must be a
|
|
170
|
+
* number the person said on the job line or its `~` rules (the SAME reader as the page number rules, src/citedwords.js `numbersSaid`: a bare number or an amount,
|
|
171
|
+
* not a piece of a time, a date or another amount), and every date (`asOf`, and the values of before / after / dateOn / dateBetween) must be a date they wrote
|
|
172
|
+
* exactly. Throws away: a text value (`equals`, `needle`), band bounds, `n`, `tolerance`, `range` are not read here (the job's words do not have to carry them).
|
|
173
|
+
* @param {any[]} checks the step's `close.sheet` @param {{n: number, text?: string, rule?: string, rules?: string[]}} jobLine @returns {string[]} reds, each naming the line
|
|
174
|
+
*/
|
|
175
|
+
export function sheetCheckWordReds(checks, jobLine) {
|
|
176
|
+
const said = numbersSaid(wordsSaidOn(jobLine));
|
|
177
|
+
const reds = [];
|
|
178
|
+
const n = jobLine.n;
|
|
179
|
+
const who = (/** @type {any} */ c) => (isRec(c) && typeof c.id === 'string' ? ` '${c.id}'` : '');
|
|
180
|
+
const num = (/** @type {any} */ c, /** @type {unknown} */ v, /** @type {string} */ where) => {
|
|
181
|
+
if (typeof v === 'number' && !said.bare.has(v) && !said.amount.has(v)) reds.push(`declaration: line ${n}: the sheet check${who(c)} has the number ${v} (${where}), but ${v} is not in your words on line ${n}. A number in a check must come from the job line or a ~ rule you wrote. Say it there, or leave the condition out.`);
|
|
182
|
+
};
|
|
183
|
+
const date = (/** @type {any} */ c, /** @type {unknown} */ v, /** @type {string} */ where) => {
|
|
184
|
+
if (typeof v === 'string' && !said.date.has(v)) reds.push(`declaration: line ${n}: the sheet check${who(c)} has the date ${v} (${where}), but ${v} is not a date in your words on line ${n}. A date in a check must be written on the job line or a ~ rule, as YYYY-MM-DD. Say it there, or leave it out.`);
|
|
185
|
+
};
|
|
186
|
+
for (const c of checks) {
|
|
187
|
+
if (!isRec(c)) continue;
|
|
188
|
+
if (c.asOf !== undefined) date(c, c.asOf, 'as of');
|
|
189
|
+
for (const w of Array.isArray(c.where) ? c.where : []) {
|
|
190
|
+
if (!isRec(w)) continue;
|
|
191
|
+
const at = `where ${String(w.column)}`;
|
|
192
|
+
if (NUMBER_CMPS.includes(w.cmp)) for (const k of w.cmp === 'between' ? ['lo', 'hi'] : ['value']) num(c, w[k], at);
|
|
193
|
+
else if (DATE_CMPS.includes(w.cmp)) for (const k of w.cmp === 'dateBetween' ? ['lo', 'hi'] : ['value']) date(c, w[k], at);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return reds;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* M10b piece 3: a step whose sheet checks are ALL `table` checks has nothing to answer (a table check judges the sheet itself and carries no claim), so the
|
|
201
|
+
* step would be asked for nothing. Refused at $0, naming the line. @param {any[]} checks @param {number} line @returns {string[]}
|
|
202
|
+
*/
|
|
203
|
+
export function sheetNoClaimReds(checks, line) {
|
|
204
|
+
if (checks.length === 0 || !checks.every((c) => isRec(c) && c.rule === 'table')) return [];
|
|
205
|
+
return [`declaration: line ${line}: every sheet check on this step is a table check, which judges the sheet itself and leaves the step nothing to answer. Pair it with at least one cells check that has a claim (for example rows, countIf, sumIf or band).`];
|
|
206
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// M10b piece 2 (docs/wiki/the-module-ladder.md "M10b scope" item 5): what a step that reads a sheet is told and what box it answers in.
|
|
2
|
+
// A step answers each `cells` check's CLAIM in bareguard's typed box ({value}, {rows}, {days}, {bands}, ...), never a cite or a formula. The shape of every box is
|
|
3
|
+
// generated from bareguard's own worked example for the op (`rubricVocabulary.rules.cells.ops.<op>.example`), never hand-copied here. The step is told the box, not the
|
|
4
|
+
// check: no op, no condition, no bound, no column ever reaches it (the construction test in test/m10b-sheet-run.test.js proves the request carries none).
|
|
5
|
+
// Throws away: a check with no claim (a `table` check judges the sheet itself) adds no box; two checks with the same claim name share one box.
|
|
6
|
+
import { rubricVocabulary } from 'bareguard';
|
|
7
|
+
|
|
8
|
+
const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
9
|
+
|
|
10
|
+
/** whole-number boxes: a row number list, and a days map (bareguard compares these as integers) */
|
|
11
|
+
const INTEGER_KEYS = Object.freeze(['rows', 'days']);
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* The JSON schema of one value in a worked example. Typed from the example's own value; `intKey` = the box key it sits under.
|
|
15
|
+
* @param {any} v @param {string} [intKey] @returns {Record<string, any>}
|
|
16
|
+
*/
|
|
17
|
+
function schemaOf(v, intKey = '') {
|
|
18
|
+
if (typeof v === 'boolean') return { type: 'boolean' };
|
|
19
|
+
if (typeof v === 'number') return { type: INTEGER_KEYS.includes(intKey) ? 'integer' : 'number' };
|
|
20
|
+
if (typeof v === 'string') return { type: 'string' };
|
|
21
|
+
if (Array.isArray(v)) return v.length > 0 ? { type: 'array', items: schemaOf(v[0], intKey) } : { type: 'array' };
|
|
22
|
+
if (isRec(v)) {
|
|
23
|
+
const keys = Object.keys(v);
|
|
24
|
+
// a map keyed by row number (days, bands): every value has the first one's type
|
|
25
|
+
if (keys.length > 0 && keys.every((k) => /^\d+$/.test(k))) return { type: 'object', additionalProperties: schemaOf(v[keys[0]], intKey) };
|
|
26
|
+
return { type: 'object', properties: Object.fromEntries(keys.map((k) => [k, schemaOf(v[k], k)])), required: keys };
|
|
27
|
+
}
|
|
28
|
+
return {};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The claim box of every `cells` check in the list: `[{claim, example}]`, one per claim name, in order. `example` is the op's worked-example answer (the box's shape
|
|
33
|
+
* with example values). A check bareguard has no example for, and a `table` check, add nothing.
|
|
34
|
+
* @param {any[]} checks a step's `close.sheet` @returns {Array<{claim: string, example: Record<string, any>, ops: string[]}>}
|
|
35
|
+
*/
|
|
36
|
+
export function sheetClaims(checks) {
|
|
37
|
+
/** @type {Map<string, {claim: string, example: Record<string, any>, ops: string[]}>} */
|
|
38
|
+
const out = new Map();
|
|
39
|
+
const ops = /** @type {any} */ (rubricVocabulary).rules?.cells?.ops ?? {};
|
|
40
|
+
for (const c of Array.isArray(checks) ? checks : []) {
|
|
41
|
+
if (!isRec(c) || c.rule !== 'cells' || typeof c.claim !== 'string' || typeof c.op !== 'string') continue;
|
|
42
|
+
const ex = ops[c.op]?.example;
|
|
43
|
+
const shape = isRec(ex) && isRec(ex.output) && isRec(ex.check) ? ex.output[ex.check.claim] : undefined;
|
|
44
|
+
if (!isRec(shape)) continue;
|
|
45
|
+
const have = out.get(c.claim);
|
|
46
|
+
if (have) { Object.assign(have.example, shape); have.ops.push(c.op); } else out.set(c.claim, { claim: c.claim, example: { ...shape }, ops: [c.op] });
|
|
47
|
+
}
|
|
48
|
+
return [...out.values()];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* The `emit_artifact` tool's properties for a step that reads a sheet: one typed box per claim, each required. (`done` is added by the caller, as for every step.)
|
|
53
|
+
* @param {any[]} checks @returns {{properties: Record<string, any>, required: string[]}}
|
|
54
|
+
*/
|
|
55
|
+
export function sheetAnswerProps(checks) {
|
|
56
|
+
/** @type {Record<string, any>} */
|
|
57
|
+
const properties = {};
|
|
58
|
+
for (const { claim, example, ops } of sheetClaims(checks)) {
|
|
59
|
+
const keys = Object.keys(example);
|
|
60
|
+
properties[claim] = {
|
|
61
|
+
type: 'object',
|
|
62
|
+
properties: Object.fromEntries(keys.map((k) => [k, ops.includes('lookup') && k === 'value' ? { type: ['string', 'number'] } : schemaOf(example[k], k)])),
|
|
63
|
+
required: keys,
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
return { properties, required: Object.keys(properties) };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* What the step is told about its answer (one key of its request): the name and the shape of each box, with the worked example's values. Never the check.
|
|
71
|
+
* @param {any[]} checks @returns {{answer: string, fields: Record<string, Record<string, any>>}}
|
|
72
|
+
*/
|
|
73
|
+
export function sheetBrief(checks) {
|
|
74
|
+
return {
|
|
75
|
+
answer: 'Answer with one field for each name in "fields", in the shape shown for it. Give the values themselves, worked out from the input - never a cell reference and never a formula. The values shown only illustrate the shape; use the real ones from the input and the job line.',
|
|
76
|
+
fields: Object.fromEntries(sheetClaims(checks).map(({ claim, example }) => [claim, example])),
|
|
77
|
+
};
|
|
78
|
+
}
|