fwdloop 0.35.2 → 0.37.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/README.md +1 -1
- package/bin/fwdloop +5 -2
- package/package.json +3 -3
- package/src/action-stop.js +1 -1
- package/src/auditchecks.js +41 -9
- package/src/authoring.js +78 -20
- package/src/blockasks.js +10 -12
- package/src/blockassemble.js +49 -43
- package/src/blockdraft.js +4 -2
- package/src/blockpick.js +10 -0
- package/src/canrun.js +2 -1
- package/src/cardlist.js +28 -5
- package/src/checkblock.js +610 -64
- package/src/checked.js +28 -33
- package/src/checklistsign.js +2 -1
- package/src/checklook.js +45 -0
- package/src/checkrows.js +202 -0
- package/src/cited-record.js +2 -2
- package/src/citedcheck.js +53 -12
- package/src/citedwords.js +7 -4
- package/src/closers.js +49 -2
- package/src/declaration.js +26 -4
- package/src/drafter.js +86 -62
- package/src/factwords.js +7 -4
- package/src/globprefix.js +26 -0
- package/src/model-step.js +22 -4
- package/src/pageask.js +6 -4
- package/src/pagedropwords.js +3 -11
- package/src/pagedry.js +75 -1
- package/src/pagefetch.js +11 -6
- package/src/pagelook.js +2 -1
- package/src/pagerules.js +8 -2
- package/src/panel/author.js +20 -8
- package/src/panel/authorcard.js +3 -3
- package/src/panel/data.js +3 -2
- package/src/panel/index.html +176 -41
- package/src/panel/result.js +40 -3
- package/src/pickrecord.js +14 -0
- package/src/planrebuild.js +55 -19
- package/src/ratelimit.js +117 -0
- package/src/report.js +216 -0
- package/src/rowresults.js +111 -0
- package/src/rubricstep.js +65 -2
- package/src/runner.js +61 -9
- package/src/send.js +19 -82
- package/src/shapebuild.js +281 -0
- package/src/shapelook.js +91 -0
- package/src/shapemenu.js +64 -0
- package/src/shaperesult.js +104 -0
- package/src/shaperows.js +263 -0
- package/src/shapewords.js +140 -0
- package/src/sheetbuild.js +41 -29
- package/src/sheetclaims.js +49 -1
- package/src/sheetfind.js +8 -0
- package/src/sheetlook.js +11 -1
- package/src/sheetrows.js +10 -64
- package/src/ticketrows.js +1 -1
- package/src/try-checks.js +39 -6
- package/src/types.js +1 -0
- package/src/whole-job.js +108 -16
- package/types/action-stop.d.ts +1 -1
- package/types/auditchecks.d.ts +13 -2
- package/types/authoring.d.ts +24 -4
- package/types/blockasks.d.ts +6 -10
- package/types/blockassemble.d.ts +13 -13
- package/types/blockdraft.d.ts +3 -2
- package/types/blockpick.d.ts +4 -0
- package/types/cardlist.d.ts +18 -2
- package/types/checkblock.d.ts +278 -28
- package/types/checked.d.ts +15 -6
- package/types/checklook.d.ts +36 -0
- package/types/checkrows.d.ts +119 -0
- package/types/citedcheck.d.ts +4 -2
- package/types/closers.d.ts +10 -1
- package/types/drafter.d.ts +8 -4
- package/types/globprefix.d.ts +5 -0
- package/types/model-step.d.ts +43 -2
- package/types/pageask.d.ts +5 -3
- package/types/pagedropwords.d.ts +0 -1
- package/types/pagedry.d.ts +27 -0
- package/types/pagefetch.d.ts +3 -2
- package/types/pagerules.d.ts +4 -0
- package/types/panel/result.d.ts +19 -2
- package/types/pickrecord.d.ts +10 -0
- package/types/ratelimit.d.ts +59 -0
- package/types/report.d.ts +46 -0
- package/types/rowresults.d.ts +28 -0
- package/types/rubricstep.d.ts +21 -0
- package/types/runner.d.ts +3 -1
- package/types/send.d.ts +13 -12
- package/types/shapebuild.d.ts +97 -0
- package/types/shapelook.d.ts +76 -0
- package/types/shapemenu.d.ts +40 -0
- package/types/shaperesult.d.ts +40 -0
- package/types/shaperows.d.ts +102 -0
- package/types/shapewords.d.ts +43 -0
- package/types/sheetbuild.d.ts +31 -13
- package/types/sheetclaims.d.ts +16 -0
- package/types/sheetfind.d.ts +1 -0
- package/types/sheetrows.d.ts +5 -36
- package/types/ticketrows.d.ts +1 -1
- package/types/try-checks.d.ts +2 -1
- package/types/types.d.ts +4 -0
- package/types/whole-job.d.ts +69 -3
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
// borrowed-from: bareloop src/shapebuild.js@v0.61.0 (fc56e1f3)
|
|
2
|
+
// SHAPE JOBS (itemShape), docs/product/ITEM33-BUILD.md "Addendum 2026-11-18: shape jobs (itemShape)", clause 2 "Build or refuse" and the code rules R1-R5 of "POC results and code rules": the ONE builder of the shape
|
|
3
|
+
// of a job line. The AI never writes the signed shape: what it sends in the row-edit reply's `itemShape` is read here only as a typed SUGGESTION, and code builds or refuses every field.
|
|
4
|
+
// menu check the kind is on the menu (src/shapemenu.js), the bound is one the kind lists, a bound has the right type, the name is legal (no `. : [ ]`, <= 128 characters, not one of bareguard's own reason
|
|
5
|
+
// words when this bareguard lists them: src/shapemenu.js `nameWhy`).
|
|
6
|
+
// R1 a bound is grounded ONLY in that field's own `~` rule (a field with no rule has no grounded bound; the one exception: `minChars: 1` on a required field, the spec's "each item has a title").
|
|
7
|
+
// R2 an AI-added field (no `~` rule of its own) whose name has no word in the job line or its rules is SUGGESTED: held out of the signed shape, off until the person's Add, no bounds.
|
|
8
|
+
// One with a word in them is job-derived (on, droppable), still with no grounded bound.
|
|
9
|
+
// R3 `oneOf` keeps each grounded value and drops only the ungrounded ones.
|
|
10
|
+
// R4 an item count is signed only when every label the AI picked is a REAL input label and the person's words say "per <label stem>" or "each <label stem>" (stem: the label without a trailing `-N`).
|
|
11
|
+
// R5 `equals` is allowed only on a field with its own `~` rule, and only as the JSON true or false.
|
|
12
|
+
// One writer per field: a field's `rule` (the `~` rule it comes from) is the AI's `fromRule`, proved here to be a rule of THIS line; `by`, `held` and every bound that stands are assigned here.
|
|
13
|
+
// What this throws away: a refused field or bound (only its plain reason is kept, in `refused`, and on the rule that named it); the AI's `required` on an AI-added field's bounds; a second field for one rule.
|
|
14
|
+
// Not built (named): the `object` kind (src/shapemenu.js); an item count read from the person's words alone (a number, not a label): the spec says "else the count comes only from the person's words" and gives no
|
|
15
|
+
// mechanism, so none is invented here. The part code signs from this (`buildShapePartOf`) and the run's brief are clauses 5 and 6, waiting for the bareguard release that carries `itemShape`.
|
|
16
|
+
import { createRubric } from 'bareguard';
|
|
17
|
+
import { lineRules, wordsSaidOn } from './pagebits.js';
|
|
18
|
+
import { underNumbers, atMostNumbers } from './blockpick.js';
|
|
19
|
+
import { SHAPE_KINDS, ENTRY_KINDS, GROUNDED_BOUNDS, UPPER_BOUNDS, COUNT_BOUNDS, nameWhy, shapeNameRules } from './shapemenu.js';
|
|
20
|
+
|
|
21
|
+
/** @param {unknown} v @returns {v is Record<string, any>} */
|
|
22
|
+
const isRec = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
23
|
+
|
|
24
|
+
/** why a `~` rule no field holds is Not checked, when no field named it (judged at Accept, not at an Ask) */
|
|
25
|
+
export const NO_FIELD_WHY = 'No field was picked for it, so you judge it at Accept.';
|
|
26
|
+
|
|
27
|
+
/** why a rule whose field carries no limit from its own words stays Not checked: a field with no bound checks nothing the person asked for (hamr 2026-11-19) */
|
|
28
|
+
export const NO_BOUND_WHY = 'The field picked for it has no limit from your words, so it checks nothing; you judge it at Accept.';
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Does a field carry at least ONE real bound the person's rule grounds (a number, a count of characters, words or entries, the one-of values, a yes/no value; `required` + `minChars: 1` is "each item has a title")?
|
|
32
|
+
* A modifier alone (a currency, a unit, how a number is read) is no bound. A list counts when its entries do.
|
|
33
|
+
* @param {Record<string, any>} bounds @returns {boolean}
|
|
34
|
+
*/
|
|
35
|
+
export function hasRealBound(bounds) {
|
|
36
|
+
if (!isRec(bounds)) return false;
|
|
37
|
+
if (Object.keys(bounds).some((k) => GROUNDED_BOUNDS.includes(k) || k === 'equals')) return true;
|
|
38
|
+
return isRec(bounds.of) && hasRealBound(bounds.of);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** bareguard's refusal of one field spec, in plain words: `price: currency must be one of "$", "€", "£"` @param {string} name @param {unknown} message @returns {string} */
|
|
42
|
+
function plainRefusal(name, message) {
|
|
43
|
+
const m = /fields\.[^.\s]+\.(\S+) (.*)$/s.exec(String(message));
|
|
44
|
+
return m ? `${name}: ${m[1]} ${m[2]}` : `${name}: ${String(message).replace(/^invalid rubric: /, '')}`;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const norm = (/** @type {unknown} */ s) => String(s).toLowerCase().replace(/\b0(\d:)/g, '$1');
|
|
48
|
+
const words = (/** @type {unknown} */ s) => String(s).replace(/([a-z0-9])([A-Z])/g, '$1 $2').toLowerCase().match(/[a-z0-9]+/g) ?? [];
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* @typedef {{name: string, kind: string, required: boolean, bounds: Record<string, any>, rule: number|null, by: 'you'|'agent', held: boolean, why?: string}} ShapeField
|
|
52
|
+
* @typedef {{rule: number, text: string, state: 'built'|'not-checked', reason: string|null, name: string|null}} ShapeRule
|
|
53
|
+
* @typedef {{line: number, ok: boolean, fields: ShapeField[], itemCount: {labels: string[], n: number}|null, rows: ShapeRule[], refused: {helper: string, why: string}[], reservedChecked: boolean}} LineShape
|
|
54
|
+
*/
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Is ONE bound value in the person's words? A number counts when it is written as a number there (an upper bound also when it is the written number minus one: "under 60" signs 59); a string value when it is
|
|
58
|
+
* written there, case and spacing aside.
|
|
59
|
+
* @param {string} key @param {unknown} v @param {string} text the person's words (the field's own rule) @param {boolean} required
|
|
60
|
+
* @returns {boolean}
|
|
61
|
+
*/
|
|
62
|
+
export function boundGrounded(key, v, text, required = false) {
|
|
63
|
+
const t = norm(text);
|
|
64
|
+
if (key === 'minChars' && v === 1 && required) return true;
|
|
65
|
+
const numeric = typeof v === 'number' || (key !== 'values' && typeof v === 'string' && /^\s*[$€£]?\s*-?\d+([.,]\d+)?\s*[$€£]?\s*$/.test(v));
|
|
66
|
+
if (numeric) {
|
|
67
|
+
const n = typeof v === 'number' ? v : Number(String(v).replace(',', '.').match(/-?\d+(?:\.\d+)?/)?.[0]);
|
|
68
|
+
if (!Number.isFinite(n)) return false;
|
|
69
|
+
const cands = UPPER_BOUNDS.includes(key) ? [n, n + 1, Math.ceil(n)] : [n];
|
|
70
|
+
const said = new Set((t.match(/\d+(?:[.,]\d+)?/g) ?? []).map((x) => Number(x.replace(',', '.'))));
|
|
71
|
+
return cands.some((c) => said.has(c));
|
|
72
|
+
}
|
|
73
|
+
return typeof v === 'string' && v.trim() !== '' && t.includes(norm(v));
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** the type of a bound: null when legal, else the plain reason @param {string} kind @param {string} key @param {unknown} v @returns {string|null} */
|
|
77
|
+
function boundTypeWhy(kind, key, v) {
|
|
78
|
+
if (COUNT_BOUNDS.includes(key)) return Number.isInteger(v) && /** @type {number} */ (v) >= 0 ? null : `${key} must be a whole number, 0 or more`;
|
|
79
|
+
if (['min', 'max', 'gt', 'lt'].includes(key)) {
|
|
80
|
+
if (kind === 'number' || kind === 'money') return typeof v === 'number' && Number.isFinite(v) ? null : `${key} must be a number`;
|
|
81
|
+
return typeof v === 'string' && v.trim() !== '' ? null : `${key} must be written as text for a ${kind}`;
|
|
82
|
+
}
|
|
83
|
+
if (key === 'values') return Array.isArray(v) && v.length >= 1 && v.length <= 50 && v.every((x) => typeof x === 'string' && x.trim() !== '') && new Set(v).size === v.length ? null : 'values must be 1 to 50 different words';
|
|
84
|
+
if (['ignoreCase', 'fromText', 'unique'].includes(key)) return typeof v === 'boolean' ? null : `${key} must be true or false`;
|
|
85
|
+
if (key === 'equals') return typeof v === 'boolean' ? null : 'equals must be true or false';
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* The person's own form of an upper bound, signed by CODE whatever the AI sent (the same law as "under N bullets = N-1", src/checkpick.js): a field's own rule that says "under / fewer than / less than / below N" signs the EXCLUSIVE
|
|
91
|
+
* form (a count: N-1, `maxChars` / `maxWords` / `maxEntries`; a number or money: `lt: N`), and one that says "at most / up to / no more than N" signs N (`max`, inclusive), whether the AI sent N or N-1. Mutates `out`.
|
|
92
|
+
* @param {string} kind @param {Record<string, any>} out the grounded bounds @param {string} text the field's own rule
|
|
93
|
+
*/
|
|
94
|
+
function lawOfWords(kind, out, text) {
|
|
95
|
+
const unders = underNumbers(text);
|
|
96
|
+
const atMost = atMostNumbers(text);
|
|
97
|
+
for (const key of ['maxChars', 'maxWords', 'maxEntries']) {
|
|
98
|
+
const v = out[key];
|
|
99
|
+
if (!Number.isInteger(v)) continue;
|
|
100
|
+
const u = unders.find((n) => n === v || n === v + 1);
|
|
101
|
+
const a = atMost.find((n) => n === v || n === v + 1);
|
|
102
|
+
if (u !== undefined) out[key] = u - 1;
|
|
103
|
+
else if (a !== undefined) out[key] = a;
|
|
104
|
+
}
|
|
105
|
+
if (kind !== 'number' && kind !== 'money') return;
|
|
106
|
+
const v = out.lt !== undefined ? out.lt : out.max;
|
|
107
|
+
if (typeof v !== 'number') return;
|
|
108
|
+
const near = (/** @type {number} */ n) => n === v || Math.ceil(v) === n || (out.max !== undefined && n === v + 1);
|
|
109
|
+
const u = unders.find(near);
|
|
110
|
+
const a = atMost.find((n) => near(n) || n === v + 1);
|
|
111
|
+
if (u !== undefined) { delete out.max; out.lt = u; } else if (a !== undefined) { delete out.lt; out.max = a; }
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* One field's bounds, built or refused: the menu check, then grounding. Pure.
|
|
116
|
+
* @param {{kind: string, bounds: unknown, required: boolean, ruleText: string|null, refuse: (what: string, why: string) => void, top?: boolean}} o `ruleText` null = the field has no `~` rule of its own
|
|
117
|
+
* @returns {Record<string, any>}
|
|
118
|
+
*/
|
|
119
|
+
function buildBounds({ kind, bounds, required, ruleText, refuse, top = true }) {
|
|
120
|
+
/** @type {Record<string, any>} */
|
|
121
|
+
const out = {};
|
|
122
|
+
const given = isRec(bounds) ? bounds : {};
|
|
123
|
+
for (const [k, v] of Object.entries(given)) {
|
|
124
|
+
if (!/** @type {readonly string[]} */ (SHAPE_KINDS[/** @type {keyof typeof SHAPE_KINDS} */ (kind)]).includes(k)) { refuse(k, `${k} is not a bound of a ${kind} field`); continue; }
|
|
125
|
+
if (k === 'of') {
|
|
126
|
+
if (!top) { refuse(k, 'a list entry cannot be a list'); continue; }
|
|
127
|
+
const entry = typeof v === 'string' ? { kind: v } : isRec(v) ? v : null;
|
|
128
|
+
if (entry === null || !ENTRY_KINDS.includes(String(entry.kind))) { refuse(k, `a list holds ${ENTRY_KINDS.join(', ')} entries`); continue; }
|
|
129
|
+
const { kind: ek, ...rest } = entry;
|
|
130
|
+
out.of = { kind: ek, ...buildBounds({ kind: String(ek), bounds: rest, required: false, ruleText, refuse, top: false }) };
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
const typed = boundTypeWhy(kind, k, v);
|
|
134
|
+
if (typed !== null) { refuse(k, typed); continue; }
|
|
135
|
+
if (k === 'equals') { // R5
|
|
136
|
+
if (ruleText === null || typeof v !== 'boolean') refuse(k, ruleText === null ? 'equals needs a rule of your own on this field' : 'equals must be true or false');
|
|
137
|
+
else out[k] = v;
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
if (!GROUNDED_BOUNDS.includes(k)) { out[k] = v; continue; } // a modifier (currency, unit, fromText ...): how the value is read, not a bound
|
|
141
|
+
// R1: only the field's own rule grounds a bound
|
|
142
|
+
if (ruleText === null && !(k === 'minChars' && v === 1 && required)) { refuse(k, `${k} ${JSON.stringify(v)} is not in a rule of yours for this field`); continue; }
|
|
143
|
+
const text = ruleText ?? '';
|
|
144
|
+
if (k === 'values') { // R3: each value on its own
|
|
145
|
+
const good = /** @type {string[]} */ (v).filter((x) => boundGrounded(k, x, text));
|
|
146
|
+
for (const x of /** @type {string[]} */ (v)) if (!good.includes(x)) refuse(`values:${x}`, `"${x}" is not in your rule for this field`);
|
|
147
|
+
if (good.length > 0) out.values = good;
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
if (!boundGrounded(k, v, text, required)) { refuse(k, `${k} ${JSON.stringify(v)} is not in your rule for this field`); continue; }
|
|
151
|
+
out[k] = v;
|
|
152
|
+
}
|
|
153
|
+
if (ruleText !== null) lawOfWords(kind, out, ruleText);
|
|
154
|
+
// an empty range is bareguard's refusal at sign time; say it here, at $0, in the same direction
|
|
155
|
+
for (const [lo, hi] of [['minChars', 'maxChars'], ['minWords', 'maxWords'], ['minEntries', 'maxEntries']]) {
|
|
156
|
+
if (Number.isInteger(out[lo]) && Number.isInteger(out[hi]) && out[lo] > out[hi]) { refuse(hi, `${hi} is below ${lo}`); delete out[hi]; }
|
|
157
|
+
}
|
|
158
|
+
return out;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Build the shape of ONE job line from the AI's suggestion, or refuse each part with its plain reason.
|
|
163
|
+
* @param {{line: {n: number, text?: string, rules?: string[], rule?: string}, labels: string[], suggestion: unknown, nameRules?: ReturnType<typeof shapeNameRules>}} o
|
|
164
|
+
* @returns {LineShape}
|
|
165
|
+
*/
|
|
166
|
+
export function buildShapeLine({ line, labels, suggestion, nameRules = shapeNameRules() }) {
|
|
167
|
+
const rules = lineRules(line);
|
|
168
|
+
const said = wordsSaidOn({ text: line.text, rules });
|
|
169
|
+
const jobWords = new Set(words(said));
|
|
170
|
+
const s = isRec(suggestion) ? suggestion : {};
|
|
171
|
+
/** @type {{helper: string, why: string}[]} */
|
|
172
|
+
const refused = [];
|
|
173
|
+
/** @type {Map<number, string>} the plain reason a refusal gives the rule that named it */
|
|
174
|
+
const refusedFor = new Map();
|
|
175
|
+
/** @type {ShapeField[]} */
|
|
176
|
+
const fields = [];
|
|
177
|
+
const seen = new Set();
|
|
178
|
+
const lists = /** @type {[string, unknown][]} */ ([['fields', s.fields], ['extraFields', s.extraFields]]);
|
|
179
|
+
for (const [listName, arr] of lists) {
|
|
180
|
+
for (const f of Array.isArray(arr) ? arr : []) {
|
|
181
|
+
const nm = isRec(f) ? f.name : undefined;
|
|
182
|
+
const rule = isRec(f) && Number.isInteger(f.fromRule) && f.fromRule >= 1 && f.fromRule <= rules.length ? /** @type {number} */ (f.fromRule) : null;
|
|
183
|
+
const refuse = (/** @type {string} */ helper, /** @type {string} */ why) => { refused.push({ helper, why }); if (rule !== null && !refusedFor.has(rule)) refusedFor.set(rule, `field refused: ${why}`); };
|
|
184
|
+
if (!isRec(f)) { refuse('schema', `an entry of ${listName} is not an object`); continue; }
|
|
185
|
+
const nameBad = nameWhy(nm, nameRules);
|
|
186
|
+
if (nameBad !== null) { refuse('name', nameBad); continue; }
|
|
187
|
+
if (seen.has(nm)) { refuse('name', `the name "${nm}" is used twice`); continue; }
|
|
188
|
+
if (f.kind === 'object') { refuse('menu', 'a nested object field is not offered yet'); continue; }
|
|
189
|
+
if (typeof f.kind !== 'string' || !Object.hasOwn(SHAPE_KINDS, f.kind)) { refuse('menu', `${String(f.kind)} is not a field kind on the menu`); continue; }
|
|
190
|
+
if (rule !== null && fields.some((x) => x.rule === rule)) { refuse('rule', `rule ${rule} already has a field`); continue; }
|
|
191
|
+
const required = f.required === true;
|
|
192
|
+
const ruleText = rule === null ? null : rules[rule - 1];
|
|
193
|
+
const own = rule !== null;
|
|
194
|
+
// R2: an AI-added field with none of its words in the job is Suggested (held out, off until Add); one with a word in the job is job-derived
|
|
195
|
+
const derived = own || words(nm).some((w) => jobWords.has(w));
|
|
196
|
+
const bounds = buildBounds({ kind: f.kind, bounds: f.bounds, required, ruleText, refuse: (what, why) => refuse(`${nm}.${what}`, why) });
|
|
197
|
+
// a field picked for the person's own rule must carry a real bound from that rule, else it checks nothing and the rule stays Not checked
|
|
198
|
+
if (own && !hasRealBound(bounds)) { refused.push({ helper: 'bound', why: `${nm}: no limit from your rule` }); refusedFor.set(/** @type {number} */ (rule), NO_BOUND_WHY); continue; }
|
|
199
|
+
// bareguard is the judge of the field: a combination it refuses (a currency word it has no sign for) is this field's refusal, told in plain words, and never the whole shape's
|
|
200
|
+
try { createRubric({ schema: 1, goal: 'field', inputs: [], checkpoints: { field: { gating: false, checks: [{ id: 'f', rule: 'itemShape', field: 'results', fields: { [nm]: { kind: f.kind, ...(required ? { required: true } : {}), ...bounds } } }] } } }); } catch (e) { refuse('bareguard', plainRefusal(nm, /** @type {any} */ (e)?.message ?? e)); continue; }
|
|
201
|
+
seen.add(nm);
|
|
202
|
+
fields.push({ name: nm, kind: f.kind, required, bounds, rule, by: own ? 'you' : 'agent', held: !derived, ...(own ? {} : { why: derived ? 'job-derived' : 'suggested' }) });
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
// the rule fields in rule order first, then the agent's, in the order sent
|
|
206
|
+
const ordered = [...fields.filter((x) => x.by === 'you').sort((a, b) => /** @type {number} */ (a.rule) - /** @type {number} */ (b.rule)), ...fields.filter((x) => x.by === 'agent')];
|
|
207
|
+
// R4: the item count
|
|
208
|
+
/** @type {{labels: string[], n: number}|null} */
|
|
209
|
+
let itemCount = null;
|
|
210
|
+
const pick = s.itemCountFrom;
|
|
211
|
+
if (Array.isArray(pick) && pick.length > 0) {
|
|
212
|
+
const set = [...new Set(pick.map(String))];
|
|
213
|
+
if (!set.every((x) => labels.includes(x))) refused.push({ helper: 'itemCount', why: `${set.filter((x) => !labels.includes(x)).map((x) => `"${x}"`).join(', ')} is not an input of this job` });
|
|
214
|
+
else {
|
|
215
|
+
const says = (/** @type {string} */ label) => {
|
|
216
|
+
const stem = label.replace(/-\d+$/, '').toLowerCase();
|
|
217
|
+
const t = said.toLowerCase();
|
|
218
|
+
// `s?\b` after the stem, read at its place in the whole text (sticky), so \b sees the stem's last character as the tag's regex does
|
|
219
|
+
const end = /s?\b/y;
|
|
220
|
+
return [...t.matchAll(/\b(?:per|each)\s+/g)].some((m) => {
|
|
221
|
+
const at = m.index + m[0].length;
|
|
222
|
+
if (!t.startsWith(stem, at)) return false;
|
|
223
|
+
end.lastIndex = at + stem.length;
|
|
224
|
+
return end.test(t);
|
|
225
|
+
});
|
|
226
|
+
};
|
|
227
|
+
if (set.every(says)) itemCount = { labels: set, n: set.length };
|
|
228
|
+
else refused.push({ helper: 'itemCount', why: 'the count is not in your words (say "per" or "each" and the input, e.g. "one summary per resume")' });
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
/** @type {ShapeRule[]} */
|
|
232
|
+
const rows = rules.map((text, i) => {
|
|
233
|
+
const n = i + 1;
|
|
234
|
+
const f = ordered.find((x) => x.rule === n);
|
|
235
|
+
return f ? { rule: n, text, state: /** @type {const} */ ('built'), reason: null, name: f.name } : { rule: n, text, state: /** @type {const} */ ('not-checked'), reason: refusedFor.get(n) ?? NO_FIELD_WHY, name: null };
|
|
236
|
+
});
|
|
237
|
+
const ok = ordered.some((x) => x.by === 'you');
|
|
238
|
+
if (!ok && fields.length === 0 && refused.length === 0 && !isRec(suggestion)) refused.push({ helper: 'schema', why: 'no shape was suggested for the line' });
|
|
239
|
+
return { line: line.n, ok, fields: ordered, itemCount, rows, refused, reservedChecked: nameRules.reserved !== null };
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* Build the shape of every candidate line from the reply's suggestions, each routed to its job line by its own `line`. A suggestion naming no candidate line, or not an object, is refused and listed.
|
|
244
|
+
* @param {{lines: {n: number, text?: string, rules?: string[], rule?: string}[], labels: string[], suggestions: unknown[], nameRules?: ReturnType<typeof shapeNameRules>}} o
|
|
245
|
+
* @returns {{built: Record<number, LineShape>, notChecked: Record<string, string>, refused: {line: number|null, helper: string, why: string}[]}}
|
|
246
|
+
* `built` holds only the lines whose shape stands (at least one field from a `~` rule); `notChecked`: `line N: "rule"` -> why, for each rule of a built line no field holds
|
|
247
|
+
*/
|
|
248
|
+
export function buildShapes({ lines, labels, suggestions, nameRules = shapeNameRules() }) {
|
|
249
|
+
/** @type {Record<number, LineShape>} */
|
|
250
|
+
const built = {};
|
|
251
|
+
/** @type {Record<string, string>} */
|
|
252
|
+
const notChecked = {};
|
|
253
|
+
/** @type {{line: number|null, helper: string, why: string}[]} */
|
|
254
|
+
const refused = [];
|
|
255
|
+
/** @type {Map<number, unknown[]>} */
|
|
256
|
+
const byLine = new Map(lines.map((l) => [l.n, []]));
|
|
257
|
+
for (const s of suggestions) {
|
|
258
|
+
if (!isRec(s)) { refused.push({ line: null, helper: 'schema', why: 'a suggestion is not an object' }); continue; }
|
|
259
|
+
const mine = byLine.get(/** @type {number} */ (s.line));
|
|
260
|
+
if (mine === undefined) { refused.push({ line: Number.isInteger(s.line) ? /** @type {number} */ (s.line) : null, helper: 'line', why: `line ${String(s.line)} is not a line a shape can be offered for` }); continue; }
|
|
261
|
+
mine.push(s);
|
|
262
|
+
}
|
|
263
|
+
for (const line of lines) {
|
|
264
|
+
const mine = byLine.get(line.n) ?? [];
|
|
265
|
+
if (mine.length === 0) continue;
|
|
266
|
+
// one shape per line: the first suggestion stands, a second is refused
|
|
267
|
+
if (mine.length > 1) refused.push({ line: line.n, helper: 'line', why: 'more than one shape was suggested for the line; the first is used' });
|
|
268
|
+
const r = buildShapeLine({ line, labels, suggestion: mine[0], nameRules });
|
|
269
|
+
for (const x of r.refused) refused.push({ line: line.n, ...x });
|
|
270
|
+
if (!r.ok) continue;
|
|
271
|
+
built[line.n] = r;
|
|
272
|
+
for (const row of r.rows) if (row.state === 'not-checked') notChecked[`line ${line.n}: "${row.text}"`] = /** @type {string} */ (row.reason);
|
|
273
|
+
}
|
|
274
|
+
return { built, notChecked, refused };
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* The signed spec of one field, as bareguard's `itemShape` reads it: `{kind, required, ...bounds}` (`required` written only when true).
|
|
279
|
+
* @param {ShapeField} f @returns {Record<string, any>}
|
|
280
|
+
*/
|
|
281
|
+
export const fieldSpec = (f) => ({ kind: f.kind, ...(f.required ? { required: true } : {}), ...f.bounds });
|
package/src/shapelook.js
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// borrowed-from: bareloop src/shapelook.js@v0.61.0 (fc56e1f3) -- the prompt, the menu lines and the strict parse are copied unchanged (test/m19-shapelook-strings.test.js holds the tag's text); `runShapeLook` is not copied: fwd's drafter owns the call, the metering and the book (its `makeCallModel`), so `lookAtShape` below takes the same `callModel` seam as `lookAtSheet` and keeps the tag's plumbing (a 429 waited once, a transport failure retried once, an unreadable answer twice is no shape)
|
|
2
|
+
// The shape look (M19 S2): ONE AI call for the whole job that proposes, for the `~` rules still left Not checked, the fields of a list of items. The AI only SUGGESTS; code builds or refuses every field (src/shapebuild.js).
|
|
3
|
+
// Third outcomes: a call that failed, a cut-off answer (unreadable), an unreadable answer twice, the cap reached before the call: each is `{ok: false, reason}` and the caller goes on without a shape (the spend stays booked).
|
|
4
|
+
import { redactSecrets } from './redact.js';
|
|
5
|
+
import { isTransportFailure } from './model-step.js';
|
|
6
|
+
import { isRateLimited, rateLimitWaitMs } from './ratelimit.js';
|
|
7
|
+
import { MAP_UNREADABLE } from './pagemap.js';
|
|
8
|
+
import { lineRules } from './pagebits.js';
|
|
9
|
+
import { SHAPE_KINDS, SHAPE_OPTION_VALUES, NAME_MAX_CHARS } from './shapemenu.js';
|
|
10
|
+
|
|
11
|
+
/** the label of the one paid call about a shape, as the drafting book and the progress line see it (the sibling of `SHEET_CALL_LABEL`) */
|
|
12
|
+
export const SHAPE_CALL_LABEL = 'shape-map';
|
|
13
|
+
/** how much of each input the call is shown (the POC's bound, declared in its preregistration) */
|
|
14
|
+
export const SHAPE_SHOWN_CHARS = 8000;
|
|
15
|
+
/** at most this many fields in one suggestion (bareguard allows 50 per `fields` object; a person's rule list is far shorter) */
|
|
16
|
+
export const MAX_SHAPE_FIELDS = 20;
|
|
17
|
+
|
|
18
|
+
export const SHAPE_SYSTEM = 'You map a person\'s job to the SHAPE of an answer: a list of items, each item with named fields. You never grade and never invent bounds: a bound is only what the person wrote. Reply with JSON only.';
|
|
19
|
+
|
|
20
|
+
/** the menu as the drafter reads it, one line per kind of src/shapemenu.js (the one place it is named): ` boolean: bounds equals` @returns {string[]} */
|
|
21
|
+
export function shapeMenuLines() {
|
|
22
|
+
return Object.entries(SHAPE_KINDS).map(([k, b]) => ` ${k}: bounds ${b.length ? b.map((o) => (SHAPE_OPTION_VALUES[k]?.[o] ? `${o} (one of ${SHAPE_OPTION_VALUES[k][o].map((v) => `"${v}"`).join(', ')})` : o)).join(', ') : '(none)'}`);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* What the AI is told: the job (its `~` rules numbered per line), the inputs (bounded), the kind menu and the answer form.
|
|
27
|
+
* @param {{jobLines: {n: number, text: string, rule?: string, rules?: string[]}[], lineNums: number[], texts: Record<string, string>, left?: {line: number, rules: number[]}[]}} o `lineNums` the lines a shape can be offered for, `left` the rules still without a check
|
|
28
|
+
* @returns {string}
|
|
29
|
+
*/
|
|
30
|
+
export function shapeLookPrompt({ jobLines, lineNums, texts, left = [] }) {
|
|
31
|
+
const job = jobLines.map((l) => `LINE ${l.n}: ${l.text}${lineRules(l).map((r, i) => `\n~ rule ${i + 1}: ${r}`).join('')}`).join('\n');
|
|
32
|
+
const inputs = Object.entries(texts).map(([label, t]) => `Input "${label}"${t.length > SHAPE_SHOWN_CHARS ? ` (first ${SHAPE_SHOWN_CHARS} of ${t.length} characters)` : ''}:\n<<<\n${t.slice(0, SHAPE_SHOWN_CHARS)}\n>>>`).join('\n\n');
|
|
33
|
+
// only when code left some `~` rules without a check: say which, so the AI gives a field for those and no other (injected only IF the case happens)
|
|
34
|
+
const needs = left.length ? `Only these ~ rules have no check yet: ${left.map((x) => `line ${x.line} rule${x.rules.length === 1 ? '' : 's'} ${x.rules.join(', ')}`).join('; ')}. Give a field for no other rule. For each of these, give a field ONLY if that rule's own words give it a limit code can check: a number, a count of characters, words or entries, a list of allowed values, or yes/no. "Each item has a title" counts: required, with minChars 1. A rule whose words give no limit gets no field; it stays with the person. "fromRule" is the rule's number on the line (1 is its first rule). Extra fields are fine.\n` : '';
|
|
35
|
+
return `THE JOB (each ~ rule applies to the line above it):\n${job}\n\nTHE INPUTS:\n${inputs}\n\n`
|
|
36
|
+
+ `A job line whose answer is a LIST OF ITEMS with named fields (for example one item per flight, per resume or per research topic) gets a shape. The lines a shape can be offered for: ${lineNums.join(', ')}. A line whose answer is not such a list gets none.\n`
|
|
37
|
+
+ needs
|
|
38
|
+
+ '- "extraFields": any other field you think would help (none is fine); its "fromRule" is null and code shows it to the person as a suggestion.\n'
|
|
39
|
+
+ '- "kind" is one of the kinds below; "bounds" holds only the bounds that kind accepts, taken from that field\'s own rule. A yes/no rule ("the flight is nonstop") is kind boolean with "equals": true.\n'
|
|
40
|
+
+ '- "itemCountFrom": the labels of the inputs that give exactly one item each, only when the person wrote it ("one blurb per resume"); otherwise [].\n'
|
|
41
|
+
+ `- A field name is at most ${NAME_MAX_CHARS} characters and holds none of . : [ ] ; a list field writes its entries as "of": {"kind": "text", ...bounds}.\n\n`
|
|
42
|
+
+ `The field kinds (and the bounds each kind accepts):\n${shapeMenuLines().join('\n')}\n\n`
|
|
43
|
+
+ 'Return ONLY a JSON object, no prose, no code fence, with "shapes" empty when no line is a list of items:\n'
|
|
44
|
+
+ '{"shapes":[{"line":1,"fields":[{"name":"...","kind":"...","required":true,"bounds":{},"fromRule":1}],"extraFields":[{"name":"...","kind":"...","required":false,"bounds":{},"fromRule":null}],"itemCountFrom":[]}]}';
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Read the AI's answer: ONE JSON object `{"shapes":[...]}`, each shape an object with a whole `line`, its `fields` and `extraFields` lists (an absent list is none). No repair: anything else is a malformed answer. What a field MEANS is judged by code (src/shapebuild.js).
|
|
49
|
+
* @param {unknown} text @returns {{ok: true, shapes: Record<string, any>[]}|{ok: false}}
|
|
50
|
+
*/
|
|
51
|
+
export function parseShapeAnswer(text) {
|
|
52
|
+
/** @type {any} */
|
|
53
|
+
let m;
|
|
54
|
+
try { m = JSON.parse(String(text ?? '').trim()); } catch { return { ok: false }; }
|
|
55
|
+
if (m === null || typeof m !== 'object' || Array.isArray(m) || !Array.isArray(m.shapes)) return { ok: false };
|
|
56
|
+
for (const s of m.shapes) {
|
|
57
|
+
if (s === null || typeof s !== 'object' || Array.isArray(s) || !Number.isInteger(s.line)) return { ok: false };
|
|
58
|
+
for (const k of ['fields', 'extraFields', 'itemCountFrom']) if (s[k] !== undefined && s[k] !== null && !Array.isArray(s[k])) return { ok: false };
|
|
59
|
+
}
|
|
60
|
+
return { ok: true, shapes: m.shapes };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Look at the shape of the answer: the call (once; once more after an unreadable answer or one transport failure; a 429 waits the vendor's stated time once and is not an attempt).
|
|
65
|
+
* `callModel(content, attempt)` makes and meters ONE model round (the drafter's `makeCallModel('shape-map', SHAPE_SYSTEM)`) and returns `{text}`, `{text, cutOff: true}` or `{error}` (with `budget: true` when the cap stopped the call, `threw` when the provider threw).
|
|
66
|
+
* @param {{texts: Record<string, string>, jobLines: {n: number, text: string, rule?: string, rules?: string[]}[], lineNums: number[], left?: {line: number, rules: number[]}[], ceilingUsd?: number|null,
|
|
67
|
+
* callModel: (content: string, attempt: number) => Promise<{text?: string, cutOff?: boolean, error?: string, budget?: boolean, threw?: any}>, sleep?: (ms: number) => Promise<void>}} o
|
|
68
|
+
* @returns {Promise<{ok: true, shapes: Record<string, any>[], attempts: number}|{ok: false, reason: string, attempts: number}>}
|
|
69
|
+
*/
|
|
70
|
+
export async function lookAtShape({ texts, jobLines, lineNums, left = [], ceilingUsd = null, callModel, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) }) {
|
|
71
|
+
const content = shapeLookPrompt({ jobLines, lineNums, texts, left });
|
|
72
|
+
let transportRetried = false;
|
|
73
|
+
let rateRetried = false;
|
|
74
|
+
let attempts = 0;
|
|
75
|
+
for (;;) {
|
|
76
|
+
attempts += 1;
|
|
77
|
+
const r = await callModel(content, attempts);
|
|
78
|
+
if (r.budget === true) return { ok: false, reason: `the AI's look at the shape of the answer was not made: the $${ceilingUsd} ceiling was already spent`, attempts };
|
|
79
|
+
if (r.threw !== undefined) {
|
|
80
|
+
if (isRateLimited(r.threw) && !rateRetried) {
|
|
81
|
+
const wait = rateLimitWaitMs(r.threw);
|
|
82
|
+
if (wait !== null) { rateRetried = true; attempts -= 1; await sleep(wait); continue; }
|
|
83
|
+
}
|
|
84
|
+
if (isTransportFailure(r.threw) && !transportRetried) { transportRetried = true; continue; }
|
|
85
|
+
}
|
|
86
|
+
if (r.error !== undefined && r.cutOff !== true) return { ok: false, reason: `the call about the shape of the answer failed: ${redactSecrets(String(r.error))}`, attempts };
|
|
87
|
+
const parsed = r.cutOff === true ? { ok: false } : parseShapeAnswer(r.text);
|
|
88
|
+
if (parsed.ok) return { ok: true, shapes: /** @type {any} */ (parsed).shapes, attempts };
|
|
89
|
+
if (attempts >= 2) return { ok: false, reason: MAP_UNREADABLE.replace('about the page', 'about the shape of the answer'), attempts };
|
|
90
|
+
}
|
|
91
|
+
}
|
package/src/shapemenu.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// borrowed-from: bareloop src/shapemenu.js@v0.61.0 (fc56e1f3)
|
|
2
|
+
// SHAPE JOBS (itemShape), docs/product/ITEM33-BUILD.md "Addendum 2026-11-18: shape jobs (itemShape)": THE ONE PLACE the kind menu is named. The offer (src/shapelook.js), the builder (src/shapebuild.js) and the tests read this table, never a copy of it.
|
|
3
|
+
// It is bareguard's own: `rubricVocabulary.rules.itemShape.fields.fields` (ruling #83; bareguard ^0.37.0) lists the kinds, the options each kind accepts, and the name rules (`reservedNames`, `nameForbiddenChars`, `nameMaxLength`).
|
|
4
|
+
// What stays bareloop's: which options are BOUNDS the person must have written (GROUNDED_BOUNDS and its kin below), and which kind is not offered.
|
|
5
|
+
// Not offered: the `object` kind (nested field specs, depth 2). The builder refuses it in plain words; a shape job with a nested object is not built yet.
|
|
6
|
+
import { rubricVocabulary } from 'bareguard';
|
|
7
|
+
|
|
8
|
+
const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
9
|
+
|
|
10
|
+
/** bareguard's field-spec descriptor of `itemShape` @type {any} */
|
|
11
|
+
const IS = /** @type {any} */ (rubricVocabulary).rules.itemShape.fields.fields;
|
|
12
|
+
|
|
13
|
+
/** kind -> the options (bounds and modifiers) the kind accepts, as bareguard lists them (`object` is not offered). `of` and `minEntries`/`maxEntries`/`unique` are the list's; `equals` is the boolean's. @type {Readonly<Record<string, readonly string[]>>} */
|
|
14
|
+
export const SHAPE_KINDS = Object.freeze(Object.fromEntries(Object.entries(IS.kinds).filter(([k]) => k !== 'object').map(([k, opts]) => [k, Object.freeze(Object.keys(/** @type {any} */ (opts)))])));
|
|
15
|
+
|
|
16
|
+
/** the options whose value must be one of a closed list, as bareguard lists them (`money.currency` is a SIGN: "$", "€", "£"; `decimal`, `date.lang`): `kind` -> option -> the allowed values @type {Readonly<Record<string, Readonly<Record<string, readonly string[]>>>>} */
|
|
17
|
+
export const SHAPE_OPTION_VALUES = Object.freeze(Object.fromEntries(Object.entries(IS.kinds).filter(([k]) => k !== 'object').map(([k, opts]) => [k, Object.freeze(Object.fromEntries(Object.entries(/** @type {any} */ (opts)).filter(([, d]) => isRec(d) && Array.isArray(d.enum)).map(([o, d]) => [o, Object.freeze(d.enum.map(String))])))])));
|
|
18
|
+
|
|
19
|
+
/** the kinds a list entry (`of`) may be: every scalar kind (never `list`, never `object`) */
|
|
20
|
+
export const ENTRY_KINDS = Object.freeze(Object.keys(SHAPE_KINDS).filter((k) => k !== 'list'));
|
|
21
|
+
|
|
22
|
+
/** the options that are BOUNDS: each must appear in the person's own words (the same law as `groundedLiterals`, src/sheetbuild.js). The other options only say how a value is read (currency, unit, of, fromText ...). `equals` has its own rule (R5). */
|
|
23
|
+
export const GROUNDED_BOUNDS = Object.freeze(['minChars', 'maxChars', 'minWords', 'maxWords', 'min', 'max', 'gt', 'lt', 'values', 'minEntries', 'maxEntries']);
|
|
24
|
+
|
|
25
|
+
/** the upper bounds: "under 60 words" may sign 59, and "under 450" 449.99, so the number the person wrote, one more and its ceiling are the candidates */
|
|
26
|
+
export const UPPER_BOUNDS = Object.freeze(['max', 'maxChars', 'maxWords', 'maxEntries']);
|
|
27
|
+
|
|
28
|
+
/** the bounds that count characters, words or entries: whole numbers, 0 or more */
|
|
29
|
+
export const COUNT_BOUNDS = Object.freeze(['minChars', 'maxChars', 'minWords', 'maxWords', 'minEntries', 'maxEntries']);
|
|
30
|
+
|
|
31
|
+
/** a field name is at most this long (bareguard's `nameMaxLength`) */
|
|
32
|
+
export const NAME_MAX_CHARS = Number(IS.nameMaxLength);
|
|
33
|
+
/** a field name holds none of these (they separate the path in a red item: bareguard's `nameForbiddenChars`) */
|
|
34
|
+
export const NAME_FORBIDDEN = Object.freeze(IS.nameForbiddenChars.map(String));
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Does the bareguard this package runs carry `itemShape`? Read from the vocabulary at call time (true from bareguard 0.37); the shape look and everything after it is OFF where it is false.
|
|
38
|
+
* @returns {boolean}
|
|
39
|
+
*/
|
|
40
|
+
export function shapeAvailable() {
|
|
41
|
+
return isRec(/** @type {any} */ (rubricVocabulary)?.rules?.itemShape);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The name rules of a signed field, all bareguard's own: the characters, the length and its reserved reason words (a field named `wrong-value` would read as a gap).
|
|
46
|
+
* @returns {{max: number, forbidden: string[], reserved: string[]}}
|
|
47
|
+
*/
|
|
48
|
+
export function shapeNameRules() {
|
|
49
|
+
return { max: NAME_MAX_CHARS, forbidden: [...NAME_FORBIDDEN], reserved: IS.reservedNames.map(String) };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Is `name` a legal signed field name? Null when it is, else the plain reason.
|
|
54
|
+
* @param {unknown} name @param {{max: number, forbidden: string[], reserved: string[]|null}} [rules]
|
|
55
|
+
* @returns {string|null}
|
|
56
|
+
*/
|
|
57
|
+
export function nameWhy(name, rules = shapeNameRules()) {
|
|
58
|
+
if (typeof name !== 'string' || name.trim() === '') return 'a field name is needed';
|
|
59
|
+
if (name.length > rules.max) return `a field name is at most ${rules.max} characters`;
|
|
60
|
+
const bad = rules.forbidden.find((c) => name.includes(c));
|
|
61
|
+
if (bad !== undefined) return `a field name cannot hold "${bad}"`;
|
|
62
|
+
if (rules.reserved !== null && rules.reserved.includes(name)) return `"${name}" is a word the checker uses for its own gaps, so it cannot name a field`;
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
// borrowed-from: bareloop src/shaperesult.js@v0.61.0 (fc56e1f3)
|
|
2
|
+
// SHAPE JOBS (itemShape), the signed mock design/shape-views-mock.html (hamr 2026-11-18): the ONE view-model of a shape line's answer, read by the Result tab's grid (src/panel/server.js -> src/panel/index.html) and the
|
|
3
|
+
// .md report (src/resultmd.js), so the grid and the report say the same thing. Items are rows, the signed fields are columns; a cell is a mark and a short value; the errors are the plain item reds. Pure.
|
|
4
|
+
// cell value: the item's own value (clipped, yes/no for a boolean, a list's entries joined), then the bound's words in brackets when the person bounded the field (`Ada (2 words)`, `a, b (2 entries)`). A red `#<i>:<path>:<reason>` (bareguard's, names and counts only) marks the cell of its field; a red with no field (`item-not-object`) marks the whole row.
|
|
5
|
+
// The words of a red here name the worker's own value where the reason is a wrong value (`status is "done", not one of: ...`): the value comes from the delivered file, never from bareguard's gap.
|
|
6
|
+
import { upper, SHAPE_HEAD_PARTS, SHAPE_TRUTH_PARTS } from './shaperows.js';
|
|
7
|
+
import { parseShapeItem, itemFieldOf, plainShapeItem } from './shapewords.js';
|
|
8
|
+
|
|
9
|
+
const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
10
|
+
const clip = (/** @type {string} */ t, n = 40) => (t.length > n ? `${t.slice(0, n - 1)}…` : t);
|
|
11
|
+
|
|
12
|
+
/** one scalar as written, whitespace folded @param {unknown} v @returns {string} */
|
|
13
|
+
const scalar = (v) => (typeof v === 'boolean' ? (v ? 'yes' : 'no') : typeof v === 'string' || typeof v === 'number' ? String(v).replace(/\s+/g, ' ').trim() : '');
|
|
14
|
+
|
|
15
|
+
/** the short value of one cell: the item's own value (clipped), then the bound's words in brackets where the field has one (`Ada (2 words)`, `a, b (2 entries)`) @param {Record<string, any>} spec @param {unknown} v @returns {string} */
|
|
16
|
+
function cellText(spec, v) {
|
|
17
|
+
if (v === undefined || v === null) return '';
|
|
18
|
+
const join = (/** @type {string} */ val, /** @type {string} */ extra) => (val && extra ? `${val} (${extra})` : val || extra);
|
|
19
|
+
switch (spec.kind) {
|
|
20
|
+
case 'text': {
|
|
21
|
+
if (typeof v !== 'string') return '';
|
|
22
|
+
const bounded = ['maxChars', 'minChars', 'maxWords', 'minWords'].some((k) => spec[k] !== undefined && !(k === 'minChars' && spec[k] === 1));
|
|
23
|
+
const extra = !bounded ? '' : spec.maxWords !== undefined || spec.minWords !== undefined ? ((n) => `${n} word${n === 1 ? '' : 's'}`)(v.trim() === '' ? 0 : v.trim().split(/\s+/).length) : `${[...v].length} chars`;
|
|
24
|
+
return join(clip(scalar(v)), extra);
|
|
25
|
+
}
|
|
26
|
+
case 'list': return Array.isArray(v) ? join(clip(v.map(scalar).filter((x) => x !== '').join(', ')), `${v.length} ${v.length === 1 ? 'entry' : 'entries'}`) : '';
|
|
27
|
+
default: return typeof v === 'object' ? '' : clip(scalar(v), 40);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* One item red in the Result tab's words: `item 3: status is "done", not one of: in progress, closed, finished`.
|
|
33
|
+
* @param {string} red `#<i>:<path>:<reason>` @param {Record<string, any>|null} field the signed field `{name, spec, rule?}` or null @param {unknown} value the worker's value @param {string} said the person's rule for the field
|
|
34
|
+
* @returns {string}
|
|
35
|
+
*/
|
|
36
|
+
export function shapeViewRed(red, field, value, said) {
|
|
37
|
+
const p = parseShapeItem(red);
|
|
38
|
+
if (p === null || p.path === null || field === null) return plainShapeItem(red);
|
|
39
|
+
const at = `item ${p.i + 1}: ${field.name}`;
|
|
40
|
+
const r = p.reason;
|
|
41
|
+
const w = /^(too-short|too-long):(chars|words):(\d+)([<>])(\d+)$/.exec(r);
|
|
42
|
+
if (w) {
|
|
43
|
+
const unit = w[2] === 'chars' ? 'characters' : 'words';
|
|
44
|
+
if (w[1] === 'too-short' && w[2] === 'chars' && w[5] === '1') return `${at} is empty`;
|
|
45
|
+
return w[1] === 'too-long' ? `${at} is too long (${w[3]} ${unit}, ${upper(Number(w[5]), '', said)})` : `${at} is too short (${w[3]} ${unit}, at least ${w[5]})`;
|
|
46
|
+
}
|
|
47
|
+
if (r === 'not-one-of') return `${at} is ${typeof value === 'string' ? `"${clip(value)}"` : 'not a word'}, not one of: ${(Array.isArray(field.spec.values) ? field.spec.values : []).join(', ')}`;
|
|
48
|
+
if (r === 'missing') return `${at} is missing`;
|
|
49
|
+
if (r === 'wrong-value') return `${at} is ${typeof value === 'boolean' ? (value ? 'yes' : 'no') : 'not what the job asks for'}, not ${field.spec.equals === true ? 'yes' : 'no'}`;
|
|
50
|
+
return plainShapeItem(red).replace(/^item (\d+): "([^"]*)"/, (_m, n, f) => `item ${n}: ${f}`);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The model of a shape line's answer.
|
|
55
|
+
* @param {{part: any, results: unknown, reds?: string[], rules?: string[]}} o `part` the signed shape part; `results` the answer's `results` list; `reds` the item reds the close recorded (`#<i>:<path>:<reason>`, none for a green run); `rules` the line's `~` rules
|
|
56
|
+
* @returns {{columns: {name: string}[], rows: {name: string, cells: {mark: 'g'|'r', text: string, why?: string}[]}[], total: number, passed: number, failed: number, errors: string[], notChecked: string, head: string}}
|
|
57
|
+
*/
|
|
58
|
+
export function shapeResultModel({ part, results, reds = [], rules = [] }) {
|
|
59
|
+
const fields = (Array.isArray(part?.fields) ? part.fields : []).filter(isRec);
|
|
60
|
+
const items = Array.isArray(results) ? results : [];
|
|
61
|
+
const said = (/** @type {any} */ f) => (Number.isInteger(f.rule) ? rules[f.rule - 1] ?? '' : '');
|
|
62
|
+
const first = fields.find((f) => f.spec?.kind === 'text');
|
|
63
|
+
const redsBy = (/** @type {number} */ i) => reds.filter((x) => parseShapeItem(x)?.i === i);
|
|
64
|
+
/** @type {string[]} */
|
|
65
|
+
const errors = [];
|
|
66
|
+
const rows = items.map((it, i) => {
|
|
67
|
+
const mine = redsBy(i);
|
|
68
|
+
const whole = mine.some((x) => itemFieldOf(x) === null && !String(x).includes(':unknown-field:'));
|
|
69
|
+
const val = (/** @type {string} */ n) => (isRec(it) ? it[n] : undefined);
|
|
70
|
+
const title = first !== undefined && typeof val(first.name) === 'string' && String(val(first.name)).trim() !== '' ? ` · ${clip(String(val(first.name)).trim())}` : '';
|
|
71
|
+
/** @type {Record<string, string>} */
|
|
72
|
+
const why = {};
|
|
73
|
+
for (const x of mine) { const nm = itemFieldOf(x); const f = fields.find((y) => y.name === nm) ?? null; const e = shapeViewRed(x, f, f ? val(f.name) : undefined, f ? said(f) : ''); errors.push(e); if (f) why[f.name] = e.replace(`item ${i + 1}: ${f.name} `, ''); }
|
|
74
|
+
const cells = fields.map((f) => {
|
|
75
|
+
const bad = whole || mine.some((x) => itemFieldOf(x) === f.name);
|
|
76
|
+
return { mark: /** @type {'g'|'r'} */ (bad ? 'r' : 'g'), text: cellText(f.spec, val(f.name)), ...(why[f.name] !== undefined ? { why: why[f.name] } : {}) };
|
|
77
|
+
});
|
|
78
|
+
return { name: `${i + 1}${title}`, cells };
|
|
79
|
+
});
|
|
80
|
+
const failed = rows.filter((r) => r.cells.some((c) => c.mark === 'r')).length;
|
|
81
|
+
return {
|
|
82
|
+
columns: fields.map((f) => ({ name: String(f.name) })), rows, total: rows.length, passed: rows.length - failed, failed, errors,
|
|
83
|
+
notChecked: SHAPE_TRUTH_PARTS.join(' — '), head: SHAPE_HEAD_PARTS.join(' · '),
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** a markdown table cell: pipes and line breaks made safe @param {string} t */
|
|
88
|
+
const md = (t) => t.replace(/\|/g, '\\|').replace(/\s*\n\s*/g, ' ');
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* The shape section of the .md report (the signed mock D): the shape-checks line, a table (items as rows, fields as columns, a mark and the short value in each cell), the Not checked line and, when any item failed, a Failed list.
|
|
92
|
+
* @param {ReturnType<typeof shapeResultModel>} m @returns {string}
|
|
93
|
+
*/
|
|
94
|
+
export function shapeMarkdown(m) {
|
|
95
|
+
const cols = m.columns.map((c) => c.name);
|
|
96
|
+
const lines = [
|
|
97
|
+
`${SHAPE_HEAD_PARTS[0]} (${SHAPE_HEAD_PARTS[1]})`, '',
|
|
98
|
+
`| item | ${cols.join(' | ')} |`, `| --- |${cols.map(() => ' --- |').join('')}`,
|
|
99
|
+
...m.rows.map((r) => `| ${md(r.name)} | ${r.cells.map((c) => md(`${c.mark === 'g' ? '✓' : '✗'}${c.text ? ` ${c.text}` : ''}`)).join(' | ')} |`),
|
|
100
|
+
'', `Not checked: ${SHAPE_TRUTH_PARTS[0]} (${SHAPE_TRUTH_PARTS[1]})`,
|
|
101
|
+
...(m.errors.length ? ['', '### Failed', '', ...m.errors.map((e) => `- ${e}`)] : []),
|
|
102
|
+
];
|
|
103
|
+
return lines.join('\n');
|
|
104
|
+
}
|