fwdloop 0.28.0 → 0.29.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/bin/fwdloop +27 -5
- package/package.json +3 -3
- package/src/ask.js +1 -1
- package/src/audit-fold.js +9 -1
- package/src/authoring.js +11 -4
- package/src/checked.js +5 -2
- package/src/checkpick.js +257 -0
- package/src/checkwords.js +24 -0
- package/src/closers.js +8 -1
- package/src/declaration.js +53 -3
- package/src/drafter.js +114 -33
- package/src/learn.js +1 -1
- package/src/learnstore.js +6 -6
- package/src/memo.js +120 -0
- package/src/model-step.js +89 -17
- package/src/pageask.js +9 -6
- package/src/pagedropwords.js +9 -0
- package/src/panel/author.js +31 -9
- package/src/panel/authorcard.js +51 -2
- package/src/panel/data.js +12 -7
- package/src/panel/index.html +137 -59
- package/src/panel/result.js +28 -7
- package/src/panel/server.js +2 -1
- package/src/pickrecord.js +146 -0
- package/src/plain-checks.js +1 -0
- package/src/provider.js +4 -1
- package/src/runfile.js +4 -2
- package/src/runner.js +82 -30
- package/src/send.js +71 -4
- package/src/setup.js +13 -1
- package/types/ask.d.ts +2 -1
- package/types/audit-fold.d.ts +13 -2
- package/types/authoring.d.ts +6 -2
- package/types/checked.d.ts +7 -2
- package/types/checkpick.d.ts +149 -0
- package/types/checkwords.d.ts +14 -0
- package/types/closers.d.ts +2 -1
- package/types/declaration.d.ts +9 -0
- package/types/drafter.d.ts +12 -25
- package/types/learn.d.ts +1 -0
- package/types/learnstore.d.ts +2 -3
- package/types/memo.d.ts +15 -0
- package/types/model-step.d.ts +5 -0
- package/types/pageask.d.ts +9 -2
- package/types/pagedropwords.d.ts +1 -0
- package/types/panel/author.d.ts +1 -1
- package/types/panel/authorcard.d.ts +41 -0
- package/types/panel/result.d.ts +9 -3
- package/types/pickrecord.d.ts +88 -0
- package/types/runfile.d.ts +7 -2
- package/types/runner.d.ts +16 -5
- package/types/send.d.ts +10 -2
- package/types/setup.d.ts +1 -56
- package/src/attemptdiff.js +0 -118
- package/types/attemptdiff.d.ts +0 -38
package/src/declaration.js
CHANGED
|
@@ -42,6 +42,7 @@ import { factPartReds } from './citedcheck.js';
|
|
|
42
42
|
import { numberRuleReds, countReds, citedWordReds } from './citedwords.js';
|
|
43
43
|
import { SHEET_RULES, MAX_SHEET_CHECKS, sheetCheckColumns, sheetCheckReds, sheetCheckWordReds, sheetNoClaimReds, sheetCoversReds } from './sheetchecks.js';
|
|
44
44
|
import { lineRules } from './pagebits.js';
|
|
45
|
+
import { OFFERED as OFFERED_RULES } from './checkwords.js';
|
|
45
46
|
import { isColumnChoiceRule } from './sheetoffer.js';
|
|
46
47
|
|
|
47
48
|
/** @typedef {import('./types.js').Arbiter} Arbiter */
|
|
@@ -217,9 +218,14 @@ function checkOwnKeys(obj, allowed, path, reds) {
|
|
|
217
218
|
export const SHAPE_KEYS = Object.freeze(['maxWords', 'sections', 'linesPerInvoice', 'mustCarry']);
|
|
218
219
|
|
|
219
220
|
/** Shape keys only the MACHINE sets (M4e amendment 15): read from the line's guardrail, never offered to the drafter's model. */
|
|
220
|
-
export const MACHINE_SHAPE_KEYS = Object.freeze(['wordsPerSection']);
|
|
221
|
+
export const MACHINE_SHAPE_KEYS = Object.freeze(['wordsPerSection', 'picked']);
|
|
221
222
|
|
|
222
223
|
const SHAPE_TYPE_CHECKS = Object.freeze({
|
|
224
|
+
// M10 am16: the checks the person picked, set by code (src/checkpick.js applyPicks), each one a bareguard rule with only that rule's own fields
|
|
225
|
+
picked: {
|
|
226
|
+
expected: 'a non-empty array of checks, each an object with a text rule of bareguard\'s list',
|
|
227
|
+
check: (v) => Array.isArray(v) && v.length > 0 && v.every((c) => isPlainObject(c) && typeof c.rule === 'string' && OFFERED_RULES.includes(c.rule)),
|
|
228
|
+
},
|
|
223
229
|
wordsPerSection: {
|
|
224
230
|
expected: 'a positive integer',
|
|
225
231
|
check: (v) => Number.isInteger(v) && v > 0,
|
|
@@ -377,6 +383,25 @@ export function guardrailWordNumbers(guardrail) {
|
|
|
377
383
|
return [...guardrail.matchAll(/(?<![\d,])(\d{1,3}(?:,\d{3})+|\d+)\s*words?\b(?!\s*(?:each|per\s+section)\b)/gi)].map((m) => readNumber(m[1]));
|
|
378
384
|
}
|
|
379
385
|
|
|
386
|
+
/** M10 amendment 14 item 2: every standalone number in a guardrail's own text (digits not joined to letters: "P1" and "250ish" are not one; "1,000" and "2.5" are one number each). */
|
|
387
|
+
export function guardrailStandaloneNumbers(guardrail) {
|
|
388
|
+
if (typeof guardrail !== 'string') return [];
|
|
389
|
+
return [...guardrail.matchAll(/(?<![A-Za-z0-9_.,])(\d{1,3}(?:,\d{3})+|\d+(?:\.\d+)?)(?![A-Za-z0-9_])/g)].map((m) => Number(m[1].replace(/,/g, '')));
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/** M10 amendment 14 item 1: the send line (a signed send) is where the accepted result is written out and no AI runs, so a guardrail under it is refused at $0, naming the line.
|
|
393
|
+
* Pure; the card (src/panel/authorcard.js checkCard) and the drafter's pre-flight both call it. @param {any[]} lines `parseSignedText`'s lines @param {{sends?: {line: number}[]}} arbiter */
|
|
394
|
+
export function checkSendLineGuardrail(lines, arbiter) {
|
|
395
|
+
const reds = [];
|
|
396
|
+
for (const s of Array.isArray(arbiter?.sends) ? arbiter.sends : []) {
|
|
397
|
+
const l = (Array.isArray(lines) ? lines : []).find((x) => x?.n === s.line);
|
|
398
|
+
if (l && typeof l.guardrail === 'string' && l.guardrail.trim() !== '') {
|
|
399
|
+
reds.push(`line ${s.line} is the send line (it writes out what you accepted at the Ask before it, and no AI runs there), so it cannot carry the guardrail "${l.guardrail.trim()}". Put the guardrail on the line that makes the result.`);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
return reds;
|
|
403
|
+
}
|
|
404
|
+
|
|
380
405
|
/** M4e amendment 15 item 1: the "<n> words each" / "<n> words per section" size in a guardrail ("about 250 words each", "250ish each" -> 250), or null. */
|
|
381
406
|
export function guardrailWordsPerSection(guardrail) {
|
|
382
407
|
const m = typeof guardrail === 'string' ? /(?<![\d,])(\d{1,3}(?:,\d{3})+|\d+)(?:\s*words?|ish(?:\s+words?)?)\s+(?:each|per\s+section)\b/i.exec(guardrail) : null;
|
|
@@ -464,7 +489,8 @@ export function checkShapeFitsJobLine(step, i, lines, reds) {
|
|
|
464
489
|
const wantPer = guardrailWordsPerSection(line?.guardrail);
|
|
465
490
|
if (shape.wordsPerSection !== undefined && shape.wordsPerSection !== wantPer) {
|
|
466
491
|
reds.push(`declaration: ${label} the check has wordsPerSection ${shape.wordsPerSection}; the guardrail says ${wantPer === null ? 'no size for each section' : `${wantPer} words each`} — change the guardrail on the card to change it`);
|
|
467
|
-
} else if (shape.wordsPerSection === undefined && wantPer !== null) {
|
|
492
|
+
} else if (shape.wordsPerSection === undefined && wantPer !== null && !Array.isArray(shape.picked)) {
|
|
493
|
+
// (a shape of picked checks, M10 am16, was kept by code and chosen by the person: the guardrail's size is a check only if it was picked)
|
|
468
494
|
reds.push(`declaration: ${label} the guardrail says ${wantPer} words each; the check has no wordsPerSection`);
|
|
469
495
|
}
|
|
470
496
|
// M4e amendment 16 C13: a size for each section needs the section names to be checked against.
|
|
@@ -625,6 +651,15 @@ function checkSheetKey(step, label, c, reds) {
|
|
|
625
651
|
for (const r of sheetCheckReds(list, step.fromLine, tables)) reds.push(r);
|
|
626
652
|
}
|
|
627
653
|
|
|
654
|
+
/** M10 am19: the tools that serve an input's kind (src/primitives.js rolePrimitiveFor): a page or ticket is frozen as text. */
|
|
655
|
+
function inputReachVerbs(source) {
|
|
656
|
+
if (source?.kind === 'page') return ['read', 'grep'];
|
|
657
|
+
const p = String(source?.path ?? '').toLowerCase();
|
|
658
|
+
if (p.endsWith('.docx')) return ['readDocx'];
|
|
659
|
+
if (isCellsPath(source?.path)) return ['addressCells'];
|
|
660
|
+
return ['read', 'grep'];
|
|
661
|
+
}
|
|
662
|
+
|
|
628
663
|
/**
|
|
629
664
|
* Validate a drafter declaration against the M1 closed schema. `arbiter`
|
|
630
665
|
* and `lines` are `parseSignedText`'s output; `catalogue` is a plain array
|
|
@@ -890,7 +925,9 @@ export function validateDeclaration(declaration, context = {}) {
|
|
|
890
925
|
if (cellsRoles.includes(readId) && !declaredEmits.has(readId)) continue; // an input with cells, frozen at run start (M4d amendment 8)
|
|
891
926
|
if (pageRoles.includes(readId) && !declaredEmits.has(readId)) continue; // a web page, frozen at run start (M10 am7 item 3)
|
|
892
927
|
if (docRoles.includes(readId) && !declaredEmits.has(readId) && step.close?.cited?.source === readId) continue; // a document the step quotes (M10 piece 5)
|
|
893
|
-
if (readId
|
|
928
|
+
if (docRoles.includes(readId) && !declaredEmits.has(readId)) {
|
|
929
|
+
reds.push(`declaration: ${label} reads document input "${readId}" — leave it out of reads and grant "read" ("readDocx" for .docx); only a step that quotes it lists it`);
|
|
930
|
+
} else if (readId === emits || !declaredEmits.has(readId)) {
|
|
894
931
|
reds.push(`declaration: ${label} reads artifact "${readId}" that no earlier step declared`);
|
|
895
932
|
}
|
|
896
933
|
}
|
|
@@ -1162,6 +1199,19 @@ export function validateDeclaration(declaration, context = {}) {
|
|
|
1162
1199
|
}
|
|
1163
1200
|
}
|
|
1164
1201
|
|
|
1202
|
+
// --- check 7 (M10 am19): every input must be reachable by a model step (not an ask step, not the send step).
|
|
1203
|
+
// Ruling A, hamr 2026-11-04: md/txt/page/ticket -> read or grep; docx -> readDocx; a sheet -> addressCells; or the role in the step's `reads`.
|
|
1204
|
+
// `picks` / `inputFacts` name headings only and are not a grant. Plan-fit check: draft, revise and sign turn `fitJobLine` on; signed flows keep running.
|
|
1205
|
+
if (fitJobLine === true) {
|
|
1206
|
+
const modelSteps = stepInfo.filter((st) => st.fromLine === null || (!askLines.includes(st.fromLine) && !sendLines.includes(st.fromLine)));
|
|
1207
|
+
for (const s of Array.isArray(safeArbiter.sources) ? safeArbiter.sources : []) {
|
|
1208
|
+
const verbs = inputReachVerbs(s);
|
|
1209
|
+
if (!modelSteps.some((st) => st.reads.includes(s.role) || st.primitives.some((v) => verbs.includes(v)))) {
|
|
1210
|
+
reds.push(`Input "${s.role}" is read by no step.`);
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
|
|
1165
1215
|
if (reds.length > 0) return deepFreeze({ ok: false, reds });
|
|
1166
1216
|
|
|
1167
1217
|
const classes = {};
|
package/src/drafter.js
CHANGED
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
import { Loop, HaltError } from 'bare-agent';
|
|
19
19
|
import { capTooSmallText, usdText } from './draftspend.js';
|
|
20
20
|
import { parseSignedText, unsignedAskTtls } from './signed-text.js';
|
|
21
|
-
import { validateDeclaration,
|
|
21
|
+
import { validateDeclaration, checkGuardrailSums, checkSendLineGuardrail } from './declaration.js';
|
|
22
22
|
import { loadCatalogue } from './catalogue.js';
|
|
23
23
|
import { findMcpPlanRed } from './canrun.js';
|
|
24
24
|
import { WIRED_VERBS, wiredMenu } from './primitives.js';
|
|
@@ -28,7 +28,11 @@ import { freezePage } from './runner.js';
|
|
|
28
28
|
import { removeFrozenPages } from './flow.js';
|
|
29
29
|
import { lookAtPage, pageInfoLines } from './pagelook.js';
|
|
30
30
|
import { lookAtSheet, sheetPrompt } from './sheetlook.js';
|
|
31
|
-
import { leftRuleLine, dropRows, dropLine } from './pagedropwords.js';
|
|
31
|
+
import { leftRuleLine, dropRows, dropLine, dropSentence, pickNoteLine } from './pagedropwords.js';
|
|
32
|
+
import {
|
|
33
|
+
scopedRules, rowsFromAnswer, checkAsks, settleRules, applyPicks, SUGGEST_SYSTEM, SUGGEST_TOOL, SUGGEST_SCHEMA, suggestUserText,
|
|
34
|
+
} from './checkpick.js';
|
|
35
|
+
import { matchRecord, entriesFromAnswers, sameWords, KEPT_WORDS } from './pickrecord.js';
|
|
32
36
|
import { MAP_SYSTEM, mapPrompt } from './pagemap.js';
|
|
33
37
|
import { askableFromLook, tooManyAsksText, MAX_LOOK_ASKS } from './pageask.js';
|
|
34
38
|
import { lineRules } from './pagebits.js';
|
|
@@ -121,13 +125,6 @@ const CITED_PROP = Object.freeze({
|
|
|
121
125
|
additionalProperties: false,
|
|
122
126
|
});
|
|
123
127
|
|
|
124
|
-
const SHAPE_PROPS = Object.freeze({
|
|
125
|
-
maxWords: { type: 'integer', minimum: 1, description: `the whole output's word ceiling; ${WHOLE_OUTPUT_CEILING_RULE}` },
|
|
126
|
-
sections: { type: 'array', minItems: 1, items: { type: 'string', minLength: 1 }, description: 'required section headings, in order' },
|
|
127
|
-
linesPerInvoice: { type: 'integer', minimum: 1, description: 'lines the output must carry per invoice' },
|
|
128
|
-
mustCarry: { type: 'array', minItems: 1, items: { type: 'string', minLength: 1 }, description: 'named fields every line must carry' },
|
|
129
|
-
});
|
|
130
|
-
|
|
131
128
|
/**
|
|
132
129
|
* 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
|
|
133
130
|
* `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.
|
|
@@ -137,11 +134,6 @@ const SHAPE_PROPS = Object.freeze({
|
|
|
137
134
|
export function buildDeclarationSchema(menu, { sheets, ticket } = {}) {
|
|
138
135
|
const sheetProp = sheets ? sheetChecksProp(sheets) : null;
|
|
139
136
|
const ticketParts = ticket ? ticketSchemaParts(ticket) : null;
|
|
140
|
-
const shapeProps = {};
|
|
141
|
-
for (const key of SHAPE_KEYS) {
|
|
142
|
-
if (!SHAPE_PROPS[key]) throw new Error(`schema: SHAPE_KEYS gained "${key}" — add its type to SHAPE_PROPS`);
|
|
143
|
-
shapeProps[key] = SHAPE_PROPS[key];
|
|
144
|
-
}
|
|
145
137
|
return {
|
|
146
138
|
type: 'object',
|
|
147
139
|
properties: {
|
|
@@ -157,7 +149,7 @@ export function buildDeclarationSchema(menu, { sheets, ticket } = {}) {
|
|
|
157
149
|
description: 'verbs this step is granted, from the menu only; [] for a pure stop',
|
|
158
150
|
},
|
|
159
151
|
...(ticketParts ? ticketParts.step : {}),
|
|
160
|
-
reads: { type: 'array', items: { type: 'string' }, description: 'artifact ids emitted by EARLIER steps only (an ask step lists the earlier output to be checked FIRST), or the role of a CSV input (a step whose line has a green guardrail must list a CSV input role here)' },
|
|
152
|
+
reads: { type: 'array', items: { type: 'string' }, description: 'artifact ids emitted by EARLIER steps only (an ask step lists the earlier output to be checked FIRST), or the role of a CSV input (a step whose line has a green guardrail must list a CSV input role here); never a .docx/.md/.txt input role unless the step quotes it (close.cited.source), otherwise grant read/readDocx instead' },
|
|
161
153
|
emits: { type: 'string', minLength: 1, description: 'the ONE new artifact id this step declares (unique)' },
|
|
162
154
|
fromLine: { type: ['integer', 'null'], description: 'the ONE numbered job line this step serves' },
|
|
163
155
|
picks: {
|
|
@@ -169,12 +161,6 @@ export function buildDeclarationSchema(menu, { sheets, ticket } = {}) {
|
|
|
169
161
|
type: 'object',
|
|
170
162
|
properties: {
|
|
171
163
|
class: { type: 'string', enum: [...CLASSES], description: "MUST equal the class of fromLine's guardrail in guardrailClasses; hitl when that line has no guardrail" },
|
|
172
|
-
shape: {
|
|
173
|
-
type: 'object',
|
|
174
|
-
properties: shapeProps,
|
|
175
|
-
additionalProperties: false,
|
|
176
|
-
description: `only when class is softgreen; keys limited to ${SHAPE_KEYS.join(', ')}`,
|
|
177
|
-
},
|
|
178
164
|
cited: CITED_PROP,
|
|
179
165
|
columns: COLUMNS_PROP,
|
|
180
166
|
...(sheetProp ? { sheet: sheetProp } : {}),
|
|
@@ -324,6 +310,9 @@ function greenReadRule(sources) {
|
|
|
324
310
|
const out = [csvRoles.length
|
|
325
311
|
? `${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.`
|
|
326
312
|
: `${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)' : ''}.`];
|
|
313
|
+
if (docRoles.length) {
|
|
314
|
+
out.push(`- A document input (${docRoles.join(', ')}) is never listed in reads by a step that does not quote it (only a green step with close.cited.source = that role lists it). A step that needs the document is granted "read" ("readDocx" for a .docx) and reads it by its role through that tool; its reads stay empty or hold only earlier outputs.`);
|
|
315
|
+
}
|
|
327
316
|
if (csvRoles.length) out.push(...sheetOfferRules(csvRoles)); // M10b piece 3: close.sheet and every rule the validator enforces on it
|
|
328
317
|
if (pageRoles.length || docRoles.length) {
|
|
329
318
|
out.push(
|
|
@@ -379,7 +368,8 @@ export function buildSystemPrompt({ menu, lines, arbiter, factsInfo }) {
|
|
|
379
368
|
'- 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".',
|
|
380
369
|
'- 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.',
|
|
381
370
|
...greenReadRule(arbiter.sources),
|
|
382
|
-
'-
|
|
371
|
+
'- You write no check. A shape guardrail (a word count, a list size, headings) is settled before you draft: the human picks each check from a list and code puts the picked checks in the plan, so there is no close.shape for you to write. Still answer close.class and guardrailClasses as above; code sets the class of a line whose guardrail it settled from what the human picked.',
|
|
372
|
+
'- The send line (the last line, when a Destination is set) writes out what the human accepted; it has no guardrail and no check of its own.',
|
|
383
373
|
'- A step whose check reads its reply (softgreen) answers in its reply text and is never granted `write`, `edit` or any other write-class verb; only the send step at the end writes files out.',
|
|
384
374
|
`- Signed ask line(s): ${askLines.length ? askLines.join(', ') : 'none'}. For each, emit EXACTLY ONE step: fromLine = that line, close.class "hitl", primitives []. It is a stop only — never grant a primitive on it, and never emit a pause at any other line.`,
|
|
385
375
|
`- Signed send line(s): ${sendLines.length ? sendLines.join(', ') : 'none'}. That step is drafted like any other: grant the write primitive and read the artifact of the ask step that comes before it. Its target and position are signed, not yours.`,
|
|
@@ -434,6 +424,9 @@ export async function draft({
|
|
|
434
424
|
proseText, slot, model, provider: injected, rates: injectedRates, modelId: injectedModelId, env,
|
|
435
425
|
priorSpend = /** @type {((ceilingUsd: number) => number)|null} */ (null), skills = DRAFT_SKILLS, makeProviderFn = makeProvider, onBook, offerQuestions = true, draftThinking = /** @type {'on'|'off'} */ ('off'),
|
|
436
426
|
draftDir = /** @type {string|null} */ (null), fetchPage = undefined, leftRules = /** @type {{line: number, rule: number}[]} */ ([]),
|
|
427
|
+
checkPicks = /** @type {import('./checkpick.js').Pick[]} */ ([]),
|
|
428
|
+
// M10 am17/am18: the picks of the plan this one follows (src/pickrecord.js entries), and a callback that is handed this draft's record (kept + newly answered) for the one writer
|
|
429
|
+
carriedPicks = /** @type {import('./pickrecord.js').Entry[]} */ ([]), onPickRecord = /** @type {((r: {picks: import('./pickrecord.js').Entry[], kept: {line: number, rule: number, ruleText: string, check: Record<string, any>|null}[]}) => void)|null} */ (null),
|
|
437
430
|
learnHints = /** @type {{text: string, ids: string[]}|null} */ (null),
|
|
438
431
|
mcpServers = /** @type {string[]|undefined} */ (undefined),
|
|
439
432
|
// M13 piece 4: the job's flow type and its MCP pick (`mcpPickFor`: `{ok, server, tools}`), both set by code from the card; the drafter is told them, never asked for them
|
|
@@ -459,6 +452,9 @@ export async function draft({
|
|
|
459
452
|
// M4e amendment 15 item 2: a guardrail that fights itself on words is red at $0, before any provider is built or called.
|
|
460
453
|
const sumReds = checkGuardrailSums(lines);
|
|
461
454
|
if (sumReds.length) return fail(sumReds);
|
|
455
|
+
// M10 amendment 14 item 1: a guardrail on the send line is refused at $0 (the card says it first; a prose file straight to `fwdloop draft` is caught here).
|
|
456
|
+
const sendReds = checkSendLineGuardrail(lines, arbiter);
|
|
457
|
+
if (sendReds.length) return fail(sendReds);
|
|
462
458
|
const menu = wiredMenu(skills);
|
|
463
459
|
// The file inputs are read first, at $0, before a provider is built (a page input is fetched only after the price and cap gates, below).
|
|
464
460
|
const fileFacts = readInputFacts((arbiter.sources ?? []).filter((s) => s.kind !== 'page'));
|
|
@@ -509,6 +505,14 @@ export async function draft({
|
|
|
509
505
|
inFlight, calls, unmetered, metered: sumMeterings(meterings), modelId, price: priceRecord(prices, rates),
|
|
510
506
|
});
|
|
511
507
|
|
|
508
|
+
/** the result of a draft that stops before any drafting round with what it spent so far (a provider red, the budget); one literal for every such stop */
|
|
509
|
+
const earlyStop = (/** @type {string[]} */ reds, /** @type {string} */ why) => {
|
|
510
|
+
const m = sumMeterings(meterings);
|
|
511
|
+
return {
|
|
512
|
+
ok: false, declaration: null, reds, rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, price: priceRecord(prices, rates), tokens: m.tokens, structureRetries: 0, revisions: 0, stop: why, log, thinking: thinkingOf(), inputs: facts.list, questions: [], droppedQuestions: [], notChecked: [], ...pageExtras,
|
|
513
|
+
};
|
|
514
|
+
};
|
|
515
|
+
|
|
512
516
|
// M10 item 1: a web page input is fetched once and frozen into the DRAFT folder (the drafting copy). A run freezes its own copy at its own start
|
|
513
517
|
// (`freezeInputs`), so a run is never checked against this one. Only now, after the $0 price and cap gates: a draft refused for money fetches nothing.
|
|
514
518
|
const pageSources = (arbiter.sources ?? []).filter((s) => s.kind === 'page' && !ticketSources.includes(s));
|
|
@@ -650,26 +654,103 @@ export async function draft({
|
|
|
650
654
|
);
|
|
651
655
|
}
|
|
652
656
|
if (sheetLooks.length) pageExtras.sheetLooks = sheetLooks; // kept beside the page looks (src/authoring.js writes both into page-look.json)
|
|
657
|
+
// M10 am16 (1): ONE suggestion call, only when a guardrail on a step line is one this call settles (scope by code, src/checkpick.js). It suggests a check from bareguard's own list
|
|
658
|
+
// per guardrail, or none; code keeps what passes keep-or-drop. The call is metered, held and booked as a drafting round (the same `meterings`). The redraft after the answers
|
|
659
|
+
// (offerQuestions false) makes no call: it settles every rule against the person's picks instead.
|
|
660
|
+
// a rule a kept page or sheet fact already serves (the look tied it: line + rule number) is settled by that fact and is not asked here
|
|
661
|
+
const shapeRules = scopedRules(lines, arbiter).filter((r) => ![...look.facts, ...sheetFacts].some((f) => f.line === r.line && f.forRule === r.rule));
|
|
662
|
+
// M10 am17/am18: a guardrail whose pick is kept from the last draft skips the suggestion call and the asks; only the rest is suggested and asked. The model never sees a pick.
|
|
663
|
+
const carried = matchRecord(carriedPicks, lines, shapeRules);
|
|
664
|
+
const keptView = carried.kept.map((k) => ({ line: k.line, rule: k.rule, ruleText: k.entry.ruleText, check: k.entry.check, added: k.entry.added, left: k.entry.left }));
|
|
665
|
+
onPickRecord?.({ picks: carried.kept.map((k) => k.entry), kept: keptView });
|
|
666
|
+
const askRules = carried.askRules;
|
|
667
|
+
/** @type {ReturnType<typeof checkAsks>} */
|
|
668
|
+
let shapeAsks = [];
|
|
669
|
+
if (askRules.length && offerQuestions) {
|
|
670
|
+
const content = suggestUserText(lines, askRules);
|
|
671
|
+
let args = null;
|
|
672
|
+
for (let attempt = 1; attempt <= 2 && args === null; attempt += 1) {
|
|
673
|
+
const spentBefore = meterings.reduce((sum, ev) => sum + (ev.costUsd ?? roundCeiling), 0);
|
|
674
|
+
if (spentBefore + ceilingCostUsd(rates, SUGGEST_SYSTEM.length + content.length + JSON.stringify(SUGGEST_SCHEMA).length) > budgetUsd) {
|
|
675
|
+
if (meterings.length === 0 && calls === 0) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); return fail([tooSmall(roundCeiling)]); }
|
|
676
|
+
return earlyStop(['the draft budget is spent'], 'budget');
|
|
677
|
+
}
|
|
678
|
+
/** @type {any} */
|
|
679
|
+
let captured;
|
|
680
|
+
const roundEvents = [];
|
|
681
|
+
const tool = { name: SUGGEST_TOOL, description: 'Suggest one check (or none) per guardrail.', parameters: SUGGEST_SCHEMA, execute: async (/** @type {any} */ a) => { captured = a; throw new HaltError('suggestion captured', { rule: 'captured' }); } };
|
|
682
|
+
const suggestLoop = new Loop({ provider, rates, onLlmResult: async (ev) => { roundEvents.push(ev); meterings.push(ev); } });
|
|
683
|
+
calls += 1;
|
|
684
|
+
book(true);
|
|
685
|
+
let res;
|
|
686
|
+
let threw = null;
|
|
687
|
+
try {
|
|
688
|
+
// thinking is off: on cannot combine with a forced tool call (the answer is one typed call, there is nothing to think through)
|
|
689
|
+
res = await suggestLoop.run([{ role: 'system', content: SUGGEST_SYSTEM }, { role: 'user', content }], [tool], { maxTokens: DRAFT_MAX_TOKENS, thinkingMode: 'off', toolChoice: { name: SUGGEST_TOOL } });
|
|
690
|
+
} catch (err) {
|
|
691
|
+
threw = err;
|
|
692
|
+
if (roundEvents.length === 0) unmetered += 1;
|
|
693
|
+
}
|
|
694
|
+
book(false);
|
|
695
|
+
const entry = /** @type {Record<string, any>} */ ({ round: log.length + 1, kind: 'check-suggest' });
|
|
696
|
+
if (res?.thinkingApplied !== undefined) entry.thinkingApplied = res.thinkingApplied;
|
|
697
|
+
if (res?.thinkingStatus !== undefined) entry.thinkingStatus = res.thinkingStatus;
|
|
698
|
+
if (threw && !(isPlainObject(captured) && threw instanceof HaltError)) {
|
|
699
|
+
entry.outcome = `provider-red: ${threw.message}`;
|
|
700
|
+
log.push(entry);
|
|
701
|
+
return earlyStop([`provider-red: ${threw.message}`], 'provider-red');
|
|
702
|
+
}
|
|
703
|
+
if (!isPlainObject(captured)) {
|
|
704
|
+
// the raw answer is kept (log.json), the cut-off said out loud; one more try, then every guardrail is "I can't check this" (never a guessed check)
|
|
705
|
+
entry.outcome = res?.stopReason === 'max_tokens' ? 'structure: truncated: the round hit the output cap with no completed tool call' : 'structure: no usable tool call (text instead of the tool)';
|
|
706
|
+
const malformed = provider?.lastMalformedToolCall ?? null;
|
|
707
|
+
if (typeof malformed?.rawArguments === 'string') entry.rawArguments = malformed.rawArguments;
|
|
708
|
+
else if (typeof res?.text === 'string' && res.text !== '') entry.rawText = res.text;
|
|
709
|
+
log.push(entry);
|
|
710
|
+
continue;
|
|
711
|
+
}
|
|
712
|
+
entry.outcome = 'answered';
|
|
713
|
+
entry.args = captured;
|
|
714
|
+
log.push(entry);
|
|
715
|
+
args = captured;
|
|
716
|
+
}
|
|
717
|
+
shapeAsks = checkAsks(rowsFromAnswer(askRules, args));
|
|
718
|
+
}
|
|
653
719
|
// M10 piece 3 (item 4, am1, am2): CODE decides the early asks from the look, after the one map call and BEFORE any drafting round. A signed ask line's own
|
|
654
720
|
// guardrail is a human stop, not a page check, so it is not asked. More than MAX_LOOK_ASKS is a job to rewrite: nothing is asked, nothing more is spent.
|
|
655
721
|
// The redraft after the answers (offerQuestions false) never asks. A sheet's offers are reading asks: they come first with the page's, in line order.
|
|
656
|
-
if ((pageSources.length || sheetAsks.length) && offerQuestions) {
|
|
722
|
+
if ((pageSources.length || sheetAsks.length || shapeAsks.length) && offerQuestions) {
|
|
657
723
|
const pageAsks = pageSources.length ? askableFromLook({ facts: [...look.facts, ...sheetFacts] }, jobLines.filter((l) => !askLines.has(l.n))) : [];
|
|
658
|
-
const
|
|
724
|
+
const lookAsks = [...[...pageAsks.filter((a) => a.ask === 'reading'), ...sheetAsks].sort((a, b) => a.line - b.line), ...pageAsks.filter((a) => a.ask !== 'reading')];
|
|
725
|
+
// am16 (3): a shape guardrail's ask follows, in line order. (5): a proposal is not an ask under am1; only a `can't check` ask counts toward the cap (the 4th stops drafting at $0).
|
|
726
|
+
const asks = [...lookAsks, ...shapeAsks];
|
|
659
727
|
if (asks.length > 0) {
|
|
660
728
|
const m = sumMeterings(meterings);
|
|
661
729
|
const spent = m.costUsd === null || unmetered > 0 ? (m.costUsd === null ? 'unknown' : `at least ${usdText(m.costUsd)}`) : usdText(m.costUsd);
|
|
662
|
-
const
|
|
730
|
+
const counted = [...lookAsks, ...shapeAsks.filter((a) => a.counted).map((a) => ({ ...a, reading: "I can't check this" }))];
|
|
731
|
+
const tooMany = counted.length > MAX_LOOK_ASKS;
|
|
663
732
|
if (tooMany && pageSources.length) removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); // a refused draft keeps no page copy
|
|
664
733
|
return {
|
|
665
|
-
ok: false, declaration: null, reds: tooMany ? [`${tooManyAsksText(
|
|
734
|
+
ok: false, declaration: null, reds: tooMany ? [`${tooManyAsksText(counted)} Spent so far: ${spent}.`] : [], rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, price: priceRecord(prices, rates), tokens: m.tokens, structureRetries: 0, revisions: 0, stop: tooMany ? 'look-asks-too-many' : 'look-asks', log, thinking: thinkingOf(), inputs: facts.list,
|
|
666
735
|
questions: tooMany ? [] : asks.map((a) => ({
|
|
667
|
-
line: a.line, question: a.question, source: a.source, ask: a.ask, ruleNo: a.rule, ruleText: a.ruleText, proposal: a.reading ?? null,
|
|
736
|
+
line: a.line, question: a.question, source: a.source, ask: a.ask, ruleNo: a.rule, ruleText: a.ruleText, proposal: a.reading ?? null, ...('check' in a && a.check ? { check: a.check } : {}), ...('pairRule' in a && typeof a.pairRule === 'number' ? { pairRule: a.pairRule } : {}),
|
|
668
737
|
})),
|
|
669
738
|
droppedQuestions: [], notChecked: pageNotChecked, ...pageExtras,
|
|
670
739
|
};
|
|
671
740
|
}
|
|
672
741
|
}
|
|
742
|
+
// M10 am16 (4, 5): the plan carries only the checks the person picked. Every shape rule this call settles is either checked by a pick or Not checked with its reason
|
|
743
|
+
// (shown on the plan card and carried as `unjudgeable`); the drafter writes no check of its own, whatever it sends is overwritten below.
|
|
744
|
+
const allPicks = [...checkPicks, ...carried.picks];
|
|
745
|
+
const allLeft = [...leftRules, ...carried.left];
|
|
746
|
+
const settled = shapeRules.length ? settleRules(shapeRules, allPicks, allLeft) : null;
|
|
747
|
+
// the record this draft hands on: what it kept plus what the person just answered (numbered on this card)
|
|
748
|
+
onPickRecord?.({ picks: [...carried.kept.map((k) => k.entry), ...entriesFromAnswers(lines, shapeRules, checkPicks, leftRules)], kept: keptView });
|
|
749
|
+
const keptNote = (/** @type {{line: number, rule: number, text: string}} */ n) => (carried.kept.some((k) => k.line === n.line && (k.rule === n.rule || (k.entry.added !== null && sameWords(k.entry.added, n.text)))) ? ` (${KEPT_WORDS})` : '');
|
|
750
|
+
for (const n of settled?.notes ?? []) {
|
|
751
|
+
const line = (n.reason === 'person-left' ? leftRuleLine(n.text) : pickNoteLine(n.text, n.reason)) + keptNote(n);
|
|
752
|
+
if (!pageNotChecked.includes(line)) pageNotChecked.push(line);
|
|
753
|
+
}
|
|
673
754
|
// The page lines go on the drafter's list of inputs: the first line of a page's block replaces the plain line readInputFacts wrote for it.
|
|
674
755
|
const factsBase = pageInfo.length ? [...facts.info.filter((l) => !pageSources.some((s) => l.startsWith(`- ${s.role}: a web page`))), ...pageInfo] : facts.info;
|
|
675
756
|
const factsInfo = [...factsBase, ...ticketSources.flatMap((s) => ticketFactsLines(s.role)), ...(flowType === 'mcp' ? mcpFactsLines(mcp.server, mcp.tools) : [])];
|
|
@@ -792,16 +873,16 @@ export async function draft({
|
|
|
792
873
|
if (Array.isArray(declaration.steps)) {
|
|
793
874
|
declaration.steps = declaration.steps.map((st) => (isPlainObject(st) ? { ...st, goal: goalForLine(st.fromLine, lines) } : st));
|
|
794
875
|
}
|
|
795
|
-
//
|
|
796
|
-
// (or dropped when the guardrail gives none), so it can never differ from the guardrail.
|
|
876
|
+
// M10 am16 (4): the drafter writes no check. Whatever `close.shape` it sent (the schema offers none) is dropped here; a check reaches the plan only from the person's picks (applyPicks, next).
|
|
797
877
|
if (Array.isArray(declaration.steps)) {
|
|
798
878
|
declaration.steps = declaration.steps.map((st) => {
|
|
799
|
-
if (!isPlainObject(st) || !isPlainObject(st.close) ||
|
|
800
|
-
const {
|
|
801
|
-
|
|
802
|
-
return { ...st, close: { ...st.close, shape: per === null ? shape : { ...shape, wordsPerSection: per } } };
|
|
879
|
+
if (!isPlainObject(st) || !isPlainObject(st.close) || st.close.shape === undefined) return st;
|
|
880
|
+
const { shape: _drop, ...close } = st.close;
|
|
881
|
+
return { ...st, close };
|
|
803
882
|
});
|
|
804
883
|
}
|
|
884
|
+
// M10 am16 (4): code sets the check of every line it settled, from the picks only; the drafter's own `close.shape` and class for such a line are gone
|
|
885
|
+
if (settled) Object.assign(declaration, applyPicks(declaration, shapeRules, settled, (n) => dropSentence({ line: n.line, fact: '', reason: n.reason })));
|
|
805
886
|
// 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
|
|
806
887
|
const verdict1 = validateDeclaration(declaration, {
|
|
807
888
|
arbiter, lines, catalogue: validationCatalogue, wired: WIRED_VERBS, verbatimGoals: true, fitJobLine: true,
|
package/src/learn.js
CHANGED
|
@@ -234,7 +234,7 @@ export function cardKey(c) {
|
|
|
234
234
|
}
|
|
235
235
|
|
|
236
236
|
/** the check name inside a gap text */
|
|
237
|
-
const nameOf = (/** @type {string} */ g) => (g.match(/check "([^"]+)"/)?.[1] ?? g.match(/close stage "([^"]+)"/)?.[1] ?? 'close');
|
|
237
|
+
export const nameOf = (/** @type {string} */ g) => (g.match(/check "([^"]+)"/)?.[1] ?? g.match(/close stage "([^"]+)"/)?.[1] ?? 'close');
|
|
238
238
|
const CODE = /\bTS\d+\b|\[[a-z][a-z-]+\]|\bE[A-Z]{2,}\b|\bERR_[A-Z_0-9]+\b/g;
|
|
239
239
|
|
|
240
240
|
/**
|
package/src/learnstore.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// borrowed-from: bareloop src/learnstore.js@v0.47.0 (66dc2b0)
|
|
2
|
-
// Adaptations: M8 item 3: the ledger home is fwdloop's configHome() (src/config.js) in place of bareloop's keysHome, so the file is <configHome>/learn/ledger.json (mode 600, as bareloop); with no explicit home under a test process and no FWDLOOP_CONFIG_HOME, ledgerPath throws, so a test can never reach the real ~/.config/fwdloop; hintsForRun is copied at the bottom (M8 item 5a) with a ledger problem THROWN (the caller records why and hands nothing), and with `path.resolve` for the place in place of bareloop's realpathSync (the F48 guard keeps realpathSync out of this file), the same place learnAtRunEnd records; stageQuestionsByName is not copied (see learnAtRunEnd: a card's `meaning` is the failing check's own text from the run's diary.jsonl); learnAtRunEnd reads fwdloop's run folder through eventsOfRun (adapted from fwdloop poc/learn/adapter.mjs, F79) because fwdloop has no bareloop spine; imports trimmed to match. F83 bug 2: learnAtRunEnd (the one run-end and seed path) folds with specHash null, so a lesson matches by workflow name alone, the same as the read side (M8 am7 item 1; a redraft's new plan hash no longer opens a new row)
|
|
2
|
+
// Adaptations: M8 item 3: the ledger home is fwdloop's configHome() (src/config.js) in place of bareloop's keysHome, so the file is <configHome>/learn/ledger.json (mode 600, as bareloop); with no explicit home under a test process and no FWDLOOP_CONFIG_HOME, ledgerPath throws, so a test can never reach the real ~/.config/fwdloop; hintsForRun is copied at the bottom (M8 item 5a) with a ledger problem THROWN (the caller records why and hands nothing), and with `path.resolve` for the place in place of bareloop's realpathSync (the F48 guard keeps realpathSync out of this file), the same place learnAtRunEnd records; stageQuestionsByName is not copied (see learnAtRunEnd: a card's `meaning` is the failing check's own text from the run's diary.jsonl); learnAtRunEnd reads fwdloop's run folder through eventsOfRun (adapted from fwdloop poc/learn/adapter.mjs, F79) because fwdloop has no bareloop spine; imports trimmed to match. F83 bug 2: learnAtRunEnd (the one run-end and seed path) folds with specHash null, so a lesson matches by workflow name alone, the same as the read side (M8 am7 item 1; a redraft's new plan hash no longer opens a new row). Nothing else changed. Known gap, kept on purpose (M8 item 7): foldRunIntoLedger and releaseRun read, change and replace the file, so two runs ending together can lose a note.
|
|
3
3
|
// The thin reader/writer around src/learn.js (cross-run learnings, ITEM33-BUILD.md rev 2). All file IO lives here and
|
|
4
4
|
// the pure rules live in learn.js; nothing in either file can reach a model.
|
|
5
5
|
//
|
|
@@ -263,10 +263,10 @@ export function eventsOfRun(runDir, workflow) {
|
|
|
263
263
|
* with a signed ask included; there is no hold. It runs whether `learningHints` is on or off. `questions` (bareloop's stageQuestionsByName) is, here, the failing check's own text from
|
|
264
264
|
* the run's diary.jsonl, so a check with no checks row there (a run from before am29) has no `meaning`.
|
|
265
265
|
* Borrowed-from: bareloop src/learnstore.js@v0.47.0:124 (learnAtRunEnd).
|
|
266
|
-
* @param {{home?: string, workflow: string, runId: string, runDir: string,
|
|
266
|
+
* @param {{home?: string, workflow: string, runId: string, runDir: string, now?: Date}} o
|
|
267
267
|
* @returns {{wrote: boolean, counted: number, held: number, problem: string|null, noise: string|null, cards: number}}
|
|
268
268
|
*/
|
|
269
|
-
export function learnAtRunEnd({ home, workflow, runId, runDir,
|
|
269
|
+
export function learnAtRunEnd({ home, workflow, runId, runDir, now = new Date() }) {
|
|
270
270
|
const rec = eventsOfRun(runDir, workflow);
|
|
271
271
|
if (!rec) return { wrote: false, counted: 0, held: 0, problem: null, noise: 'no-tries', cards: 0 };
|
|
272
272
|
const runid = `${workflow}/${runId}`;
|
|
@@ -296,7 +296,7 @@ export function seedLedger({ root, home }) {
|
|
|
296
296
|
if (door.skip) return { ...out, skippedNoDoor: true };
|
|
297
297
|
home = door.home;
|
|
298
298
|
}
|
|
299
|
-
/** @type {{workflow: string, runId: string, runDir: string, end: Date
|
|
299
|
+
/** @type {{workflow: string, runId: string, runDir: string, end: Date}[]} */
|
|
300
300
|
const todo = [];
|
|
301
301
|
for (const workflow of listFlowNames(root)) {
|
|
302
302
|
const flowDir = join(root, workflow);
|
|
@@ -313,7 +313,7 @@ export function seedLedger({ root, home }) {
|
|
|
313
313
|
const endRow = history.findLast((r) => r?.runId === runId && !NOT_A_RUN_END.has(r.outcome) && Number.isFinite(Date.parse(r.at)));
|
|
314
314
|
if (!endRow) { out.skipped['no-end'] += 1; continue; }
|
|
315
315
|
if (!log) { out.skipped.unreadable += 1; continue; }
|
|
316
|
-
todo.push({ workflow, runId, runDir, end: new Date(endRow.at)
|
|
316
|
+
todo.push({ workflow, runId, runDir, end: new Date(endRow.at) });
|
|
317
317
|
} catch { out.skipped.unreadable += 1; }
|
|
318
318
|
}
|
|
319
319
|
}
|
|
@@ -323,7 +323,7 @@ export function seedLedger({ root, home }) {
|
|
|
323
323
|
if (cur.problem) { out.problem = cur.problem; return out; }
|
|
324
324
|
if (Object.hasOwn(cur.ledger.health, `${t.workflow}/${t.runId}`)) { out.skipped['already-in'] += 1; continue; }
|
|
325
325
|
try {
|
|
326
|
-
const r = learnAtRunEnd({ home, workflow: t.workflow, runId: t.runId, runDir: t.runDir,
|
|
326
|
+
const r = learnAtRunEnd({ home, workflow: t.workflow, runId: t.runId, runDir: t.runDir, now: t.end });
|
|
327
327
|
if (r.problem) { out.problem = r.problem; return out; }
|
|
328
328
|
if (r.noise) out.skipped.noise += 1;
|
|
329
329
|
else out.added += r.counted;
|
package/src/memo.js
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
// M14 items 1-6 (docs/wiki/the-module-ladder.md, "M14 — memory improvements", and "M14 amendment 1" item 2): the carry memo, "what happened so far in this run".
|
|
2
|
+
// Plain code, no AI, built fresh before each model try from the run's OWN files only: audit.jsonl (the tries and how each ended), the consumed answers and
|
|
3
|
+
// `asks/<id>.json` (the human's words, by `listArchivedAsks`), `job/declaration.json` (step order) and `run.json`'s `rerun` section. It writes nothing: the exact
|
|
4
|
+
// text a try was handed is kept by that try's audit row (`memoText`, runner.js `makeAuditRow`), so no new run-folder file. Pure over those files, so it survives a
|
|
5
|
+
// pause, a resume and a restart. It never carries money or time (no cost, no duration); gap texts are the closer's own words, kept as they are (cut at GAP_CHARS).
|
|
6
|
+
import { readAudit } from './books.js';
|
|
7
|
+
import { readFileInside } from './flow.js';
|
|
8
|
+
import { listArchivedAsks, DECISION_STATUS } from './ask.js';
|
|
9
|
+
import { readRunRecord } from './runfile.js';
|
|
10
|
+
import {
|
|
11
|
+
foldCards, nameOf, errorKinds, flaggedTokens, quoteLines,
|
|
12
|
+
} from './learn.js';
|
|
13
|
+
|
|
14
|
+
/** M14 am1 item 2: the memo's fixed words */
|
|
15
|
+
export const MEMO_HEADING = 'What happened so far in this run (written by code, from the record)';
|
|
16
|
+
export const MEMO_CUT_NOTE = '(older lines cut to fit)';
|
|
17
|
+
/** M14 item 5 */
|
|
18
|
+
export const MEMO_CAP = 4000;
|
|
19
|
+
/** one gap text is cut here (with an ellipsis), so a single long red cannot eat the whole cap */
|
|
20
|
+
const GAP_CHARS = 300;
|
|
21
|
+
|
|
22
|
+
/** a try that closed well; every other verdict of a model try is a failure the memo names */
|
|
23
|
+
const WELL = new Set(['green', 'hitl']);
|
|
24
|
+
const DECISION_OF = Object.fromEntries(Object.entries(DECISION_STATUS).map(([k, v]) => [v, k]));
|
|
25
|
+
|
|
26
|
+
const oneLine = (/** @type {unknown} */ t) => (typeof t === 'string' ? t.replace(/\s+/g, ' ').trim() : '');
|
|
27
|
+
const cutGap = (/** @type {string} */ g) => (g.length > GAP_CHARS ? `${g.slice(0, GAP_CHARS)}…` : g);
|
|
28
|
+
const says = (/** @type {string} */ words) => (words === '' ? '' : ` — user says "${words}"`);
|
|
29
|
+
|
|
30
|
+
/** step names in the job's own order, from the run's copy of the job (`[]` when it cannot be read) @param {string} runDir @returns {string[]} */
|
|
31
|
+
function stepOrder(runDir) {
|
|
32
|
+
const r = readFileInside(runDir, 'job/declaration.json');
|
|
33
|
+
if (!r.ok) return [];
|
|
34
|
+
try {
|
|
35
|
+
const steps = JSON.parse(r.text)?.steps;
|
|
36
|
+
return Array.isArray(steps) ? steps.map((s) => s?.emits).filter((e) => typeof e === 'string') : [];
|
|
37
|
+
} catch { return []; }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** the human lines: the rerun line first (this run began as a rerun), then one per answered ask in the order they were asked (N counts every ask of this run) @param {string} runDir @param {string[]} order @returns {string[]} */
|
|
41
|
+
function humanLines(runDir, order) {
|
|
42
|
+
/** @type {string[]} */
|
|
43
|
+
const lines = [];
|
|
44
|
+
const rec = readRunRecord(runDir);
|
|
45
|
+
const rr = rec.ok ? rec.rec.rerun : null;
|
|
46
|
+
if (rr && typeof rr === 'object' && rr.decision === 'rerun' && typeof rr.words === 'string') lines.push(`rerun${says(oneLine(rr.words))}`);
|
|
47
|
+
const listed = listArchivedAsks(runDir);
|
|
48
|
+
if (!listed.archived) return lines;
|
|
49
|
+
const asks = [...listed.asks].sort((a, b) => String(a.askedAt ?? '').localeCompare(String(b.askedAt ?? '')));
|
|
50
|
+
asks.forEach((ask, i) => {
|
|
51
|
+
const decision = DECISION_OF[ask.answer.status];
|
|
52
|
+
if (!decision) return;
|
|
53
|
+
const at = order.indexOf(ask.emits ?? '');
|
|
54
|
+
const after = at > 0 ? order[at - 1] : 'the start';
|
|
55
|
+
lines.push(`ask ${i + 1} (after step ${after}): ${decision}${says(oneLine(ask.answer.reason))}`);
|
|
56
|
+
});
|
|
57
|
+
return lines;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Fold repeated failures into one line each, by the learnings fold rule (`foldCards`: same check, an agreeing error kind, 60% token overlap), here with the step and
|
|
62
|
+
* verdict as the "job" so only the same step failing the same way folds. Returns the groups in first-seen order.
|
|
63
|
+
* @template {{step: string, verdict: string, gap: string}} T @param {T[]} items @returns {T[][]}
|
|
64
|
+
*/
|
|
65
|
+
function foldRepeats(items) {
|
|
66
|
+
const cards = items.map((it) => {
|
|
67
|
+
const quote = quoteLines(it.gap).join('\n');
|
|
68
|
+
return { it, job: `${it.step}|${it.verdict}`, check: nameOf(it.gap), kinds: errorKinds(quote).kinds, tokens: flaggedTokens(quote) };
|
|
69
|
+
});
|
|
70
|
+
// `foldCards` only reads job, check, kinds and tokens of a card
|
|
71
|
+
return foldCards(/** @type {any} */ (cards)).map((g) => g.map((c) => /** @type {any} */ (c).it));
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* The memo for the try about to run, as text; `''` when nothing has happened yet in this run (no human line, no earlier try).
|
|
76
|
+
* @param {string|null} runDir the run's folder (null = no record = nothing happened)
|
|
77
|
+
* @param {{step: string|null, cap?: number}} o `step` = the step the try belongs to (names its earlier tries and tells a retry from a later step's first try)
|
|
78
|
+
* @returns {string}
|
|
79
|
+
*/
|
|
80
|
+
export function buildMemo(runDir, { step, cap = MEMO_CAP }) {
|
|
81
|
+
if (typeof runDir !== 'string') return '';
|
|
82
|
+
const order = stepOrder(runDir);
|
|
83
|
+
const human = humanLines(runDir, order);
|
|
84
|
+
// the model tries so far, in file order; a try is labelled by its count within its step (the audit `attempt` restarts after a redo, F130)
|
|
85
|
+
/** @type {Map<string, number>} */
|
|
86
|
+
const seen = new Map();
|
|
87
|
+
const tries = readAudit(runDir)
|
|
88
|
+
.filter((r) => r && r.model != null && typeof r.step === 'string' && r.verdict !== 'stopped')
|
|
89
|
+
.map((r) => {
|
|
90
|
+
const n = (seen.get(r.step) ?? 0) + 1;
|
|
91
|
+
seen.set(r.step, n);
|
|
92
|
+
return { step: /** @type {string} */ (r.step), n, verdict: String(r.verdict), gap: oneLine(r.gap) };
|
|
93
|
+
});
|
|
94
|
+
if (human.length === 0 && tries.length === 0) return '';
|
|
95
|
+
|
|
96
|
+
const last = tries.at(-1) ?? null;
|
|
97
|
+
// item 6: the newest failure's words are left out when the retry (the same step, straight after a failure) already gets them as its gap
|
|
98
|
+
const retryGetsGap = last !== null && last.step === step && !WELL.has(last.verdict);
|
|
99
|
+
const earlier = tries.slice(0, -1);
|
|
100
|
+
const sameStep = earlier.filter((t) => t.step === step);
|
|
101
|
+
const failures = earlier.filter((t) => t.step !== step && !WELL.has(t.verdict));
|
|
102
|
+
const label = (/** @type {{step: string, n: number, verdict: string, gap: string}} */ t) => `step ${t.step} try ${t.n} — result: ${t.verdict}`;
|
|
103
|
+
const gapOf = (/** @type {{gap: string}} */ t) => (t.gap === '' ? '' : ` — ${cutGap(t.gap)}`);
|
|
104
|
+
const foldLine = (/** @type {string} */ kind, /** @type {any[]} */ g) => ({ kind, text: `${kind}: ${label(g[0])}${gapOf(g[0])}${g.length > 1 ? ` (x${g.length})` : ''}` });
|
|
105
|
+
|
|
106
|
+
const lastLine = last === null ? [] : [{ kind: 'last', text: `last try: ${label(last)}${retryGetsGap ? '' : gapOf(last)}` }];
|
|
107
|
+
const tryLines = foldRepeats(sameStep).map((g) => foldLine('earlier try', g));
|
|
108
|
+
const failLines = foldRepeats(failures).map((g) => foldLine('earlier failure', g));
|
|
109
|
+
let work = [...lastLine, ...tryLines, ...failLines];
|
|
110
|
+
let cut = false;
|
|
111
|
+
const text = () => [MEMO_HEADING, ...human, ...work.map((w) => w.text), ...(cut ? [MEMO_CUT_NOTE] : [])].join('\n');
|
|
112
|
+
// item 5: oldest tries first, then oldest failures; the heading, the human lines and the last-try line stay
|
|
113
|
+
while (text().length > cap) {
|
|
114
|
+
const drop = work.find((w) => w.kind === 'earlier try') ?? work.find((w) => w.kind === 'earlier failure');
|
|
115
|
+
if (!drop) break;
|
|
116
|
+
work = work.filter((w) => w !== drop);
|
|
117
|
+
cut = true;
|
|
118
|
+
}
|
|
119
|
+
return text();
|
|
120
|
+
}
|