fwdloop 0.37.0 → 0.39.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 +5 -19
- package/bin/fwdloop +51 -29
- package/package.json +1 -1
- package/src/ask.js +70 -148
- package/src/audit-fold.js +5 -4
- package/src/auditchecks.js +6 -4
- package/src/authoring.js +36 -64
- package/src/blockasks.js +2 -1
- package/src/blockassemble.js +7 -9
- package/src/blockdraft.js +2 -2
- package/src/blockpick.js +5 -5
- package/src/books.js +217 -12
- package/src/checkblock.js +25 -55
- package/src/checked.js +2 -3
- package/src/checklistsign.js +26 -5
- package/src/checklook.js +3 -1
- package/src/checkpick.js +5 -76
- package/src/cited-source.js +4 -4
- package/src/citedcheck.js +6 -11
- package/src/citedwords.js +9 -8
- package/src/closers.js +9 -6
- package/src/declaration.js +22 -55
- package/src/diary.js +23 -1
- package/src/draft-steps.js +11 -1
- package/src/drafter.js +28 -23
- package/src/draftfiles.js +127 -0
- package/src/draftspend.js +165 -17
- package/src/flow.js +42 -87
- package/src/flowmodel.js +1 -1
- package/src/index.js +3 -2
- package/src/inside.js +86 -0
- package/src/isrec.js +2 -0
- package/src/jsonl-append.js +33 -1
- package/src/learn.js +1 -1
- package/src/learnstore.js +20 -22
- package/src/line-checks.js +2 -3
- package/src/liveness.js +3 -0
- package/src/mcp-use.js +8 -9
- package/src/memo.js +13 -16
- package/src/minrule.js +16 -0
- package/src/model-step.js +3 -3
- package/src/page-words.js +8 -0
- package/src/pageask.js +8 -3
- package/src/pagebits.js +8 -1
- package/src/pagedropwords.js +1 -1
- package/src/pagerules.js +6 -3
- package/src/panel/author.js +121 -78
- package/src/panel/authorcard.js +21 -8
- package/src/panel/authorflows.js +3 -3
- package/src/panel/authorresume.js +3 -3
- package/src/panel/authorstart.js +15 -16
- package/src/panel/authortrigger.js +43 -70
- package/src/panel/data.js +125 -168
- package/src/panel/index.html +154 -63
- package/src/panel/jobgrid.js +3 -7
- package/src/panel/result.js +7 -10
- package/src/panel/resume.js +4 -3
- package/src/panel/scheduler.js +9 -9
- package/src/panel/server.js +8 -4
- package/src/panel/spawn.js +22 -11
- package/src/panel/tickets.js +2 -2
- package/src/pickrecord.js +51 -31
- package/src/placerule.js +3 -4
- package/src/planrebuild.js +19 -19
- package/src/primitives.js +1 -1
- package/src/provider.js +1 -1
- package/src/reasons.js +25 -0
- package/src/report.js +2 -1
- package/src/runfile.js +26 -2
- package/src/runner.js +57 -105
- package/src/runvalues.js +47 -24
- package/src/schedule-choices.js +41 -0
- package/src/schedule-shape.js +39 -0
- package/src/schedule.js +9 -8
- package/src/setup.js +20 -36
- package/src/shaperows.js +2 -2
- package/src/sheet-record.js +1 -2
- package/src/sheetblock.js +3 -4
- package/src/sheetbuild.js +5 -5
- package/src/sheetchecks.js +1 -2
- package/src/sheetclaims.js +1 -2
- package/src/sheetoffer.js +1 -1
- package/src/sheetrun.js +5 -7
- package/src/summary-words.js +2 -1
- package/src/thinking.js +5 -2
- package/src/ticketrows.js +8 -30
- package/src/trigger-clock.js +9 -23
- package/src/trigger-files.js +30 -22
- package/src/trigger-tickets.js +15 -14
- package/src/try-checks.js +2 -1
- package/src/types.js +2 -0
- package/types/ask.d.ts +25 -20
- package/types/authoring.d.ts +8 -42
- package/types/blockassemble.d.ts +0 -1
- package/types/blockpick.d.ts +1 -1
- package/types/books.d.ts +256 -4
- package/types/checkblock.d.ts +2 -25
- package/types/checklist.d.ts +3 -3
- package/types/checklistsign.d.ts +7 -0
- package/types/checkpick.d.ts +0 -21
- package/types/citedwords.d.ts +7 -4
- package/types/closers.d.ts +1 -0
- package/types/declaration.d.ts +4 -14
- package/types/diary.d.ts +14 -1
- package/types/draft-steps.d.ts +7 -0
- package/types/drafter.d.ts +3 -2
- package/types/draftfiles.d.ts +89 -0
- package/types/draftspend.d.ts +74 -0
- package/types/flow.d.ts +32 -54
- package/types/index.d.ts +3 -3
- package/types/inside.d.ts +58 -0
- package/types/isrec.d.ts +1 -0
- package/types/jsonl-append.d.ts +20 -0
- package/types/learnstore.d.ts +0 -2
- package/types/liveness.d.ts +1 -0
- package/types/minrule.d.ts +6 -0
- package/types/page-words.d.ts +6 -0
- package/types/pageask.d.ts +2 -0
- package/types/pagebits.d.ts +3 -0
- package/types/pagerules.d.ts +1 -0
- package/types/panel/author.d.ts +7 -3
- package/types/panel/authorcard.d.ts +0 -6
- package/types/panel/authorflows.d.ts +4 -4
- package/types/panel/authortrigger.d.ts +16 -2
- package/types/panel/data.d.ts +36 -11
- package/types/panel/spawn.d.ts +18 -2
- package/types/pickrecord.d.ts +29 -0
- package/types/reasons.d.ts +23 -0
- package/types/runfile.d.ts +14 -0
- package/types/runner.d.ts +6 -38
- package/types/runvalues.d.ts +17 -2
- package/types/schedule-choices.d.ts +9 -0
- package/types/schedule-shape.d.ts +15 -0
- package/types/sheetbuild.d.ts +1 -1
- package/types/sheetclaims.d.ts +0 -1
- package/types/thinking.d.ts +1 -0
- package/types/ticketrows.d.ts +0 -9
- package/types/trigger-clock.d.ts +3 -2
- package/types/trigger-files.d.ts +15 -4
- package/types/types.d.ts +8 -0
package/src/drafter.js
CHANGED
|
@@ -49,11 +49,11 @@ import { questionsOfBlock } from './blockasks.js';
|
|
|
49
49
|
import { NOTE_KIND, NOTE_TOOL, NOTE_SYSTEM, NOTE_SCHEMA, notePrompt, noteAnswers } from './noteask.js';
|
|
50
50
|
import { ledgerRecord, LEDGER_SYSTEM, LEDGER_SCHEMA, LEDGER_TOOL, ledgerUserText } from './checklist.js';
|
|
51
51
|
import { ROW_EDIT_SYSTEM, ROW_EDIT_REVISE, rowEditUserText, rowEditChannel, editsOf, ticketFilterBlock } from './rowedit.js';
|
|
52
|
-
import { matchRecord, entriesFromAnswers, columnEntries, columnsOnLines } from './pickrecord.js';
|
|
52
|
+
import { matchRecord, entriesFromAnswers, columnEntries, columnsOnLines, addedCountsOf } from './pickrecord.js';
|
|
53
53
|
import { MAP_SYSTEM, mapPrompt } from './pagemap.js';
|
|
54
54
|
import { tooManyAsksText, MAX_LOOK_ASKS } from './pageask.js';
|
|
55
55
|
import { lineRules } from './pagebits.js';
|
|
56
|
-
import {
|
|
56
|
+
import { isCountable } from './blockpick.js';
|
|
57
57
|
import path from 'node:path';
|
|
58
58
|
import { isCellsPath } from './closers.js';
|
|
59
59
|
import { parseCsv, sheetTable } from './csv.js';
|
|
@@ -61,13 +61,14 @@ import { sheetSuggestProp, sheetOfferRules, agreedColumnWords } from './sheetoff
|
|
|
61
61
|
import { uncoveredRules, csvRolesOf } from './sheetblock.js';
|
|
62
62
|
import { withSheetRows, withSheetCard } from './sheetrows.js';
|
|
63
63
|
import { buildSheetChecks, unbuiltSheetLines } from './sheetbuild.js';
|
|
64
|
-
import {
|
|
64
|
+
import { ticketRuleField, proposalReds, withTicketRows } from './ticketrows.js';
|
|
65
|
+
import { TICKET_FIELDS } from './checklistsign.js';
|
|
65
66
|
import {
|
|
66
67
|
makeProvider, ModelRefusal, sumMeterings, ceilingCostUsd, priceRecord,
|
|
67
68
|
} from './provider.js';
|
|
68
69
|
import { LIVE_PROVIDER_OPTIONS } from './model-step.js';
|
|
69
70
|
import { ConfigError } from './config.js';
|
|
70
|
-
import { thinkingSay, worstThinkingStatus } from './thinking.js';
|
|
71
|
+
import { thinkingSay, worstThinkingStatus, isThinkingMode } from './thinking.js';
|
|
71
72
|
import { repairTrailingBraces } from './jsonbrace.js';
|
|
72
73
|
|
|
73
74
|
export const MAX_STRUCTURE_RETRIES = 2;
|
|
@@ -243,7 +244,7 @@ export function normalizeQuestions(raw, failedLines) {
|
|
|
243
244
|
|
|
244
245
|
// M10 am27 (1): at draft time a count guardrail is hidden from the AI (the page look and the drafter); code keeps the ORIGINAL rule numbers and text.
|
|
245
246
|
// M16 S5: not on a line the check block is given (`all`): its count rules are shown like any other (am27 (1) is replaced for the lines of the list)
|
|
246
|
-
const shownRules = (/** @type {string} */ guardrail, all = false) => lineRules({ rule: guardrail }).filter((r) => all || !
|
|
247
|
+
const shownRules = (/** @type {string} */ guardrail, all = false) => lineRules({ rule: guardrail }).filter((r) => all || !isCountable(r)).join('; ');
|
|
247
248
|
|
|
248
249
|
/**
|
|
249
250
|
* The job lines as the page look may see them (no count rule), and `toOriginal`, which takes a look fact's / dropped entry's visible rule number back to the guardrail's own number.
|
|
@@ -251,10 +252,10 @@ const shownRules = (/** @type {string} */ guardrail, all = false) => lineRules({
|
|
|
251
252
|
*/
|
|
252
253
|
export function hideCounts(jobLines, shown = /** @type {Set<number>} */ (new Set())) {
|
|
253
254
|
// M16 item 5: the lines the check block is given show their count rules to the look (`shown`); every other line is as before
|
|
254
|
-
const seenLines = jobLines.map((l) => { const kept = lineRules(l).filter((r) => shown.has(l.n) || !
|
|
255
|
+
const seenLines = jobLines.map((l) => { const kept = lineRules(l).filter((r) => shown.has(l.n) || !isCountable(r)); return { n: l.n, text: l.text, ...(kept.length ? { rule: kept.join('; ') } : {}) }; });
|
|
255
256
|
const ruleMap = (/** @type {number} */ line, /** @type {number|undefined} */ vis) => {
|
|
256
257
|
if (vis === undefined || shown.has(line)) return vis;
|
|
257
|
-
const orig = lineRules(jobLines.find((x) => x.n === line)).map((r, i) => ({ r, no: i + 1 })).filter((x) => !
|
|
258
|
+
const orig = lineRules(jobLines.find((x) => x.n === line)).map((r, i) => ({ r, no: i + 1 })).filter((x) => !isCountable(x.r));
|
|
258
259
|
return orig[vis - 1]?.no ?? vis;
|
|
259
260
|
};
|
|
260
261
|
const toOriginal = (/** @type {any} */ f) => (f.forRule !== undefined ? { ...f, forRule: ruleMap(f.line, f.forRule) } : f.rule !== undefined ? { ...f, rule: ruleMap(f.line, f.rule) } : f);
|
|
@@ -362,7 +363,7 @@ function isPlainObject(v) { return !!v && typeof v === 'object' && !Array.isArra
|
|
|
362
363
|
* @returns {Promise<{ok:boolean, declaration:object|null, reds:string[], rounds:number, calls:number, spendComplete:boolean,
|
|
363
364
|
* costUsd:number|null, modelReturned:string|null, modelId?:string, price?:object|null, tokens?:object|null, structureRetries:number, revisions:number, stop:string|null, log:object[],
|
|
364
365
|
* questions?:{line:number, question:string}[], proseText?:string, action?:{line:number, by?:'agent'|'you', dropped?:true}|null, droppedQuestions?:object[], notChecked?:string[], thinking?:{asked:string, status:string|null, say:string|null}, inputs?:{role:string, detail:string}[],
|
|
365
|
-
* checkCard?:ReturnType<typeof cardOfPlanBlock>, sheetBuilt?:Awaited<ReturnType<typeof buildSheetChecks>>, notCheckedBy?:Record<string,'you'|'agent'|'default'>, look?:{facts:any[], dropped:any[]}, pageLooks?:{role:string, address:string, sha256:string, bytes:number, frozen:string, attempts:number, mapping:any}[], sheetLooks?:any[]}>}
|
|
366
|
+
* checkCard?:ReturnType<typeof cardOfPlanBlock>, sheetBuilt?:Awaited<ReturnType<typeof buildSheetChecks>>, notCheckedBy?:Record<string,'you'|'agent'|'default'>, look?:{facts:any[], dropped:any[]}, pageLooks?:{role:string, address:string, sha256:string, bytes:number, frozen:string, attempts:number, mapping:any}[], sheetLooks?:any[], box?:string}>}
|
|
366
367
|
* `learnHints` (M8 item 5a): the earlier runs' notes block (src/learnstore.js hintsForRun), appended to the drafter's system prompt; null = nothing.
|
|
367
368
|
* `look` / `pageLooks` (M10 item 3) are there when the job signs a web page: the kept facts (with their `reading`, the input a later ask reads), every drop, and per page its address, sha256 and the AI's map. Each drop is also a line in `notChecked`.
|
|
368
369
|
*/
|
|
@@ -386,37 +387,38 @@ export async function draft({
|
|
|
386
387
|
const status = worstThinkingStatus(log.map((e) => e.thinkingStatus));
|
|
387
388
|
return { asked: draftThinking, status, say: thinkingSay(status) };
|
|
388
389
|
};
|
|
389
|
-
const fail = (reds, extra = {}) => ({
|
|
390
|
+
const fail = (reds, extra = /** @type {{box?: string}} */ ({})) => ({
|
|
390
391
|
ok: false, declaration: null, reds, rounds: 0, calls: 0, spendComplete: true, costUsd: 0, modelReturned: null, structureRetries: 0, revisions: 0, stop: 'pre-flight', log: [], ...extra,
|
|
391
392
|
});
|
|
392
393
|
|
|
393
394
|
// ---- $0 gates, before any provider is built -------------------------------
|
|
394
395
|
// `draftThinking` ('on'|'off', M4d am6 item 7 / am7: the Chat tick-box, per job) is an intent only: turning thinking on or off on the wire is bareagent's (am7 item 3).
|
|
395
|
-
if (draftThinking
|
|
396
|
+
if (!isThinkingMode(draftThinking)) return fail([`config: draftThinking must be on | off, got ${JSON.stringify(draftThinking)}`]);
|
|
396
397
|
if (actionMode !== null && actionMode !== 'check' && actionMode !== 'known') return fail([`config: actionMode must be check | known, got ${JSON.stringify(actionMode)}`]);
|
|
397
398
|
const parsed = parseSignedText(proseText);
|
|
398
|
-
if (!parsed.ok) return fail(parsed.reds.map((r) => `signed-text: ${r}`));
|
|
399
|
+
if (!parsed.ok) return fail(parsed.reds.map((r) => `signed-text: ${r}`), { box: 'job' });
|
|
399
400
|
const { lines } = parsed;
|
|
400
401
|
let { arbiter } = parsed;
|
|
401
402
|
const ttlReds = unsignedAskTtls(arbiter);
|
|
402
|
-
if (ttlReds.length) return fail(ttlReds);
|
|
403
|
+
if (ttlReds.length) return fail(ttlReds, { box: 'job' });
|
|
403
404
|
// M4e amendment 15 item 2: a guardrail that fights itself on words is red at $0, before any provider is built or called.
|
|
404
405
|
const sumReds = checkGuardrailSums(lines);
|
|
405
|
-
if (sumReds.length) return fail(sumReds);
|
|
406
|
+
if (sumReds.length) return fail(sumReds, { box: 'job' });
|
|
406
407
|
// 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).
|
|
407
408
|
// M13 am11: with an actionMode the send is the card's tentative one; the refusal is made after the AI says whether the last line is the action (below)
|
|
408
409
|
const sendReds = actionMode === null ? checkSendLineGuardrail(lines, arbiter) : [];
|
|
409
|
-
if (sendReds.length) return fail(sendReds);
|
|
410
|
+
if (sendReds.length) return fail(sendReds, { box: 'job' });
|
|
410
411
|
const menu = wiredMenu(skills);
|
|
411
412
|
// 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).
|
|
412
413
|
const fileFacts = readInputFacts((arbiter.sources ?? []).filter((s) => s.kind !== 'page'));
|
|
413
|
-
if (!fileFacts.ok) return fail(fileFacts.reds);
|
|
414
|
+
if (!fileFacts.ok) return fail(fileFacts.reds, { box: 'inputs' });
|
|
414
415
|
// 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.
|
|
415
416
|
// 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.
|
|
416
417
|
const ticketSources = flowType === 'tickets' ? ticketSourcesOf(arbiter.sources) : [];
|
|
417
418
|
const servers = flowType === 'plain' ? [] : (mcpServers ?? userMcpServers());
|
|
418
419
|
const flowReds = ticketReds({ flowType, ticketSources, pick: mcp, servers });
|
|
419
|
-
|
|
420
|
+
// M19 am14b: the Tickets list address is an Inputs line; every other flow red is about the picked MCP
|
|
421
|
+
if (flowReds.length) return fail(flowReds, { box: flowType === 'tickets' && ticketSources.length === 0 ? 'inputs' : 'mcp' });
|
|
420
422
|
|
|
421
423
|
let { provider, rates, modelId } = { provider: injected, rates: injectedRates, modelId: injectedModelId };
|
|
422
424
|
let prices = null; // the one price lookup's result (live provider only); the cap check below uses the SAME price
|
|
@@ -426,7 +428,7 @@ export async function draft({
|
|
|
426
428
|
provider, rates, modelId, prices = null,
|
|
427
429
|
} = makeProviderFn(slot, { model, env, ...LIVE_PROVIDER_OPTIONS }));
|
|
428
430
|
} catch (err) {
|
|
429
|
-
return fail([err instanceof ModelRefusal ? err.message : `${err instanceof ConfigError ? 'config' : 'key'}: ${err.message}`]);
|
|
431
|
+
return fail([err instanceof ModelRefusal ? err.message : `${err instanceof ConfigError ? 'config' : 'key'}: ${err.message}`], { box: 'model' });
|
|
430
432
|
}
|
|
431
433
|
}
|
|
432
434
|
|
|
@@ -436,7 +438,7 @@ export async function draft({
|
|
|
436
438
|
if (!cat.ok) return fail([`catalogue: ${cat.reds.join('; ')}`]);
|
|
437
439
|
const validationCatalogue = cat.primitives;
|
|
438
440
|
// The hold: the picked model's own Settings prices (or the rates a test injected) times the token bounds - never a table.
|
|
439
|
-
if (!rates) return fail(['price: this round has no price to hold - tick a model in Settings > Providers with both prices first']);
|
|
441
|
+
if (!rates) return fail(['price: this round has no price to hold - tick a model in Settings > Providers with both prices first'], { box: 'model' });
|
|
440
442
|
const roundCeiling = ceilingCostUsd(rates);
|
|
441
443
|
// M4d am13: the draft is capped by the card's Cap $ (the cap signed in the prose), the same number the run is capped at.
|
|
442
444
|
// One round at its ceiling must fit that cap, or refuse at $0 before any provider call.
|
|
@@ -447,7 +449,7 @@ export async function draft({
|
|
|
447
449
|
const tooSmall = (ceiling) => (priorUsd > 0
|
|
448
450
|
? `Cap ${usdText(arbiter.capUsd)} less ${usdText(priorUsd)} already spent on drafting leaves ${usdText(Math.max(0, budgetUsd))}, below one drafting round's worst case for ${modelId}, $${ceiling.toFixed(4)}. Raise Cap $ or pick another model.`
|
|
449
451
|
: capTooSmallText('drafting', arbiter.capUsd, ceiling, modelId));
|
|
450
|
-
if (roundCeiling > budgetUsd) return fail([tooSmall(roundCeiling)]);
|
|
452
|
+
if (roundCeiling > budgetUsd) return fail([tooSmall(roundCeiling)], { box: 'capUsd' });
|
|
451
453
|
|
|
452
454
|
const meterings = [];
|
|
453
455
|
const log = [];
|
|
@@ -455,6 +457,8 @@ export async function draft({
|
|
|
455
457
|
let unmetered = 0; // calls that failed with no metering: their cost is unknown
|
|
456
458
|
const book = (inFlight) => onBook?.({
|
|
457
459
|
inFlight, calls, unmetered, metered: sumMeterings(meterings), modelId, price: priceRecord(prices, rates),
|
|
460
|
+
// M20 am1 item 5: the result so far, in log.json's shape, for the step lines (src/draftspend.js makeStepWriter)
|
|
461
|
+
partial: () => { const m = sumMeterings(meterings); return { ok: false, reds: [], rounds: m.rounds, modelId, costUsd: m.costUsd, spendComplete: unmetered === 0 && m.costUsd !== null, thinking: thinkingOf(), inputs: facts.list, log }; },
|
|
458
462
|
});
|
|
459
463
|
|
|
460
464
|
/** 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 */
|
|
@@ -504,7 +508,7 @@ export async function draft({
|
|
|
504
508
|
for (let attempt = 1; attempt <= attempts; attempt += 1) {
|
|
505
509
|
const spentBefore = meterings.reduce((sum, ev) => sum + (ev.costUsd ?? roundCeiling), 0);
|
|
506
510
|
if (spentBefore + ceilingCostUsd(rates, sys.length + messages.reduce((n, m) => n + m.content.length, 0) + JSON.stringify(spec.schema).length) > budgetUsd) {
|
|
507
|
-
if (meterings.length === 0 && calls === 0) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); return { early: fail([tooSmall(roundCeiling)]) }; }
|
|
511
|
+
if (meterings.length === 0 && calls === 0) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); return { early: fail([tooSmall(roundCeiling)], { box: 'capUsd' }) }; }
|
|
508
512
|
return { early: earlyStop(['the draft budget is spent'], 'budget') };
|
|
509
513
|
}
|
|
510
514
|
/** @type {any} */
|
|
@@ -638,7 +642,7 @@ export async function draft({
|
|
|
638
642
|
const mapCeiling = ceilingCostUsd(rates, mapPrompt({ jobLines: seenLines, label: s.role, text: pg.text }).length + MAP_SYSTEM.length);
|
|
639
643
|
const spentBefore = meterings.reduce((sum, ev) => sum + (ev.costUsd ?? roundCeiling), 0);
|
|
640
644
|
if (spentBefore + mapCeiling > budgetUsd) {
|
|
641
|
-
if (meterings.length === 0 && calls === 0) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); return fail([tooSmall(mapCeiling)]); }
|
|
645
|
+
if (meterings.length === 0 && calls === 0) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); return fail([tooSmall(mapCeiling)], { box: 'capUsd' }); }
|
|
642
646
|
}
|
|
643
647
|
const callModel = makeCallModel('page-map');
|
|
644
648
|
const got0 = await lookAtPage({ label: s.role, text: pg.text, jobLines: seenLines, callModel });
|
|
@@ -698,7 +702,7 @@ export async function draft({
|
|
|
698
702
|
const text = headings === undefined ? facts.sheets[role] : '';
|
|
699
703
|
const spentBefore = meterings.reduce((sum, ev) => sum + (ev.costUsd ?? roundCeiling), 0);
|
|
700
704
|
const hold = ceilingCostUsd(rates, sheetPrompt({ jobLines: sheetJobLines, label: role, text, headings }).length + MAP_SYSTEM.length);
|
|
701
|
-
if (spentBefore + hold > budgetUsd && meterings.length === 0 && calls === 0) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); return fail([tooSmall(hold)]); }
|
|
705
|
+
if (spentBefore + hold > budgetUsd && meterings.length === 0 && calls === 0) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); return fail([tooSmall(hold)], { box: 'capUsd' }); }
|
|
702
706
|
const got = await lookAtSheet({ label: role, text, headings, jobLines: sheetJobLines, callModel: makeCallModel('sheet-map') });
|
|
703
707
|
if (!got.ok) {
|
|
704
708
|
const m = sumMeterings(meterings);
|
|
@@ -728,7 +732,7 @@ export async function draft({
|
|
|
728
732
|
const shapeEverywhere = offerRules(lines, arbiter, [...look.facts, ...sheetFacts]);
|
|
729
733
|
// M16 S1: the lines the block is given (step lines; a sheet line the sheet look tied to a column stays on the sheet path, R6). Their rules go to the block; every other shape rule keeps today's path.
|
|
730
734
|
// a job with a CSV input: a line with a rule that is not a count belongs to the sheet path even when the sheet look tied none of its words (its sheet checks are the drafter's, M10b, which the list leaves as they are; the declaration is not there yet to say it)
|
|
731
|
-
const csvRuleLines = Object.keys(facts.sheets ?? {}).length ? jobLines.filter((l) => !askLines.has(l.n) && lineRules(l).some((r) => !
|
|
735
|
+
const csvRuleLines = Object.keys(facts.sheets ?? {}).length ? jobLines.filter((l) => !askLines.has(l.n) && lineRules(l).some((r) => !isCountable(r))).map((l) => l.n) : [];
|
|
732
736
|
const blockPlan = blockJobLines(proseText, undefined, [...new Set([...sheetFacts.filter((f) => f.forRule !== undefined), ...sheetAsks, ...sheetLooks.flatMap((l) => l.dropped)].map((x) => x.line)), ...csvRuleLines]);
|
|
733
737
|
if (blockPlan && !blockPlan.ok) return fail(blockPlan.reds.map((r) => `signed-text: ${r}`));
|
|
734
738
|
const blockLineNums = new Set(blockPlan ? blockPlan.jobLines.map((l) => l.n) : []);
|
|
@@ -1093,6 +1097,7 @@ export async function draft({
|
|
|
1093
1097
|
const planLookFacts = inPlan ? look.facts.filter((f) => !blockLineNums.has(f.line) || inPlan.has(`${f.line}:${f.name}`)) : look.facts;
|
|
1094
1098
|
const verdict1 = validateDeclaration(declaration, {
|
|
1095
1099
|
arbiter, lines, catalogue: validationCatalogue, wired: WIRED_VERBS, verbatimGoals: true, fitJobLine: true,
|
|
1100
|
+
addedCounts: block ? addedCountsOf(block.choicesRecord(), lines) : new Set(),
|
|
1096
1101
|
// 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
|
|
1097
1102
|
sheetWords: sheetTables ? { headers: Object.fromEntries(Object.entries(sheetTables).map(([role, t]) => [role, t.header])), facts: sheetFacts.filter((f) => f.shape === 'column' && !(sheetHitl?.lines ?? []).includes(f.line)), tables: sheetTables } : undefined,
|
|
1098
1103
|
pageWords: { texts: { ...(facts.docs ?? {}), ...Object.fromEntries(Object.entries(pages).map(([role, pg]) => [role, pg.text])) }, look: pageSources.length ? { facts: planLookFacts, dropped: look.dropped } : null, docs: docRolesOf(arbiter.sources) },
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
// M20 am3b item 2: what a plan folder's own files say, apart from the sign: its verdict, its questions with their answers, and the key scrub. Moved out of
|
|
2
|
+
// src/authoring.js so src/setup.js (which records them) and src/authoring.js (which calls writeSetup) no longer import each other.
|
|
3
|
+
import { readDraftLog, readJsonFile } from './flow.js';
|
|
4
|
+
import { readFileInside } from './inside.js';
|
|
5
|
+
import { isRec } from './isrec.js';
|
|
6
|
+
import { parseSignedText } from './signed-text.js';
|
|
7
|
+
|
|
8
|
+
export const SPEC_HASH_FILE = 'spec.hash';
|
|
9
|
+
/** Written when the end sweep finds a key in the draft dir; sign refuses a dir that has it. */
|
|
10
|
+
export const LEAK_MARKER_FILE = 'scrub-leak.red';
|
|
11
|
+
/**
|
|
12
|
+
* M20 am3 item 12: the ONE reader of one plan folder's verdict, from its files (`spec.hash`, `scrub-leak.red`, `log.json`). Green = a
|
|
13
|
+
* non-empty spec.hash; red = a leak marker or a log that says not ok (`reds` = the log's own reds, then the marker's text); none otherwise.
|
|
14
|
+
* `hashFile` and `leak` are the raw reads, so sign can name a missing or refused file in its own words. Callers scrub `reds` themselves.
|
|
15
|
+
* @param {string} dir the folder that holds the plan folder @param {string} [rel] `draft`, `draft-<n>` or `.` (the plan folder itself)
|
|
16
|
+
* @returns {{verdict: 'green'|'red'|'none', hash: string|null, hashFile: ReturnType<typeof readFileInside>, leak: ReturnType<typeof readFileInside>, log: any, reds: string[]}}
|
|
17
|
+
*/
|
|
18
|
+
export function draftVerdict(dir, rel = '.') {
|
|
19
|
+
const hashFile = readFileInside(dir, `${rel}/${SPEC_HASH_FILE}`);
|
|
20
|
+
const hash = hashFile.ok && hashFile.text.trim() !== '' ? hashFile.text.trim() : null;
|
|
21
|
+
const leak = readFileInside(dir, `${rel}/${LEAK_MARKER_FILE}`);
|
|
22
|
+
const log = readDraftLog(dir, rel);
|
|
23
|
+
const reds = [...(Array.isArray(log?.reds) ? log.reds.map(String) : []), ...(leak.ok ? [leak.text.trim()] : [])];
|
|
24
|
+
return { verdict: hash ? 'green' : (leak.ok || (log && log.ok === false)) ? 'red' : 'none', hash, hashFile, leak, log, reds };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export const QUESTIONS_FILE = 'questions.json';
|
|
28
|
+
export const ANSWER_FILE = (k) => `answer-${k}.json`;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The questions a plan folder raised and the answers on disk, READ from its files — the ONE reader (the panel's phase reader, the sign
|
|
32
|
+
* checks and the page all use it). `questions` = [{ k, line, question, answer|null }], `open` = those with no answer. A blank or unreadable
|
|
33
|
+
* answer file counts as no answer. No questions file = `{ questions: [], open: [] }`.
|
|
34
|
+
* @param {string} planDir
|
|
35
|
+
* A question the page look raised (M10 piece 3) also carries `source: 'look'`, `ask` ('reading' | 'cant-check'), `ruleNo`, `ruleText` and `proposal`; an answer file carries `at`.
|
|
36
|
+
* @returns {{ questions: {k:number, line:number, question:string, answer:string|null, at?:string, rule?:string|null, choice?:'agree'|'drop'|'rule'|'column', source?:string, ask?:string, ruleNo?:number, ruleText?:string, proposal?:string|null, check?:Record<string, any>, pairRule?:number, columns?:string[], readings?:Record<string,string>}[], open: {k:number, line:number, question:string, answer:null}[] }}
|
|
37
|
+
*/
|
|
38
|
+
export function readQuestions(planDir) {
|
|
39
|
+
const none = { questions: [], open: [] };
|
|
40
|
+
const f = readFileInside(planDir, QUESTIONS_FILE);
|
|
41
|
+
if (!f.ok) return none;
|
|
42
|
+
let list;
|
|
43
|
+
try { list = JSON.parse(f.text)?.questions; } catch { return none; }
|
|
44
|
+
if (!Array.isArray(list)) return none;
|
|
45
|
+
const questions = list.map((q, i) => {
|
|
46
|
+
const k = i + 1;
|
|
47
|
+
const a = readFileInside(planDir, ANSWER_FILE(k));
|
|
48
|
+
let answer = null;
|
|
49
|
+
let at;
|
|
50
|
+
/** @type {string|null|undefined} the `~` rule the answer added (null = it left the rule Not checked), as the answer file recorded it */
|
|
51
|
+
let rule;
|
|
52
|
+
/** @type {'agree'|'drop'|'rule'|'column'|undefined} M10 am29: which one the answer used (`agree`, `drop` or `rule`), when the file records it */
|
|
53
|
+
let choice;
|
|
54
|
+
if (a.ok) {
|
|
55
|
+
try {
|
|
56
|
+
const j = JSON.parse(a.text);
|
|
57
|
+
const t = j?.answer;
|
|
58
|
+
if (typeof t === 'string' && t.trim() !== '') { answer = t; if (typeof j.at === 'string') at = j.at; if (j.rule === null || typeof j.rule === 'string') rule = j.rule; if (j.choice === 'agree' || j.choice === 'drop' || j.choice === 'rule' || j.choice === 'column') choice = j.choice; }
|
|
59
|
+
} catch { /* unreadable = unanswered */ }
|
|
60
|
+
}
|
|
61
|
+
return {
|
|
62
|
+
k, line: q.line, question: String(q.question), answer, ...(at === undefined ? {} : { at }), ...(rule === undefined ? {} : { rule }), ...(choice === undefined ? {} : { choice }),
|
|
63
|
+
...(q.source === 'look' ? { source: 'look', ask: q.ask, ruleNo: q.ruleNo, ruleText: q.ruleText, proposal: typeof q.proposal === 'string' ? q.proposal : null, ...(q.check && typeof q.check === 'object' ? { check: q.check } : {}), ...(Number.isInteger(q.pairRule) ? { pairRule: q.pairRule } : {}), ...(Array.isArray(q.columns) && q.columns.length > 0 && q.readings && typeof q.readings === 'object' ? { columns: q.columns.map(String), readings: q.readings } : {}) } : {}),
|
|
64
|
+
};
|
|
65
|
+
});
|
|
66
|
+
return { questions, open: /** @type {any} */ (questions.filter((q) => q.answer === null)) };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Literal (never RegExp) key scrub; a secret under 8 chars is skipped so it can't blank ordinary text. */
|
|
70
|
+
export function scrub(text, secrets) {
|
|
71
|
+
let out = text;
|
|
72
|
+
for (const s of secrets) if (typeof s === 'string' && s.length >= 8) out = out.split(s).join('[redacted-key]');
|
|
73
|
+
return out;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
/** the drafter's own "Not checked" reading, kept in a plan folder (information only; never in the readout, so never in the hash) */
|
|
78
|
+
export const NOT_CHECKED_FILE = 'not-checked.json';
|
|
79
|
+
/**
|
|
80
|
+
* M20 am3 item 10: the ONE reader of a plan folder's `not-checked.json`. `notChecked` is the file's own list as it is (any type; the callers keep what they
|
|
81
|
+
* accept of it: `notCheckedBlock`/`notCheckedView` filter strings, the rebuild keeps strings), `by` the tag of each line when the file holds an object, else null.
|
|
82
|
+
* A missing, refused, unparseable or non-object file reads as `{notChecked: undefined, by: null}` (a plan from before amendment 25 has none).
|
|
83
|
+
* @param {string} dir the folder that holds the plan folder @param {string} [rel] `draft`, `draft-<n>` or `.` (the plan folder itself)
|
|
84
|
+
* @returns {{notChecked: any, by: Record<string, any>|null}}
|
|
85
|
+
*/
|
|
86
|
+
export function readNotCheckedFile(dir, rel = '.') {
|
|
87
|
+
const f = readJsonFile(dir, `${rel}/${NOT_CHECKED_FILE}`);
|
|
88
|
+
return { notChecked: f?.notChecked, by: isRec(f?.by) ? f.by : null };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* M20 am3e item 17: a draft session folder's card files, spelled and read here only. `card.json` is the first card (n 0 or none), `card-<n>.json` the card of
|
|
93
|
+
* revise or redraft n. `readCard` is the tolerant read: the card object, or null (missing, refused, not JSON, not an object). A site that only asks "is there a
|
|
94
|
+
* readable file" (src/draftspend.js, the money count) is not this question and keeps its own check.
|
|
95
|
+
* @param {number} [n] @returns {string}
|
|
96
|
+
*/
|
|
97
|
+
export const cardFileName = (n = 0) => (n > 0 ? `card-${n}.json` : 'card.json');
|
|
98
|
+
/** @param {string} dir the session folder @param {number} [n] @returns {Record<string, any>|null} */
|
|
99
|
+
export const readCard = (dir, n = 0) => readJsonFile(dir, cardFileName(n));
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* M20 am3e item 18: `redraft-<n>.json`, the marker that plan n is a redraft after the person's answers or a Drop/Add edit, not a revise. Its name and its one read:
|
|
103
|
+
* the marker object as written (`fromPlan`, `answers`, `left`), or null (missing, refused, not JSON, not an object). `rowEdit` is typed: an object, or the key is
|
|
104
|
+
* left out (none): a `rowEdit` that is not an object reads as none everywhere.
|
|
105
|
+
* @param {number} n @returns {string}
|
|
106
|
+
*/
|
|
107
|
+
export const redraftFileName = (n) => `redraft-${n}.json`;
|
|
108
|
+
/** @param {string} dir the session folder @param {number} n @returns {Record<string, any>|null} */
|
|
109
|
+
export function readRedraftMarker(dir, n) {
|
|
110
|
+
const m = readJsonFile(dir, redraftFileName(n));
|
|
111
|
+
if (m === null || !Object.hasOwn(m, 'rowEdit') || isRec(m.rowEdit)) return m;
|
|
112
|
+
const { rowEdit: _dropped, ...rest } = m;
|
|
113
|
+
return rest;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* M20 am3e item 20: a draft plan folder's job text and steps, the ONE reader. `proseText` is prose.txt as it is (null when missing or refused), `parsed` the signed-text
|
|
118
|
+
* parse of it (`parseSignedText`'s result, ok or not; null when there is no prose), `declaration` declaration.json as an object (null when missing, refused, not JSON or not
|
|
119
|
+
* an object). Each caller keeps its own sentence for what it does when one is null. (A flow folder with a signature is `readFlow`'s; a plan that falls back to
|
|
120
|
+
* declaration.rejected.json is src/panel/author.js `stepListOf`'s own question.)
|
|
121
|
+
* @param {string} dir the folder that holds the plan folder @param {string} [rel] `draft`, `draft-<n>` or `.` (the plan folder itself)
|
|
122
|
+
* @returns {{proseText: string|null, parsed: ReturnType<typeof parseSignedText>|null, declaration: any}}
|
|
123
|
+
*/
|
|
124
|
+
export function readPlanTexts(dir, rel = '.') {
|
|
125
|
+
const prose = readFileInside(dir, `${rel}/prose.txt`);
|
|
126
|
+
return { proseText: prose.ok ? prose.text : null, parsed: prose.ok ? parseSignedText(prose.text) : null, declaration: readJsonFile(dir, `${rel}/declaration.json`) };
|
|
127
|
+
}
|
package/src/draftspend.js
CHANGED
|
@@ -19,7 +19,8 @@
|
|
|
19
19
|
import { renameSync, writeFileSync } from 'node:fs';
|
|
20
20
|
import { basename, dirname, join, resolve } from 'node:path';
|
|
21
21
|
|
|
22
|
-
import { readdirInside, readFileInside } from './
|
|
22
|
+
import { readdirInside, readFileInside } from './inside.js';
|
|
23
|
+
import { draftStepList, DRAFT_LOG_RE } from './draft-steps.js';
|
|
23
24
|
import { readSpendRows, rowCeilingUsd, spendRowCost, unmeteredCalls } from './provider.js';
|
|
24
25
|
import { parseSignedText } from './signed-text.js';
|
|
25
26
|
|
|
@@ -78,6 +79,17 @@ export const EARLIER_MISSING_SAY = "An earlier draft of this job is missing, so
|
|
|
78
79
|
export const STARTED_OVER_FILE = 'started-over-from.json';
|
|
79
80
|
const SESSION_ID_RE = /^d-[0-9a-z]{10}-[0-9a-f]{4}$/;
|
|
80
81
|
|
|
82
|
+
/**
|
|
83
|
+
* M20 am3 item 12: the ONE reader of a session folder's `started-over-from.json`: the `startedOverFrom` value it holds, or null when
|
|
84
|
+
* there is no file, it is unreadable, or it holds none. (A value that is not a session id is the caller's to judge.)
|
|
85
|
+
* @param {string} sessionDir @returns {unknown}
|
|
86
|
+
*/
|
|
87
|
+
export function readStartedOverFrom(sessionDir) {
|
|
88
|
+
const so = readFileInside(sessionDir, STARTED_OVER_FILE);
|
|
89
|
+
if (!so.ok) return null;
|
|
90
|
+
try { return JSON.parse(so.text)?.startedOverFrom ?? null; } catch { return null; }
|
|
91
|
+
}
|
|
92
|
+
|
|
81
93
|
/**
|
|
82
94
|
* M4d amendment 16 item 1: what ALL of a job's drafting spent — the one writer of that total. A panel draft's session folder holds one plan
|
|
83
95
|
* folder per draft (`draft/`, `draft-<n>/` for each revise and the redraft after answers); each is read by `readDirSpendRows` and priced by
|
|
@@ -108,22 +120,18 @@ export function draftingSpent(sessionDir, { ceilingUsd = 0, exclude } = {}, seen
|
|
|
108
120
|
}
|
|
109
121
|
// M4d am19 item 3: a Start over opens a new session folder that names the one it started over from (`started-over-from.json`, written once by the panel):
|
|
110
122
|
// what the earlier session spent is still this job's drafting, so the chain is followed (a name that points back at a folder already counted is not).
|
|
111
|
-
const
|
|
112
|
-
if (
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
if (
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
missingEarlier = before.missingEarlier;
|
|
124
|
-
}
|
|
125
|
-
} else if (typeof from === 'string' && !SESSION_ID_RE.test(from)) missingEarlier = true;
|
|
126
|
-
}
|
|
123
|
+
const from = readStartedOverFrom(sessionDir);
|
|
124
|
+
if (typeof from === 'string' && SESSION_ID_RE.test(from) && !seen.has(resolve(dirname(sessionDir), from))) {
|
|
125
|
+
const prev = join(dirname(sessionDir), from);
|
|
126
|
+
// M4d am21 item 2: a link naming a folder that is gone is NOT $0: what it spent cannot be counted (`missingEarlier`, never a clean figure)
|
|
127
|
+
if (!readFileInside(prev, 'card.json').ok) missingEarlier = true;
|
|
128
|
+
else {
|
|
129
|
+
const before = draftingSpent(prev, { ceilingUsd }, seen);
|
|
130
|
+
usd += before.usd;
|
|
131
|
+
notPriced += before.notPriced;
|
|
132
|
+
missingEarlier = before.missingEarlier;
|
|
133
|
+
}
|
|
134
|
+
} else if (typeof from === 'string' && !SESSION_ID_RE.test(from)) missingEarlier = true;
|
|
127
135
|
return { usd, notPriced, complete: notPriced === 0 && !missingEarlier, missingEarlier };
|
|
128
136
|
}
|
|
129
137
|
|
|
@@ -174,3 +182,143 @@ export function draftHoldUsd(proseText, outDir, ceilingUsd) {
|
|
|
174
182
|
export function capTooSmallText(kind, capUsd, minUsd, modelId) {
|
|
175
183
|
return `Cap ${usdText(capUsd)} is below one ${kind} round's worst case for ${modelId}, $${minUsd.toFixed(4)}. Raise Cap $ or pick another model.`;
|
|
176
184
|
}
|
|
185
|
+
|
|
186
|
+
// M20 am1 items 5-6 + am2: the drafting step lines. The `fwdloop draft` child writes them into the draft's existing child.log (as `fwdloop: refusal-record`, M19 am14b):
|
|
187
|
+
// `fwdloop: step-start {no, id, label, at}` and `fwdloop: step-end {no, status, label, at}`.
|
|
188
|
+
// `id` and `label` are `draftStepList`'s own (src/draft-steps.js) for the step; the `thinking` line and a `Fix:` note get no line (they have no time).
|
|
189
|
+
// Throws away: the model's replies and every per-round figure but what the label carries. Third outcomes: a torn or unparseable line is skipped; no lines = no times.
|
|
190
|
+
export const STEP_LINE_RE = /^fwdloop: (step-start|step-end) (\{.*\})$/;
|
|
191
|
+
export const STEP_LINE_PREFIXES = ['fwdloop: step-start ', 'fwdloop: step-end '];
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* The ONE writer of the step lines. `emit(kind, record)` prints one line (the CLI passes stderr). Each call is given the result so far
|
|
195
|
+
* (`log`, as log.json will hold it) and writes a start for every step not yet started, and an end for every step but the last (the running one);
|
|
196
|
+
* `final` ends them all. A step is keyed by its `id`: written once.
|
|
197
|
+
* @param {(kind: 'step-start'|'step-end', rec: Record<string, any>) => void} emit
|
|
198
|
+
*/
|
|
199
|
+
export function makeStepWriter(emit) {
|
|
200
|
+
/** @type {string[]} */
|
|
201
|
+
const started = [];
|
|
202
|
+
const ended = new Set();
|
|
203
|
+
return (/** @type {any} */ log, /** @type {any} */ declaration, final) => {
|
|
204
|
+
const list = draftStepList({ log, declaration, questionOpen: !final });
|
|
205
|
+
const items = (list ?? []).filter((st) => st.note !== true && st.id !== 'thinking');
|
|
206
|
+
items.forEach((st, i) => {
|
|
207
|
+
const at = new Date().toISOString();
|
|
208
|
+
if (!started.includes(st.id)) { started.push(st.id); emit('step-start', { no: started.length - 1, id: st.id, label: st.label, at }); }
|
|
209
|
+
if ((final || i < items.length - 1) && !ended.has(st.id)) {
|
|
210
|
+
ended.add(st.id);
|
|
211
|
+
emit('step-end', { no: started.indexOf(st.id), status: st.status === 'failed' ? 'failed' : 'done', label: st.label, at });
|
|
212
|
+
}
|
|
213
|
+
});
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Fold the step lines of `<dir>/child.log` into one record per step, oldest first. A line that cannot be parsed is skipped.
|
|
219
|
+
* @param {string} dir the draft folder @param {string} [file] the child's log: `child.log` (the first draft), `revise-<n>.log` or `redraft-<n>.log`
|
|
220
|
+
* @returns {{no: number, id: string, label: string, status: 'running'|'done'|'failed', startedAt: string, endedAt: string|null, wallMs: number|null}[]}
|
|
221
|
+
*/
|
|
222
|
+
export function readDraftSteps(dir, file = 'child.log') {
|
|
223
|
+
const r = readFileInside(dir, file);
|
|
224
|
+
if (!r.ok) return [];
|
|
225
|
+
/** @type {Map<number, any>} */
|
|
226
|
+
const byNo = new Map();
|
|
227
|
+
for (const line of r.text.split('\n')) {
|
|
228
|
+
const m = STEP_LINE_RE.exec(line);
|
|
229
|
+
if (!m) continue;
|
|
230
|
+
let ev;
|
|
231
|
+
try { ev = JSON.parse(m[2]); } catch { continue; }
|
|
232
|
+
if (!ev || typeof ev !== 'object' || !Number.isInteger(ev.no)) continue;
|
|
233
|
+
if (m[1] === 'step-start') {
|
|
234
|
+
byNo.set(ev.no, { no: ev.no, id: String(ev.id), label: String(ev.label), status: 'running', startedAt: ev.at, endedAt: null, wallMs: null });
|
|
235
|
+
} else if (byNo.has(ev.no)) {
|
|
236
|
+
const x = byNo.get(ev.no);
|
|
237
|
+
x.status = ev.status === 'failed' ? 'failed' : 'done';
|
|
238
|
+
x.endedAt = ev.at;
|
|
239
|
+
if (typeof ev.label === 'string') x.label = ev.label;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
const steps = [...byNo.values()].sort((a, b) => a.no - b.no);
|
|
243
|
+
for (const x of steps) {
|
|
244
|
+
const a = Date.parse(x.startedAt);
|
|
245
|
+
const b = x.endedAt === null ? NaN : Date.parse(x.endedAt);
|
|
246
|
+
x.wallMs = Number.isFinite(a) && Number.isFinite(b) ? Math.max(0, b - a) : null;
|
|
247
|
+
}
|
|
248
|
+
return steps;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// borrowed-from: bareloop src/draftspend.js@v0.63.0 (7bc2719b): TIME_STEP_MS, mmss, stepped, draftWallMs, withDraftTimes, draftedLine
|
|
252
|
+
/** a running time moves in 30 s steps, never a ticking clock (the page polls often; the words change every 30 s) */
|
|
253
|
+
export const TIME_STEP_MS = 30_000;
|
|
254
|
+
|
|
255
|
+
/** M:SS, the ONE spelling of a drafting time ("took 0:42", "Drafting so far: 2:00"). @param {number} ms @returns {string} */
|
|
256
|
+
export function mmss(ms) {
|
|
257
|
+
const s = Math.max(0, Math.floor(ms / 1000));
|
|
258
|
+
return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** a running time floored to its 30 s step @param {number} ms @returns {number} */
|
|
262
|
+
export const stepped = (ms) => Math.floor(Math.max(0, ms) / TIME_STEP_MS) * TIME_STEP_MS;
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* The drafting's whole time: the first step's start to the last step's end; `null` when no step has both times.
|
|
266
|
+
* @param {{startedAt: string, endedAt: string|null}[]} steps `readDraftSteps`' records
|
|
267
|
+
* @returns {number|null}
|
|
268
|
+
*/
|
|
269
|
+
export function draftWallMs(steps) {
|
|
270
|
+
const starts = steps.map((x) => Date.parse(x.startedAt)).filter(Number.isFinite);
|
|
271
|
+
const ends = steps.map((x) => (x.endedAt === null ? NaN : Date.parse(x.endedAt))).filter(Number.isFinite);
|
|
272
|
+
return starts.length && ends.length ? Math.max(0, Math.max(...ends) - Math.min(...starts)) : null;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* The ONE owner of the times on the chat's drafting list. While the draft runs the list is the started steps (`no` order, latest label), each `time` "M:SS so far"
|
|
277
|
+
* (a finished one "took M:SS") and `draftSoFar` is "Drafting so far: M:SS". After it ends `list` is `draftStepList`'s list unchanged, each line taking the times of the
|
|
278
|
+
* step line with the same `id` (the first unused, in order); a line no step line matches (thinking, a Fix note) has no time. No lines = no times, `draftSoFar` null.
|
|
279
|
+
* A revise or answer redraft is read from its own log (`file`); its one `plan` line (`reviseStepList`) takes the draft's whole time (`wholeId`).
|
|
280
|
+
* @param {{dir: string, running: boolean, list: any[]|null, nowMs?: number, file?: string, wholeId?: string}} p `dir` = the draft folder, `file` = the child's log in it, `list` = draftStepList's (or reviseStepList's) list or null
|
|
281
|
+
* @returns {{list: any[]|null, draftSoFar: string|null}}
|
|
282
|
+
*/
|
|
283
|
+
export function withDraftTimes({ dir, running, list, nowMs = Date.now(), file = 'child.log', wholeId }) {
|
|
284
|
+
const logged = readDraftSteps(dir, file);
|
|
285
|
+
const timeOf = (/** @type {any} */ x) => {
|
|
286
|
+
const a = Date.parse(x.startedAt);
|
|
287
|
+
if (!Number.isFinite(a)) return null;
|
|
288
|
+
if (x.status === 'running') return `${mmss(stepped(nowMs - a))} so far`;
|
|
289
|
+
return x.wallMs !== null ? `took ${mmss(x.wallMs)}` : null;
|
|
290
|
+
};
|
|
291
|
+
const starts = logged.map((x) => Date.parse(x.startedAt)).filter(Number.isFinite);
|
|
292
|
+
const draftSoFar = running && logged.some((x) => x.status === 'running') && starts.length ? `Drafting so far: ${mmss(stepped(nowMs - Math.min(...starts)))}` : null;
|
|
293
|
+
if (running) {
|
|
294
|
+
return { list: logged.length ? logged.map((x) => ({ id: x.id, label: x.label, status: x.status === 'failed' ? 'failed' : (x.status === 'running' ? 'running' : 'done'), details: [], time: timeOf(x) })) : list, draftSoFar };
|
|
295
|
+
}
|
|
296
|
+
if (list === null) return { list, draftSoFar: null };
|
|
297
|
+
const used = new Set();
|
|
298
|
+
const whole = wholeId !== undefined ? draftWallMs(logged) : null;
|
|
299
|
+
return {
|
|
300
|
+
list: list.map((st) => {
|
|
301
|
+
if (st.id === wholeId) return { ...st, time: whole === null ? null : `took ${mmss(whole)}` };
|
|
302
|
+
const x = logged.find((l) => l.id === st.id && !used.has(l.no));
|
|
303
|
+
if (x) used.add(x.no);
|
|
304
|
+
return { ...st, time: x ? timeOf(x) : null };
|
|
305
|
+
}),
|
|
306
|
+
draftSoFar: null,
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/** the logs of every draft of a session folder: the first draft's `child.log`, then each revise's and answer redraft's own */
|
|
311
|
+
const draftLogFiles = (/** @type {string} */ dir) => ['child.log', ...readdirInside(dir, '.').filter((n) => DRAFT_LOG_RE.test(n))];
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* The plan card's one line: "Drafted in M:SS · $X". The time is the session's first step start to its last step end across ALL its drafts (the first, each revise,
|
|
315
|
+
* each answer redraft); the money is the session's drafting spend (`draftingSpent`, handed in as `spentUsd`; "at least" when `complete` is false). `null` when no
|
|
316
|
+
* step line has a time or the spend is not a number (a Reuse, an old draft, a session that never knew its cost): nothing is made up.
|
|
317
|
+
* @param {{dir: string, spentUsd: number|null, complete: boolean}} p `dir` = the session's draft folder
|
|
318
|
+
* @returns {string|null}
|
|
319
|
+
*/
|
|
320
|
+
export function draftedLine({ dir, spentUsd, complete }) {
|
|
321
|
+
const ms = draftWallMs(draftLogFiles(dir).flatMap((f) => readDraftSteps(dir, f)));
|
|
322
|
+
if (ms === null || typeof spentUsd !== 'number') return null;
|
|
323
|
+
return `Drafted in ${mmss(ms)} \u00B7 ${complete ? '' : 'at least '}${usdText(spentUsd)}`;
|
|
324
|
+
}
|