fwdloop 0.22.0 → 0.24.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/bin/fwdloop +31 -8
- package/package.json +2 -2
- package/src/ask.js +34 -4
- package/src/attemptdiff.js +118 -0
- package/src/audit-fold.js +2 -0
- package/src/authoring.js +36 -2
- package/src/canrun.js +5 -0
- package/src/checked.js +14 -3
- package/src/citedcheck.js +16 -1
- package/src/citedwords.js +36 -2
- package/src/closers.js +13 -223
- package/src/config.js +5 -1
- package/src/csv.js +69 -12
- package/src/declaration.js +64 -6
- package/src/drafter.js +43 -17
- package/src/flowmodel.js +56 -1
- package/src/learn.js +952 -0
- package/src/learnstore.js +346 -0
- package/src/model-step.js +15 -21
- package/src/pagedry.js +3 -4
- package/src/pagefetch.js +9 -2
- package/src/pagerules.js +28 -5
- package/src/panel/author.js +2 -1
- package/src/panel/authorcard.js +9 -2
- package/src/panel/data.js +80 -17
- package/src/panel/index.html +186 -12
- package/src/panel/result.js +6 -0
- package/src/redact.js +6 -6
- package/src/runner.js +151 -24
- package/src/sheet-record.js +57 -0
- package/src/sheetblock.js +170 -0
- package/src/sheetchecks.js +206 -0
- package/src/sheetclaims.js +78 -0
- package/src/sheetoffer.js +125 -0
- package/src/sheetrun.js +105 -0
- package/src/thinking.js +11 -0
- package/src/try-checks.js +6 -0
- package/src/types.js +1 -9
- package/types/ask.d.ts +8 -2
- package/types/attemptdiff.d.ts +38 -0
- package/types/checked.d.ts +9 -3
- package/types/citedwords.d.ts +14 -0
- package/types/closers.d.ts +6 -31
- package/types/csv.d.ts +25 -4
- package/types/declaration.d.ts +6 -1
- package/types/drafter.d.ts +28 -9
- package/types/flowmodel.d.ts +36 -0
- package/types/learn.d.ts +576 -0
- package/types/learnstore.d.ts +168 -0
- package/types/model-step.d.ts +19 -30
- package/types/pagerules.d.ts +7 -0
- package/types/panel/authorcard.d.ts +2 -1
- package/types/panel/data.d.ts +2 -1
- package/types/panel/result.d.ts +1 -1
- package/types/runner.d.ts +19 -6
- package/types/sheet-record.d.ts +24 -0
- package/types/sheetblock.d.ts +116 -0
- package/types/sheetchecks.d.ts +70 -0
- package/types/sheetclaims.d.ts +26 -0
- package/types/sheetoffer.d.ts +25 -0
- package/types/sheetrun.d.ts +35 -0
- package/types/thinking.d.ts +11 -0
- package/types/types.d.ts +16 -11
package/src/runner.js
CHANGED
|
@@ -60,16 +60,21 @@ import { configHome, configDoorHome } from './config.js';
|
|
|
60
60
|
import { closeByClass, isCellsPath } from './closers.js';
|
|
61
61
|
import { readRunSource } from './cited-source.js';
|
|
62
62
|
import { citedLineOf, writeCitedLine } from './cited-record.js';
|
|
63
|
+
import { sheetRolesOf, tableShaOfFrozen, readRunSheets } from './sheetrun.js';
|
|
64
|
+
import { writeSheetLine } from './sheet-record.js';
|
|
63
65
|
import {
|
|
64
66
|
appendAudit, appendHistory, readAudit, readHistory, endRow, HALT_OUTCOMES,
|
|
65
67
|
} from './books.js';
|
|
68
|
+
import { learnAtRunEnd, NOT_A_RUN_END, hintsForRun, placeSpecOf } from './learnstore.js';
|
|
69
|
+
import { redactSecrets } from './redact.js';
|
|
70
|
+
import { appendRow } from './jsonl-append.js';
|
|
66
71
|
import { applyRunValues, pickRunValues } from './runvalues.js';
|
|
67
|
-
import { stepThinkingMode } from './thinking.js';
|
|
72
|
+
import { stepThinkingMode, stepHintsWanted } from './thinking.js';
|
|
68
73
|
import { appendChecks, nextRound } from './diary.js';
|
|
69
74
|
import {
|
|
70
75
|
doneRecord, happenedRecord, outputRecord, closeRecords,
|
|
71
76
|
} from './try-checks.js';
|
|
72
|
-
import { readJobThinking, writeRunThinking, writeRunModel } from './flowmodel.js';
|
|
77
|
+
import { readJobThinking, writeRunThinking, writeRunModel, takeLearningsRecord } from './flowmodel.js';
|
|
73
78
|
import { fetchPageText, isWebUrl } from './pagefetch.js';
|
|
74
79
|
import {
|
|
75
80
|
readResumeLock, recordPid, writeLockHolder, procStartOf, LOCK_NO_HOLDER,
|
|
@@ -216,9 +221,9 @@ const holdOf = (ceilingUsd) => (Number.isFinite(ceilingUsd) && /** @type {number
|
|
|
216
221
|
// WITHOUT the cap (M2 scope item 3, the load-bearing invariant).
|
|
217
222
|
// ---------------------------------------------------------------------------
|
|
218
223
|
|
|
219
|
-
const EXECUTOR_FIELDS = Object.freeze(['goal', 'primitives', 'reads', 'gap']);
|
|
224
|
+
const EXECUTOR_FIELDS = Object.freeze(['goal', 'primitives', 'reads', 'gap', 'hints']);
|
|
220
225
|
|
|
221
|
-
/** @param {{goal:string, primitives?:string[], reads?:Record<string,any>, gap?:string|null}} opts */
|
|
226
|
+
/** @param {{goal:string, primitives?:string[], reads?:Record<string,any>, gap?:string|null, hints?:string|null}} opts `hints` (M8 am7): the earlier runs' block, text only, for a retry / redo / rerun try */
|
|
222
227
|
export function buildExecutorContext(opts) {
|
|
223
228
|
for (const key of Object.keys(opts ?? {})) {
|
|
224
229
|
if (!EXECUTOR_FIELDS.includes(key)) {
|
|
@@ -226,13 +231,14 @@ export function buildExecutorContext(opts) {
|
|
|
226
231
|
}
|
|
227
232
|
}
|
|
228
233
|
const {
|
|
229
|
-
goal, primitives = [], reads = {}, gap = null,
|
|
234
|
+
goal, primitives = [], reads = {}, gap = null, hints = null,
|
|
230
235
|
} = opts ?? {};
|
|
231
236
|
return Object.freeze({
|
|
232
237
|
goal,
|
|
233
238
|
primitives: Object.freeze([...primitives]),
|
|
234
239
|
reads: Object.freeze({ ...reads }),
|
|
235
240
|
gap: gap ?? null,
|
|
241
|
+
hints: hints ?? null,
|
|
236
242
|
});
|
|
237
243
|
}
|
|
238
244
|
|
|
@@ -413,8 +419,11 @@ export async function freezePage(dir, id, url, { fetchPage = fetchPageText } = {
|
|
|
413
419
|
* unreadable source refuses by name. A source that is a web address
|
|
414
420
|
* (M10 item 1) is fetched and frozen by `freezePage`, in the same manifest.
|
|
415
421
|
* @param {string} runDir @param {Array<{id: string, path: string}>} sources
|
|
416
|
-
*
|
|
417
|
-
|
|
422
|
+
* M10b amendment 1: a CSV input named in `tableRoles` (the sheets a step's `close.sheet` reads) also gets its `tableSha` (bareguard's fingerprint of the table made
|
|
423
|
+
* from the FROZEN copy) in its manifest entry - the ONE place it is written, once, with the run's inputs; every sheet check of the run uses this recorded value.
|
|
424
|
+
* A sheet bareguard cannot read as a table refuses the run here, naming the input.
|
|
425
|
+
* @param {{fetchPage?: (url: string) => Promise<{ok: true, text: string, url: string}|{ok: false, error: string}>, tableRoles?: string[]}} [o] */
|
|
426
|
+
export async function freezeInputs(runDir, sources, { fetchPage, tableRoles = [] } = {}) {
|
|
418
427
|
const inputsDir = join(runDir, 'inputs');
|
|
419
428
|
mkdirSync(inputsDir, { recursive: true });
|
|
420
429
|
const manifest = [];
|
|
@@ -432,9 +441,16 @@ export async function freezeInputs(runDir, sources, { fetchPage } = {}) {
|
|
|
432
441
|
copyFileSync(sourcePath, frozenPath);
|
|
433
442
|
const sha256 = hashFile(frozenPath);
|
|
434
443
|
const { size: bytes } = statSync(frozenPath);
|
|
435
|
-
|
|
444
|
+
/** @type {Record<string, any>} */
|
|
445
|
+
const entry = {
|
|
436
446
|
id, source: sourcePath, frozen: frozenPath, sha256, bytes,
|
|
437
|
-
}
|
|
447
|
+
};
|
|
448
|
+
if (tableRoles.includes(id)) {
|
|
449
|
+
const tsha = isCellsPath(frozenPath) ? tableShaOfFrozen(runDir, basename(frozenPath)) : null;
|
|
450
|
+
if (tsha === null) return { ok: false, red: `freeze: input "${id}" cannot be read as a table (a row with more or fewer cells than the header, or a repeated column name); fix the sheet` };
|
|
451
|
+
entry.tableSha = tsha;
|
|
452
|
+
}
|
|
453
|
+
manifest.push(entry);
|
|
438
454
|
}
|
|
439
455
|
writeFileSync(join(runDir, 'inputs.json'), JSON.stringify(manifest, null, 2));
|
|
440
456
|
return { ok: true, manifest };
|
|
@@ -669,6 +685,59 @@ function recordLateAnswerIfAny(runDir, now = () => new Date().toISOString()) {
|
|
|
669
685
|
});
|
|
670
686
|
}
|
|
671
687
|
|
|
688
|
+
// ---------------------------------------------------------------------------
|
|
689
|
+
// M8 items 2 and 4 (item 4 replaced by am4): the run-end tally of cross-run learnings ($0, code only, no model call). ONE call per run
|
|
690
|
+
// exit, from the three callers of `foldFromStep` (runFlow, resumeRun, continueRun), the expired-ask exit and the rerun exit. A record,
|
|
691
|
+
// never a verdict: it can never change a run's outcome, result, spend or books. It runs whether `learningHints` is on or off.
|
|
692
|
+
// - M8 am4: every run's notes COUNT when the run ends, FIXED and NEVER FIXED alike, whatever the ending and whether or not its asks
|
|
693
|
+
// were accepted. No hold, no release (bareloop's ruling for both repos, 2026-10-24).
|
|
694
|
+
// - A run waiting at an ask has not ended ('paused', or a Stop whose set-aside failed): no note yet. A Stop or a cap-halt HAS ended
|
|
695
|
+
// the leg, as in bareloop: its notes are made then, and a later resume folds the whole run again (the ledger counts a run once per row).
|
|
696
|
+
// - Noise runs (provider red, a crashed check) make no note: buildCards reads them off the escalation events eventsOfRun builds.
|
|
697
|
+
// Under a test process with no FWDLOOP_CONFIG_HOME nothing is written (`configDoorHome`), as for every config read.
|
|
698
|
+
// borrowed-from: bareloop src/userrun.js@v0.46.0:2035 (the call site, in its own try/catch)
|
|
699
|
+
// ---------------------------------------------------------------------------
|
|
700
|
+
|
|
701
|
+
/** where a failure of learnings work that must not stop the run is recorded (one appended row, in the run's own folder): the run-end tally (`recordRunNotes`) and the take of the draft's learnings record (`takeLearningsRecord`, in runFlow). The run itself is unaffected */
|
|
702
|
+
export const LEARN_ERROR_FILE = 'learn-error.jsonl';
|
|
703
|
+
|
|
704
|
+
/**
|
|
705
|
+
* @param {{flowName: string, runId: string, runDir: string, outcome: string, specHash: string|null, now: () => string}} o
|
|
706
|
+
*/
|
|
707
|
+
function recordRunNotes({
|
|
708
|
+
flowName, runId, runDir, outcome, specHash, now,
|
|
709
|
+
}) {
|
|
710
|
+
if (NOT_A_RUN_END.has(outcome)) return;
|
|
711
|
+
const door = configDoorHome();
|
|
712
|
+
if (door.skip) return;
|
|
713
|
+
try {
|
|
714
|
+
const r = learnAtRunEnd({
|
|
715
|
+
home: door.home, workflow: flowName, runId, runDir, specHash, now: new Date(now()),
|
|
716
|
+
});
|
|
717
|
+
if (r.problem) throw new Error(r.problem);
|
|
718
|
+
} catch (/** @type {any} */ e) {
|
|
719
|
+
try {
|
|
720
|
+
appendRow(join(runDir, LEARN_ERROR_FILE), { at: now(), error: redactSecrets(String(e?.message ?? e)).split('\n')[0] });
|
|
721
|
+
} catch { /* the record of the failure is itself best-effort */ }
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
/**
|
|
726
|
+
* M8 am7 item 1: the step's side of "one block". `hintsForRun` (src/learnstore.js) is the ONE function that makes the block the drafter is handed; a step's try
|
|
727
|
+
* calls that same function, with the run's own workflow name, first input source and clock, and a null specHash exactly as the drafter does (so no second filter by job version), and takes its answer whole (no second render, no filter).
|
|
728
|
+
* Returns null when `learningHints` is off, when there is no ledger or nothing readable, or in a test process with no config home. A ledger problem THROWS (the caller
|
|
729
|
+
* hands nothing and records why as `hintsError` on the try's audit row, never a failed step).
|
|
730
|
+
* @param {{flowName: string, source: string|null, now: () => string}} o
|
|
731
|
+
* @returns {() => {text: string, ids: string[]}|null}
|
|
732
|
+
*/
|
|
733
|
+
function stepHintsReader({ flowName, source, now }) {
|
|
734
|
+
return () => {
|
|
735
|
+
const door = configDoorHome();
|
|
736
|
+
if (door.skip) return null;
|
|
737
|
+
return hintsForRun({ home: door.home, spec: placeSpecOf(flowName, source), specHash: null, now: new Date(now()) });
|
|
738
|
+
};
|
|
739
|
+
}
|
|
740
|
+
|
|
672
741
|
// ---------------------------------------------------------------------------
|
|
673
742
|
// The ralph loop with strikes (M2 scope item 5) for ONE step.
|
|
674
743
|
// ---------------------------------------------------------------------------
|
|
@@ -710,6 +779,10 @@ function sumKnownUsd(...values) {
|
|
|
710
779
|
function makeAuditRow({
|
|
711
780
|
step, attempt, verdict, gap, usd, spendComplete, wallMs, model = null, modelMatch = null, strike, at, tokens = null, tools = null, ungranted = /** @type {string[]|undefined} */ (undefined), refused = /** @type {Array<{verb:string,path:string,rule:string}>} */ ([]),
|
|
712
781
|
thinking = /** @type {{asked:string, status:string|null}|undefined} */ (undefined),
|
|
782
|
+
hints = /** @type {number|undefined} */ (undefined),
|
|
783
|
+
hintsText = /** @type {string|undefined} */ (undefined),
|
|
784
|
+
hintIds = /** @type {string[]|undefined} */ (undefined),
|
|
785
|
+
hintsError = /** @type {string|undefined} */ (undefined),
|
|
713
786
|
}) {
|
|
714
787
|
const row = {
|
|
715
788
|
step: step?.emits ?? step?.goal ?? null,
|
|
@@ -731,6 +804,10 @@ function makeAuditRow({
|
|
|
731
804
|
if (ungranted !== undefined && ungranted.length > 0) row.ungranted = ungranted;
|
|
732
805
|
// M4d am25 item 4: the thinking this model call asked for and what bareagent reported back; the ONE writer of the field. A row with no model call has none.
|
|
733
806
|
if (thinking !== undefined) row.thinking = thinking;
|
|
807
|
+
// M8 am7 item 4: how many hints from earlier runs this try was handed, the exact text and the ids; the keys are absent when none were. The ONE place the handed text is kept
|
|
808
|
+
// (this row, written after the call from what the try held in memory); a failed ask for the block is `hintsError`, the first line, secrets redacted.
|
|
809
|
+
if (hints !== undefined) { row.hints = hints; row.hintsText = hintsText; row.hintIds = hintIds; }
|
|
810
|
+
if (hintsError !== undefined) row.hintsError = hintsError;
|
|
734
811
|
return row;
|
|
735
812
|
}
|
|
736
813
|
|
|
@@ -753,6 +830,7 @@ function makeAuditRow({
|
|
|
753
830
|
* @param {(row: any, modelOutput?: any) => void} opts.recordAudit
|
|
754
831
|
* @param {string|null} [opts.initialGap]
|
|
755
832
|
* @param {number} [opts.attemptOffset]
|
|
833
|
+
* @param {(() => {text: string, ids: string[]}|null)|null} [opts.learnHints] - M8 am7: `stepHintsReader`'s closure (the drafter's one block function); asked only on a retry, redo or rerun try
|
|
756
834
|
* @param {boolean} [opts.thinkingBox] - M4d am25: the job's "Thinking on" box as this run's copy keeps it (default off)
|
|
757
835
|
* @param {() => string} [opts.now] - M4a-2: stamps each audit row's `at`;
|
|
758
836
|
* defaults to the real wall clock.
|
|
@@ -767,6 +845,7 @@ export async function runStepRalph({
|
|
|
767
845
|
step, primitivesMap, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd, recordAudit, initialGap = null, attemptOffset = 0,
|
|
768
846
|
// M4d am25: the job's "Thinking on" box as the run's own copy keeps it; read once by the caller (`readJobThinking`), decided per try below by `stepThinkingMode`.
|
|
769
847
|
thinkingBox = false,
|
|
848
|
+
learnHints = null,
|
|
770
849
|
// M4a-2: the run's own injected clock (never the bare wall clock) —
|
|
771
850
|
// stamps every audit row's `at` with this attempt's finish time. Defaults
|
|
772
851
|
// to the real wall clock so a caller that doesn't inject one (there are
|
|
@@ -823,8 +902,29 @@ export async function runStepRalph({
|
|
|
823
902
|
}
|
|
824
903
|
|
|
825
904
|
const grantedTools = Object.fromEntries((step.primitives ?? []).map((verb) => [verb, primitivesMap?.[verb]]));
|
|
905
|
+
// M8 am7: the earlier runs' block for THIS try only - a retry, a redo or a rerun (`stepHintsWanted`; the Chat box never decides it). It is the drafter's one block
|
|
906
|
+
// function asked again now. What it handed is kept in memory and rides EVERY audit row this try writes (the row is written after the call, so the record exists once the
|
|
907
|
+
// try's row does); any failure hands nothing and rides the row as `hintsError`.
|
|
908
|
+
/** @type {{text: string, ids: string[]}|null} */
|
|
909
|
+
let handed = null;
|
|
910
|
+
/** @type {string|undefined} */
|
|
911
|
+
let handedError;
|
|
912
|
+
if (learnHints !== null && stepHintsWanted({ attempt, rerunReason: n === 1 ? initialGap : null })) {
|
|
913
|
+
try {
|
|
914
|
+
handed = learnHints();
|
|
915
|
+
} catch (/** @type {any} */ e) {
|
|
916
|
+
handed = null;
|
|
917
|
+
handedError = redactSecrets(String(e?.message ?? e)).split('\n')[0];
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
// every row this try writes from here on carries how many hints it was handed, which, and what (none handed = no field)
|
|
921
|
+
const rowOf = (/** @type {any} */ a) => makeAuditRow({
|
|
922
|
+
...a,
|
|
923
|
+
...(handed !== null ? { hints: handed.ids.length, hintsText: handed.text, hintIds: handed.ids } : {}),
|
|
924
|
+
...(handedError !== undefined ? { hintsError: handedError } : {}),
|
|
925
|
+
});
|
|
826
926
|
const executorContext = buildExecutorContext({
|
|
827
|
-
goal: step.goal, primitives: step.primitives ?? [], reads: readsMap, gap,
|
|
927
|
+
goal: step.goal, primitives: step.primitives ?? [], reads: readsMap, gap, hints: handed === null ? null : handed.text,
|
|
828
928
|
});
|
|
829
929
|
|
|
830
930
|
// `stepMeta` is a SEPARATE argument from `executorContext` — never a
|
|
@@ -836,7 +936,7 @@ export async function runStepRalph({
|
|
|
836
936
|
// M4d am25: `thinkingMode` is the ONE decision of what this try asks of thinking (`stepThinkingMode`); the model step only passes it on.
|
|
837
937
|
// M10 am7 item 3: `cited` is the fact part of a green step that quotes a saved page - the form of its ANSWER ({results: [{quote, values}]}) and the facts it must hold,
|
|
838
938
|
// told to the step in plain words by the model step. It is not the check: the quotes are checked by `closeCited` against the run's own copy.
|
|
839
|
-
const stepMeta = Object.freeze({ class: step.close?.class ?? null, cited: step.close?.class === 'green' && step.close.cited ? step.close.cited : null, attempt, step: step?.emits ?? step?.goal ?? null, thinkingMode: stepThinkingMode({ boxOn: thinkingBox, attempt }) });
|
|
939
|
+
const stepMeta = Object.freeze({ class: step.close?.class ?? null, cited: step.close?.class === 'green' && step.close.cited ? step.close.cited : null, sheet: step.close?.class === 'green' && Array.isArray(step.close.sheet) ? step.close.sheet : null, attempt, step: step?.emits ?? step?.goal ?? null, thinkingMode: stepThinkingMode({ boxOn: thinkingBox, attempt }) });
|
|
840
940
|
|
|
841
941
|
const stopSeam = readStop ? Object.freeze({ stopRequested: readStop }) : undefined;
|
|
842
942
|
|
|
@@ -880,7 +980,7 @@ export async function runStepRalph({
|
|
|
880
980
|
if (typeof result.costUsd === 'number') spent.value += result.costUsd;
|
|
881
981
|
const usd = sumKnownUsd(attemptFloorUsd, result.costUsd);
|
|
882
982
|
const ranCalls = (turns ?? 0) > 0 || attemptFloorUsd !== null;
|
|
883
|
-
return stopped(stopWords(ranCalls ? attempt : attempt - 1, turns ?? 0),
|
|
983
|
+
return stopped(stopWords(ranCalls ? attempt : attempt - 1, turns ?? 0), rowOf({
|
|
884
984
|
step, attempt: ranCalls ? attempt : null, verdict: 'stopped', gap: null, usd, spendComplete: usd !== null, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false, at: now(), tokens: result.tokens ?? null, tools: result.tools ?? null, ungranted: result.ungranted, refused: result.refused, thinking: result.thinking,
|
|
885
985
|
}));
|
|
886
986
|
}
|
|
@@ -891,7 +991,7 @@ export async function runStepRalph({
|
|
|
891
991
|
// already added to `spent.value` above (never double-added here); a
|
|
892
992
|
// null second cost never zeroes out a known first floor.
|
|
893
993
|
const usd = sumKnownUsd(attemptFloorUsd, result.costUsd);
|
|
894
|
-
recordAudit(
|
|
994
|
+
recordAudit(rowOf({
|
|
895
995
|
step, attempt, verdict: 'provider-red', gap, usd, spendComplete: false, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false, at: now(), tokens: result.tokens ?? null, tools: result.tools ?? null, ungranted: result.ungranted, refused: result.refused, thinking: result.thinking,
|
|
896
996
|
}), result.red ?? 'transport fault twice');
|
|
897
997
|
return { ok: false, outcome: 'provider-red', red: `provider-red: step "${step.goal}" attempt ${attempt}: ${result.red ?? 'transport fault twice'}` };
|
|
@@ -911,7 +1011,7 @@ export async function runStepRalph({
|
|
|
911
1011
|
seenGaps.add(normalised);
|
|
912
1012
|
if (strike) strikes += 1;
|
|
913
1013
|
const usd = sumKnownUsd(attemptFloorUsd, result?.costUsd);
|
|
914
|
-
recordAudit(
|
|
1014
|
+
recordAudit(rowOf({
|
|
915
1015
|
step, attempt, verdict: 'red', gap: red, usd, spendComplete: usd !== null, wallMs, model: result?.model, modelMatch: result?.modelMatch, strike, at: now(), tokens: result?.tokens ?? null, tools: result?.tools ?? null, ungranted: result?.ungranted, refused: result?.refused, thinking: result?.thinking,
|
|
916
1016
|
}), red);
|
|
917
1017
|
if (n === maxN) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: step "${step.goal}" — ${red}` };
|
|
@@ -922,7 +1022,7 @@ export async function runStepRalph({
|
|
|
922
1022
|
}
|
|
923
1023
|
|
|
924
1024
|
if (result.costUsd === null || result.costUsd === undefined) {
|
|
925
|
-
recordAudit(
|
|
1025
|
+
recordAudit(rowOf({
|
|
926
1026
|
step, attempt, verdict: 'pricing-red', gap, usd: attemptFloorUsd, spendComplete: false, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false, at: now(), tokens: result.tokens ?? null, tools: result.tools ?? null, ungranted: result.ungranted, refused: result.refused, thinking: result.thinking,
|
|
927
1027
|
}), result.artifact ?? null);
|
|
928
1028
|
return { ok: false, outcome: 'pricing-red', red: `pricing-red: step "${step.goal}" attempt ${attempt} returned no cost (never "?? 0")` };
|
|
@@ -949,7 +1049,7 @@ export async function runStepRalph({
|
|
|
949
1049
|
tryChecks.push(doneRecord(doneCheck, result.artifact));
|
|
950
1050
|
if (doneCheck.verdict === 'not-done') {
|
|
951
1051
|
saveTry();
|
|
952
|
-
recordAudit(
|
|
1052
|
+
recordAudit(rowOf({
|
|
953
1053
|
step, attempt, verdict: 'not-done', gap: doneCheck.red, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false, at: now(), tokens: result.tokens ?? null, tools: result.tools ?? null, ungranted: result.ungranted, refused: result.refused, thinking: result.thinking,
|
|
954
1054
|
}), result.artifact ?? null);
|
|
955
1055
|
return { ok: false, outcome: 'not-done', red: doneCheck.red };
|
|
@@ -965,7 +1065,7 @@ export async function runStepRalph({
|
|
|
965
1065
|
// (never gated by novelty — an empty artifact is always the same
|
|
966
1066
|
// failure) — matches poc/m2/gapback.mjs's own rule exactly.
|
|
967
1067
|
strikes += 1;
|
|
968
|
-
recordAudit(
|
|
1068
|
+
recordAudit(rowOf({
|
|
969
1069
|
step, attempt, verdict: 'red', gap: happened.red, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike: true, at: now(), tokens: result.tokens ?? null, tools: result.tools ?? null, ungranted: result.ungranted, refused: result.refused, thinking: result.thinking,
|
|
970
1070
|
}), result.artifact ?? null);
|
|
971
1071
|
if (n === maxN) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: ${happened.red}` };
|
|
@@ -979,7 +1079,12 @@ export async function runStepRalph({
|
|
|
979
1079
|
// written by the one writer, `writeCitedLine`, whatever the verdict - the Result tab says why a line did not pass.
|
|
980
1080
|
const citedPart = step?.close?.class === 'green' ? step?.close?.cited : undefined;
|
|
981
1081
|
const source = citedPart && runDir !== null ? readRunSource(runDir, citedPart.source, { docx: true }) : undefined;
|
|
982
|
-
|
|
1082
|
+
// M10b piece 2: a step with `close.sheet` is checked by bareguard on the run's own frozen copy and the `tableSha` recorded at its start; the record of what it
|
|
1083
|
+
// said is written by the one writer, `writeSheetLine`, whatever the verdict.
|
|
1084
|
+
const sheetPart = step?.close?.class === 'green' && Array.isArray(step?.close?.sheet) ? step.close.sheet : undefined;
|
|
1085
|
+
const sheet = sheetPart && runDir !== null ? readRunSheets(runDir, sheetPart) : undefined;
|
|
1086
|
+
const closed = await closeByClass(step, artifact, { reads: readsMap, businessDate, source, sheet });
|
|
1087
|
+
if (sheetPart && runDir !== null && closed.sheetRecord) writeSheetLine(runDir, { n: step.fromLine, try: attempt, checks: sheetPart, closed });
|
|
983
1088
|
if (citedPart && runDir !== null && closed.cited) {
|
|
984
1089
|
writeCitedLine(runDir, citedLineOf({
|
|
985
1090
|
n: step.fromLine, part: closed.cited.part, results: closed.cited.results, check: closed.cited.check,
|
|
@@ -989,7 +1094,7 @@ export async function runStepRalph({
|
|
|
989
1094
|
saveTry();
|
|
990
1095
|
|
|
991
1096
|
if (closed.verdict === 'green' || closed.verdict === 'hitl') {
|
|
992
|
-
recordAudit(
|
|
1097
|
+
recordAudit(rowOf({
|
|
993
1098
|
step, attempt, verdict: closed.verdict, gap: null, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false, at: now(), tokens: result.tokens ?? null, tools: result.tools ?? null, ungranted: result.ungranted, refused: result.refused, thinking: result.thinking,
|
|
994
1099
|
}), result.artifact);
|
|
995
1100
|
return {
|
|
@@ -1000,7 +1105,7 @@ export async function runStepRalph({
|
|
|
1000
1105
|
if (closed.verdict !== 'red') {
|
|
1001
1106
|
// A closer that renders no judgment ('unparseable'/'crash') is a
|
|
1002
1107
|
// CASUALTY, never a red and never a strike (bareloop F17).
|
|
1003
|
-
recordAudit(
|
|
1108
|
+
recordAudit(rowOf({
|
|
1004
1109
|
step, attempt, verdict: 'close-casualty', gap: closed.red, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false, at: now(), tokens: result.tokens ?? null, tools: result.tools ?? null, ungranted: result.ungranted, refused: result.refused, thinking: result.thinking,
|
|
1005
1110
|
}), result.artifact);
|
|
1006
1111
|
return { ok: false, outcome: 'close-casualty', red: `close-casualty: step "${step.goal}" — ${closed.red} (${closed.verdict})` };
|
|
@@ -1010,7 +1115,7 @@ export async function runStepRalph({
|
|
|
1010
1115
|
const strike = seenGaps.has(normalised);
|
|
1011
1116
|
seenGaps.add(normalised);
|
|
1012
1117
|
if (strike) strikes += 1;
|
|
1013
|
-
recordAudit(
|
|
1118
|
+
recordAudit(rowOf({
|
|
1014
1119
|
step, attempt, verdict: 'red', gap: closed.red, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike, at: now(), tokens: result.tokens ?? null, tools: result.tools ?? null, ungranted: result.ungranted, refused: result.refused, thinking: result.thinking,
|
|
1015
1120
|
}), result.artifact);
|
|
1016
1121
|
|
|
@@ -1162,8 +1267,14 @@ export async function runFlow({
|
|
|
1162
1267
|
// M4d am25: the run keeps the job's "Thinking on" box as it is now (read by `readJobThinking` on every try and every resume)
|
|
1163
1268
|
writeRunThinking(flowDir, runDir);
|
|
1164
1269
|
if (runModel) writeRunModel(runDir, runModel); // M4d am33: the one record of the model this run started on
|
|
1270
|
+
// M8 item 6: the first run from a freshly signed flow takes the learnings its draft was handed (the Audit box); a run that kept its own plan already has its record; a failure never stops the run
|
|
1271
|
+
if (!runOwnsPlan(runDir)) {
|
|
1272
|
+
try { takeLearningsRecord(flowDir, runDir); } catch (/** @type {any} */ e) {
|
|
1273
|
+
try { appendRow(join(runDir, LEARN_ERROR_FILE), { at: now(), error: redactSecrets(`learnings record: ${e?.message ?? e}`).split('\n')[0] }); } catch { /* best-effort */ }
|
|
1274
|
+
}
|
|
1275
|
+
}
|
|
1165
1276
|
|
|
1166
|
-
const frozen = await freezeInputs(runDir, sources ?? [], { fetchPage });
|
|
1277
|
+
const frozen = await freezeInputs(runDir, sources ?? [], { fetchPage, tableRoles: sheetRolesOf(declaration.steps) });
|
|
1167
1278
|
if (!frozen.ok) {
|
|
1168
1279
|
return haltRun({
|
|
1169
1280
|
flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: frozen.red, spent: { value: 0 },
|
|
@@ -1264,6 +1375,9 @@ export async function runFlow({
|
|
|
1264
1375
|
attemptsLog,
|
|
1265
1376
|
firstStepGap: initialGap ?? null,
|
|
1266
1377
|
});
|
|
1378
|
+
recordRunNotes({
|
|
1379
|
+
flowName: name, runId, runDir, outcome: result.outcome, specHash: signature.flow, now,
|
|
1380
|
+
});
|
|
1267
1381
|
|
|
1268
1382
|
if (result.outcome === 'complete') return { ...result, auditRows };
|
|
1269
1383
|
return result;
|
|
@@ -1527,7 +1641,7 @@ async function runAskSlot({
|
|
|
1527
1641
|
}
|
|
1528
1642
|
// eslint-disable-next-line no-await-in-loop
|
|
1529
1643
|
const redoResult = await runStepRalph({
|
|
1530
|
-
step: priorStep, primitivesMap: primitives, readsMap: priorReadsResult.map, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, initialGap: reason, attemptOffset: lastTryNumber(runDir, priorStep.emits ?? priorStep.goal ?? null), thinkingBox: readJobThinking(flowDir, runDir), now, runDir,
|
|
1644
|
+
step: priorStep, primitivesMap: primitives, readsMap: priorReadsResult.map, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, 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,
|
|
1531
1645
|
readStop: () => stopPending(runDir), stepNo: priorStepNo, prevStepId: priorPrevStepId,
|
|
1532
1646
|
});
|
|
1533
1647
|
if (!redoResult.ok) {
|
|
@@ -1782,7 +1896,7 @@ async function foldFromStep({
|
|
|
1782
1896
|
// redo's `initialGap` above.
|
|
1783
1897
|
// eslint-disable-next-line no-await-in-loop
|
|
1784
1898
|
const stepResult = await runStepRalph({
|
|
1785
|
-
step, primitivesMap: primitives, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, initialGap: i === i0 ? firstStepGap : null, thinkingBox: readJobThinking(flowDir, runDir), now, runDir,
|
|
1899
|
+
step, primitivesMap: primitives, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, initialGap: i === i0 ? firstStepGap : null, thinkingBox: readJobThinking(flowDir, runDir), learnHints: stepHintsReader({ flowName, source: inputsManifest?.[0]?.source ?? null, now }), now, runDir,
|
|
1786
1900
|
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,
|
|
1787
1901
|
});
|
|
1788
1902
|
if (!stepResult.ok) {
|
|
@@ -2239,6 +2353,9 @@ export async function resumeRun({
|
|
|
2239
2353
|
appendHistory(flowDir, {
|
|
2240
2354
|
runId, at: now(), outcome: 'ask-expired', spentUsd: spent.value, spendComplete: spendComplete.value, capUsd: arbiter.capUsd ?? null, wallMs: getNowMs() - runStartedAt, signatureHash: state.signatureHash,
|
|
2241
2355
|
});
|
|
2356
|
+
recordRunNotes({
|
|
2357
|
+
flowName: name, runId, runDir, outcome: 'ask-expired', specHash: state.signatureHash, now,
|
|
2358
|
+
});
|
|
2242
2359
|
return { outcome: 'ask-expired', runDir, spentUsd: spent.value };
|
|
2243
2360
|
}
|
|
2244
2361
|
|
|
@@ -2272,6 +2389,10 @@ export async function resumeRun({
|
|
|
2272
2389
|
runId, at: now(), outcome: 'rerun', spentUsd: spent.value, spendComplete: spendComplete.value, capUsd: arbiter.capUsd ?? null, wallMs: getNowMs() - runStartedAt, signatureHash: state.signatureHash,
|
|
2273
2390
|
});
|
|
2274
2391
|
}
|
|
2392
|
+
// M8 am4: a rerun ends THIS run, so its notes count now (the new run, started below, makes its own).
|
|
2393
|
+
recordRunNotes({
|
|
2394
|
+
flowName: name, runId, runDir, outcome: 'rerun', specHash: state.signatureHash, now,
|
|
2395
|
+
});
|
|
2275
2396
|
|
|
2276
2397
|
// Deterministic derived id (M3 scope item 7) — refused by name, never
|
|
2277
2398
|
// silently renumbered, if it already exists.
|
|
@@ -2462,6 +2583,9 @@ export async function resumeRun({
|
|
|
2462
2583
|
recordAudit,
|
|
2463
2584
|
attemptsLog,
|
|
2464
2585
|
});
|
|
2586
|
+
recordRunNotes({
|
|
2587
|
+
flowName: name, runId, runDir, outcome: result.outcome, specHash: state.signatureHash, now,
|
|
2588
|
+
});
|
|
2465
2589
|
|
|
2466
2590
|
if (result.outcome === 'complete') return { ...result, auditRows };
|
|
2467
2591
|
return result;
|
|
@@ -2664,6 +2788,9 @@ export async function continueRun({
|
|
|
2664
2788
|
recordAudit,
|
|
2665
2789
|
attemptsLog,
|
|
2666
2790
|
});
|
|
2791
|
+
recordRunNotes({
|
|
2792
|
+
flowName: name, runId, runDir, outcome: result.outcome, specHash: halt.signatureHash, now,
|
|
2793
|
+
});
|
|
2667
2794
|
if (result.outcome === 'complete') return { ...result, auditRows };
|
|
2668
2795
|
return result;
|
|
2669
2796
|
} finally {
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// M10b piece 2: the ONE writer of `<run>/sheet-checks.json`, the record of what each sheet check said in this run, for the separate checker that re-runs a run's
|
|
2
|
+
// signed checks against its saved sheet (M10b "Done when"). Append-only: one entry per (job line, try), written the moment that try's check has run, never replaced.
|
|
3
|
+
// Shape: { lines: [ { n, try, passed, tables: [{name, tableSha}], checks: [the signed check objects], claims: <the step's answer>, results: [{id, text, ok, result}], red } ] }.
|
|
4
|
+
// `tables[].tableSha` is the one recorded at the run's start (inputs.json), the one the check used. Throws away: nothing the check saw; no cell text is kept here.
|
|
5
|
+
import { writeFileSync, renameSync } from 'node:fs';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
import { readFileInside } from './flow.js';
|
|
8
|
+
|
|
9
|
+
/** the record's name in the run's own folder */
|
|
10
|
+
export const SHEET_CHECKS_FILE = 'sheet-checks.json';
|
|
11
|
+
|
|
12
|
+
const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* @param {string} runDir @param {{n: number, try: number, checks: any[], closed: {verdict: string, red?: string|null, sheetRecord?: any}}} o
|
|
16
|
+
* @returns {void}
|
|
17
|
+
*/
|
|
18
|
+
export function writeSheetLine(runDir, { n, try: attempt, checks, closed }) {
|
|
19
|
+
const rec = closed.sheetRecord;
|
|
20
|
+
if (!rec) return;
|
|
21
|
+
/** @type {any[]} */
|
|
22
|
+
let lines = [];
|
|
23
|
+
const had = readFileInside(runDir, SHEET_CHECKS_FILE);
|
|
24
|
+
if (had.ok) {
|
|
25
|
+
try {
|
|
26
|
+
const parsed = JSON.parse(had.text);
|
|
27
|
+
if (isRec(parsed) && Array.isArray(parsed.lines)) lines = parsed.lines;
|
|
28
|
+
} catch { lines = []; }
|
|
29
|
+
}
|
|
30
|
+
if (lines.some((l) => isRec(l) && l.n === n && l.try === attempt)) return;
|
|
31
|
+
lines.push({
|
|
32
|
+
n, try: attempt, passed: closed.verdict === 'green',
|
|
33
|
+
tables: rec.inputs.map((/** @type {any} */ i) => ({ name: i.name, tableSha: i.sha256 })),
|
|
34
|
+
checks: JSON.parse(JSON.stringify(checks)),
|
|
35
|
+
claims: rec.claims,
|
|
36
|
+
results: rec.checks,
|
|
37
|
+
red: closed.verdict === 'green' ? null : (closed.red ?? null),
|
|
38
|
+
});
|
|
39
|
+
const file = join(runDir, SHEET_CHECKS_FILE);
|
|
40
|
+
const tmp = `${file}.tmp`;
|
|
41
|
+
writeFileSync(tmp, `${JSON.stringify({ lines }, null, 2)}\n`);
|
|
42
|
+
renameSync(tmp, file);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The reader of the record, for the Result tab and the separate checker: `{lines: [...]}`, or null when the file is missing or is not that shape (the page then
|
|
47
|
+
* shows no verdicts, never a half-read record). Read through the safe gateway.
|
|
48
|
+
* @param {string} runDir @returns {{lines: any[]}|null}
|
|
49
|
+
*/
|
|
50
|
+
export function readSheetChecks(runDir) {
|
|
51
|
+
const got = readFileInside(runDir, SHEET_CHECKS_FILE);
|
|
52
|
+
if (!got.ok) return null;
|
|
53
|
+
try {
|
|
54
|
+
const parsed = JSON.parse(got.text);
|
|
55
|
+
return isRec(parsed) && Array.isArray(parsed.lines) ? { lines: parsed.lines } : null;
|
|
56
|
+
} catch { return null; }
|
|
57
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
// M10b piece 4 (docs/wiki/the-module-ladder.md "M10b amendment 2", items 4 and 7): the ONE builder of what a job line that reads a sheet shows -
|
|
2
|
+
// { guardrails, checked: [{id, name, words, covers, text}], notChecked: [guardrail, ...] | 'none' }
|
|
3
|
+
// from the signed declaration (the step's `close.sheet`, each check's `covers` tag) and the job line's own `~` rules. After a run, `record` (the
|
|
4
|
+
// `sheet-checks.json` lines, src/sheet-record.js) adds to each check its verdict and what was found: `{ok, found}`. Every surface (the Chat plan card, the Job tab, the
|
|
5
|
+
// Result tab, the Audit's check rows) shows this block's strings; none of them words a check itself.
|
|
6
|
+
// Throws away: the check's id, claim, range and the other typed fields that do not change what it says (src/sheetchecks.js `sheetCheckSentence` drops them too).
|
|
7
|
+
// A green "found" is the step's OWN claimed value in plain words (a number, or a count of rows / days / bands / groups); a string claim (a looked-up cell) is never
|
|
8
|
+
// repeated, because it is cell text. A red "found" is bareguard's gap words (row numbers and counts), never a cell's text.
|
|
9
|
+
// Third outcomes, named: a line the run never reached (no record) carries no verdict; a check the record lacks carries none (the page shows no mark).
|
|
10
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
11
|
+
import { rubricVocabulary } from 'bareguard';
|
|
12
|
+
import { lineRules } from './pagebits.js';
|
|
13
|
+
import { sheetCheckSentence } from './sheetchecks.js';
|
|
14
|
+
import { isColumnChoiceRule } from './sheetoffer.js';
|
|
15
|
+
|
|
16
|
+
const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
17
|
+
|
|
18
|
+
/** the short plain name of each bareguard op (the ONE table; a test fails when bareguard gains an op this table does not name). `noDuplicates` and `noEmpty` add the column. */
|
|
19
|
+
export const SHEET_OP_NAMES = Object.freeze({
|
|
20
|
+
count: 'count', countEmpty: 'empty count', countIf: 'count', uniqueCount: 'unique count',
|
|
21
|
+
sum: 'sum', sumIf: 'sum', average: 'average', averageIf: 'average', median: 'median', min: 'min', max: 'max',
|
|
22
|
+
found: 'found', lookup: 'lookup', rows: 'rows', topN: 'top', duplicates: 'duplicates', groupTotals: 'group totals', percentOfTotal: 'percent of total',
|
|
23
|
+
band: 'bucket', daysBetween: 'days between', daysSince: 'date', earliest: 'earliest date', latest: 'latest date',
|
|
24
|
+
allNumbers: 'all numbers', allDates: 'all dates', noEmpty: 'no empty', noDuplicates: 'no duplicate', rowCount: 'row count', rowMath: 'row math',
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
/** the ops of bareguard that a name is needed for @returns {string[]} */
|
|
28
|
+
export function vocabularyOps() {
|
|
29
|
+
const V = /** @type {any} */ (rubricVocabulary);
|
|
30
|
+
return [...new Set(['cells', 'table'].flatMap((r) => Object.keys(V.rules[r].ops)))];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** @param {any} check a bareguard cells / table check @returns {string} the short name: `rows`, `count`, `sum`, `no duplicate Invoice #` ... */
|
|
34
|
+
export function sheetCheckName(check) {
|
|
35
|
+
if (!isRec(check)) return 'a check';
|
|
36
|
+
const base = Object.hasOwn(SHEET_OP_NAMES, check.op) ? /** @type {Record<string, string>} */ (SHEET_OP_NAMES)[check.op] : String(check.op);
|
|
37
|
+
return (check.op === 'noDuplicates' || check.op === 'noEmpty') && typeof check.column === 'string' ? `${base} ${check.column}` : base;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* What the step claimed for one check, in plain words (a green check's "found"). Null when the claim has nothing to say (a `table` check, a missing box, a string).
|
|
42
|
+
* @param {any} check @param {unknown} claims the step's answer @returns {string|null}
|
|
43
|
+
*/
|
|
44
|
+
export function sheetFoundWords(check, claims) {
|
|
45
|
+
if (!isRec(check) || typeof check.claim !== 'string' || !isRec(claims) || !isRec(/** @type {any} */ (claims)[check.claim])) return null;
|
|
46
|
+
const box = /** @type {Record<string, any>} */ (/** @type {any} */ (claims)[check.claim]);
|
|
47
|
+
const plural = (/** @type {number} */ n, /** @type {string} */ one, /** @type {string} */ many) => `${n} ${n === 1 ? one : many}`;
|
|
48
|
+
if (typeof box.value === 'number' || typeof box.value === 'boolean') return typeof box.value === 'boolean' ? (box.value ? 'yes' : 'no') : String(box.value);
|
|
49
|
+
if (Array.isArray(box.rows)) return plural(box.rows.length, 'row', 'rows');
|
|
50
|
+
if (Array.isArray(box.keys)) return plural(box.keys.length, 'row', 'rows');
|
|
51
|
+
if (Array.isArray(box.values)) return plural(box.values.length, 'value', 'values');
|
|
52
|
+
if (Array.isArray(box.totals)) return plural(box.totals.length, 'group', 'groups');
|
|
53
|
+
if (isRec(box.days)) return plural(Object.keys(box.days).length, 'row', 'rows');
|
|
54
|
+
if (isRec(box.bands)) return plural(Object.keys(box.bands).length, 'row', 'rows');
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** @param {any} l a job line `{rules?, guardrail?, rule?}` @returns {string[]} its `~` rules, numbered from 1 by position */
|
|
59
|
+
export const rulesOfLine = (l) => lineRules({ ...(Array.isArray(l?.rules) ? { rules: l.rules } : {}), rule: l?.guardrail ?? l?.rule });
|
|
60
|
+
|
|
61
|
+
/** the "covers ..." words of one check @param {string[]} rules @returns {string} "" when it covers none */
|
|
62
|
+
export const coversWords = (rules) => rules.map((r) => `covers "${r}"`).join(' · ');
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* The block of every job line whose step reads a sheet. A line qualifies when its green step carries `close.sheet`, or (with `csvRoles`) reads a CSV input and carries no
|
|
66
|
+
* older `close.columns` / `close.cited` check (then every guardrail is Not checked).
|
|
67
|
+
* @param {{declaration: any, lines: Array<{n: number, rules?: string[], guardrail?: string, rule?: string}>, csvRoles?: string[], record?: any}} o
|
|
68
|
+
* `record` = the parsed `sheet-checks.json` (`{lines: [...]}`), only after a run
|
|
69
|
+
* @returns {Array<{line: number, guardrails: string[], checked: Array<{id: string, name: string, words: string, covers: string[], coversWords: string, text: string, ok?: boolean, found?: string}>, notChecked: string[]|'none'}>}
|
|
70
|
+
*/
|
|
71
|
+
export function sheetLineBlocks({ declaration, lines, csvRoles = [], record }) {
|
|
72
|
+
const out = [];
|
|
73
|
+
if (!isRec(declaration) || !Array.isArray(declaration.steps)) return out;
|
|
74
|
+
const seen = new Set();
|
|
75
|
+
for (const st of declaration.steps) {
|
|
76
|
+
if (!isRec(st) || !isRec(st.close) || st.close.class !== 'green' || !Number.isInteger(st.fromLine) || seen.has(st.fromLine)) continue;
|
|
77
|
+
const hasSheet = Array.isArray(st.close.sheet) && st.close.sheet.length > 0;
|
|
78
|
+
const readsCsv = Array.isArray(st.reads) && st.reads.some((/** @type {string} */ r) => csvRoles.includes(r));
|
|
79
|
+
if (!hasSheet && (!readsCsv || st.close.columns !== undefined || st.close.cited !== undefined)) continue;
|
|
80
|
+
seen.add(st.fromLine);
|
|
81
|
+
const guardrails = rulesOfLine((Array.isArray(lines) ? lines : []).find((l) => l.n === st.fromLine));
|
|
82
|
+
const covered = new Set();
|
|
83
|
+
const tried = Array.isArray(record?.lines) ? record.lines.filter((/** @type {any} */ l) => isRec(l) && l.n === st.fromLine && Number.isInteger(l.try)) : [];
|
|
84
|
+
const newest = tried.reduce((/** @type {any} */ m, /** @type {any} */ l) => (m === null || l.try >= m.try ? l : m), null);
|
|
85
|
+
const checked = (hasSheet ? st.close.sheet : []).map((/** @type {any} */ c) => {
|
|
86
|
+
const nums = Array.isArray(c.covers) ? c.covers.filter((/** @type {unknown} */ x) => Number.isInteger(x) && /** @type {number} */ (x) >= 1 && /** @type {number} */ (x) <= guardrails.length) : [];
|
|
87
|
+
for (const x of nums) covered.add(x);
|
|
88
|
+
const rules = [...new Set(nums)].sort((a, b) => a - b).map((x) => guardrails[x - 1]);
|
|
89
|
+
const name = sheetCheckName(c);
|
|
90
|
+
const words = sheetCheckSentence(c);
|
|
91
|
+
const cw = coversWords(rules);
|
|
92
|
+
/** @type {any} */
|
|
93
|
+
const e = { id: typeof c.id === 'string' ? c.id : '', name, words, covers: rules, coversWords: cw, text: [name, ...(words === name ? [] : [words]), ...(cw ? [cw] : [])].join(' — ') };
|
|
94
|
+
const res = newest && Array.isArray(newest.results) ? newest.results.find((/** @type {any} */ r) => isRec(r) && r.id === c.id) : undefined;
|
|
95
|
+
if (isRec(res) && typeof res.ok === 'boolean') {
|
|
96
|
+
e.ok = res.ok;
|
|
97
|
+
if (res.ok) {
|
|
98
|
+
const f = sheetFoundWords(c, newest.claims);
|
|
99
|
+
e.found = f === null ? `${name} checked` : `${name} checked — ${f}`;
|
|
100
|
+
} else {
|
|
101
|
+
const gap = typeof res.result === 'string' ? res.result.split('\n').map((/** @type {string} */ x) => x.trim().replace(`${e.id}: `, '')).filter(Boolean).join('; ') : '';
|
|
102
|
+
e.found = `${name} — ${gap || 'did not pass'}`;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return e;
|
|
106
|
+
});
|
|
107
|
+
const notChecked = guardrails.filter((r, i) => !isColumnChoiceRule(r) && !covered.has(i + 1));
|
|
108
|
+
out.push({ line: st.fromLine, guardrails, checked, notChecked: notChecked.length === 0 ? /** @type {'none'} */ ('none') : notChecked });
|
|
109
|
+
}
|
|
110
|
+
return out;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* The guardrail rules of a sheet step that no check covers, as the drafter's Not-checked lines (`line N: "rule" - no sheet check covers it`): the block's own
|
|
115
|
+
* `notChecked`, one list for the plan card and the drafter's saved record.
|
|
116
|
+
* @param {any} declaration @param {Array<{n: number, rules?: string[], guardrail?: string, rule?: string}>} lines @param {string[]} csvRoles @returns {string[]}
|
|
117
|
+
*/
|
|
118
|
+
export function uncoveredRules(declaration, lines, csvRoles) {
|
|
119
|
+
if (csvRoles.length === 0) return [];
|
|
120
|
+
return sheetLineBlocks({ declaration, lines, csvRoles }).flatMap((b) => (b.notChecked === 'none' ? [] : b.notChecked.map((r) => `line ${b.line}: "${r}" \u2014 no sheet check covers it`)));
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** @param {any} arbiter @returns {string[]} the roles of the signed sources that are a CSV file (the sheets a check reads) */
|
|
124
|
+
export function csvRolesOf(arbiter) {
|
|
125
|
+
return (Array.isArray(arbiter?.sources) ? arbiter.sources : [])
|
|
126
|
+
.filter((/** @type {any} */ s) => isRec(s) && s.kind !== 'page' && typeof s.path === 'string' && s.path.toLowerCase().endsWith('.csv') && typeof s.role === 'string')
|
|
127
|
+
.map((/** @type {any} */ s) => s.role);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** one value of a claim in the words of a line: text as it is, anything else as JSON */
|
|
131
|
+
const claimShow = (/** @type {unknown} */ v) => (typeof v === 'string' ? v : JSON.stringify(v));
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* M10b am4: the step's answer (its claim boxes) value by value, one line each: `invoiceCount: 8`, `daysPastDue: row 2 -> 124`. A list is one line per entry (a list of row
|
|
135
|
+
* numbers reads `row N`); a map is one line per key (`row <key> -> <value>`). An empty list or map reads `<name>: none`, never no line.
|
|
136
|
+
* Throws away: nothing but the box's own key (`value`, `rows`, `days`...), which the line's words already say.
|
|
137
|
+
* @param {unknown} claims the step's answer @returns {string[]}
|
|
138
|
+
*/
|
|
139
|
+
export function claimLines(claims) {
|
|
140
|
+
const out = [];
|
|
141
|
+
if (!isRec(claims)) return out;
|
|
142
|
+
for (const [name, box] of Object.entries(/** @type {Record<string, any>} */ (claims))) {
|
|
143
|
+
if (!isRec(box)) { out.push(`${name}: ${claimShow(box)}`); continue; }
|
|
144
|
+
for (const [key, v] of Object.entries(box)) {
|
|
145
|
+
if (Array.isArray(v)) {
|
|
146
|
+
if (v.length === 0) out.push(`${name}: none`);
|
|
147
|
+
for (const e of v) out.push(`${name}: ${key === 'rows' || key === 'keys' ? 'row ' : ''}${claimShow(e)}`);
|
|
148
|
+
} else if (isRec(v)) {
|
|
149
|
+
if (Object.keys(v).length === 0) out.push(`${name}: none`);
|
|
150
|
+
for (const [k, e] of Object.entries(v)) out.push(`${name}: row ${k} \u2192 ${claimShow(e)}`);
|
|
151
|
+
} else out.push(`${name}: ${claimShow(v)}`);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return out;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* M10b am4: what an ask card shows for the claim boxes it was given. The step is the sheet step whose saved try (`sheet-checks.json`) holds exactly these claims; its block is
|
|
159
|
+
* the Result tab's own (`sheetLineBlocks`, that try's verdicts), and `answer` is the claims value by value. Null when no saved try matches: the caller then keeps the old line.
|
|
160
|
+
* @param {{claims: unknown, declaration: any, lines: Array<{n: number, rules?: string[], guardrail?: string, rule?: string}>, csvRoles?: string[], record?: any}} o
|
|
161
|
+
* @returns {{block: ReturnType<typeof sheetLineBlocks>[number], answer: string[]}|null}
|
|
162
|
+
*/
|
|
163
|
+
export function askSheetCard({ claims, declaration, lines, csvRoles = [], record }) {
|
|
164
|
+
if (!isRec(claims) || !Array.isArray(record?.lines)) return null;
|
|
165
|
+
const same = record.lines.filter((/** @type {any} */ l) => isRec(l) && Number.isInteger(l.try) && Number.isInteger(l.n) && isDeepStrictEqual(l.claims, claims));
|
|
166
|
+
const newest = same.reduce((/** @type {any} */ m, /** @type {any} */ l) => (m === null || l.try >= m.try ? l : m), null);
|
|
167
|
+
if (newest === null) return null;
|
|
168
|
+
const block = sheetLineBlocks({ declaration, lines, csvRoles, record: { lines: [newest] } }).find((b) => b.line === newest.n);
|
|
169
|
+
return block ? { block, answer: claimLines(claims) } : null;
|
|
170
|
+
}
|