fwdloop 0.23.0 → 0.25.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.
Files changed (71) hide show
  1. package/bin/fwdloop +62 -32
  2. package/package.json +1 -1
  3. package/src/ask.js +15 -1
  4. package/src/attemptdiff.js +118 -0
  5. package/src/audit-fold.js +2 -0
  6. package/src/authoring.js +32 -2
  7. package/src/cited-record.js +3 -22
  8. package/src/cited-source.js +5 -6
  9. package/src/citedwords.js +36 -2
  10. package/src/config.js +5 -1
  11. package/src/diary.js +21 -17
  12. package/src/drafter.js +6 -2
  13. package/src/flowmodel.js +52 -28
  14. package/src/keysfile.js +1 -1
  15. package/src/launcher.js +552 -0
  16. package/src/learn.js +952 -0
  17. package/src/learnstore.js +348 -0
  18. package/src/line-checks.js +55 -0
  19. package/src/model-step.js +2 -0
  20. package/src/opener.js +33 -0
  21. package/src/pagedry.js +3 -4
  22. package/src/pagefetch.js +9 -2
  23. package/src/pagerules.js +28 -5
  24. package/src/panel/author.js +2 -0
  25. package/src/panel/authorflows.js +9 -9
  26. package/src/panel/authorresume.js +4 -3
  27. package/src/panel/data.js +63 -14
  28. package/src/panel/index.html +162 -16
  29. package/src/panel/result.js +7 -12
  30. package/src/panel/server.js +53 -5
  31. package/src/panel/settings.js +4 -18
  32. package/src/panel/spawn.js +0 -9
  33. package/src/prompts.js +33 -0
  34. package/src/redact.js +6 -6
  35. package/src/runfile.js +60 -0
  36. package/src/runner.js +144 -33
  37. package/src/sheet-record.js +15 -35
  38. package/src/sheetblock.js +3 -3
  39. package/src/sheetrun.js +6 -6
  40. package/src/summary-words.js +13 -5
  41. package/src/thinking.js +11 -0
  42. package/src/tty-colour.js +29 -0
  43. package/types/ask.d.ts +7 -2
  44. package/types/attemptdiff.d.ts +38 -0
  45. package/types/cited-record.d.ts +0 -2
  46. package/types/citedwords.d.ts +14 -0
  47. package/types/diary.d.ts +2 -5
  48. package/types/drafter.d.ts +6 -1
  49. package/types/flowmodel.d.ts +37 -20
  50. package/types/keysfile.d.ts +7 -0
  51. package/types/launcher.d.ts +307 -0
  52. package/types/learn.d.ts +576 -0
  53. package/types/learnstore.d.ts +168 -0
  54. package/types/line-checks.d.ts +26 -0
  55. package/types/opener.d.ts +12 -0
  56. package/types/pagerules.d.ts +7 -0
  57. package/types/panel/author.d.ts +2 -0
  58. package/types/panel/data.d.ts +2 -1
  59. package/types/panel/result.d.ts +2 -4
  60. package/types/panel/server.d.ts +24 -3
  61. package/types/panel/settings.d.ts +2 -2
  62. package/types/panel/spawn.d.ts +0 -6
  63. package/types/prompts.d.ts +14 -0
  64. package/types/runfile.d.ts +48 -0
  65. package/types/runner.d.ts +14 -5
  66. package/types/sheet-record.d.ts +0 -2
  67. package/types/sheetblock.d.ts +2 -2
  68. package/types/sheetrun.d.ts +1 -1
  69. package/types/summary-words.d.ts +2 -1
  70. package/types/thinking.d.ts +11 -0
  71. package/types/tty-colour.d.ts +33 -0
package/src/diary.js CHANGED
@@ -1,11 +1,11 @@
1
- // M4d am29 item 1-3: the run's three add-only diaries, in the run's own folder, the way bareloop keeps its gate audit sidecar
2
- // (src/planrun.js: `new Gate({ audit: { path } })`, the path denied to the worker with `fs.deny`).
3
- // calls.jsonl one row per MODEL CALL: step, try, round, cost, tokens, time, stop reason, thinking asked and status
4
- // tools.jsonl one row per TOOL CALL: step, try, round, tool, path, the guard's decision (allow / deny + rule / no check)
5
- // checks.jsonl one row per TRY that ran checks: each check numbered, ✓/✗, its result, where it comes from, and the output it judged
1
+ // M4d am29 item 1-3 / M8b item 2: the run's one add-only step diary, `diary.jsonl`, in the run's own folder, the way bareloop keeps its gate audit sidecar
2
+ // (src/planrun.js: `new Gate({ audit: { path } })`, the path denied to the worker with `fs.deny`). Every row carries `kind`, in the order the rows were written:
3
+ // kind 'call' one row per MODEL CALL: step, try, round, cost, tokens, time, stop reason, thinking asked and status
4
+ // kind 'tool' one row per TOOL CALL: step, try, round, tool, path, the guard's decision (allow / deny + rule / no check)
5
+ // kind 'checks' one row per TRY that ran checks: each check numbered, ✓/✗, its result, where it comes from, and the output it judged
6
6
  // Never saved: what the model said, what was in any file (a tool row names a path, never its content). Every string is scrubbed with the
7
- // ONE secret inventory (`redactSecrets`, src/redact.js) before the row is written. The model can never read these files: the step's
8
- // bareguard Gate denies them (src/primitives.js) and a grep over the run folder drops their hits.
7
+ // ONE secret inventory (`redactSecrets`, src/redact.js) before the row is written. The model can never read this file: the step's
8
+ // bareguard Gate denies it (src/primitives.js) and a grep over the run folder drops its hits.
9
9
  // Rounds count from 1 in EACH STEP (they keep counting across that step's tries); `nextRound` reads the count off the diary.
10
10
  //
11
11
  // borrowed-from: bareloop src/planrun.js@fd78723 (the gate audit sidecar + fs.deny of its path; the per-round rows emitted from the onLlmResult wrapper)
@@ -14,10 +14,12 @@ import { appendRow } from './jsonl-append.js';
14
14
  import { readLines } from './books.js';
15
15
  import { redactSecrets } from './redact.js';
16
16
 
17
- export const DIARY_FILES = Object.freeze({ calls: 'calls.jsonl', tools: 'tools.jsonl', checks: 'checks.jsonl' });
17
+ export const DIARY_FILE = 'diary.jsonl';
18
18
 
19
- /** Every diary's absolute path for a run, for the model's deny list. @param {string} runDir @returns {string[]} */
20
- export const diaryPaths = (runDir) => Object.values(DIARY_FILES).map((f) => join(runDir, f));
19
+ /** The diary's absolute path for a run, for the model's deny list (a list, as the deny lists take one). @param {string} runDir @returns {string[]} */
20
+ export const diaryPaths = (runDir) => [join(runDir, DIARY_FILE)];
21
+
22
+ /** @typedef {'call'|'tool'|'checks'} DiaryKind */
21
23
 
22
24
  /** A copy of a JSON value with every string scrubbed. @param {any} v @returns {any} */
23
25
  function scrub(v) {
@@ -27,22 +29,24 @@ function scrub(v) {
27
29
  return v;
28
30
  }
29
31
 
30
- /** The ONE writer of a diary row. @param {string} runDir @param {keyof typeof DIARY_FILES} kind @param {Record<string, any>} row */
31
- function write(runDir, kind, row) { appendRow(join(runDir, DIARY_FILES[kind]), scrub(row)); }
32
+ /** The ONE writer of a diary row. @param {string} runDir @param {DiaryKind} kind @param {Record<string, any>} row */
33
+ function write(runDir, kind, row) { appendRow(join(runDir, DIARY_FILE), scrub({ kind, ...row })); }
32
34
 
33
35
  /** @param {string} runDir @param {{step:string|null, try:number|null, round:number, at:string, model:string|null, costUsd:number|null, tokens:{in:number,out:number,cache:number}|null, ms:number|null, stopReason:string|null, thinking:{asked:string|null,status:string|null}}} row */
34
- export const appendCall = (runDir, row) => write(runDir, 'calls', row);
36
+ export const appendCall = (runDir, row) => write(runDir, 'call', row);
35
37
  /** @param {string} runDir @param {{step:string|null, try:number|null, round:number, at:string, tool:string, path:string|null, decision:'allow'|'deny'|'no check', rule:string|null}} row */
36
- export const appendTool = (runDir, row) => write(runDir, 'tools', row);
38
+ export const appendTool = (runDir, row) => write(runDir, 'tool', row);
37
39
  /** @param {string} runDir @param {{step:string|null, try:number, at:string, lastRound:number, checks:Array<{n:number, text:string, ok:boolean, result:string|null, source:string}>, output:{file:string, bytes:number, sha256:string}|null}} row */
38
40
  export const appendChecks = (runDir, row) => write(runDir, 'checks', row);
39
41
 
42
+ /** The rows of one kind, in the order they were written; a torn or unparseable line is skipped (the writer's fresh-line rule is its other half). @param {string} runDir @param {DiaryKind} kind @returns {any[]} */
43
+ const readKind = (runDir, kind) => readLines(runDir, DIARY_FILE).filter((r) => r.kind === kind);
40
44
  /** @param {string} runDir @returns {any[]} */
41
- export const readCalls = (runDir) => readLines(runDir, DIARY_FILES.calls);
45
+ export const readCalls = (runDir) => readKind(runDir, 'call');
42
46
  /** @param {string} runDir @returns {any[]} */
43
- export const readTools = (runDir) => readLines(runDir, DIARY_FILES.tools);
47
+ export const readTools = (runDir) => readKind(runDir, 'tool');
44
48
  /** @param {string} runDir @returns {any[]} */
45
- export const readChecks = (runDir) => readLines(runDir, DIARY_FILES.checks);
49
+ export const readChecks = (runDir) => readKind(runDir, 'checks');
46
50
 
47
51
  /** The round number of this step's next model call: one more than the highest round it has in the diary, so it counts on across tries and across resumes.
48
52
  * Read off the file each time (the diary is the one record), never a copy held in memory. @param {string} runDir @param {string|null} step */
package/src/drafter.js CHANGED
@@ -326,7 +326,7 @@ function greenReadRule(sources) {
326
326
  '- Fact shapes: money takes unit or currency, rule, anchor; number, date and time take rule, anchor; text takes anchor and until (until needs an anchor); phrase takes only phrase (fixed words every result must say). Never put a field on a shape that does not take it.',
327
327
  '- A label (anchor, until) is PICKED from the kept labels listed under Inputs for that page, never typed. A phrase, a unit or a currency is copied from the page words listed there. A word listed as Not checked or dropped can never be used.',
328
328
  '- A place listed under Inputs as "place phrases" must have EVERY one of its phrases as its own phrase fact (one fact per phrase, the phrase word for word). A place name alone does not tell a result that leaves the other way.',
329
- '- A fact\'s rule (under, over, between) may only use a number that is in the person\'s own words on that job line (the line or its guardrail). Never make a number up; leave the rule out if the person gave none.',
329
+ '- A fact\'s rule (under, over, between) may only use a number that is in the person\'s own words on that job line (the line or its guardrail). Never make a number up; leave the rule out if the person gave none. When the Kept list says "limit read from your words" for a fact, the fact that reads that value MUST carry that rule (same kind, op and bound), or the line is refused.',
330
330
  '- A label or a phrase that sits in each result must appear on the page at least as many times as close.cited.count.min, or the line is refused.',
331
331
  ...(docRoles.length ? ['- For a document input there is no list of kept labels: a label (anchor) or a phrase is words the document really says, copied from it, and each must be in the document at least as many times as close.cited.count.min.'] : []),
332
332
  );
@@ -421,12 +421,14 @@ function isPlainObject(v) { return !!v && typeof v === 'object' && !Array.isArra
421
421
  * costUsd:number|null, modelReturned:string|null, modelId?:string, price?:object|null, tokens?:object|null, structureRetries:number, revisions:number, stop:string|null, log:object[],
422
422
  * questions?:{line:number, question:string}[], droppedQuestions?:object[], notChecked?:string[], thinking?:{asked:string, status:string|null, say:string|null}, inputs?:{role:string, detail:string}[],
423
423
  * look?:{facts:any[], dropped:any[]}, pageLooks?:{role:string, address:string, sha256:string, bytes:number, frozen:string, attempts:number, mapping:any}[], sheetLooks?:any[]}>}
424
+ * `learnHints` (M8 item 5a): the earlier runs' notes block (src/learnstore.js hintsForRun), appended to the drafter's system prompt; null = nothing.
424
425
  * `look` / `pageLooks` (M10 item 3) are there when the job signs a web page: the kept facts (with their `reading`, the input a later ask reads), every drop, and per page its address, sha256 and the AI's map. Each drop is also a line in `notChecked`.
425
426
  */
426
427
  export async function draft({
427
428
  proseText, slot, model, provider: injected, rates: injectedRates, modelId: injectedModelId, env,
428
429
  priorSpend = /** @type {((ceilingUsd: number) => number)|null} */ (null), skills = DRAFT_SKILLS, makeProviderFn = makeProvider, onBook, offerQuestions = true, draftThinking = /** @type {'on'|'off'} */ ('off'),
429
430
  draftDir = /** @type {string|null} */ (null), fetchPage = undefined, leftRules = /** @type {{line: number, rule: number}[]} */ ([]),
431
+ learnHints = /** @type {{text: string, ids: string[]}|null} */ (null),
430
432
  }) {
431
433
  // What was asked of thinking and the WORST status bareagent reported across the rounds (the page says it loudly unless 'applied'). Read from the round log, the one record.
432
434
  const thinkingOf = () => {
@@ -660,7 +662,9 @@ export async function draft({
660
662
  // M10b piece 3: the drafting copy's table of each CSV input - the header the drafter may pick from, the table bareguard's sign-time test runs over
661
663
  const sheetTables = Object.keys(facts.sheets ?? {}).length ? Object.fromEntries(Object.entries(facts.sheets).map(([role, t]) => [role, sheetTable(parseCsv(t))])) : undefined;
662
664
  const baseSystem = buildSystemPrompt({ menu, lines, arbiter, factsInfo });
663
- const system = `${baseSystem}\n\n${NOTCHECKED_PROMPT}`;
665
+ // M8 item 5a: the earlier runs' notes go on the DRAFTER's system prompt only (F81's B arm), the one `system` every round of this draft uses (revise and structure retries too).
666
+ // Absent or empty: the prompt is byte-identical to what it was.
667
+ const system = `${baseSystem}\n\n${NOTCHECKED_PROMPT}${learnHints?.text ? `\n\n${learnHints.text}` : ''}`;
664
668
  let structureRetries = 0;
665
669
  let revisions = 0;
666
670
  let lastReds = [];
package/src/flowmodel.js CHANGED
@@ -2,9 +2,10 @@
2
2
  // and a model id - is recorded in `model.json`, beside the draft and then beside the signed flow. It is NOT one of the signed files: which model
3
3
  // runs, and at what price, is Settings' to say (a line that is no longer ticked is refused by name at run time), so the record only remembers the choice.
4
4
  // One writer (`writeModelRecord`), one reader (`readModelRecord`); both go through the safe gateway.
5
- import { writeFileSync } from 'node:fs';
5
+ import { writeFileSync, renameSync } from 'node:fs';
6
6
  import { join } from 'node:path';
7
7
  import { readFileInside } from './flow.js';
8
+ import { readRunRecord, readRunThinking } from './runfile.js';
8
9
  import { isKeyName } from './provider.js';
9
10
 
10
11
  export const MODEL_FILE = 'model.json';
@@ -35,11 +36,8 @@ function writeOnce(file, obj) {
35
36
  writeFileSync(file, `${JSON.stringify(obj, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
36
37
  }
37
38
 
38
- /** M4d am25: the file in a run's folder that keeps the box as the run started with it (outside `job/`, which holds the three signed files only). */
39
- export const RUN_THINKING_FILE = 'thinking.json';
40
-
41
39
  /**
42
- * M4d am25: the ONE reader of the job's "Thinking on" box for a run. A run reads its OWN record (`<run>/thinking.json`, written once when the run
40
+ * M4d am25: the ONE reader of the job's "Thinking on" box for a run. A run reads its OWN record (`thinking` in `<run>/run.json`, written once when the run
43
41
  * started) when it has one; otherwise the flow folder's `model.json`. No record, an unreadable one, or one without `thinking` is box OFF: a job
44
42
  * signed before am25 stored nothing, and it must not start thinking on every try.
45
43
  * @param {string} flowDir @param {string|null} runDir @returns {boolean}
@@ -49,40 +47,66 @@ export function readJobThinking(flowDir, runDir) {
49
47
  }
50
48
 
51
49
  /**
52
- * M4d am26: the run's OWN record of the box (`<run>/thinking.json`) and nothing else: `true`/`false`, or `null` when the run has none (a run from before am25).
53
- * An unreadable record is box off, as `readJobThinking` has always read it. @param {string|null} runDir @returns {boolean|null}
50
+ * M4d am33: the ONE reader of the model a run started on (`model` in `<run>/run.json`), or null (a run from before the record, or an unusable one: the caller then keeps today's pick).
51
+ * @param {string|null} runDir @returns {{ slot: string, model: string }|null}
54
52
  */
55
- export function readRunThinking(runDir) {
56
- const own = typeof runDir === 'string' ? readFileInside(runDir, RUN_THINKING_FILE) : null;
57
- if (!own?.ok) return null;
58
- try { return JSON.parse(own.text)?.thinking === true; } catch { return false; }
53
+ export function readRunModel(runDir) {
54
+ const got = readRunRecord(runDir);
55
+ const m = got.ok ? got.rec.model : null;
56
+ return isKeyName(m?.slot) && typeof m?.model === 'string' && m.model !== '' ? { slot: m.slot, model: m.model } : null;
59
57
  }
60
58
 
61
59
  /**
62
- * M4d am25: a run keeps the box as the job had it when the run started (write-once, so an Edit of the job never changes a run already going).
63
- * Written for every fresh run, ticked or not. @param {string} flowDir @param {string} runDir
60
+ * M8 item 5a: the file that keeps EXACTLY what the drafter was handed from earlier runs (the Audit box of item 6 reads it). Bareloop's
61
+ * `learnings` spine record shape, `{phase, text, ids, chars}`. Write-once (never over an existing record); written with something handed, or by `writeLearningsError` with an empty `text`
62
+ * (a failed ask: nothing handed, why in `error`); a reader treats empty text as no record, so no file or empty text = nothing handed = no box. Borrowed-from: bareloop src/planrun.js@v0.46.0:3092 (emit('learnings', ...)).
64
63
  */
65
- export function writeRunThinking(flowDir, runDir) {
66
- writeOnce(join(runDir, RUN_THINKING_FILE), { thinking: readModelRecord(flowDir)?.thinking === true });
64
+ export const LEARNINGS_FILE = 'learnings.json';
65
+
66
+ /** @param {string} dir @param {{text: string, ids: string[]}} hints */
67
+ export function writeLearningsRecord(dir, { text, ids }) {
68
+ writeOnce(join(dir, LEARNINGS_FILE), { phase: 'draft', text, ids, chars: text.length });
67
69
  }
68
70
 
69
- /** M4d am33: the file in a run's folder that records the model the run STARTED on (write-once; every continue path keeps it). */
70
- export const RUN_MODEL_FILE = 'run-model.json';
71
+ /**
72
+ * The drafter's failed ask for the block (or failed record write) rides the same record: nothing handed (`text: ''`, no ids), and `error` (first line, secrets redacted).
73
+ * `readLearningsRecord` reads an empty text as no record, so the Audit box stays hidden and `copyLearningsRecord` copies nothing.
74
+ * @param {string} dir @param {string} error
75
+ */
76
+ export function writeLearningsError(dir, error) {
77
+ writeOnce(join(dir, LEARNINGS_FILE), { phase: 'draft', text: '', ids: [], chars: 0, error });
78
+ }
71
79
 
72
80
  /**
73
- * M4d am33: the ONE reader of the model a run started on, or null (a run from before the record, or an unusable one: the caller then keeps today's pick).
74
- * @param {string|null} runDir @returns {{ slot: string, model: string }|null}
81
+ * M8 item 6: the Audit box reads the record in the RUN's folder. It reaches the run the way `model.json` does: a draft's record is copied (write-once) into the folder it is signed
82
+ * into (`copyLearningsRecord`: the flow folder at a new job's sign, the new run's folder at a red run's redraft), and the first run that starts from a flow folder TAKES it
83
+ * (`takeLearningsRecord`: a rename, so it moves once and a second run of the same job never shows it). A run that reused its plan has no draft, so it has none.
84
+ * @param {string} fromDir a draft folder @param {string} toDir a flow folder or a run folder @returns {boolean} true when a record was copied
75
85
  */
76
- export function readRunModel(runDir) {
77
- const r = typeof runDir === 'string' ? readFileInside(runDir, RUN_MODEL_FILE) : null;
78
- if (!r?.ok) return null;
86
+ export function copyLearningsRecord(fromDir, toDir) {
87
+ const rec = readLearningsRecord(fromDir);
88
+ if (rec === null) return false;
89
+ writeOnce(join(toDir, LEARNINGS_FILE), rec); // `writeOnce`, the same write-once JSON writer and shape as `writeLearningsRecord`: a record that reads is copied, one that does not is not
90
+ return true;
91
+ }
92
+
93
+ /** @param {string} flowDir @param {string} runDir @returns {boolean} true when the flow's record moved into the run (it is no longer in the flow folder) */
94
+ export function takeLearningsRecord(flowDir, runDir) {
95
+ if (!readFileInside(flowDir, LEARNINGS_FILE).ok || readFileInside(runDir, LEARNINGS_FILE).ok) return false;
96
+ renameSync(join(flowDir, LEARNINGS_FILE), join(runDir, LEARNINGS_FILE));
97
+ return true;
98
+ }
99
+
100
+ /**
101
+ * The ONE reader of a run's record. null = no record, or one that is not `{phase, text, ids, chars}` (the box is then hidden, never guessed).
102
+ * @param {string} runDir @returns {{phase: string, text: string, ids: string[], chars: number}|null}
103
+ */
104
+ export function readLearningsRecord(runDir) {
105
+ const r = readFileInside(runDir, LEARNINGS_FILE);
106
+ if (!r.ok) return null;
79
107
  try {
80
108
  const j = JSON.parse(r.text);
81
- return isKeyName(j?.slot) && typeof j?.model === 'string' && j.model !== '' ? { slot: j.slot, model: j.model } : null;
109
+ return j && typeof j.text === 'string' && j.text !== '' && Array.isArray(j.ids) && j.ids.every((/** @type {any} */ x) => typeof x === 'string')
110
+ ? { phase: String(j.phase ?? 'draft'), text: j.text, ids: j.ids, chars: Number.isInteger(j.chars) ? j.chars : j.text.length } : null;
82
111
  } catch { return null; }
83
112
  }
84
-
85
- /** M4d am33: the ONE writer, called once when a fresh run starts (`runFlow`); never over an existing record. @param {string} runDir @param {{ slot: string, model: string }} pick */
86
- export function writeRunModel(runDir, { slot, model }) {
87
- writeOnce(join(runDir, RUN_MODEL_FILE), { slot, model });
88
- }
package/src/keysfile.js CHANGED
@@ -99,7 +99,7 @@ export function parseKeysText(text) {
99
99
  * @param {string} [home]
100
100
  * @returns {boolean} true if it was created
101
101
  */
102
- function createKeysFile(home) {
102
+ export function createKeysFile(home) {
103
103
  mkdirSync(keysHome(home), { recursive: true, mode: 0o700 });
104
104
  const body = '# fwdloop keys — type NAME=value by hand; this file is never shown or written by fwdloop.\n'
105
105
  + '# One line per provider key, e.g. MY_PROVIDER_API_KEY=... ; each key becomes a row in Settings > Providers.\n';