fwdloop 0.36.0 → 0.38.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 +6 -20
- package/bin/fwdloop +35 -12
- 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 -46
- 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 +598 -61
- package/src/checked.js +27 -33
- package/src/checklistsign.js +3 -3
- 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 +34 -10
- package/src/drafter.js +99 -74
- package/src/factwords.js +7 -4
- package/src/globprefix.js +26 -0
- package/src/isrec.js +2 -0
- package/src/line-checks.js +1 -2
- package/src/minrule.js +16 -0
- package/src/model-step.js +22 -4
- package/src/pageask.js +0 -3
- 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 +33 -8
- package/src/panel/data.js +3 -2
- package/src/panel/index.html +177 -37
- package/src/panel/result.js +34 -1
- package/src/pickrecord.js +14 -0
- package/src/planrebuild.js +55 -19
- package/src/ratelimit.js +117 -0
- package/src/report.js +14 -2
- package/src/rowresults.js +111 -0
- package/src/rubricstep.js +65 -2
- package/src/runner.js +38 -5
- 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/sheet-record.js +1 -2
- package/src/sheetblock.js +1 -2
- package/src/sheetbuild.js +41 -29
- package/src/sheetchecks.js +1 -2
- package/src/sheetclaims.js +1 -2
- package/src/sheetoffer.js +1 -1
- package/src/sheetrows.js +10 -64
- package/src/sheetrun.js +1 -2
- package/src/ticketrows.js +2 -3
- package/src/try-checks.js +39 -6
- package/src/types.js +1 -0
- package/src/whole-job.js +24 -8
- package/types/action-stop.d.ts +1 -1
- package/types/auditchecks.d.ts +13 -2
- package/types/authoring.d.ts +21 -2
- package/types/blockasks.d.ts +6 -10
- package/types/blockassemble.d.ts +12 -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 +276 -27
- 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 +9 -4
- package/types/globprefix.d.ts +5 -0
- package/types/isrec.d.ts +1 -0
- package/types/minrule.d.ts +6 -0
- package/types/model-step.d.ts +43 -2
- package/types/pageask.d.ts +0 -1
- 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 +16 -1
- package/types/pickrecord.d.ts +10 -0
- package/types/ratelimit.d.ts +59 -0
- package/types/report.d.ts +2 -1
- package/types/rowresults.d.ts +28 -0
- package/types/rubricstep.d.ts +21 -0
- package/types/runner.d.ts +3 -1
- 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/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 +20 -4
package/src/runner.js
CHANGED
|
@@ -933,6 +933,7 @@ function makeAuditRow({
|
|
|
933
933
|
* @param {number} [opts.triesDone] - tries a Stop already closed on this step (they count against its limit)
|
|
934
934
|
* @param {string|null} [opts.runDir] - M4d am29 item 2: the run's folder, where each try saves its checks
|
|
935
935
|
* @param {any[]} [opts.checkList] - M16 item 5: the plan's signed list; a list line's checks carry the row's `by`
|
|
936
|
+
* @param {any[]} [opts.jobLines] - M19 am11 item 4: the signed job lines; the words of a list line's rows read the person's rule
|
|
936
937
|
* @param {Record<string, any>} [opts.mcpGranted] - M13 item 5: this step's signed MCP tools, already bound to its bridge (`runStepRalph` builds them); handed to the model with the verbs
|
|
937
938
|
* @returns {Promise<{ok:true, artifact:any, attempts:number, hitl?:boolean} | {ok:false, outcome:string, red:string, stop?:{where:string, book:Record<string, any>, step?:string|null}}>}
|
|
938
939
|
*/
|
|
@@ -959,6 +960,8 @@ async function runStepTries({
|
|
|
959
960
|
mcpGranted = {},
|
|
960
961
|
// M16 item 5: the signed list (declaration.checkList), so a check of a list line is tagged by its row in the Audit
|
|
961
962
|
checkList = undefined,
|
|
963
|
+
// M19 am11 item 4: the signed job lines (the words of a list line's rows)
|
|
964
|
+
jobLines = undefined,
|
|
962
965
|
}) {
|
|
963
966
|
/** @type {string|null} */
|
|
964
967
|
let gap = initialGap ?? null;
|
|
@@ -1047,7 +1050,7 @@ async function runStepTries({
|
|
|
1047
1050
|
// M4d am25: `thinkingMode` is the ONE decision of what this try asks of thinking (`stepThinkingMode`); the model step only passes it on.
|
|
1048
1051
|
// 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,
|
|
1049
1052
|
// 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.
|
|
1050
|
-
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, withText: step.close?.class === 'green' && Array.isArray(step.close.picked) && step.close.picked.length > 0, picked: step.close?.class === 'green' && Array.isArray(step.close.picked) ? step.close.picked : null, attempt, step: step?.emits ?? step?.goal ?? null, thinkingMode: stepThinkingMode({ boxOn: thinkingBox, attempt }) });
|
|
1053
|
+
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, withText: step.close?.class === 'green' && Array.isArray(step.close.picked) && step.close.picked.length > 0, picked: step.close?.class === 'green' && Array.isArray(step.close.picked) ? step.close.picked : null, attempt, itemShape: step.close?.itemShape && typeof step.close.itemShape === 'object' ? step.close.itemShape : null, line: step.fromLine ?? null, step: step?.emits ?? step?.goal ?? null, thinkingMode: stepThinkingMode({ boxOn: thinkingBox, attempt }) });
|
|
1051
1054
|
|
|
1052
1055
|
const stopSeam = readStop ? Object.freeze({ stopRequested: readStop }) : undefined;
|
|
1053
1056
|
|
|
@@ -1210,7 +1213,7 @@ async function runStepTries({
|
|
|
1210
1213
|
n: step.fromLine, part: closed.cited.part, results: closed.cited.results, check: closed.cited.check,
|
|
1211
1214
|
}));
|
|
1212
1215
|
}
|
|
1213
|
-
tryChecks.push(...closeRecords(step, artifact, closed, checkList));
|
|
1216
|
+
tryChecks.push(...closeRecords(step, artifact, closed, checkList, jobLines));
|
|
1214
1217
|
saveTry();
|
|
1215
1218
|
|
|
1216
1219
|
if (closed.verdict === 'green' || closed.verdict === 'hitl') {
|
|
@@ -1663,6 +1666,8 @@ async function runAskSlot({
|
|
|
1663
1666
|
rebuildPrior = /** @type {null | (() => ({ok:true,value:any}|{ok:false,red:string}))} */ (null),
|
|
1664
1667
|
// M16 item 5: the signed list, handed on to a redo's tries
|
|
1665
1668
|
checkList = /** @type {any[]|undefined} */ (undefined),
|
|
1669
|
+
// M19 am11 item 4: the signed job lines, handed on to a redo's tries with the list
|
|
1670
|
+
jobLines = /** @type {any[]|undefined} */ (undefined),
|
|
1666
1671
|
}) {
|
|
1667
1672
|
let redone = initialRedone;
|
|
1668
1673
|
let currentPrior = priorArtifact;
|
|
@@ -1839,7 +1844,7 @@ async function runAskSlot({
|
|
|
1839
1844
|
}
|
|
1840
1845
|
// eslint-disable-next-line no-await-in-loop
|
|
1841
1846
|
const redoResult = await runStepRalph({
|
|
1842
|
-
step: priorStep, primitivesMap: primitives, readsMap: priorReadsResult.map, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, mcpServer, checkList, initialGap: reason, attemptOffset: lastTryNumber(runDir, priorStep.emits ?? priorStep.goal ?? null), thinkingBox: readJobThinking(flowDir, runDir), learnHints: stepHintsReader({ flowName, source: inputsManifest?.[0]?.source ?? null, now }), now, runDir,
|
|
1847
|
+
step: priorStep, primitivesMap: primitives, readsMap: priorReadsResult.map, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, mcpServer, checkList, jobLines, initialGap: reason, attemptOffset: lastTryNumber(runDir, priorStep.emits ?? priorStep.goal ?? null), thinkingBox: readJobThinking(flowDir, runDir), learnHints: stepHintsReader({ flowName, source: inputsManifest?.[0]?.source ?? null, now }), now, runDir,
|
|
1843
1848
|
readStop: () => stopPending(runDir), stepNo: priorStepNo, prevStepId: priorPrevStepId,
|
|
1844
1849
|
});
|
|
1845
1850
|
if (!redoResult.ok) {
|
|
@@ -1969,6 +1974,19 @@ async function foldFromStep({
|
|
|
1969
1974
|
});
|
|
1970
1975
|
}
|
|
1971
1976
|
let content = contentResult.value;
|
|
1977
|
+
// M15 am4: a job with no signed Ask shows and binds the WHOLE body (every work line, in line order) at the stop, so what is accepted is what is written. It is built before the stop, from the saved outputs.
|
|
1978
|
+
const noAsk = askLines.size === 0 && wholeIdx < 0;
|
|
1979
|
+
let noAskBody = /** @type {{ ok: true, body: string } | null} */ (null);
|
|
1980
|
+
if (noAsk) {
|
|
1981
|
+
const built = sendBodyOf({ content, wholeIdx, steps, sendIndex: i, askLines, context: reportContextOf({ runDir, steps, jobLines, checkList }), readResult: (id) => readArtifactResult(runDir, id) });
|
|
1982
|
+
if (!built.ok) {
|
|
1983
|
+
return haltRun({
|
|
1984
|
+
flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts, outcome: 'red', red: built.red,
|
|
1985
|
+
});
|
|
1986
|
+
}
|
|
1987
|
+
noAskBody = built;
|
|
1988
|
+
content = { text: built.body };
|
|
1989
|
+
}
|
|
1972
1990
|
const decided = decideAction({ acceptedSha: lastAcceptedSha(steps, i, acceptedAskEmitsThisRun), outgoing: content });
|
|
1973
1991
|
let shaToSend = decided.outgoingSha;
|
|
1974
1992
|
if (!decided.go) {
|
|
@@ -1980,6 +1998,7 @@ async function foldFromStep({
|
|
|
1980
1998
|
const stop = await runAskSlot({
|
|
1981
1999
|
mcpServer,
|
|
1982
2000
|
checkList,
|
|
2001
|
+
jobLines,
|
|
1983
2002
|
step,
|
|
1984
2003
|
stepIndex: i,
|
|
1985
2004
|
askSlot: { question: decided.question, ttlMs: stopWaitMs(steps, i, askLines, sendSlot.waitMs), kind: ACTION_STOP_KIND },
|
|
@@ -2027,7 +2046,7 @@ async function foldFromStep({
|
|
|
2027
2046
|
}
|
|
2028
2047
|
}
|
|
2029
2048
|
// M15 am3 item 6: what is written is the accepted body (the whole-job text built at the last Ask) under the title and the Passed line the send adds; the hash check stays on `content`
|
|
2030
|
-
const sendBody = sendBodyOf({ content, wholeIdx, steps, sendIndex: i, askLines, context: reportContextOf({ runDir, steps, jobLines, checkList }) });
|
|
2049
|
+
const sendBody = noAskBody ?? sendBodyOf({ content, wholeIdx, steps, sendIndex: i, askLines, context: reportContextOf({ runDir, steps, jobLines, checkList }) });
|
|
2031
2050
|
if (!sendBody.ok) {
|
|
2032
2051
|
return haltRun({
|
|
2033
2052
|
flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts, outcome: 'red', red: sendBody.red,
|
|
@@ -2097,6 +2116,7 @@ async function foldFromStep({
|
|
|
2097
2116
|
const askResult = await runAskSlot({
|
|
2098
2117
|
mcpServer,
|
|
2099
2118
|
checkList,
|
|
2119
|
+
jobLines,
|
|
2100
2120
|
step,
|
|
2101
2121
|
stepIndex: i,
|
|
2102
2122
|
askSlot,
|
|
@@ -2170,7 +2190,7 @@ async function foldFromStep({
|
|
|
2170
2190
|
// redo's `initialGap` above.
|
|
2171
2191
|
// eslint-disable-next-line no-await-in-loop
|
|
2172
2192
|
const stepResult = await runStepRalph({
|
|
2173
|
-
step, primitivesMap: primitives, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, mcpServer, checkList, initialGap: i === i0 ? firstStepGap : null, thinkingBox: readJobThinking(flowDir, runDir), learnHints: stepHintsReader({ flowName, source: inputsManifest?.[0]?.source ?? null, now }), now, runDir,
|
|
2193
|
+
step, primitivesMap: primitives, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, mcpServer, checkList, jobLines, initialGap: i === i0 ? firstStepGap : null, thinkingBox: readJobThinking(flowDir, runDir), learnHints: stepHintsReader({ flowName, source: inputsManifest?.[0]?.source ?? null, now }), now, runDir,
|
|
2174
2194
|
readStop: () => stopPending(runDir), stepNo: i + 1, prevStepId: i > 0 ? (steps[i - 1].emits ?? steps[i - 1].goal ?? null) : null, attemptOffset: i === i0 ? resumeTries.numbered : 0, triesDone: i === i0 ? resumeTries.done : 0,
|
|
2175
2195
|
});
|
|
2176
2196
|
if (!stepResult.ok) {
|
|
@@ -2773,6 +2793,18 @@ export async function resumeRun({
|
|
|
2773
2793
|
let priorArtifact = readArtifact(runDir, priorId);
|
|
2774
2794
|
// M13 am9: the Ask that shows the whole job rebuilds `{text}` from the saved outputs, as the first pass did
|
|
2775
2795
|
const wholeIdx = wholeJobAskIndex({ steps, askLines, sendLines });
|
|
2796
|
+
if (isStop && askLines.size === 0 && wholeIdx < 0) {
|
|
2797
|
+
// M15 am4: the stop of a job with no Ask shows the whole body, rebuilt as the first pass built it (the answer's hash is of this text)
|
|
2798
|
+
const built = sendBodyOf({ content: priorArtifact, wholeIdx, steps, sendIndex: state.stepIndex, askLines, context: reportContextOf({ runDir, steps, jobLines: read.lines, checkList: declaration.checkList }), readResult: (id) => readArtifactResult(runDir, id) });
|
|
2799
|
+
if (!built.ok) {
|
|
2800
|
+
return haltRun({
|
|
2801
|
+
flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs: getNowMs, signatureHash: state.signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts,
|
|
2802
|
+
outcome: 'red', red: built.red,
|
|
2803
|
+
resumeAt: { stepIndex: state.stepIndex, flowRoot: root, flowName: name, inputsManifest: state.inputsManifest, unjudged: state.evidenceUnjudged ?? [], redone: typeof state.redone === 'number' ? state.redone : 0 },
|
|
2804
|
+
});
|
|
2805
|
+
}
|
|
2806
|
+
priorArtifact = { text: built.body };
|
|
2807
|
+
}
|
|
2776
2808
|
const rebuildWhole = () => wholeJobText({ steps, askLines, lastAskIndex: wholeIdx, readResult: (id) => readArtifactResult(runDir, id), context: reportContextOf({ runDir, steps, jobLines: read.lines, checkList: declaration.checkList }) });
|
|
2777
2809
|
if (state.stepIndex === wholeIdx) {
|
|
2778
2810
|
const whole = rebuildWhole();
|
|
@@ -2791,6 +2823,7 @@ export async function resumeRun({
|
|
|
2791
2823
|
const askResult = await runAskSlot({
|
|
2792
2824
|
mcpServer: declaration.mcp?.server ?? null,
|
|
2793
2825
|
checkList: declaration.checkList,
|
|
2826
|
+
jobLines: read.lines,
|
|
2794
2827
|
step,
|
|
2795
2828
|
stepIndex: state.stepIndex,
|
|
2796
2829
|
askSlot,
|
|
@@ -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
|
+
}
|