fwdloop 0.38.0 → 0.40.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 +6 -9
- package/bin/fwdloop +21 -19
- package/package.json +1 -1
- package/src/ask.js +70 -148
- package/src/audit-fold.js +6 -5
- package/src/auditchecks.js +6 -4
- package/src/authoring.js +32 -60
- package/src/blockasks.js +2 -1
- package/src/blockassemble.js +15 -3
- package/src/blockdraft.js +2 -2
- package/src/blockpick.js +42 -16
- package/src/books.js +237 -12
- package/src/checkblock.js +24 -44
- package/src/checklistsign.js +25 -3
- package/src/checklook.js +3 -1
- package/src/checkpick.js +6 -77
- 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 +14 -49
- package/src/diary.js +23 -1
- package/src/draft-steps.js +11 -1
- package/src/drafter.js +18 -12
- 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 +106 -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 +1 -1
- package/src/liveness.js +3 -0
- package/src/mcp-use.js +8 -9
- package/src/memo.js +13 -16
- package/src/model-step.js +2 -2
- 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 +99 -75
- 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 +186 -188
- package/src/panel/index.html +139 -115
- 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/plain-checks.js +1 -1
- 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/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/sheetblock.js +2 -2
- package/src/sheetbuild.js +5 -5
- package/src/sheetrun.js +4 -5
- package/src/summary-words.js +2 -1
- package/src/thinking.js +5 -2
- package/src/ticketrows.js +7 -28
- 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 +7 -42
- package/types/blockpick.d.ts +1 -1
- package/types/books.d.ts +380 -4
- package/types/checkblock.d.ts +1 -23
- 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 +1 -1
- 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 +71 -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/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 +50 -16
- 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/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);
|
|
@@ -392,7 +393,7 @@ export async function draft({
|
|
|
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
399
|
if (!parsed.ok) return fail(parsed.reds.map((r) => `signed-text: ${r}`), { box: 'job' });
|
|
@@ -416,8 +417,8 @@ export async function draft({
|
|
|
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
|
-
// M19 am14b: the Tickets list address is an Inputs line; every other flow red is about the picked MCP
|
|
420
|
-
if (flowReds.length) return fail(flowReds,
|
|
420
|
+
// M19 am14b: the Tickets list address is an Inputs line; M20 am9e: every other flow red is about the picked MCP and sits under the Draft button (no box)
|
|
421
|
+
if (flowReds.length) return fail(flowReds, flowType === 'tickets' && ticketSources.length === 0 ? { box: 'inputs' } : {});
|
|
421
422
|
|
|
422
423
|
let { provider, rates, modelId } = { provider: injected, rates: injectedRates, modelId: injectedModelId };
|
|
423
424
|
let prices = null; // the one price lookup's result (live provider only); the cap check below uses the SAME price
|
|
@@ -456,6 +457,8 @@ export async function draft({
|
|
|
456
457
|
let unmetered = 0; // calls that failed with no metering: their cost is unknown
|
|
457
458
|
const book = (inFlight) => onBook?.({
|
|
458
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 }; },
|
|
459
462
|
});
|
|
460
463
|
|
|
461
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 */
|
|
@@ -729,7 +732,7 @@ export async function draft({
|
|
|
729
732
|
const shapeEverywhere = offerRules(lines, arbiter, [...look.facts, ...sheetFacts]);
|
|
730
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.
|
|
731
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)
|
|
732
|
-
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) : [];
|
|
733
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]);
|
|
734
737
|
if (blockPlan && !blockPlan.ok) return fail(blockPlan.reds.map((r) => `signed-text: ${r}`));
|
|
735
738
|
const blockLineNums = new Set(blockPlan ? blockPlan.jobLines.map((l) => l.n) : []);
|
|
@@ -1094,6 +1097,7 @@ export async function draft({
|
|
|
1094
1097
|
const planLookFacts = inPlan ? look.facts.filter((f) => !blockLineNums.has(f.line) || inPlan.has(`${f.line}:${f.name}`)) : look.facts;
|
|
1095
1098
|
const verdict1 = validateDeclaration(declaration, {
|
|
1096
1099
|
arbiter, lines, catalogue: validationCatalogue, wired: WIRED_VERBS, verbatimGoals: true, fitJobLine: true,
|
|
1100
|
+
addedCounts: block ? addedCountsOf(block.choicesRecord(), lines) : new Set(),
|
|
1097
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
|
|
1098
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,
|
|
1099
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) },
|
|
@@ -1118,7 +1122,9 @@ export async function draft({
|
|
|
1118
1122
|
// (`uncovered`). A drop of a prose word is no rule and stays.
|
|
1119
1123
|
const ruleKey = (/** @type {string} */ t) => t.split(' \u2014 ')[0];
|
|
1120
1124
|
const sheetRuleKeys = new Set(jobLines.filter((l) => sheetLineNums.includes(l.n)).flatMap((l) => lineRules(l).map((r) => `line ${l.n}: "${r}"`)));
|
|
1121
|
-
|
|
1125
|
+
// M20 am9h (F238): the page look's own lines are told to the drafter only (pageInfoLines); the block says each drop once (src/blockassemble.js). Without a block the lines stay.
|
|
1126
|
+
const onSheetLine = (/** @type {string} */ t) => sheetLineNums.includes(Number(t.slice(5, t.indexOf(':'))));
|
|
1127
|
+
const lookNotChecked = pageNotChecked.filter((t) => !sheetRuleKeys.has(ruleKey(t)) && (!assembled || onSheetLine(t)));
|
|
1122
1128
|
/** @type {Record<string, 'you'|'agent'|'default'>} */
|
|
1123
1129
|
const noteBy = Object.fromEntries([...lookNotChecked, ...uncovered].map((t) => [t, 'default']));
|
|
1124
1130
|
const ticketNotChecked = (ticketOnList?.notChecked ?? []).map((t) => `not checked · "${t.rule}" — ${t.reason}`);
|
|
@@ -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
|
+
}
|
package/src/flow.js
CHANGED
|
@@ -31,6 +31,7 @@ import { signFlow, verifyFlow } from './signature.js';
|
|
|
31
31
|
import { validateDeclaration } from './declaration.js';
|
|
32
32
|
import { describeChange } from './signed-diff.js';
|
|
33
33
|
import { stripTrigger } from './trigger-line.js';
|
|
34
|
+
import { readFileInside } from './inside.js';
|
|
34
35
|
|
|
35
36
|
/** @typedef {import('./types.js').WriteFlowResult} WriteFlowResult */
|
|
36
37
|
/** @typedef {import('./types.js').ReadFlowResult} ReadFlowResult */
|
|
@@ -313,85 +314,24 @@ export function claimRunId(flowDir) {
|
|
|
313
314
|
}
|
|
314
315
|
|
|
315
316
|
/**
|
|
316
|
-
*
|
|
317
|
-
*
|
|
318
|
-
*
|
|
319
|
-
*
|
|
320
|
-
*
|
|
321
|
-
* to somewhere inside `realpath(baseDir)` — the second check alone also
|
|
322
|
-
* catches a symlinked ANCESTOR directory partway down `relPath` (e.g.
|
|
323
|
-
* `asks/` itself replaced by a symlink to an outside directory), the same
|
|
324
|
-
* shape `readFlow`'s own `runs/` check and `resolveRunDir` already apply one
|
|
325
|
-
* level up. A path that does not exist yet is reported as `missing: true`
|
|
326
|
-
* (never a red) so every existing caller keeps its own "not written yet"
|
|
327
|
-
* behaviour unchanged.
|
|
328
|
-
*
|
|
329
|
-
* @param {string} baseDir
|
|
330
|
-
* @param {string} relPath
|
|
331
|
-
* @returns {{ok:true, full:string}|{ok:false, missing:true}|{ok:false, missing:false, red:string}}
|
|
317
|
+
* M20 am1 item 4: the ONE reader of a DRAFT's `log.json` (`<dir>/<rel>/log.json`, or `<dir>/log.json` with no `rel`): what the drafter kept of its rounds,
|
|
318
|
+
* its `checkCard` and its `action`. The run's `log.json` is another file, read only by `readLog` (src/books.js). `null` when missing, refused by the
|
|
319
|
+
* gateway, unparseable or not an object (a torn write), never a thrown error.
|
|
320
|
+
* @param {string} dir @param {string} [rel] a plan folder under `dir` (`draft`, `draft-<n>`)
|
|
321
|
+
* @returns {any|null}
|
|
332
322
|
*/
|
|
333
|
-
export function
|
|
334
|
-
|
|
335
|
-
let stat;
|
|
336
|
-
try {
|
|
337
|
-
stat = lstatSync(full);
|
|
338
|
-
} catch {
|
|
339
|
-
return { ok: false, missing: true };
|
|
340
|
-
}
|
|
341
|
-
if (stat.isSymbolicLink()) {
|
|
342
|
-
return { ok: false, missing: false, red: `"${relPath}" is a symlink, refused` };
|
|
343
|
-
}
|
|
344
|
-
let realBase;
|
|
345
|
-
let realFull;
|
|
346
|
-
try {
|
|
347
|
-
realBase = realpathSync(baseDir);
|
|
348
|
-
realFull = realpathSync(full);
|
|
349
|
-
} catch (err) {
|
|
350
|
-
return { ok: false, missing: false, red: `could not resolve "${relPath}" — ${err.message}` };
|
|
351
|
-
}
|
|
352
|
-
if (realFull !== realBase && !realFull.startsWith(realBase + path.sep)) {
|
|
353
|
-
return { ok: false, missing: false, red: `"${relPath}" resolves outside its directory — refused` };
|
|
354
|
-
}
|
|
355
|
-
return { ok: true, full };
|
|
323
|
+
export function readDraftLog(dir, rel = '') {
|
|
324
|
+
return readJsonFile(dir, rel === '' ? 'log.json' : `${rel}/log.json`);
|
|
356
325
|
}
|
|
357
326
|
|
|
358
327
|
/**
|
|
359
|
-
*
|
|
360
|
-
*
|
|
361
|
-
* @param {string} baseDir
|
|
362
|
-
* @param {string} relPath
|
|
363
|
-
* @returns {{ok:true, text:string}|{ok:false, missing:true}|{ok:false, missing:false, red:string}}
|
|
328
|
+
* M20 am3 item 12: the ONE tolerant JSON read of a file in a folder, through the gateway: the parsed object, or null when the file is missing, refused,
|
|
329
|
+
* unparseable (a torn write) or not an object. Never throws. @param {string} dir @param {string} rel @returns {any|null}
|
|
364
330
|
*/
|
|
365
|
-
export function
|
|
366
|
-
const
|
|
367
|
-
if (!
|
|
368
|
-
try {
|
|
369
|
-
return { ok: true, text: readFileSync(resolved.full, 'utf8') };
|
|
370
|
-
} catch (err) {
|
|
371
|
-
return { ok: false, missing: false, red: `could not read "${relPath}" — ${err.message}` };
|
|
372
|
-
}
|
|
373
|
-
}
|
|
374
|
-
|
|
375
|
-
/**
|
|
376
|
-
* `readdirSync` guarded the same way: refuses (returns `[]`) when `relDir`
|
|
377
|
-
* itself is a symlink or resolves outside `baseDir`, and skips (never
|
|
378
|
-
* follows) any individual entry that is itself a symlink — a directory
|
|
379
|
-
* listing must never hand a caller a name that, joined back onto `relDir`,
|
|
380
|
-
* would escape `baseDir`. `[]` when `relDir` doesn't exist.
|
|
381
|
-
* @param {string} baseDir
|
|
382
|
-
* @param {string} relDir
|
|
383
|
-
* @returns {string[]}
|
|
384
|
-
*/
|
|
385
|
-
export function readdirInside(baseDir, relDir) {
|
|
386
|
-
const resolved = resolveInside(baseDir, relDir);
|
|
387
|
-
if (!resolved.ok) return [];
|
|
388
|
-
let entries;
|
|
389
|
-
try {
|
|
390
|
-
entries = readdirSync(resolved.full, { withFileTypes: true });
|
|
391
|
-
} catch {
|
|
392
|
-
return [];
|
|
393
|
-
}
|
|
394
|
-
return entries.filter((e) => !e.isSymbolicLink()).map((e) => e.name);
|
|
331
|
+
export function readJsonFile(dir, rel) {
|
|
332
|
+
const r = readFileInside(dir, rel);
|
|
333
|
+
if (!r.ok) return null;
|
|
334
|
+
try { const j = JSON.parse(r.text); return j !== null && typeof j === 'object' && !Array.isArray(j) ? j : null; } catch { return null; }
|
|
395
335
|
}
|
|
396
336
|
|
|
397
337
|
function readTextFile(filePath, label, reds) {
|
|
@@ -709,19 +649,31 @@ function replaceSigned({
|
|
|
709
649
|
export function planForReuse({
|
|
710
650
|
root, name, runDir, catalogue,
|
|
711
651
|
}) {
|
|
712
|
-
const
|
|
713
|
-
if (!
|
|
652
|
+
const job = sameJob({ flowDir: path.join(root, name), runDir, catalogue });
|
|
653
|
+
if (!job.present) return { ok: true, same: true };
|
|
714
654
|
const runId = path.basename(runDir);
|
|
715
|
-
if (!
|
|
716
|
-
|
|
717
|
-
const
|
|
655
|
+
if (!job.ok) return { ok: false, red: `The plan ${runId} kept does not match its signature (${job.reds[0]}), so it cannot be reused. Nothing was started.` };
|
|
656
|
+
if (job.same) return { ok: true, same: true };
|
|
657
|
+
const { present, same, ...rest } = job;
|
|
658
|
+
void present; void same;
|
|
659
|
+
return { ok: true, same: false, read: /** @type {any} */ (rest) };
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
/**
|
|
663
|
+
* M20 am3 item 1 (as am3a): the ONE rule for "this run ran the job the flow holds now": the run's verified job copy (`readRunJobCopy`), the exact
|
|
664
|
+
* declaration, the prose without its trigger line. `{present:false}` = the run kept no copy (before M6); `{present:true, ok:false, reds}` = a copy that
|
|
665
|
+
* fails its signature; `{present:true, ok:true, same, ...copy}` otherwise.
|
|
666
|
+
* @param {{flowDir: string, runDir: string, catalogue: unknown}} a
|
|
667
|
+
* @returns {{present: false} | {present: true, ok: false, reds: string[]} | ({present: true, same: boolean} & ReadFlowResult & {ok: true})}
|
|
668
|
+
*/
|
|
669
|
+
export function sameJob({ flowDir, runDir, catalogue }) {
|
|
670
|
+
const kept = readRunJobCopy(runDir, catalogue);
|
|
671
|
+
if (!kept.present) return { present: false };
|
|
672
|
+
if (!kept.ok) return /** @type {any} */ ({ present: true, ok: false, reds: kept.reds });
|
|
718
673
|
const b = readFileInside(flowDir, 'declaration.json');
|
|
719
|
-
const ap = readFileInside(runDir, `${RUN_JOB_DIR}/prose.txt`);
|
|
720
674
|
const bp = readFileInside(flowDir, 'prose.txt');
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
void present;
|
|
724
|
-
return { ok: true, same: false, read: /** @type {any} */ (rest) };
|
|
675
|
+
const same = b.ok && bp.ok && kept.declarationText === b.text && stripTrigger(kept.proseText ?? '') === stripTrigger(bp.text);
|
|
676
|
+
return /** @type {any} */ ({ ...kept, same });
|
|
725
677
|
}
|
|
726
678
|
|
|
727
679
|
/**
|
|
@@ -1024,11 +976,14 @@ export function readRunJobCopy(runDir, catalogue) {
|
|
|
1024
976
|
if (reds.length > 0) return { present: true, ok: false, reds };
|
|
1025
977
|
const verified = verifyFlow({ proseText, declarationText, signature: signatureJson });
|
|
1026
978
|
if (!verified.ok) return { present: true, ok: false, reds: [...verified.reds] };
|
|
979
|
+
const read = interpretSigned({
|
|
980
|
+
proseText: /** @type {string} */ (proseText), declarationJson, signatureJson, catalogue, dir,
|
|
981
|
+
});
|
|
982
|
+
// a good read carries the verified bytes, so no caller reads `job/` a second time (M20 am3 item 2)
|
|
1027
983
|
return {
|
|
1028
984
|
present: /** @type {true} */ (true),
|
|
1029
|
-
...
|
|
1030
|
-
|
|
1031
|
-
}),
|
|
985
|
+
...read,
|
|
986
|
+
...(read.ok ? { proseText: /** @type {string} */ (proseText), declarationText: /** @type {string} */ (declarationText) } : {}),
|
|
1032
987
|
};
|
|
1033
988
|
}
|
|
1034
989
|
|
package/src/flowmodel.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
// One writer (`writeModelRecord`), one reader (`readModelRecord`); both go through the safe gateway.
|
|
5
5
|
import { writeFileSync, renameSync } from 'node:fs';
|
|
6
6
|
import { join } from 'node:path';
|
|
7
|
-
import { readFileInside } from './
|
|
7
|
+
import { readFileInside } from './inside.js';
|
|
8
8
|
import { readRunRecord, readRunThinking } from './runfile.js';
|
|
9
9
|
import { isKeyName } from './provider.js';
|
|
10
10
|
|