fwdloop 0.27.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 +54 -13
- package/package.json +3 -3
- package/src/ask.js +1 -1
- package/src/audit-fold.js +9 -1
- package/src/authoring.js +22 -5
- package/src/canrun.js +19 -16
- 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/config.js +18 -0
- package/src/declaration.js +85 -5
- package/src/drafter.js +143 -47
- package/src/flow.js +2 -1
- package/src/launcher.js +4 -2
- package/src/learn.js +1 -1
- package/src/learnstore.js +8 -7
- package/src/mcp-checks.js +50 -0
- package/src/mcp-pick.js +33 -0
- package/src/mcp-sources.js +84 -0
- package/src/mcp-use.js +54 -0
- package/src/memo.js +120 -0
- package/src/model-step.js +89 -17
- package/src/natural.js +23 -0
- package/src/pageask.js +9 -6
- package/src/pagedropwords.js +9 -0
- package/src/panel/author.js +50 -28
- package/src/panel/authorcard.js +86 -2
- package/src/panel/authorflows.js +18 -14
- package/src/panel/authortrigger.js +241 -84
- package/src/panel/data.js +99 -11
- package/src/panel/index.html +683 -210
- package/src/panel/jobgrid.js +127 -0
- package/src/panel/result.js +28 -7
- package/src/panel/scheduler.js +8 -2
- package/src/panel/server.js +17 -7
- package/src/panel/settings.js +119 -4
- package/src/panel/tickets.js +12 -7
- package/src/pickrecord.js +146 -0
- package/src/plain-checks.js +1 -0
- package/src/primitives.js +34 -5
- package/src/provider.js +4 -1
- package/src/runfile.js +4 -2
- package/src/runner.js +170 -45
- package/src/send.js +71 -4
- package/src/setup.js +13 -1
- package/src/summary-words.js +15 -3
- package/src/ticket-draft.js +40 -42
- package/src/ticket-labels.js +10 -0
- package/src/ticket-mcp.js +33 -10
- package/src/ticket-next.js +33 -0
- package/src/ticket-shape.js +9 -0
- package/src/trigger-clock.js +4 -4
- package/src/trigger-files.js +3 -3
- package/src/trigger-tickets.js +41 -12
- package/types/ask.d.ts +2 -1
- package/types/audit-fold.d.ts +13 -2
- package/types/authoring.d.ts +10 -2
- package/types/canrun.d.ts +5 -12
- 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/config.d.ts +6 -0
- package/types/declaration.d.ts +17 -0
- package/types/drafter.d.ts +446 -50
- package/types/learn.d.ts +1 -0
- package/types/learnstore.d.ts +2 -3
- package/types/mcp-checks.d.ts +8 -0
- package/types/mcp-pick.d.ts +23 -0
- package/types/mcp-sources.d.ts +51 -0
- package/types/mcp-use.d.ts +12 -0
- package/types/memo.d.ts +15 -0
- package/types/model-step.d.ts +5 -0
- package/types/natural.d.ts +2 -0
- package/types/pageask.d.ts +9 -2
- package/types/pagedropwords.d.ts +1 -0
- package/types/panel/author.d.ts +37 -1
- package/types/panel/authorcard.d.ts +52 -0
- package/types/panel/authorflows.d.ts +9 -1
- package/types/panel/authortrigger.d.ts +73 -7
- package/types/panel/data.d.ts +56 -2
- package/types/panel/jobgrid.d.ts +109 -0
- package/types/panel/result.d.ts +9 -3
- package/types/panel/server.d.ts +5 -1
- package/types/panel/settings.d.ts +3 -2
- package/types/panel/tickets.d.ts +26 -4
- package/types/pickrecord.d.ts +88 -0
- package/types/primitives.d.ts +15 -2
- package/types/runfile.d.ts +7 -2
- package/types/runner.d.ts +128 -77
- package/types/send.d.ts +10 -2
- package/types/setup.d.ts +1 -56
- package/types/summary-words.d.ts +22 -3
- package/types/ticket-draft.d.ts +40 -32
- package/types/ticket-labels.d.ts +6 -0
- package/types/ticket-mcp.d.ts +18 -1
- package/types/ticket-next.d.ts +23 -0
- package/types/ticket-shape.d.ts +5 -0
- package/types/trigger-clock.d.ts +4 -3
- package/types/trigger-files.d.ts +1 -1
- package/types/trigger-tickets.d.ts +18 -4
- package/src/attemptdiff.js +0 -118
- package/types/attemptdiff.d.ts +0 -38
package/src/drafter.js
CHANGED
|
@@ -18,16 +18,21 @@
|
|
|
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
|
+
import { findMcpPlanRed } from './canrun.js';
|
|
23
24
|
import { WIRED_VERBS, wiredMenu } from './primitives.js';
|
|
24
|
-
import { ticketSourcesOf, ticketFactsLines, ticketSchemaParts, ticketReds, userMcpServers } from './ticket-draft.js';
|
|
25
|
+
import { ticketSourcesOf, ticketFactsLines, mcpFactsLines, ticketSchemaParts, ticketReds, userMcpServers } from './ticket-draft.js';
|
|
25
26
|
import { readInputFacts } from './input-facts.js';
|
|
26
27
|
import { freezePage } from './runner.js';
|
|
27
28
|
import { removeFrozenPages } from './flow.js';
|
|
28
29
|
import { lookAtPage, pageInfoLines } from './pagelook.js';
|
|
29
30
|
import { lookAtSheet, sheetPrompt } from './sheetlook.js';
|
|
30
|
-
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';
|
|
31
36
|
import { MAP_SYSTEM, mapPrompt } from './pagemap.js';
|
|
32
37
|
import { askableFromLook, tooManyAsksText, MAX_LOOK_ASKS } from './pageask.js';
|
|
33
38
|
import { lineRules } from './pagebits.js';
|
|
@@ -120,27 +125,15 @@ const CITED_PROP = Object.freeze({
|
|
|
120
125
|
additionalProperties: false,
|
|
121
126
|
});
|
|
122
127
|
|
|
123
|
-
const SHAPE_PROPS = Object.freeze({
|
|
124
|
-
maxWords: { type: 'integer', minimum: 1, description: `the whole output's word ceiling; ${WHOLE_OUTPUT_CEILING_RULE}` },
|
|
125
|
-
sections: { type: 'array', minItems: 1, items: { type: 'string', minLength: 1 }, description: 'required section headings, in order' },
|
|
126
|
-
linesPerInvoice: { type: 'integer', minimum: 1, description: 'lines the output must carry per invoice' },
|
|
127
|
-
mustCarry: { type: 'array', minItems: 1, items: { type: 'string', minLength: 1 }, description: 'named fields every line must carry' },
|
|
128
|
-
});
|
|
129
|
-
|
|
130
128
|
/**
|
|
131
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
|
|
132
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.
|
|
133
|
-
*
|
|
134
|
-
* @param {any[]} menu @param {{sheets?: Record<string, {header: string[]}>, ticket?: {
|
|
131
|
+
* M13 piece 4: `ticket` = `{flowType, tools}` for MCP (generic) and Tickets; then a step may carry `mcpTools` (an enum of the job's tools) and, for Tickets, the tool carries `ticketFilter` and `ticketWatch` (src/ticket-draft.js). The job's `mcp` block and `flowType` are set by code, never offered.
|
|
132
|
+
* @param {any[]} menu @param {{sheets?: Record<string, {header: string[]}>, ticket?: {flowType: 'mcp'|'tickets', tools: string[]}}} [o]
|
|
135
133
|
*/
|
|
136
134
|
export function buildDeclarationSchema(menu, { sheets, ticket } = {}) {
|
|
137
135
|
const sheetProp = sheets ? sheetChecksProp(sheets) : null;
|
|
138
|
-
const ticketParts = ticket ? ticketSchemaParts(ticket
|
|
139
|
-
const shapeProps = {};
|
|
140
|
-
for (const key of SHAPE_KEYS) {
|
|
141
|
-
if (!SHAPE_PROPS[key]) throw new Error(`schema: SHAPE_KEYS gained "${key}" — add its type to SHAPE_PROPS`);
|
|
142
|
-
shapeProps[key] = SHAPE_PROPS[key];
|
|
143
|
-
}
|
|
136
|
+
const ticketParts = ticket ? ticketSchemaParts(ticket) : null;
|
|
144
137
|
return {
|
|
145
138
|
type: 'object',
|
|
146
139
|
properties: {
|
|
@@ -156,7 +149,7 @@ export function buildDeclarationSchema(menu, { sheets, ticket } = {}) {
|
|
|
156
149
|
description: 'verbs this step is granted, from the menu only; [] for a pure stop',
|
|
157
150
|
},
|
|
158
151
|
...(ticketParts ? ticketParts.step : {}),
|
|
159
|
-
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' },
|
|
160
153
|
emits: { type: 'string', minLength: 1, description: 'the ONE new artifact id this step declares (unique)' },
|
|
161
154
|
fromLine: { type: ['integer', 'null'], description: 'the ONE numbered job line this step serves' },
|
|
162
155
|
picks: {
|
|
@@ -168,12 +161,6 @@ export function buildDeclarationSchema(menu, { sheets, ticket } = {}) {
|
|
|
168
161
|
type: 'object',
|
|
169
162
|
properties: {
|
|
170
163
|
class: { type: 'string', enum: [...CLASSES], description: "MUST equal the class of fromLine's guardrail in guardrailClasses; hitl when that line has no guardrail" },
|
|
171
|
-
shape: {
|
|
172
|
-
type: 'object',
|
|
173
|
-
properties: shapeProps,
|
|
174
|
-
additionalProperties: false,
|
|
175
|
-
description: `only when class is softgreen; keys limited to ${SHAPE_KEYS.join(', ')}`,
|
|
176
|
-
},
|
|
177
164
|
cited: CITED_PROP,
|
|
178
165
|
columns: COLUMNS_PROP,
|
|
179
166
|
...(sheetProp ? { sheet: sheetProp } : {}),
|
|
@@ -244,7 +231,7 @@ export const QUESTIONS_PROMPT = [
|
|
|
244
231
|
].join('\n');
|
|
245
232
|
|
|
246
233
|
/** The declaration schema plus the optional `notChecked` (every try) and, on try 3 only, `questions`. Neither is in `required`. */
|
|
247
|
-
/** @param {any[]} menu @param {{questions?: boolean, sheets?: Record<string, {header: string[]}>|undefined, ticket?: {
|
|
234
|
+
/** @param {any[]} menu @param {{questions?: boolean, sheets?: Record<string, {header: string[]}>|undefined, ticket?: {flowType: 'mcp'|'tickets', tools: string[]}}} [o] */
|
|
248
235
|
export function buildRoundSchema(menu, { questions = false, sheets = undefined, ticket = undefined } = {}) {
|
|
249
236
|
const s = buildDeclarationSchema(menu, { sheets, ticket });
|
|
250
237
|
const extra = { notChecked: { type: 'array', items: { type: 'string' }, description: 'what the job asks for that no typed check verifies' } };
|
|
@@ -323,6 +310,9 @@ function greenReadRule(sources) {
|
|
|
323
310
|
const out = [csvRoles.length
|
|
324
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.`
|
|
325
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
|
+
}
|
|
326
316
|
if (csvRoles.length) out.push(...sheetOfferRules(csvRoles)); // M10b piece 3: close.sheet and every rule the validator enforces on it
|
|
327
317
|
if (pageRoles.length || docRoles.length) {
|
|
328
318
|
out.push(
|
|
@@ -378,7 +368,8 @@ export function buildSystemPrompt({ menu, lines, arbiter, factsInfo }) {
|
|
|
378
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".',
|
|
379
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.',
|
|
380
370
|
...greenReadRule(arbiter.sources),
|
|
381
|
-
'-
|
|
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.',
|
|
382
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.',
|
|
383
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.`,
|
|
384
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.`,
|
|
@@ -433,8 +424,13 @@ export async function draft({
|
|
|
433
424
|
proseText, slot, model, provider: injected, rates: injectedRates, modelId: injectedModelId, env,
|
|
434
425
|
priorSpend = /** @type {((ceilingUsd: number) => number)|null} */ (null), skills = DRAFT_SKILLS, makeProviderFn = makeProvider, onBook, offerQuestions = true, draftThinking = /** @type {'on'|'off'} */ ('off'),
|
|
435
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),
|
|
436
430
|
learnHints = /** @type {{text: string, ids: string[]}|null} */ (null),
|
|
437
431
|
mcpServers = /** @type {string[]|undefined} */ (undefined),
|
|
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
|
|
433
|
+
flowType = /** @type {'plain'|'mcp'|'tickets'} */ ('plain'), mcp = /** @type {any} */ (null),
|
|
438
434
|
}) {
|
|
439
435
|
// 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.
|
|
440
436
|
const thinkingOf = () => {
|
|
@@ -456,14 +452,19 @@ export async function draft({
|
|
|
456
452
|
// M4e amendment 15 item 2: a guardrail that fights itself on words is red at $0, before any provider is built or called.
|
|
457
453
|
const sumReds = checkGuardrailSums(lines);
|
|
458
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);
|
|
459
458
|
const menu = wiredMenu(skills);
|
|
460
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).
|
|
461
460
|
const fileFacts = readInputFacts((arbiter.sources ?? []).filter((s) => s.kind !== 'page'));
|
|
462
461
|
if (!fileFacts.ok) return fail(fileFacts.reds);
|
|
463
|
-
//
|
|
464
|
-
|
|
465
|
-
const
|
|
466
|
-
|
|
462
|
+
// M13 piece 4: with flow type Tickets, a GitHub issues list is a ticket role, not a page: never fetched at draft; the drafter is told it exists and may suggest a label filter.
|
|
463
|
+
// The job's flow type and MCP (server + every tool of its newest OK check) come from the card; the refusals are at $0, before any provider is built.
|
|
464
|
+
const ticketSources = flowType === 'tickets' ? ticketSourcesOf(arbiter.sources) : [];
|
|
465
|
+
const servers = flowType === 'plain' ? [] : (mcpServers ?? userMcpServers());
|
|
466
|
+
const flowReds = ticketReds({ flowType, ticketSources, pick: mcp, servers });
|
|
467
|
+
if (flowReds.length) return fail(flowReds);
|
|
467
468
|
|
|
468
469
|
let { provider, rates, modelId } = { provider: injected, rates: injectedRates, modelId: injectedModelId };
|
|
469
470
|
let prices = null; // the one price lookup's result (live provider only); the cap check below uses the SAME price
|
|
@@ -504,6 +505,14 @@ export async function draft({
|
|
|
504
505
|
inFlight, calls, unmetered, metered: sumMeterings(meterings), modelId, price: priceRecord(prices, rates),
|
|
505
506
|
});
|
|
506
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
|
+
|
|
507
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
|
|
508
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.
|
|
509
518
|
const pageSources = (arbiter.sources ?? []).filter((s) => s.kind === 'page' && !ticketSources.includes(s));
|
|
@@ -645,29 +654,106 @@ export async function draft({
|
|
|
645
654
|
);
|
|
646
655
|
}
|
|
647
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
|
+
}
|
|
648
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
|
|
649
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.
|
|
650
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.
|
|
651
|
-
if ((pageSources.length || sheetAsks.length) && offerQuestions) {
|
|
722
|
+
if ((pageSources.length || sheetAsks.length || shapeAsks.length) && offerQuestions) {
|
|
652
723
|
const pageAsks = pageSources.length ? askableFromLook({ facts: [...look.facts, ...sheetFacts] }, jobLines.filter((l) => !askLines.has(l.n))) : [];
|
|
653
|
-
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];
|
|
654
727
|
if (asks.length > 0) {
|
|
655
728
|
const m = sumMeterings(meterings);
|
|
656
729
|
const spent = m.costUsd === null || unmetered > 0 ? (m.costUsd === null ? 'unknown' : `at least ${usdText(m.costUsd)}`) : usdText(m.costUsd);
|
|
657
|
-
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;
|
|
658
732
|
if (tooMany && pageSources.length) removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); // a refused draft keeps no page copy
|
|
659
733
|
return {
|
|
660
|
-
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,
|
|
661
735
|
questions: tooMany ? [] : asks.map((a) => ({
|
|
662
|
-
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 } : {}),
|
|
663
737
|
})),
|
|
664
738
|
droppedQuestions: [], notChecked: pageNotChecked, ...pageExtras,
|
|
665
739
|
};
|
|
666
740
|
}
|
|
667
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
|
+
}
|
|
668
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.
|
|
669
755
|
const factsBase = pageInfo.length ? [...facts.info.filter((l) => !pageSources.some((s) => l.startsWith(`- ${s.role}: a web page`))), ...pageInfo] : facts.info;
|
|
670
|
-
const factsInfo = [...factsBase, ...ticketSources.flatMap((s) => ticketFactsLines(s.role,
|
|
756
|
+
const factsInfo = [...factsBase, ...ticketSources.flatMap((s) => ticketFactsLines(s.role)), ...(flowType === 'mcp' ? mcpFactsLines(mcp.server, mcp.tools) : [])];
|
|
671
757
|
|
|
672
758
|
// `notChecked` is offered on every try (information, not asking); `questions` only on try 3 (below).
|
|
673
759
|
// 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
|
|
@@ -700,7 +786,7 @@ export async function draft({
|
|
|
700
786
|
// 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
|
|
701
787
|
// validator's refusals fed back), gets the `questions` property; the redraft after an answer passes offerQuestions:false and never does.
|
|
702
788
|
const askOpen = offerQuestions && revisions === MAX_REVISIONS;
|
|
703
|
-
const schema = buildRoundSchema(menu, { questions: askOpen, sheets: sheetTables, ticket:
|
|
789
|
+
const schema = buildRoundSchema(menu, { questions: askOpen, sheets: sheetTables, ticket: flowType === 'plain' ? undefined : { flowType, tools: mcp.tools } });
|
|
704
790
|
const tool = {
|
|
705
791
|
name: TOOL,
|
|
706
792
|
description: 'Emit the flow declaration over the granted primitives, or refuse lines you cannot serve.',
|
|
@@ -747,6 +833,9 @@ export async function draft({
|
|
|
747
833
|
: malformed ? `the tool call's arguments were not valid JSON (${malformed.error})`
|
|
748
834
|
: 'no usable tool call (text instead of the tool)';
|
|
749
835
|
entry.outcome = `structure: ${why}`;
|
|
836
|
+
// the raw answer is kept (log.json): the unparseable arguments as sent, else the model's text
|
|
837
|
+
if (typeof malformed?.rawArguments === 'string') entry.rawArguments = malformed.rawArguments;
|
|
838
|
+
else if (typeof result?.text === 'string' && result.text !== '') entry.rawText = result.text;
|
|
750
839
|
log.push(entry);
|
|
751
840
|
lastReds = [why];
|
|
752
841
|
// M4d am3 A3: a round cut off at the output cap before tries 1 and 2 are spent is a FAILED TRY, advancing the same counter a
|
|
@@ -776,33 +865,40 @@ export async function draft({
|
|
|
776
865
|
const { questions: rawQuestions, notChecked: rawNotChecked, ...captureRest } = /** @type {Record<string, any>} */ (captured);
|
|
777
866
|
/** @type {Record<string, any>} */
|
|
778
867
|
const declaration = { ...(askOpen ? captureRest : { ...captureRest, ...(rawQuestions === undefined ? {} : { questions: rawQuestions }) }), inputFacts: facts.inputFacts };
|
|
868
|
+
// M13 piece 4: the flow type and the job's MCP (server + every tool of the newest OK check, R1) are set by code; whatever the model sent for them is overwritten.
|
|
869
|
+
declaration.flowType = flowType;
|
|
870
|
+
if (flowType === 'plain') delete declaration.mcp;
|
|
871
|
+
else declaration.mcp = { server: mcp.server, tools: [...mcp.tools] };
|
|
779
872
|
// M6a amendment 1 (F50): the goal is the signed line, set by the machine; whatever the model sent is overwritten.
|
|
780
873
|
if (Array.isArray(declaration.steps)) {
|
|
781
874
|
declaration.steps = declaration.steps.map((st) => (isPlainObject(st) ? { ...st, goal: goalForLine(st.fromLine, lines) } : st));
|
|
782
875
|
}
|
|
783
|
-
//
|
|
784
|
-
// (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).
|
|
785
877
|
if (Array.isArray(declaration.steps)) {
|
|
786
878
|
declaration.steps = declaration.steps.map((st) => {
|
|
787
|
-
if (!isPlainObject(st) || !isPlainObject(st.close) ||
|
|
788
|
-
const {
|
|
789
|
-
|
|
790
|
-
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 };
|
|
791
882
|
});
|
|
792
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 })));
|
|
793
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
|
|
794
|
-
const
|
|
887
|
+
const verdict1 = validateDeclaration(declaration, {
|
|
795
888
|
arbiter, lines, catalogue: validationCatalogue, wired: WIRED_VERBS, verbatimGoals: true, fitJobLine: true,
|
|
796
889
|
// 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
|
|
797
890
|
sheetWords: sheetTables ? { headers: Object.fromEntries(Object.entries(sheetTables).map(([role, t]) => [role, t.header])), facts: sheetFacts.filter((f) => f.shape === 'column'), tables: sheetTables } : undefined,
|
|
798
891
|
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) },
|
|
799
892
|
});
|
|
800
|
-
|
|
801
|
-
const
|
|
893
|
+
// M13 piece 4 (F105 rewritten): a generic MCP job whose steps call none of its tools is fed back like any validator red (the run would refuse it at $0, by the same sentence)
|
|
894
|
+
const planRed = verdict1.ok ? findMcpPlanRed(declaration) : null;
|
|
895
|
+
const verdict = planRed ? { ok: false, reds: [planRed] } : verdict1;
|
|
802
896
|
lastDecl = declaration;
|
|
803
897
|
const asked = askOpen ? normalizeQuestions(rawQuestions, failedLines) : { kept: [], dropped: [] };
|
|
804
898
|
extras = { questions: asked.kept, droppedQuestions: asked.dropped, notChecked: [...new Set([...pageNotChecked, ...cleanNotChecked(rawNotChecked), ...uncoveredRules(declaration, jobLines, Object.keys(facts.sheets ?? {}))])] };
|
|
805
899
|
if (asked.dropped.length) entry.droppedQuestions = asked.dropped;
|
|
900
|
+
// the declaration the model sent, as parsed, before any code overwrite (log.json keeps it per try)
|
|
901
|
+
entry.args = captured;
|
|
806
902
|
if (verdict.ok) {
|
|
807
903
|
entry.outcome = 'valid';
|
|
808
904
|
log.push(entry);
|
package/src/flow.js
CHANGED
|
@@ -25,6 +25,7 @@ import {
|
|
|
25
25
|
} from 'node:fs';
|
|
26
26
|
import path from 'node:path';
|
|
27
27
|
|
|
28
|
+
import { compareNatural } from './natural.js';
|
|
28
29
|
import { parseSignedText } from './signed-text.js';
|
|
29
30
|
import { signFlow, verifyFlow } from './signature.js';
|
|
30
31
|
import { validateDeclaration } from './declaration.js';
|
|
@@ -251,7 +252,7 @@ export function listRunIds(flowDir) {
|
|
|
251
252
|
return entries
|
|
252
253
|
.filter((e) => e.isDirectory() && checkRunId(e.name).ok)
|
|
253
254
|
.map((e) => e.name)
|
|
254
|
-
.sort();
|
|
255
|
+
.sort(compareNatural);
|
|
255
256
|
}
|
|
256
257
|
|
|
257
258
|
/**
|
package/src/launcher.js
CHANGED
|
@@ -25,7 +25,7 @@ import { openAsker } from './prompts.js';
|
|
|
25
25
|
import { dirname, join } from 'node:path';
|
|
26
26
|
import { fileURLToPath } from 'node:url';
|
|
27
27
|
import { readConfig, updateConfig, configPath, defaultFlowsRoot, ConfigError } from './config.js';
|
|
28
|
-
import { keysHome, keysFilePath, createKeysFile } from './keysfile.js';
|
|
28
|
+
import { keysHome, keysFilePath, createKeysFile, isKeyName } from './keysfile.js';
|
|
29
29
|
import { openInOs } from './opener.js';
|
|
30
30
|
import { PLAIN, makePaint } from './tty-colour.js';
|
|
31
31
|
import { readOwnVersion } from './version.js';
|
|
@@ -307,7 +307,9 @@ export function runNpm(args, o = {}) {
|
|
|
307
307
|
const spawnImpl = o.spawnImpl ?? realSpawn;
|
|
308
308
|
return new Promise((resolve) => {
|
|
309
309
|
let child;
|
|
310
|
-
|
|
310
|
+
// M13 am1: npm and its install scripts get the shell's env without any `*_KEY` setting (`isKeyName`); only the panel spawn (startCmd) carries keys
|
|
311
|
+
const env = Object.fromEntries(Object.entries(process.env).filter(([n]) => !isKeyName(n)));
|
|
312
|
+
try { child = spawnImpl('npm', args, { shell: false, stdio: 'inherit', env }); } catch { resolve(1); return; }
|
|
311
313
|
let done = false;
|
|
312
314
|
const end = (/** @type {number} */ code) => { if (done) return; done = true; clearTimeout(timer); resolve(code); };
|
|
313
315
|
const timer = setTimeout(() => { try { child.kill('SIGTERM'); } catch { /* already gone */ } end(1); }, o.deadlineMs ?? NPM_DEADLINE_MS);
|
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
|
//
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync, chmodSync } from 'node:fs';
|
|
11
11
|
import { join, dirname, resolve } from 'node:path';
|
|
12
12
|
import { homedir } from 'node:os';
|
|
13
|
+
import { compareNatural } from './natural.js';
|
|
13
14
|
import { configHome, configDoorHome, readConfig } from './config.js';
|
|
14
15
|
import { emptyLedger, redactDeep, countLedger, releasePending, recordHealth, buildCards, placeOf, renderHints } from './learn.js';
|
|
15
16
|
import { readAudit, readHistory } from './books.js';
|
|
@@ -262,10 +263,10 @@ export function eventsOfRun(runDir, workflow) {
|
|
|
262
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
|
|
263
264
|
* the run's diary.jsonl, so a check with no checks row there (a run from before am29) has no `meaning`.
|
|
264
265
|
* Borrowed-from: bareloop src/learnstore.js@v0.47.0:124 (learnAtRunEnd).
|
|
265
|
-
* @param {{home?: string, workflow: string, runId: string, runDir: string,
|
|
266
|
+
* @param {{home?: string, workflow: string, runId: string, runDir: string, now?: Date}} o
|
|
266
267
|
* @returns {{wrote: boolean, counted: number, held: number, problem: string|null, noise: string|null, cards: number}}
|
|
267
268
|
*/
|
|
268
|
-
export function learnAtRunEnd({ home, workflow, runId, runDir,
|
|
269
|
+
export function learnAtRunEnd({ home, workflow, runId, runDir, now = new Date() }) {
|
|
269
270
|
const rec = eventsOfRun(runDir, workflow);
|
|
270
271
|
if (!rec) return { wrote: false, counted: 0, held: 0, problem: null, noise: 'no-tries', cards: 0 };
|
|
271
272
|
const runid = `${workflow}/${runId}`;
|
|
@@ -295,7 +296,7 @@ export function seedLedger({ root, home }) {
|
|
|
295
296
|
if (door.skip) return { ...out, skippedNoDoor: true };
|
|
296
297
|
home = door.home;
|
|
297
298
|
}
|
|
298
|
-
/** @type {{workflow: string, runId: string, runDir: string, end: Date
|
|
299
|
+
/** @type {{workflow: string, runId: string, runDir: string, end: Date}[]} */
|
|
299
300
|
const todo = [];
|
|
300
301
|
for (const workflow of listFlowNames(root)) {
|
|
301
302
|
const flowDir = join(root, workflow);
|
|
@@ -312,17 +313,17 @@ export function seedLedger({ root, home }) {
|
|
|
312
313
|
const endRow = history.findLast((r) => r?.runId === runId && !NOT_A_RUN_END.has(r.outcome) && Number.isFinite(Date.parse(r.at)));
|
|
313
314
|
if (!endRow) { out.skipped['no-end'] += 1; continue; }
|
|
314
315
|
if (!log) { out.skipped.unreadable += 1; continue; }
|
|
315
|
-
todo.push({ workflow, runId, runDir, end: new Date(endRow.at)
|
|
316
|
+
todo.push({ workflow, runId, runDir, end: new Date(endRow.at) });
|
|
316
317
|
} catch { out.skipped.unreadable += 1; }
|
|
317
318
|
}
|
|
318
319
|
}
|
|
319
|
-
todo.sort((a, b) => a.end.getTime() - b.end.getTime() || `${a.workflow}/${a.runId}
|
|
320
|
+
todo.sort((a, b) => a.end.getTime() - b.end.getTime() || compareNatural(`${a.workflow}/${a.runId}`, `${b.workflow}/${b.runId}`));
|
|
320
321
|
for (const t of todo) {
|
|
321
322
|
const cur = readLedger(home);
|
|
322
323
|
if (cur.problem) { out.problem = cur.problem; return out; }
|
|
323
324
|
if (Object.hasOwn(cur.ledger.health, `${t.workflow}/${t.runId}`)) { out.skipped['already-in'] += 1; continue; }
|
|
324
325
|
try {
|
|
325
|
-
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 });
|
|
326
327
|
if (r.problem) { out.problem = r.problem; return out; }
|
|
327
328
|
if (r.noise) out.skipped.noise += 1;
|
|
328
329
|
else out.added += r.counted;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// M13 piece 3 (hamr 2026-10-31): the log of `check tools` presses, `mcp-checks.jsonl` beside config.json. APPEND-ONLY: each press appends one line, nothing is ever rewritten
|
|
2
|
+
// or removed. A line is `{server, path, at, ok, tools:[{name, hint}]}` or `{server, path, at, ok:false, error}`. The page shows the newest line per path and server.
|
|
3
|
+
// A torn or foreign line is skipped when reading, so a half-written last line never hides the earlier ones.
|
|
4
|
+
import { appendFileSync, mkdirSync, readFileSync } from 'node:fs';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import { configHome } from './config.js';
|
|
7
|
+
|
|
8
|
+
export const MCP_CHECKS_FILE = 'mcp-checks.jsonl';
|
|
9
|
+
|
|
10
|
+
/** @param {string|undefined} home the config home */
|
|
11
|
+
export const mcpChecksFile = (home) => join(configHome(home), MCP_CHECKS_FILE);
|
|
12
|
+
|
|
13
|
+
/** append ONE line; throws when it cannot be written @param {string|undefined} home @param {Record<string, any>} entry */
|
|
14
|
+
export function appendMcpCheck(home, entry) {
|
|
15
|
+
mkdirSync(configHome(home), { recursive: true, mode: 0o700 });
|
|
16
|
+
appendFileSync(mcpChecksFile(home), `${JSON.stringify(entry)}\n`, { mode: 0o600 });
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** every well-formed line, oldest first; none when the file is missing @param {string|undefined} home @returns {any[]} */
|
|
20
|
+
function checkLines(home) {
|
|
21
|
+
let text = '';
|
|
22
|
+
try { text = readFileSync(mcpChecksFile(home), 'utf8'); } catch { return []; }
|
|
23
|
+
const out = [];
|
|
24
|
+
for (const line of text.split('\n')) {
|
|
25
|
+
let r;
|
|
26
|
+
try { r = JSON.parse(line); } catch { continue; }
|
|
27
|
+
if (typeof r?.server !== 'string' || typeof r?.path !== 'string' || typeof r?.at !== 'string') continue;
|
|
28
|
+
out.push(r);
|
|
29
|
+
}
|
|
30
|
+
return out;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** the newest line per `path\tserver` @param {string|undefined} home @returns {Map<string, any>} */
|
|
34
|
+
export function newestMcpChecks(home) {
|
|
35
|
+
const out = new Map();
|
|
36
|
+
for (const r of checkLines(home)) out.set(`${r.path}\t${r.server}`, r);
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** M13 piece 4 (R1): the tool names of the newest OK line (with at least one tool) for this server at this path, or null @param {string|undefined} home @param {string} server @param {string} path @returns {string[]|null} */
|
|
41
|
+
export function newestOkMcpTools(home, server, path) {
|
|
42
|
+
/** @type {string[]|null} */
|
|
43
|
+
let tools = null;
|
|
44
|
+
for (const r of checkLines(home)) {
|
|
45
|
+
if (r.server !== server || r.path !== path || r.ok !== true || !Array.isArray(r.tools)) continue;
|
|
46
|
+
const names = r.tools.map((/** @type {any} */ x) => x?.name).filter((/** @type {unknown} */ n) => typeof n === 'string' && n !== '');
|
|
47
|
+
if (names.length > 0) tools = [...new Set(names)];
|
|
48
|
+
}
|
|
49
|
+
return tools;
|
|
50
|
+
}
|
package/src/mcp-pick.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// M13 piece 4 (hamr ruling R1, 2026-10-31): the ONE place that decides the tools a job gets from its MCP. A job with an MCP gets ALL the tools of that MCP's newest OK line in
|
|
2
|
+
// `mcp-checks.jsonl` (src/mcp-checks.js), set by code: never chosen by the drafter, never reviewed by the person, and no server is ever started here (a server starts only on
|
|
3
|
+
// a press of `check tools`). A tool the server gains later is not in the job (signed item 3). Read-only; writes nothing.
|
|
4
|
+
import { newestOkMcpTools } from './mcp-checks.js';
|
|
5
|
+
import { mcpSources, mcpConfigFor } from './mcp-sources.js';
|
|
6
|
+
import { configDoorHome, configHome } from './config.js';
|
|
7
|
+
import { remoteRefusal } from './ticket-mcp.js';
|
|
8
|
+
|
|
9
|
+
/** the one refusal for an MCP nobody has checked (or whose check never succeeded) */
|
|
10
|
+
export const NEVER_CHECKED_SAY = 'press check tools in Settings > MCP first';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* @param {string} server @param {string|undefined|null} home the config home; undefined = the door's decision (`configDoorHome`: a test process with no `FWDLOOP_CONFIG_HOME` has none, so "never checked"; otherwise the default config home); null = none
|
|
14
|
+
* @returns {{ ok: true, server: string, tools: string[] } | { ok: false, say: string }}
|
|
15
|
+
*/
|
|
16
|
+
export function mcpPickFor(server, home) {
|
|
17
|
+
if (home === undefined) {
|
|
18
|
+
const door = configDoorHome();
|
|
19
|
+
if (door.skip) return { ok: false, say: NEVER_CHECKED_SAY };
|
|
20
|
+
home = configHome(door.home);
|
|
21
|
+
}
|
|
22
|
+
if (typeof home !== 'string') return { ok: false, say: NEVER_CHECKED_SAY };
|
|
23
|
+
const place = mcpSources({ home }).places.find((p) => p.servers.some((s) => s.name === server));
|
|
24
|
+
if (!place) return { ok: false, say: `${server} is not in any MCP config (Settings > MCP lists the ones found)` };
|
|
25
|
+
if (mcpConfigFor(server, { home })?.remote) return { ok: false, say: remoteRefusal(server) };
|
|
26
|
+
const tools = newestOkMcpTools(home, server, place.path);
|
|
27
|
+
return tools === null ? { ok: false, say: NEVER_CHECKED_SAY } : { ok: true, server, tools };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** `mcpPickFor` at the config home this process uses (a test process with no `FWDLOOP_CONFIG_HOME` has none) @param {string} server */
|
|
31
|
+
export function mcpPickHere(server) {
|
|
32
|
+
return mcpPickFor(server, undefined);
|
|
33
|
+
}
|