fwdloop 0.20.0 → 0.22.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 +2 -0
- package/bin/fwdloop +85 -34
- package/package.json +4 -3
- package/src/audit-fold.js +181 -0
- package/src/authoring.js +33 -7
- package/src/books.js +1 -1
- package/src/checked.js +18 -1
- package/src/cited-record.js +138 -0
- package/src/cited-source.js +49 -0
- package/src/citedcheck.js +306 -0
- package/src/citedwords.js +197 -0
- package/src/closers.js +105 -9
- package/src/ctx-tools.js +2 -14
- package/src/declaration.js +85 -5
- package/src/diary.js +49 -0
- package/src/docx.js +16 -2
- package/src/draft-steps.js +1 -1
- package/src/drafter.js +292 -25
- package/src/flow.js +33 -7
- package/src/flowmodel.js +63 -5
- package/src/input-facts.js +20 -3
- package/src/model-step.js +132 -9
- package/src/pageask.js +136 -0
- package/src/pagebits.js +107 -0
- package/src/pagedropwords.js +171 -0
- package/src/pagedry.js +120 -0
- package/src/pagefetch.js +164 -0
- package/src/pagelook.js +155 -0
- package/src/pagemap.js +55 -0
- package/src/pageplace.js +103 -0
- package/src/pagerules.js +318 -0
- package/src/panel/author.js +41 -20
- package/src/panel/authorcard.js +11 -1
- package/src/panel/authorflows.js +21 -15
- package/src/panel/authorstart.js +2 -4
- package/src/panel/authortrigger.js +14 -4
- package/src/panel/data.js +130 -10
- package/src/panel/index.html +499 -41
- package/src/panel/result.js +295 -0
- package/src/panel/server.js +27 -3
- package/src/primitives.js +43 -2
- package/src/provider.js +5 -2
- package/src/redact.js +17 -0
- package/src/runner.js +128 -21
- package/src/schedule.js +3 -3
- package/src/setup.js +16 -1
- package/src/sheetfind.js +50 -0
- package/src/sheetlook.js +157 -0
- package/src/signed-text.js +11 -1
- package/src/thinking.js +39 -0
- package/src/try-checks.js +68 -0
- package/src/types.js +4 -2
- package/types/audit-fold.d.ts +54 -0
- package/types/authoring.d.ts +20 -2
- package/types/books.d.ts +17 -0
- package/types/checked.d.ts +10 -0
- package/types/cited-record.d.ts +21 -0
- package/types/cited-source.d.ts +18 -0
- package/types/citedcheck.d.ts +95 -0
- package/types/citedwords.d.ts +97 -0
- package/types/closers.d.ts +55 -3
- package/types/declaration.d.ts +15 -1
- package/types/diary.d.ts +57 -0
- package/types/docx.d.ts +14 -0
- package/types/drafter.d.ts +244 -2
- package/types/flow.d.ts +21 -0
- package/types/flowmodel.d.ts +40 -3
- package/types/input-facts.d.ts +12 -2
- package/types/model-step.d.ts +38 -3
- package/types/pageask.d.ts +75 -0
- package/types/pagebits.d.ts +32 -0
- package/types/pagedropwords.d.ts +40 -0
- package/types/pagedry.d.ts +38 -0
- package/types/pagefetch.d.ts +86 -0
- package/types/pagelook.d.ts +75 -0
- package/types/pagemap.d.ts +31 -0
- package/types/pageplace.d.ts +22 -0
- package/types/pagerules.d.ts +86 -0
- package/types/panel/authorcard.d.ts +2 -0
- package/types/panel/authorflows.d.ts +2 -0
- package/types/panel/data.d.ts +26 -0
- package/types/panel/result.d.ts +156 -0
- package/types/provider.d.ts +3 -1
- package/types/redact.d.ts +1 -0
- package/types/runner.d.ts +156 -7
- package/types/schedule.d.ts +0 -11
- package/types/setup.d.ts +13 -0
- package/types/sheetfind.d.ts +46 -0
- package/types/sheetlook.d.ts +120 -0
- package/types/thinking.d.ts +31 -0
- package/types/try-checks.d.ts +55 -0
- package/types/types.d.ts +20 -3
package/src/runner.js
CHANGED
|
@@ -58,10 +58,19 @@ import {
|
|
|
58
58
|
} from './canrun.js'; // M4e am7 item 7: the ONE decider (F46 refusal lives there)
|
|
59
59
|
import { configHome, configDoorHome } from './config.js';
|
|
60
60
|
import { closeByClass, isCellsPath } from './closers.js';
|
|
61
|
+
import { readRunSource } from './cited-source.js';
|
|
62
|
+
import { citedLineOf, writeCitedLine } from './cited-record.js';
|
|
61
63
|
import {
|
|
62
64
|
appendAudit, appendHistory, readAudit, readHistory, endRow, HALT_OUTCOMES,
|
|
63
65
|
} from './books.js';
|
|
64
66
|
import { applyRunValues, pickRunValues } from './runvalues.js';
|
|
67
|
+
import { stepThinkingMode } from './thinking.js';
|
|
68
|
+
import { appendChecks, nextRound } from './diary.js';
|
|
69
|
+
import {
|
|
70
|
+
doneRecord, happenedRecord, outputRecord, closeRecords,
|
|
71
|
+
} from './try-checks.js';
|
|
72
|
+
import { readJobThinking, writeRunThinking, writeRunModel } from './flowmodel.js';
|
|
73
|
+
import { fetchPageText, isWebUrl } from './pagefetch.js';
|
|
65
74
|
import {
|
|
66
75
|
readResumeLock, recordPid, writeLockHolder, procStartOf, LOCK_NO_HOLDER,
|
|
67
76
|
} from './liveness.js';
|
|
@@ -384,14 +393,38 @@ export function checkFreshRunDir(runDir) {
|
|
|
384
393
|
return { ok: true };
|
|
385
394
|
}
|
|
386
395
|
|
|
396
|
+
/** M10 item 1: fetch a web page and freeze its text as `<dir>/<id>.txt`; the sha256 is of the FROZEN bytes, like a file input. The ONE writer of a
|
|
397
|
+
* page's frozen copy: drafting calls it with its draft folder, a run start (via `freezeInputs`) with the run's `inputs/`, so the two are
|
|
398
|
+
* separate files and a run is only ever checked against its own. The fetch is tried once; a refusal names the input and says why in plain words.
|
|
399
|
+
* @param {string} dir @param {string} id @param {string} url
|
|
400
|
+
* @param {{fetchPage?: (url: string) => Promise<{ok: true, text: string, url: string}|{ok: false, error: string}>}} [o]
|
|
401
|
+
* @returns {Promise<{ok: true, text: string, entry: {id: string, source: string, frozen: string, sha256: string, bytes: number}}|{ok: false, red: string}>} `text` = the frozen text itself, for the caller that reads it (drafting) */
|
|
402
|
+
export async function freezePage(dir, id, url, { fetchPage = fetchPageText } = {}) {
|
|
403
|
+
const got = await fetchPage(url);
|
|
404
|
+
if (!got.ok) return { ok: false, red: `freeze: input "${id}": ${got.error}` };
|
|
405
|
+
mkdirSync(dir, { recursive: true });
|
|
406
|
+
const frozen = join(dir, `${id}.txt`);
|
|
407
|
+
writeFileSync(frozen, got.text, 'utf8');
|
|
408
|
+
return { ok: true, text: got.text, entry: { id, source: url, frozen, sha256: hashFile(frozen), bytes: statSync(frozen).size } };
|
|
409
|
+
}
|
|
410
|
+
|
|
387
411
|
/** Copy each named source into `<runDir>/inputs/`, hash the FROZEN copy
|
|
388
412
|
* (never the original again after this), write `inputs.json`. An
|
|
389
|
-
* unreadable source refuses by name.
|
|
390
|
-
|
|
413
|
+
* unreadable source refuses by name. A source that is a web address
|
|
414
|
+
* (M10 item 1) is fetched and frozen by `freezePage`, in the same manifest.
|
|
415
|
+
* @param {string} runDir @param {Array<{id: string, path: string}>} sources
|
|
416
|
+
* @param {{fetchPage?: (url: string) => Promise<{ok: true, text: string, url: string}|{ok: false, error: string}>}} [o] */
|
|
417
|
+
export async function freezeInputs(runDir, sources, { fetchPage } = {}) {
|
|
391
418
|
const inputsDir = join(runDir, 'inputs');
|
|
392
419
|
mkdirSync(inputsDir, { recursive: true });
|
|
393
420
|
const manifest = [];
|
|
394
421
|
for (const { id, path: sourcePath } of sources ?? []) {
|
|
422
|
+
if (isWebUrl(sourcePath)) {
|
|
423
|
+
const page = await freezePage(inputsDir, id, sourcePath, { fetchPage });
|
|
424
|
+
if (!page.ok) return page;
|
|
425
|
+
manifest.push(page.entry);
|
|
426
|
+
continue;
|
|
427
|
+
}
|
|
395
428
|
if (!existsSync(sourcePath)) {
|
|
396
429
|
return { ok: false, red: `freeze: input "${id}" is unreadable at ${sourcePath}` };
|
|
397
430
|
}
|
|
@@ -563,7 +596,7 @@ export function readArtifact(runDir, id) {
|
|
|
563
596
|
* indistinguishable from "not written yet") into a step.
|
|
564
597
|
* @returns {{ok:true, map:Record<string,any>} | {ok:false, red:string}}
|
|
565
598
|
*/
|
|
566
|
-
function readArtifactsMapChecked(runDir, ids) {
|
|
599
|
+
export function readArtifactsMapChecked(runDir, ids, { docxRoles = /** @type {string[]} */ ([]) } = {}) {
|
|
567
600
|
const map = {};
|
|
568
601
|
for (const id of ids ?? []) {
|
|
569
602
|
const result = readArtifactResult(runDir, id);
|
|
@@ -575,12 +608,21 @@ function readArtifactsMapChecked(runDir, ids) {
|
|
|
575
608
|
const input = readInputCells(runDir, id);
|
|
576
609
|
if (!input.ok && !input.missing) return { ok: false, red: `input "${id}" — ${input.red}` };
|
|
577
610
|
if (input.ok) { map[id] = input.value; continue; }
|
|
611
|
+
// M10 am7 item 3: an id that names a saved web page (or a text file) is read as its text, from the RUN'S OWN frozen copy, sha-checked, through the one safe
|
|
612
|
+
// read gateway (`readFileInside`, in `readRunSource`). By role, text only: a copy that is missing or changed refuses the step; an id that is no text input
|
|
613
|
+
// of this run is left as it was (undefined).
|
|
614
|
+
const page = readRunSource(runDir, id, { docx: docxRoles.includes(id) });
|
|
615
|
+
if (page.ok) { map[id] = { kind: 'text', text: page.text }; continue; }
|
|
616
|
+
if (page.code === 'unreadable') return { ok: false, red: page.red };
|
|
578
617
|
}
|
|
579
618
|
map[id] = result.ok ? result.value : undefined;
|
|
580
619
|
}
|
|
581
620
|
return { ok: true, map };
|
|
582
621
|
}
|
|
583
622
|
|
|
623
|
+
/** M10 piece 5 (item 2): the role a green step quotes from - the one input whose .docx text its check (and so the step itself) may be handed. @param {any} step @returns {string[]} */
|
|
624
|
+
const citedRolesOf = (step) => (step?.close?.class === 'green' && typeof step.close.cited?.source === 'string' ? [step.close.cited.source] : []);
|
|
625
|
+
|
|
584
626
|
/** A frozen CSV input as `{kind:'cells', header, rows}` (the shape `addressCells` gives), checked against the sha256 recorded at freeze.
|
|
585
627
|
* Same three outcomes as `readArtifactResult`: not an input of this run (`missing`), refused (`red`), or the cells. */
|
|
586
628
|
function readInputCells(runDir, id) {
|
|
@@ -667,6 +709,7 @@ function sumKnownUsd(...values) {
|
|
|
667
709
|
// unchanged.
|
|
668
710
|
function makeAuditRow({
|
|
669
711
|
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
|
+
thinking = /** @type {{asked:string, status:string|null}|undefined} */ (undefined),
|
|
670
713
|
}) {
|
|
671
714
|
const row = {
|
|
672
715
|
step: step?.emits ?? step?.goal ?? null,
|
|
@@ -686,6 +729,8 @@ function makeAuditRow({
|
|
|
686
729
|
refused,
|
|
687
730
|
};
|
|
688
731
|
if (ungranted !== undefined && ungranted.length > 0) row.ungranted = ungranted;
|
|
732
|
+
// 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
|
+
if (thinking !== undefined) row.thinking = thinking;
|
|
689
734
|
return row;
|
|
690
735
|
}
|
|
691
736
|
|
|
@@ -708,16 +753,20 @@ function makeAuditRow({
|
|
|
708
753
|
* @param {(row: any, modelOutput?: any) => void} opts.recordAudit
|
|
709
754
|
* @param {string|null} [opts.initialGap]
|
|
710
755
|
* @param {number} [opts.attemptOffset]
|
|
756
|
+
* @param {boolean} [opts.thinkingBox] - M4d am25: the job's "Thinking on" box as this run's copy keeps it (default off)
|
|
711
757
|
* @param {() => string} [opts.now] - M4a-2: stamps each audit row's `at`;
|
|
712
758
|
* defaults to the real wall clock.
|
|
713
759
|
* @param {(() => boolean)|null} [opts.readStop] - amendment 7 item 8: the run's stop reader, asked before every try and (via modelStep's seam) every model call
|
|
714
760
|
* @param {number} [opts.stepNo] - this step's 1-based number, for the words of a stop row
|
|
715
761
|
* @param {string|null} [opts.prevStepId] - the id of step stepNo-1 (null for step 1): the step a "stopped after step N-1" row is filed under
|
|
716
762
|
* @param {number} [opts.triesDone] - tries a Stop already closed on this step (they count against its limit)
|
|
763
|
+
* @param {string|null} [opts.runDir] - M4d am29 item 2: the run's folder, where each try saves its checks
|
|
717
764
|
* @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}}>}
|
|
718
765
|
*/
|
|
719
|
-
async function runStepRalph({
|
|
766
|
+
export async function runStepRalph({
|
|
720
767
|
step, primitivesMap, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd, recordAudit, initialGap = null, attemptOffset = 0,
|
|
768
|
+
// 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
|
+
thinkingBox = false,
|
|
721
770
|
// M4a-2: the run's own injected clock (never the bare wall clock) —
|
|
722
771
|
// stamps every audit row's `at` with this attempt's finish time. Defaults
|
|
723
772
|
// to the real wall clock so a caller that doesn't inject one (there are
|
|
@@ -729,6 +778,8 @@ async function runStepRalph({
|
|
|
729
778
|
// cut this step short of (their numbering is in `attemptOffset`; a try the Stop cut mid-way is replaced by the new one, never counted
|
|
730
779
|
// against the limit, so Resume always gets at least one new try).
|
|
731
780
|
readStop = null, stepNo = 0, triesDone = 0,
|
|
781
|
+
// M4d am29 item 2: the run's folder, where each try saves its checks (`checks.jsonl`, src/diary.js)
|
|
782
|
+
runDir = null,
|
|
732
783
|
// the id of step stepNo-1 (null for step 1): a Stop before this step's first call words itself "after step N-1" and is filed under that step
|
|
733
784
|
prevStepId = null,
|
|
734
785
|
}) {
|
|
@@ -782,7 +833,10 @@ async function runStepRalph({
|
|
|
782
833
|
// schema without the executor context ever needing to carry one (M2
|
|
783
834
|
// scope item 3's own invariant: the schema is class-only, and the
|
|
784
835
|
// construction test below proves the context itself stays clean).
|
|
785
|
-
|
|
836
|
+
// M4d am25: `thinkingMode` is the ONE decision of what this try asks of thinking (`stepThinkingMode`); the model step only passes it on.
|
|
837
|
+
// 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
|
+
// 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 }) });
|
|
786
840
|
|
|
787
841
|
const stopSeam = readStop ? Object.freeze({ stopRequested: readStop }) : undefined;
|
|
788
842
|
|
|
@@ -827,7 +881,7 @@ async function runStepRalph({
|
|
|
827
881
|
const usd = sumKnownUsd(attemptFloorUsd, result.costUsd);
|
|
828
882
|
const ranCalls = (turns ?? 0) > 0 || attemptFloorUsd !== null;
|
|
829
883
|
return stopped(stopWords(ranCalls ? attempt : attempt - 1, turns ?? 0), makeAuditRow({
|
|
830
|
-
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,
|
|
884
|
+
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,
|
|
831
885
|
}));
|
|
832
886
|
}
|
|
833
887
|
|
|
@@ -838,7 +892,7 @@ async function runStepRalph({
|
|
|
838
892
|
// null second cost never zeroes out a known first floor.
|
|
839
893
|
const usd = sumKnownUsd(attemptFloorUsd, result.costUsd);
|
|
840
894
|
recordAudit(makeAuditRow({
|
|
841
|
-
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,
|
|
895
|
+
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,
|
|
842
896
|
}), result.red ?? 'transport fault twice');
|
|
843
897
|
return { ok: false, outcome: 'provider-red', red: `provider-red: step "${step.goal}" attempt ${attempt}: ${result.red ?? 'transport fault twice'}` };
|
|
844
898
|
}
|
|
@@ -849,13 +903,16 @@ async function runStepRalph({
|
|
|
849
903
|
// step's own failure to produce, not a system halt), strike-eligible
|
|
850
904
|
// like any other close red.
|
|
851
905
|
const red = result?.red ?? 'model step failed with no artifact';
|
|
906
|
+
// The try may have cost money (a length stop: "truncated: N tokens, no tool call"). Its row carries that cost below, so the run's spend
|
|
907
|
+
// - the cap check, the history total - takes it here, the same one add as the stop and transport branches (books must balance).
|
|
908
|
+
if (typeof result?.costUsd === 'number') spent.value += result.costUsd;
|
|
852
909
|
const normalised = normaliseGap(red);
|
|
853
910
|
const strike = seenGaps.has(normalised);
|
|
854
911
|
seenGaps.add(normalised);
|
|
855
912
|
if (strike) strikes += 1;
|
|
856
913
|
const usd = sumKnownUsd(attemptFloorUsd, result?.costUsd);
|
|
857
914
|
recordAudit(makeAuditRow({
|
|
858
|
-
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,
|
|
915
|
+
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,
|
|
859
916
|
}), red);
|
|
860
917
|
if (n === maxN) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: step "${step.goal}" — ${red}` };
|
|
861
918
|
if (strikes >= STRIKE_LIMIT) return { ok: false, outcome: 'struck-out', red: `struck-out: step "${step.goal}" — ${red}` };
|
|
@@ -866,35 +923,50 @@ async function runStepRalph({
|
|
|
866
923
|
|
|
867
924
|
if (result.costUsd === null || result.costUsd === undefined) {
|
|
868
925
|
recordAudit(makeAuditRow({
|
|
869
|
-
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,
|
|
926
|
+
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,
|
|
870
927
|
}), result.artifact ?? null);
|
|
871
928
|
return { ok: false, outcome: 'pricing-red', red: `pricing-red: step "${step.goal}" attempt ${attempt} returned no cost (never "?? 0")` };
|
|
872
929
|
}
|
|
873
930
|
spent.value += result.costUsd;
|
|
874
931
|
const attemptUsd = sumKnownUsd(attemptFloorUsd, result.costUsd);
|
|
875
932
|
|
|
933
|
+
// M4d am29 item 2: this try's checks, in the order they run; `saveTry` writes them (and the output they judged) once, just before the try's audit row
|
|
934
|
+
const tryChecks = /** @type {any[]} */ ([]);
|
|
935
|
+
let judged = null;
|
|
936
|
+
const saveTry = () => {
|
|
937
|
+
if (runDir === null) return;
|
|
938
|
+
appendChecks(runDir, {
|
|
939
|
+
step: step?.emits ?? step?.goal ?? null, try: attempt, at: now(), lastRound: nextRound(runDir, step?.emits ?? step?.goal ?? null) - 1, checks: [...tryChecks].sort((a, b) => a.n - b.n), output: judged,
|
|
940
|
+
});
|
|
941
|
+
};
|
|
942
|
+
|
|
876
943
|
// The model's own word, taken at face value — before the happened check,
|
|
877
944
|
// before any close, no exception (M2 amendment 1 item 1). A halt, not a
|
|
878
945
|
// strike, not a retry: `recordAudit`'s modelOutput arg keeps the RAW
|
|
879
946
|
// `result.artifact` (done/blocker included) for log.json; everything
|
|
880
947
|
// downstream of a `done: true` gets the STRIPPED artifact.
|
|
881
948
|
const doneCheck = checkDoneBlocker(step, result.artifact);
|
|
949
|
+
tryChecks.push(doneRecord(doneCheck, result.artifact));
|
|
882
950
|
if (doneCheck.verdict === 'not-done') {
|
|
951
|
+
saveTry();
|
|
883
952
|
recordAudit(makeAuditRow({
|
|
884
|
-
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,
|
|
953
|
+
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,
|
|
885
954
|
}), result.artifact ?? null);
|
|
886
955
|
return { ok: false, outcome: 'not-done', red: doneCheck.red };
|
|
887
956
|
}
|
|
888
957
|
const artifact = stripDoneBlocker(result.artifact);
|
|
889
958
|
|
|
890
959
|
const happened = checkArtifactHappened(step, artifact);
|
|
960
|
+
tryChecks.push(happenedRecord(happened, artifact));
|
|
961
|
+
judged = outputRecord(step, artifact);
|
|
891
962
|
if (happened.verdict === 'red') {
|
|
963
|
+
saveTry();
|
|
892
964
|
// Item 5: "or wrote no artifact" strikes unconditionally, every time
|
|
893
965
|
// (never gated by novelty — an empty artifact is always the same
|
|
894
966
|
// failure) — matches poc/m2/gapback.mjs's own rule exactly.
|
|
895
967
|
strikes += 1;
|
|
896
968
|
recordAudit(makeAuditRow({
|
|
897
|
-
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,
|
|
969
|
+
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,
|
|
898
970
|
}), result.artifact ?? null);
|
|
899
971
|
if (n === maxN) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: ${happened.red}` };
|
|
900
972
|
if (strikes >= STRIKE_LIMIT) return { ok: false, outcome: 'struck-out', red: `struck-out: ${happened.red}` };
|
|
@@ -903,11 +975,22 @@ async function runStepRalph({
|
|
|
903
975
|
continue;
|
|
904
976
|
}
|
|
905
977
|
|
|
906
|
-
|
|
978
|
+
// M10 piece 4: a step that cites quotes reads the run's OWN frozen copy of its source (never the drafting copy); the record of what the check said is
|
|
979
|
+
// written by the one writer, `writeCitedLine`, whatever the verdict - the Result tab says why a line did not pass.
|
|
980
|
+
const citedPart = step?.close?.class === 'green' ? step?.close?.cited : undefined;
|
|
981
|
+
const source = citedPart && runDir !== null ? readRunSource(runDir, citedPart.source, { docx: true }) : undefined;
|
|
982
|
+
const closed = await closeByClass(step, artifact, { reads: readsMap, businessDate, source });
|
|
983
|
+
if (citedPart && runDir !== null && closed.cited) {
|
|
984
|
+
writeCitedLine(runDir, citedLineOf({
|
|
985
|
+
n: step.fromLine, part: closed.cited.part, results: closed.cited.results, check: closed.cited.check,
|
|
986
|
+
}));
|
|
987
|
+
}
|
|
988
|
+
tryChecks.push(...closeRecords(step, artifact, closed));
|
|
989
|
+
saveTry();
|
|
907
990
|
|
|
908
991
|
if (closed.verdict === 'green' || closed.verdict === 'hitl') {
|
|
909
992
|
recordAudit(makeAuditRow({
|
|
910
|
-
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,
|
|
993
|
+
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,
|
|
911
994
|
}), result.artifact);
|
|
912
995
|
return {
|
|
913
996
|
ok: true, artifact, attempts: attempt, hitl: closed.verdict === 'hitl',
|
|
@@ -918,7 +1001,7 @@ async function runStepRalph({
|
|
|
918
1001
|
// A closer that renders no judgment ('unparseable'/'crash') is a
|
|
919
1002
|
// CASUALTY, never a red and never a strike (bareloop F17).
|
|
920
1003
|
recordAudit(makeAuditRow({
|
|
921
|
-
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,
|
|
1004
|
+
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,
|
|
922
1005
|
}), result.artifact);
|
|
923
1006
|
return { ok: false, outcome: 'close-casualty', red: `close-casualty: step "${step.goal}" — ${closed.red} (${closed.verdict})` };
|
|
924
1007
|
}
|
|
@@ -928,7 +1011,7 @@ async function runStepRalph({
|
|
|
928
1011
|
seenGaps.add(normalised);
|
|
929
1012
|
if (strike) strikes += 1;
|
|
930
1013
|
recordAudit(makeAuditRow({
|
|
931
|
-
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,
|
|
1014
|
+
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,
|
|
932
1015
|
}), result.artifact);
|
|
933
1016
|
|
|
934
1017
|
if (n === maxN) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: step "${step.goal}" — ${closed.red}` };
|
|
@@ -958,16 +1041,20 @@ async function runStepRalph({
|
|
|
958
1041
|
* @param {() => string} [opts.clock] - returns the current ISO timestamp; defaults to the wall clock.
|
|
959
1042
|
* @param {string} opts.businessDate - the run's explicit "as of today", never the wall clock.
|
|
960
1043
|
* @param {number} [opts.ceilingUsd] - per-attempt ceiling override; the model's hold from Settings prices (`ceilingCostUsd`); absent = no hold.
|
|
1044
|
+
* @param {{slot: string, model: string}} [opts.runModel] - M4d am33: the model this run started on; recorded once in the run folder (run-model.json) and kept by every resume/continue.
|
|
961
1045
|
* @param {string|null} [opts.initialGap] - M3 scope item 7 (rerun as a fresh
|
|
962
1046
|
* run): a human's rerun reason, carried as the FIRST ordinary step's
|
|
963
1047
|
* starting gap. Never used by a plain `runFlow` call outside `resumeRun`'s
|
|
964
1048
|
* own rerun path.
|
|
1049
|
+
* @param {(url: string) => Promise<{ok: true, text: string, url: string}|{ok: false, error: string}>} [opts.fetchPage] - M10: the web-page fetch (default barebrowse via src/pagefetch.js); a test injects one.
|
|
965
1050
|
* @param {() => number} [opts.nowMs] - F45 finding 3: returns the current
|
|
966
1051
|
* epoch ms; defaults to the wall clock. Mirrors `clock` (ISO) so a test
|
|
967
1052
|
* can advance wall time across a park/resume boundary without a real wait.
|
|
968
1053
|
*/
|
|
969
1054
|
export async function runFlow({
|
|
970
|
-
root, name, runId, sources, catalogue, modelStep, askStep, sendStep, primitives, primitiveReds, clock, businessDate, ceilingUsd, initialGap,
|
|
1055
|
+
root, name, runId, sources, catalogue, modelStep, askStep, sendStep, primitives, primitiveReds, clock, businessDate, ceilingUsd, initialGap, fetchPage,
|
|
1056
|
+
// M4d am33: the model this run STARTED on ({ slot, model }); recorded once beside the run, kept by every resume/continue. Absent = nothing recorded.
|
|
1057
|
+
runModel,
|
|
971
1058
|
// F45 finding 3's test needs to advance wall time across a park/resume
|
|
972
1059
|
// boundary without a real wait, exactly like `clock` already does for ISO
|
|
973
1060
|
// timestamps — `nowMs` is the same idea for epoch-ms wall-clock reads.
|
|
@@ -1072,7 +1159,11 @@ export async function runFlow({
|
|
|
1072
1159
|
});
|
|
1073
1160
|
}
|
|
1074
1161
|
|
|
1075
|
-
|
|
1162
|
+
// 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
|
+
writeRunThinking(flowDir, runDir);
|
|
1164
|
+
if (runModel) writeRunModel(runDir, runModel); // M4d am33: the one record of the model this run started on
|
|
1165
|
+
|
|
1166
|
+
const frozen = await freezeInputs(runDir, sources ?? [], { fetchPage });
|
|
1076
1167
|
if (!frozen.ok) {
|
|
1077
1168
|
return haltRun({
|
|
1078
1169
|
flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: frozen.red, spent: { value: 0 },
|
|
@@ -1223,6 +1314,19 @@ function makeOneShotThenParkAskStep({ decision, reason, artifactSha256 }) {
|
|
|
1223
1314
|
};
|
|
1224
1315
|
}
|
|
1225
1316
|
|
|
1317
|
+
/**
|
|
1318
|
+
* M4d am30: the highest try number a step has used in this run, read from the books (audit.jsonl, the source of truth). A Redo's re-run is
|
|
1319
|
+
* numbered after it, so a number is used once per step. Only the NUMBER moves: the limit counts the re-run's own tries (`n` in `runStepRalph`).
|
|
1320
|
+
* @param {string} runDir @param {string|null} stepId
|
|
1321
|
+
*/
|
|
1322
|
+
function lastTryNumber(runDir, stepId) {
|
|
1323
|
+
let last = 0;
|
|
1324
|
+
for (const r of readAudit(runDir)) {
|
|
1325
|
+
if (r.step === stepId && Number.isInteger(r.attempt) && r.verdict !== 'cap-halt' && r.verdict !== 'stop-asked' && r.verdict !== 'stop-not-honoured' && r.attempt > last) last = r.attempt;
|
|
1326
|
+
}
|
|
1327
|
+
return last;
|
|
1328
|
+
}
|
|
1329
|
+
|
|
1226
1330
|
/**
|
|
1227
1331
|
* One signed ask slot's own loop (M2's ask branch, unchanged in spirit,
|
|
1228
1332
|
* extracted so `resumeRun` can re-enter the SAME logic mid-ask instead of
|
|
@@ -1417,13 +1521,13 @@ async function runAskSlot({
|
|
|
1417
1521
|
// swap / unparseable JSON) is tampering, never "not written yet", and
|
|
1418
1522
|
// must halt the redo rather than silently feed forged/garbage content
|
|
1419
1523
|
// into the model step that is about to re-run.
|
|
1420
|
-
const priorReadsResult = readArtifactsMapChecked(runDir, priorStep.reads);
|
|
1524
|
+
const priorReadsResult = readArtifactsMapChecked(runDir, priorStep.reads, { docxRoles: citedRolesOf(priorStep) });
|
|
1421
1525
|
if (!priorReadsResult.ok) {
|
|
1422
1526
|
return { type: 'halted', outcome: 'red', red: `redo: step "${priorStep.goal}" ${priorReadsResult.red}` };
|
|
1423
1527
|
}
|
|
1424
1528
|
// eslint-disable-next-line no-await-in-loop
|
|
1425
1529
|
const redoResult = await runStepRalph({
|
|
1426
|
-
step: priorStep, primitivesMap: primitives, readsMap: priorReadsResult.map, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, initialGap: reason, attemptOffset:
|
|
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,
|
|
1427
1531
|
readStop: () => stopPending(runDir), stepNo: priorStepNo, prevStepId: priorPrevStepId,
|
|
1428
1532
|
});
|
|
1429
1533
|
if (!redoResult.ok) {
|
|
@@ -1664,7 +1768,7 @@ async function foldFromStep({
|
|
|
1664
1768
|
// F48 round 4: every id in `step.reads` names an earlier step in THIS
|
|
1665
1769
|
// same fold pass, already run and already written — a `red` read here
|
|
1666
1770
|
// halts rather than silently feeding tampered/unreadable content in.
|
|
1667
|
-
const readsMapResult = readArtifactsMapChecked(runDir, step.reads);
|
|
1771
|
+
const readsMapResult = readArtifactsMapChecked(runDir, step.reads, { docxRoles: citedRolesOf(step) });
|
|
1668
1772
|
if (!readsMapResult.ok) {
|
|
1669
1773
|
return haltRun({
|
|
1670
1774
|
flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts,
|
|
@@ -1678,7 +1782,7 @@ async function foldFromStep({
|
|
|
1678
1782
|
// redo's `initialGap` above.
|
|
1679
1783
|
// eslint-disable-next-line no-await-in-loop
|
|
1680
1784
|
const stepResult = await runStepRalph({
|
|
1681
|
-
step, primitivesMap: primitives, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, initialGap: i === i0 ? firstStepGap : null, now,
|
|
1785
|
+
step, primitivesMap: primitives, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, initialGap: i === i0 ? firstStepGap : null, thinkingBox: readJobThinking(flowDir, runDir), now, runDir,
|
|
1682
1786
|
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,
|
|
1683
1787
|
});
|
|
1684
1788
|
if (!stepResult.ok) {
|
|
@@ -1854,11 +1958,13 @@ function sameRoot(recorded, requested) {
|
|
|
1854
1958
|
* @param {() => string} [opts.clock]
|
|
1855
1959
|
* @param {string} opts.businessDate
|
|
1856
1960
|
* @param {number} [opts.ceilingUsd]
|
|
1961
|
+
* @param {{slot: string, model: string}} [opts.runModel] - M4d am33: the model this run started on; recorded once in the run folder (run-model.json) and kept by every resume/continue.
|
|
1857
1962
|
* @param {() => number} [opts.nowMs] - F45 finding 3; see `runFlow`'s own.
|
|
1858
1963
|
* @param {(newRunDir:string) => void} [opts.onRerunStart] - amendment 16 C2: called with the new run's folder just before a `rerun` starts it.
|
|
1859
1964
|
*/
|
|
1860
1965
|
export async function resumeRun({
|
|
1861
1966
|
root, name, runId, catalogue, modelStep, sendStep, primitives, primitiveReds, clock, businessDate, ceilingUsd,
|
|
1967
|
+
runModel, // M4d am33: the model the resumed run keeps; a rerun (a new run) records it too
|
|
1862
1968
|
// F45 finding 3 (see `runFlow`'s own `nowMs`): additive, defaults to the
|
|
1863
1969
|
// real `Date.now` for every existing caller.
|
|
1864
1970
|
nowMs,
|
|
@@ -2201,6 +2307,7 @@ export async function resumeRun({
|
|
|
2201
2307
|
clock,
|
|
2202
2308
|
businessDate,
|
|
2203
2309
|
ceilingUsd,
|
|
2310
|
+
runModel,
|
|
2204
2311
|
// Item 7: the reason becomes the new run's FIRST step's starting gap.
|
|
2205
2312
|
initialGap: reason,
|
|
2206
2313
|
});
|
package/src/schedule.js
CHANGED
|
@@ -28,10 +28,10 @@ import { triggerHash } from './trigger-line.js';
|
|
|
28
28
|
* }} Schedule
|
|
29
29
|
*/
|
|
30
30
|
|
|
31
|
-
|
|
32
|
-
|
|
31
|
+
const SCHEDULE_FILE = 'schedule.json';
|
|
32
|
+
const LEDGER_FILE = 'schedule-ledger.jsonl';
|
|
33
33
|
/** The words of the am16 row (also for a Cancel): signed text, M9 am16. @param {string} name */
|
|
34
|
-
|
|
34
|
+
const droppedSay = (name) => `${name} was waiting when the schedule changed, so it will not run. Drop it in again to run it.`;
|
|
35
35
|
|
|
36
36
|
/** @param {string} flowDir */
|
|
37
37
|
export const scheduleFileOf = (flowDir) => join(flowDir, SCHEDULE_FILE);
|
package/src/setup.js
CHANGED
|
@@ -11,7 +11,7 @@ import { lstatSync, writeFileSync } from 'node:fs';
|
|
|
11
11
|
import { triesOf } from './draft-steps.js';
|
|
12
12
|
import { join } from 'node:path';
|
|
13
13
|
|
|
14
|
-
import { scrub } from './authoring.js';
|
|
14
|
+
import { readQuestions, scrub } from './authoring.js';
|
|
15
15
|
import { notCheckedBlock } from './checked.js';
|
|
16
16
|
import { readDraftSpend } from './draftspend.js';
|
|
17
17
|
import { readFileInside, readdirInside } from './flow.js';
|
|
@@ -58,6 +58,19 @@ function planRow(sessionDir, rel, kind, n) {
|
|
|
58
58
|
};
|
|
59
59
|
}
|
|
60
60
|
|
|
61
|
+
/**
|
|
62
|
+
* M10 am2 item 4: one row per question the page look raised and the person answered, in the plan folder that raised it (the draft log's human rows, read
|
|
63
|
+
* from the answer files). The question, the answer, the line and the time, plus the proposal and the rule the answer added as their own fields (never cut
|
|
64
|
+
* out of the question text). A question nobody answered leaves no row.
|
|
65
|
+
* @param {string} sessionDir @param {string} rel
|
|
66
|
+
*/
|
|
67
|
+
function humanRows(sessionDir, rel) {
|
|
68
|
+
return readQuestions(join(sessionDir, rel)).questions.filter((q) => q.source === 'look' && q.answer !== null).map((q) => ({
|
|
69
|
+
kind: 'human', n: q.k, at: q.at ?? null, source: 'look', ask: q.ask, question: q.question, answer: q.answer, line: q.line,
|
|
70
|
+
ruleNo: q.ruleNo, ruleText: q.ruleText, proposal: q.proposal ?? null, rule: q.rule ?? null,
|
|
71
|
+
}));
|
|
72
|
+
}
|
|
73
|
+
|
|
61
74
|
/**
|
|
62
75
|
* The rows of a draft's record, oldest first. `sessionDir` is the panel's draft folder (card.json, draft/, card-<n>.json, draft-<n>/); a CLI
|
|
63
76
|
* draft has none, so its record is its one plan folder (`planDir`, read as `draft`) plus the sign.
|
|
@@ -73,6 +86,7 @@ export function buildSetupRows({
|
|
|
73
86
|
// amendment 14 item 6: a draft begun by Start over says so (written once by the panel's start); its row reads `start over`
|
|
74
87
|
const so = readJson(sessionDir, 'started-over-from.json');
|
|
75
88
|
rows.push(planRow(sessionDir, 'draft', typeof so?.startedOverFrom === 'string' ? 'startover' : 'draft', 0));
|
|
89
|
+
rows.push(...humanRows(sessionDir, 'draft'));
|
|
76
90
|
// amendment 14 item 6: each revise is the card as submitted, then its plan row (model, cost, verdict, hash); there is no note row
|
|
77
91
|
const ns = readdirInside(sessionDir, '.').map((f) => CARD_RE.exec(f)?.[1]).filter((x) => x !== undefined).map(Number).sort((a, b) => a - b);
|
|
78
92
|
for (const n of ns) {
|
|
@@ -80,6 +94,7 @@ export function buildSetupRows({
|
|
|
80
94
|
if (card) rows.push({ kind: 'card', n, at: mtimeIso(sessionDir, `card-${n}.json`), card });
|
|
81
95
|
// M4e amendment 24 item 4: a plan drafted again after the human's answers is booked as `redraft`, not `revise` (it uses none of the 2 revises)
|
|
82
96
|
rows.push(planRow(sessionDir, `draft-${n}`, readJson(sessionDir, `redraft-${n}.json`) ? 'redraft' : 'revise', n));
|
|
97
|
+
rows.push(...humanRows(sessionDir, `draft-${n}`));
|
|
83
98
|
}
|
|
84
99
|
} else {
|
|
85
100
|
const r = planRow(planDir, '.', 'draft', 0);
|
package/src/sheetfind.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// M10 piece 5 (docs/wiki/the-module-ladder.md "M10", item 7): when a job's word is not a column of the sheet, CODE finds the column that passes the same test
|
|
2
|
+
// the page words pass - a value of the right kind in the rows - and builds the ask. The model names a word and nothing else; it never names a column to offer and
|
|
3
|
+
// never decides an ask (test/m10-sheetfind.test.js, test/m10-sheetask.test.js).
|
|
4
|
+
// The finder is fwdloop's own (F71 Test 3, C1-C4, $0): bareloop reads "label then value on the same line", and a header sits on line 1, so the discipline
|
|
5
|
+
// transfers, not the code (docs/product/fwd-borrow-from-bareloop-rubric-2026-10-18.md section 3).
|
|
6
|
+
// A column FITS when a plain number fills at least FIT_RATIO of the rows (F71 (b)). A plain number is the whole cell: optional sign, digits, thousands commas,
|
|
7
|
+
// optional decimals. One fitting column with the most rows is the one ask. Two or more fitting columns with equal rows offer nothing (F71 C2, hamr 2026-10-19).
|
|
8
|
+
// Throws away: every column but the winner, the cells' values, and everything but the header and the count of number cells.
|
|
9
|
+
import { parseCsv } from './csv.js';
|
|
10
|
+
import { wordForms } from './pagebits.js';
|
|
11
|
+
|
|
12
|
+
/** a column fits when a plain number fills at least this share of the rows (F71 (b)) */
|
|
13
|
+
export const FIT_RATIO = 0.9;
|
|
14
|
+
const PLAIN_NUMBER = /^[-+]?\d[\d,]*(\.\d+)?$/;
|
|
15
|
+
|
|
16
|
+
/** @param {string} h @returns {string} a header as it is compared: trimmed, white space made one space, lower case */
|
|
17
|
+
const norm = (h) => String(h ?? '').trim().replace(/\s+/g, ' ').toLowerCase();
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @typedef {{kind: 'header', column: string}} FoundHeader the word IS a column (nothing to ask)
|
|
21
|
+
* @typedef {{kind: 'ask', column: string, numbers: number, rows: number}} FoundAsk exactly one column fits: the one ask
|
|
22
|
+
* @typedef {{kind: 'tie', columns: string[], rows: number}} FoundTie two or more columns fit equally: no ask
|
|
23
|
+
* @typedef {{kind: 'none', rows: number}} FoundNone no column fits: no ask
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Where a job word lands in a sheet's columns.
|
|
28
|
+
* @param {string} csvText the sheet's text @param {string} word the job's word
|
|
29
|
+
* @returns {FoundHeader|FoundAsk|FoundTie|FoundNone}
|
|
30
|
+
*/
|
|
31
|
+
export function findColumn(csvText, word) {
|
|
32
|
+
const { header, rows } = parseCsv(csvText);
|
|
33
|
+
const hit = header.find((h) => norm(h) === norm(word) && norm(h) !== '') ?? header.find((h) => norm(h) !== '' && wordForms(word).includes(norm(h)));
|
|
34
|
+
if (hit !== undefined) return { kind: 'header', column: hit };
|
|
35
|
+
const n = rows.length;
|
|
36
|
+
const cols = header.map((h) => ({ h, n: rows.filter((r) => PLAIN_NUMBER.test(String(r.byName[h] ?? '').trim())).length }));
|
|
37
|
+
const fit = cols.filter((c) => n > 0 && c.n / n >= FIT_RATIO);
|
|
38
|
+
if (fit.length === 0) return { kind: 'none', rows: n };
|
|
39
|
+
const best = Math.max(...fit.map((c) => c.n));
|
|
40
|
+
const top = fit.filter((c) => c.n === best);
|
|
41
|
+
if (top.length > 1) return { kind: 'tie', columns: top.map((c) => c.h), rows: n };
|
|
42
|
+
return { kind: 'ask', column: top[0].h, numbers: top[0].n, rows: n };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The question, as signed (item 7's example, then am8 item 1's answer words):
|
|
47
|
+
* `no column 'Price'; 'Amount' has numbers in 40 of 40 rows. Use it? Answer "agree", or type your own words (your answer is added as a new ~ rule on line N).`
|
|
48
|
+
* @param {string} word @param {FoundAsk} found @param {number} line @returns {string}
|
|
49
|
+
*/
|
|
50
|
+
export const columnQuestion = (word, found, line) => `no column '${word}'; '${found.column}' has numbers in ${found.numbers} of ${found.rows} rows. Use it? Answer "agree", or type your own words (your answer is added as a new ~ rule on line ${line}).`;
|