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/drafter.js
CHANGED
|
@@ -32,7 +32,9 @@ import { askableFromLook, tooManyAsksText, MAX_LOOK_ASKS } from './pageask.js';
|
|
|
32
32
|
import { lineRules } from './pagebits.js';
|
|
33
33
|
import path from 'node:path';
|
|
34
34
|
import { isCellsPath } from './closers.js';
|
|
35
|
-
import { parseCsv } from './csv.js';
|
|
35
|
+
import { parseCsv, sheetTable } from './csv.js';
|
|
36
|
+
import { sheetChecksProp, sheetOfferRules } from './sheetoffer.js';
|
|
37
|
+
import { uncoveredRules } from './sheetblock.js';
|
|
36
38
|
import {
|
|
37
39
|
makeProvider, ModelRefusal, sumMeterings, ceilingCostUsd, priceRecord,
|
|
38
40
|
} from './provider.js';
|
|
@@ -56,12 +58,12 @@ const docRolesOf = (sources) => (sources ?? []).filter((s) => s.kind === 'file'
|
|
|
56
58
|
/** the document inputs a quote can come from (M10 piece 5, item 2) */
|
|
57
59
|
const DOC_EXTS = Object.freeze(['.docx', '.md', '.txt']);
|
|
58
60
|
|
|
59
|
-
/** M10 am8 item 2: the column lock of a green step that
|
|
61
|
+
/** M10 am8 item 2: the column lock of a green step that reads a CSV input (`close.columns`): the exact header(s) its values come from. */
|
|
60
62
|
const COLUMNS_PROP = Object.freeze({
|
|
61
63
|
type: 'array',
|
|
62
64
|
minItems: 1,
|
|
63
65
|
maxItems: 10,
|
|
64
|
-
description: "only on a green step that
|
|
66
|
+
description: "only on a green step that reads a CSV input: the exact column names (the sheet's header) its values come from. Omit on any other step",
|
|
65
67
|
items: {
|
|
66
68
|
type: 'object',
|
|
67
69
|
properties: {
|
|
@@ -124,8 +126,13 @@ const SHAPE_PROPS = Object.freeze({
|
|
|
124
126
|
mustCarry: { type: 'array', minItems: 1, items: { type: 'string', minLength: 1 }, description: 'named fields every line must carry' },
|
|
125
127
|
});
|
|
126
128
|
|
|
127
|
-
/**
|
|
128
|
-
|
|
129
|
+
/**
|
|
130
|
+
* The forced tool's parameter schema. `menu` = wiredMenu(). `sheets` (M10b piece 3, optional) = the drafting copy's table of each CSV input role: with it a step may carry
|
|
131
|
+
* `close.sheet`, and every column a check names is an enum of that sheet's exact header (src/sheetoffer.js); without it (no CSV input) no sheet property exists.
|
|
132
|
+
* @param {any[]} menu @param {{sheets?: Record<string, {header: string[]}>}} [o]
|
|
133
|
+
*/
|
|
134
|
+
export function buildDeclarationSchema(menu, { sheets } = {}) {
|
|
135
|
+
const sheetProp = sheets ? sheetChecksProp(sheets) : null;
|
|
129
136
|
const shapeProps = {};
|
|
130
137
|
for (const key of SHAPE_KEYS) {
|
|
131
138
|
if (!SHAPE_PROPS[key]) throw new Error(`schema: SHAPE_KEYS gained "${key}" — add its type to SHAPE_PROPS`);
|
|
@@ -165,6 +172,7 @@ export function buildDeclarationSchema(menu) {
|
|
|
165
172
|
},
|
|
166
173
|
cited: CITED_PROP,
|
|
167
174
|
columns: COLUMNS_PROP,
|
|
175
|
+
...(sheetProp ? { sheet: sheetProp } : {}),
|
|
168
176
|
},
|
|
169
177
|
required: ['class'],
|
|
170
178
|
additionalProperties: false,
|
|
@@ -208,7 +216,7 @@ export const MAX_QUESTIONS = 2;
|
|
|
208
216
|
|
|
209
217
|
/** What fwdloop's typed checks can really check (bareloop F174: give the model the real list, or "Not checked" is invented). */
|
|
210
218
|
export const CHECKABLE = Object.freeze([
|
|
211
|
-
'green: a figure
|
|
219
|
+
'green: a sheet figure is recomputed by bareguard from the saved sheet',
|
|
212
220
|
'softgreen: the output carries named section headings (sections), in order',
|
|
213
221
|
`softgreen: a word ceiling for the whole output (maxWords; ${WHOLE_OUTPUT_CEILING_RULE}) and per section (wordsPerSection)`,
|
|
214
222
|
'softgreen: a line count per invoice (linesPerInvoice) and fields every line must carry (mustCarry)',
|
|
@@ -231,8 +239,9 @@ export const QUESTIONS_PROMPT = [
|
|
|
231
239
|
].join('\n');
|
|
232
240
|
|
|
233
241
|
/** The declaration schema plus the optional `notChecked` (every try) and, on try 3 only, `questions`. Neither is in `required`. */
|
|
234
|
-
|
|
235
|
-
|
|
242
|
+
/** @param {any[]} menu @param {{questions?: boolean, sheets?: Record<string, {header: string[]}>|undefined}} [o] */
|
|
243
|
+
export function buildRoundSchema(menu, { questions = false, sheets = undefined } = {}) {
|
|
244
|
+
const s = buildDeclarationSchema(menu, { sheets });
|
|
236
245
|
const extra = { notChecked: { type: 'array', items: { type: 'string' }, description: 'what the job asks for that no typed check verifies' } };
|
|
237
246
|
if (questions) {
|
|
238
247
|
extra.questions = {
|
|
@@ -305,10 +314,11 @@ function greenReadRule(sources) {
|
|
|
305
314
|
const pageRoles = (sources ?? []).filter((s) => s.kind === 'page').map((s) => s.role);
|
|
306
315
|
// M10 piece 5 (item 2): a quote in a doc - a .docx / .md / .txt input is quoted the way a page is
|
|
307
316
|
const docRoles = docRolesOf(sources);
|
|
308
|
-
const rule = '- A step whose line has a "green" guardrail must list the CSV input\'s role in its reads (for example reads: ["aging"]), because only an input with cells can be
|
|
317
|
+
const rule = '- A step whose line has a "green" guardrail must list the CSV input\'s role in its reads (for example reads: ["aging"]), because only an input with cells can be checked against its sheet; a text output of an earlier step has no cells. A green step that reads only other steps is refused.';
|
|
309
318
|
const out = [csvRoles.length
|
|
310
|
-
? `${rule} CSV inputs in this job: ${csvRoles.join(', ')}. close.columns = [{source, column}] names the exact column(s) of the CSV header that the step's
|
|
311
|
-
: `${rule} This job signs no CSV input, so a guardrail that needs
|
|
319
|
+
? `${rule} CSV inputs in this job: ${csvRoles.join(', ')}. close.columns = [{source, column}] names the exact column(s) of the CSV header that the step's values come from. Where the Inputs list says a line "is column 'X'", that line's step must name that column. A step that has close.sheet is not held to close.columns by a word that merely matches a header (such as a bucket name); but when a line carries a rule "use the column 'X' for ...", at least one of that line's close.sheet checks must use that column. Leave close.columns out when the line names no column.`
|
|
320
|
+
: `${rule} This job signs no CSV input, so a guardrail that needs a sheet check cannot be classed green here: class it "hitl"${pageRoles.length ? ' (unless it is about a web page, below)' : ''}.`];
|
|
321
|
+
if (csvRoles.length) out.push(...sheetOfferRules(csvRoles)); // M10b piece 3: close.sheet and every rule the validator enforces on it
|
|
312
322
|
if (pageRoles.length || docRoles.length) {
|
|
313
323
|
out.push(
|
|
314
324
|
`- ${[pageRoles.length ? `Web page inputs in this job: ${pageRoles.join(', ')}.` : '', docRoles.length ? `Document inputs in this job: ${docRoles.join(', ')}.` : ''].filter(Boolean).join(' ')} A step whose line asks for things found in one of them, and whose guardrail is about them, is "green" and checks quotes: it lists that input's role in its reads and carries close.cited = {source, facts, count}. close.cited is for a green step only.`,
|
|
@@ -316,7 +326,7 @@ function greenReadRule(sources) {
|
|
|
316
326
|
'- Fact shapes: money takes unit or currency, rule, anchor; number, date and time take rule, anchor; text takes anchor and until (until needs an anchor); phrase takes only phrase (fixed words every result must say). Never put a field on a shape that does not take it.',
|
|
317
327
|
'- A label (anchor, until) is PICKED from the kept labels listed under Inputs for that page, never typed. A phrase, a unit or a currency is copied from the page words listed there. A word listed as Not checked or dropped can never be used.',
|
|
318
328
|
'- A place listed under Inputs as "place phrases" must have EVERY one of its phrases as its own phrase fact (one fact per phrase, the phrase word for word). A place name alone does not tell a result that leaves the other way.',
|
|
319
|
-
'- A fact\'s rule (under, over, between) may only use a number that is in the person\'s own words on that job line (the line or its guardrail). Never make a number up; leave the rule out if the person gave none.',
|
|
329
|
+
'- A fact\'s rule (under, over, between) may only use a number that is in the person\'s own words on that job line (the line or its guardrail). Never make a number up; leave the rule out if the person gave none. When the Kept list says "limit read from your words" for a fact, the fact that reads that value MUST carry that rule (same kind, op and bound), or the line is refused.',
|
|
320
330
|
'- A label or a phrase that sits in each result must appear on the page at least as many times as close.cited.count.min, or the line is refused.',
|
|
321
331
|
...(docRoles.length ? ['- For a document input there is no list of kept labels: a label (anchor) or a phrase is words the document really says, copied from it, and each must be in the document at least as many times as close.cited.count.min.'] : []),
|
|
322
332
|
);
|
|
@@ -339,6 +349,14 @@ function whenToUse(menu) {
|
|
|
339
349
|
return Object.entries(WHEN_TO_USE).filter(([verb]) => on.has(verb)).map(([, line]) => line);
|
|
340
350
|
}
|
|
341
351
|
|
|
352
|
+
/** M10b piece 3: with a CSV input, the guardrail rules of each line by number (the numbers `covers` names), in the order the validator counts them. Otherwise nothing. */
|
|
353
|
+
function sheetRuleNumbers(lines, arbiter) {
|
|
354
|
+
const csvRoles = (arbiter.sources ?? []).filter((s) => s.kind === 'file' && isCellsPath(s.path));
|
|
355
|
+
if (csvRoles.length === 0) return [];
|
|
356
|
+
const rows = lines.map((l) => ({ n: l.n, rules: lineRules(l.guardrail ? { rule: l.guardrail } : {}) })).filter((x) => x.rules.length > 0);
|
|
357
|
+
return rows.length === 0 ? [] : ['', 'The guardrail rules by number (what "covers" counts):', ...rows.map((x) => `- line ${x.n}: ${x.rules.map((r, i) => `${i + 1}) ${r}`).join(' ')}`)];
|
|
358
|
+
}
|
|
359
|
+
|
|
342
360
|
export function buildSystemPrompt({ menu, lines, arbiter, factsInfo }) {
|
|
343
361
|
const askLines = arbiter.asks.map((a) => a.line);
|
|
344
362
|
const sendLines = arbiter.sends.map((s) => s.line);
|
|
@@ -352,7 +370,7 @@ export function buildSystemPrompt({ menu, lines, arbiter, factsInfo }) {
|
|
|
352
370
|
'Rules:',
|
|
353
371
|
'- Steps share one artifact space. Each step: primitives (verbs it needs, [] if none), reads (artifact ids emitted by an EARLIER step, or the role of a CSV input listed under Inputs), emits (ONE new unique artifact id), fromLine (the ONE job line it serves), close. The machine fills each step\'s goal with that signed line, verbatim — you never write a goal.',
|
|
354
372
|
'- Every numbered job line must be served by a step (fromLine = that line) or listed in "refused" with a reason.',
|
|
355
|
-
'- guardrailClasses: for each job line that HAS a guardrail, classify its wording once: "green" (every figure must
|
|
373
|
+
'- guardrailClasses: for each job line that HAS a guardrail, classify its wording once: "green" (every figure must be checkable against its source: a sheet figure by the bareguard checks of the sheet), "softgreen" (the human declared a SHAPE the output must take), "hitl" (an ask/accept/review gate, or anything you are not sure of). When unsure, "hitl".',
|
|
356
374
|
'- close.class MUST equal the class of the guardrail on that step\'s fromLine (guardrailClasses[fromLine]); a line with no guardrail is "hitl". A step cannot claim a class its own line does not earn.',
|
|
357
375
|
...greenReadRule(arbiter.sources),
|
|
358
376
|
'- close.shape only on a softgreen step; it is the human\'s declared shape in structured form.',
|
|
@@ -368,6 +386,7 @@ export function buildSystemPrompt({ menu, lines, arbiter, factsInfo }) {
|
|
|
368
386
|
'',
|
|
369
387
|
'The numbered job lines:',
|
|
370
388
|
jobLinesText(lines, arbiter.asks),
|
|
389
|
+
...sheetRuleNumbers(lines, arbiter),
|
|
371
390
|
].join('\n');
|
|
372
391
|
}
|
|
373
392
|
|
|
@@ -402,12 +421,14 @@ function isPlainObject(v) { return !!v && typeof v === 'object' && !Array.isArra
|
|
|
402
421
|
* costUsd:number|null, modelReturned:string|null, modelId?:string, price?:object|null, tokens?:object|null, structureRetries:number, revisions:number, stop:string|null, log:object[],
|
|
403
422
|
* questions?:{line:number, question:string}[], droppedQuestions?:object[], notChecked?:string[], thinking?:{asked:string, status:string|null, say:string|null}, inputs?:{role:string, detail:string}[],
|
|
404
423
|
* look?:{facts:any[], dropped:any[]}, pageLooks?:{role:string, address:string, sha256:string, bytes:number, frozen:string, attempts:number, mapping:any}[], sheetLooks?:any[]}>}
|
|
424
|
+
* `learnHints` (M8 item 5a): the earlier runs' notes block (src/learnstore.js hintsForRun), appended to the drafter's system prompt; null = nothing.
|
|
405
425
|
* `look` / `pageLooks` (M10 item 3) are there when the job signs a web page: the kept facts (with their `reading`, the input a later ask reads), every drop, and per page its address, sha256 and the AI's map. Each drop is also a line in `notChecked`.
|
|
406
426
|
*/
|
|
407
427
|
export async function draft({
|
|
408
428
|
proseText, slot, model, provider: injected, rates: injectedRates, modelId: injectedModelId, env,
|
|
409
429
|
priorSpend = /** @type {((ceilingUsd: number) => number)|null} */ (null), skills = DRAFT_SKILLS, makeProviderFn = makeProvider, onBook, offerQuestions = true, draftThinking = /** @type {'on'|'off'} */ ('off'),
|
|
410
430
|
draftDir = /** @type {string|null} */ (null), fetchPage = undefined, leftRules = /** @type {{line: number, rule: number}[]} */ ([]),
|
|
431
|
+
learnHints = /** @type {{text: string, ids: string[]}|null} */ (null),
|
|
411
432
|
}) {
|
|
412
433
|
// What was asked of thinking and the WORST status bareagent reported across the rounds (the page says it loudly unless 'applied'). Read from the round log, the one record.
|
|
413
434
|
const thinkingOf = () => {
|
|
@@ -638,8 +659,12 @@ export async function draft({
|
|
|
638
659
|
const factsInfo = pageInfo.length ? [...facts.info.filter((l) => !pageSources.some((s) => l.startsWith(`- ${s.role}: a web page`))), ...pageInfo] : facts.info;
|
|
639
660
|
|
|
640
661
|
// `notChecked` is offered on every try (information, not asking); `questions` only on try 3 (below).
|
|
662
|
+
// M10b piece 3: the drafting copy's table of each CSV input - the header the drafter may pick from, the table bareguard's sign-time test runs over
|
|
663
|
+
const sheetTables = Object.keys(facts.sheets ?? {}).length ? Object.fromEntries(Object.entries(facts.sheets).map(([role, t]) => [role, sheetTable(parseCsv(t))])) : undefined;
|
|
641
664
|
const baseSystem = buildSystemPrompt({ menu, lines, arbiter, factsInfo });
|
|
642
|
-
|
|
665
|
+
// M8 item 5a: the earlier runs' notes go on the DRAFTER's system prompt only (F81's B arm), the one `system` every round of this draft uses (revise and structure retries too).
|
|
666
|
+
// Absent or empty: the prompt is byte-identical to what it was.
|
|
667
|
+
const system = `${baseSystem}\n\n${NOTCHECKED_PROMPT}${learnHints?.text ? `\n\n${learnHints.text}` : ''}`;
|
|
643
668
|
let structureRetries = 0;
|
|
644
669
|
let revisions = 0;
|
|
645
670
|
let lastReds = [];
|
|
@@ -664,7 +689,7 @@ export async function draft({
|
|
|
664
689
|
// Amendment 25: a lock is a mechanism. Only try 3 of 3, and only when tries 1 and 2 BOTH failed validation (`revisions` counts the
|
|
665
690
|
// validator's refusals fed back), gets the `questions` property; the redraft after an answer passes offerQuestions:false and never does.
|
|
666
691
|
const askOpen = offerQuestions && revisions === MAX_REVISIONS;
|
|
667
|
-
const schema = buildRoundSchema(menu, { questions: askOpen });
|
|
692
|
+
const schema = buildRoundSchema(menu, { questions: askOpen, sheets: sheetTables });
|
|
668
693
|
const tool = {
|
|
669
694
|
name: TOOL,
|
|
670
695
|
description: 'Emit the flow declaration over the granted primitives, or refuse lines you cannot serve.',
|
|
@@ -754,15 +779,16 @@ export async function draft({
|
|
|
754
779
|
return { ...st, close: { ...st.close, shape: per === null ? shape : { ...shape, wordsPerSection: per } } };
|
|
755
780
|
});
|
|
756
781
|
}
|
|
782
|
+
// M10b piece 4: `covers` (which ~ rules a check verifies) stays on the check and is signed; the validator checks it, the plan card shows it
|
|
757
783
|
const verdict = validateDeclaration(declaration, {
|
|
758
784
|
arbiter, lines, catalogue: validationCatalogue, wired: WIRED_VERBS, verbatimGoals: true, fitJobLine: true,
|
|
759
785
|
// M10 am7 item 1: the words of every cited fact are proved on the drafting copy of the page, against what the page-word map kept
|
|
760
|
-
sheetWords:
|
|
786
|
+
sheetWords: sheetTables ? { headers: Object.fromEntries(Object.entries(sheetTables).map(([role, t]) => [role, t.header])), facts: sheetFacts.filter((f) => f.shape === 'column'), tables: sheetTables } : undefined,
|
|
761
787
|
pageWords: { texts: { ...(facts.docs ?? {}), ...Object.fromEntries(Object.entries(pages).map(([role, pg]) => [role, pg.text])) }, look: pageSources.length ? { facts: look.facts, dropped: look.dropped } : null, docs: docRolesOf(arbiter.sources) },
|
|
762
788
|
});
|
|
763
789
|
lastDecl = declaration;
|
|
764
790
|
const asked = askOpen ? normalizeQuestions(rawQuestions, failedLines) : { kept: [], dropped: [] };
|
|
765
|
-
extras = { questions: asked.kept, droppedQuestions: asked.dropped, notChecked: [...pageNotChecked, ...cleanNotChecked(rawNotChecked)
|
|
791
|
+
extras = { questions: asked.kept, droppedQuestions: asked.dropped, notChecked: [...new Set([...pageNotChecked, ...cleanNotChecked(rawNotChecked), ...uncoveredRules(declaration, jobLines, Object.keys(facts.sheets ?? {}))])] };
|
|
766
792
|
if (asked.dropped.length) entry.droppedQuestions = asked.dropped;
|
|
767
793
|
if (verdict.ok) {
|
|
768
794
|
entry.outcome = 'valid';
|
package/src/flowmodel.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// and a model id - is recorded in `model.json`, beside the draft and then beside the signed flow. It is NOT one of the signed files: which model
|
|
3
3
|
// runs, and at what price, is Settings' to say (a line that is no longer ticked is refused by name at run time), so the record only remembers the choice.
|
|
4
4
|
// One writer (`writeModelRecord`), one reader (`readModelRecord`); both go through the safe gateway.
|
|
5
|
-
import { writeFileSync } from 'node:fs';
|
|
5
|
+
import { writeFileSync, renameSync } from 'node:fs';
|
|
6
6
|
import { join } from 'node:path';
|
|
7
7
|
import { readFileInside } from './flow.js';
|
|
8
8
|
import { isKeyName } from './provider.js';
|
|
@@ -86,3 +86,58 @@ export function readRunModel(runDir) {
|
|
|
86
86
|
export function writeRunModel(runDir, { slot, model }) {
|
|
87
87
|
writeOnce(join(runDir, RUN_MODEL_FILE), { slot, model });
|
|
88
88
|
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* M8 item 5a: the file that keeps EXACTLY what the drafter was handed from earlier runs (the Audit box of item 6 reads it). Bareloop's
|
|
92
|
+
* `learnings` spine record shape, `{phase, text, ids, chars}`. Write-once (never over an existing record); written with something handed, or by `writeLearningsError` with an empty `text`
|
|
93
|
+
* (a failed ask: nothing handed, why in `error`); a reader treats empty text as no record, so no file or empty text = nothing handed = no box. Borrowed-from: bareloop src/planrun.js@v0.46.0:3092 (emit('learnings', ...)).
|
|
94
|
+
*/
|
|
95
|
+
export const LEARNINGS_FILE = 'learnings.json';
|
|
96
|
+
|
|
97
|
+
/** @param {string} dir @param {{text: string, ids: string[]}} hints */
|
|
98
|
+
export function writeLearningsRecord(dir, { text, ids }) {
|
|
99
|
+
writeOnce(join(dir, LEARNINGS_FILE), { phase: 'draft', text, ids, chars: text.length });
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* The drafter's failed ask for the block (or failed record write) rides the same record: nothing handed (`text: ''`, no ids), and `error` (first line, secrets redacted).
|
|
104
|
+
* `readLearningsRecord` reads an empty text as no record, so the Audit box stays hidden and `copyLearningsRecord` copies nothing.
|
|
105
|
+
* @param {string} dir @param {string} error
|
|
106
|
+
*/
|
|
107
|
+
export function writeLearningsError(dir, error) {
|
|
108
|
+
writeOnce(join(dir, LEARNINGS_FILE), { phase: 'draft', text: '', ids: [], chars: 0, error });
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* M8 item 6: the Audit box reads the record in the RUN's folder. It reaches the run the way `model.json` does: a draft's record is copied (write-once) into the folder it is signed
|
|
113
|
+
* into (`copyLearningsRecord`: the flow folder at a new job's sign, the new run's folder at a red run's redraft), and the first run that starts from a flow folder TAKES it
|
|
114
|
+
* (`takeLearningsRecord`: a rename, so it moves once and a second run of the same job never shows it). A run that reused its plan has no draft, so it has none.
|
|
115
|
+
* @param {string} fromDir a draft folder @param {string} toDir a flow folder or a run folder @returns {boolean} true when a record was copied
|
|
116
|
+
*/
|
|
117
|
+
export function copyLearningsRecord(fromDir, toDir) {
|
|
118
|
+
const rec = readLearningsRecord(fromDir);
|
|
119
|
+
if (rec === null) return false;
|
|
120
|
+
writeOnce(join(toDir, LEARNINGS_FILE), rec); // `writeOnce`, the same write-once JSON writer and shape as `writeLearningsRecord`: a record that reads is copied, one that does not is not
|
|
121
|
+
return true;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** @param {string} flowDir @param {string} runDir @returns {boolean} true when the flow's record moved into the run (it is no longer in the flow folder) */
|
|
125
|
+
export function takeLearningsRecord(flowDir, runDir) {
|
|
126
|
+
if (!readFileInside(flowDir, LEARNINGS_FILE).ok || readFileInside(runDir, LEARNINGS_FILE).ok) return false;
|
|
127
|
+
renameSync(join(flowDir, LEARNINGS_FILE), join(runDir, LEARNINGS_FILE));
|
|
128
|
+
return true;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* The ONE reader of a run's record. null = no record, or one that is not `{phase, text, ids, chars}` (the box is then hidden, never guessed).
|
|
133
|
+
* @param {string} runDir @returns {{phase: string, text: string, ids: string[], chars: number}|null}
|
|
134
|
+
*/
|
|
135
|
+
export function readLearningsRecord(runDir) {
|
|
136
|
+
const r = readFileInside(runDir, LEARNINGS_FILE);
|
|
137
|
+
if (!r.ok) return null;
|
|
138
|
+
try {
|
|
139
|
+
const j = JSON.parse(r.text);
|
|
140
|
+
return j && typeof j.text === 'string' && j.text !== '' && Array.isArray(j.ids) && j.ids.every((/** @type {any} */ x) => typeof x === 'string')
|
|
141
|
+
? { phase: String(j.phase ?? 'draft'), text: j.text, ids: j.ids, chars: Number.isInteger(j.chars) ? j.chars : j.text.length } : null;
|
|
142
|
+
} catch { return null; }
|
|
143
|
+
}
|