fwdloop 0.21.0 → 0.23.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 (104) hide show
  1. package/bin/fwdloop +85 -34
  2. package/package.json +4 -3
  3. package/src/ask.js +20 -4
  4. package/src/audit-fold.js +5 -1
  5. package/src/authoring.js +36 -6
  6. package/src/canrun.js +5 -0
  7. package/src/checked.js +32 -4
  8. package/src/cited-record.js +138 -0
  9. package/src/cited-source.js +49 -0
  10. package/src/citedcheck.js +321 -0
  11. package/src/citedwords.js +197 -0
  12. package/src/closers.js +37 -198
  13. package/src/csv.js +69 -12
  14. package/src/ctx-tools.js +2 -14
  15. package/src/declaration.js +143 -5
  16. package/src/diary.js +2 -2
  17. package/src/docx.js +16 -2
  18. package/src/draft-steps.js +1 -1
  19. package/src/drafter.js +322 -33
  20. package/src/flow.js +33 -7
  21. package/src/flowmodel.js +21 -0
  22. package/src/input-facts.js +20 -3
  23. package/src/model-step.js +38 -21
  24. package/src/pageask.js +136 -0
  25. package/src/pagebits.js +107 -0
  26. package/src/pagedropwords.js +171 -0
  27. package/src/pagedry.js +120 -0
  28. package/src/pagefetch.js +164 -0
  29. package/src/pagelook.js +155 -0
  30. package/src/pagemap.js +55 -0
  31. package/src/pageplace.js +103 -0
  32. package/src/pagerules.js +318 -0
  33. package/src/panel/author.js +43 -21
  34. package/src/panel/authorcard.js +20 -3
  35. package/src/panel/authorflows.js +21 -15
  36. package/src/panel/authorstart.js +2 -4
  37. package/src/panel/authortrigger.js +14 -4
  38. package/src/panel/data.js +102 -6
  39. package/src/panel/index.html +321 -12
  40. package/src/panel/result.js +301 -0
  41. package/src/panel/server.js +27 -3
  42. package/src/primitives.js +2 -3
  43. package/src/provider.js +5 -2
  44. package/src/redact.js +17 -0
  45. package/src/runner.js +102 -14
  46. package/src/schedule.js +3 -3
  47. package/src/setup.js +16 -1
  48. package/src/sheet-record.js +57 -0
  49. package/src/sheetblock.js +170 -0
  50. package/src/sheetchecks.js +206 -0
  51. package/src/sheetclaims.js +78 -0
  52. package/src/sheetfind.js +50 -0
  53. package/src/sheetlook.js +157 -0
  54. package/src/sheetoffer.js +125 -0
  55. package/src/sheetrun.js +105 -0
  56. package/src/signed-text.js +11 -1
  57. package/src/thinking.js +1 -1
  58. package/src/try-checks.js +12 -0
  59. package/src/types.js +4 -11
  60. package/types/ask.d.ts +2 -1
  61. package/types/authoring.d.ts +19 -2
  62. package/types/checked.d.ts +19 -3
  63. package/types/cited-record.d.ts +21 -0
  64. package/types/cited-source.d.ts +18 -0
  65. package/types/citedcheck.d.ts +95 -0
  66. package/types/citedwords.d.ts +97 -0
  67. package/types/closers.d.ts +37 -10
  68. package/types/csv.d.ts +25 -4
  69. package/types/ctx-tools.d.ts +0 -1
  70. package/types/declaration.d.ts +20 -1
  71. package/types/docx.d.ts +14 -0
  72. package/types/drafter.d.ts +264 -8
  73. package/types/flow.d.ts +21 -0
  74. package/types/flowmodel.d.ts +15 -0
  75. package/types/input-facts.d.ts +12 -2
  76. package/types/model-step.d.ts +40 -19
  77. package/types/pageask.d.ts +75 -0
  78. package/types/pagebits.d.ts +32 -0
  79. package/types/pagedropwords.d.ts +40 -0
  80. package/types/pagedry.d.ts +38 -0
  81. package/types/pagefetch.d.ts +86 -0
  82. package/types/pagelook.d.ts +75 -0
  83. package/types/pagemap.d.ts +31 -0
  84. package/types/pageplace.d.ts +22 -0
  85. package/types/pagerules.d.ts +86 -0
  86. package/types/panel/authorcard.d.ts +4 -1
  87. package/types/panel/authorflows.d.ts +2 -0
  88. package/types/panel/data.d.ts +26 -0
  89. package/types/panel/result.d.ts +156 -0
  90. package/types/provider.d.ts +3 -1
  91. package/types/redact.d.ts +1 -0
  92. package/types/runner.d.ts +162 -9
  93. package/types/schedule.d.ts +0 -11
  94. package/types/setup.d.ts +13 -0
  95. package/types/sheet-record.d.ts +24 -0
  96. package/types/sheetblock.d.ts +116 -0
  97. package/types/sheetchecks.d.ts +70 -0
  98. package/types/sheetclaims.d.ts +26 -0
  99. package/types/sheetfind.d.ts +46 -0
  100. package/types/sheetlook.d.ts +120 -0
  101. package/types/sheetoffer.d.ts +25 -0
  102. package/types/sheetrun.d.ts +35 -0
  103. package/types/thinking.d.ts +1 -1
  104. package/types/types.d.ts +27 -14
package/bin/fwdloop CHANGED
@@ -37,7 +37,7 @@ import { resolvePrimitives } from '../src/primitives.js';
37
37
  import {
38
38
  checkKeyPreflight, resolveUsableModel, pickTicked, readPriceConfig, ceilingCostUsd,
39
39
  } from '../src/provider.js';
40
- import { readModelRecord } from '../src/flowmodel.js';
40
+ import { readModelRecord, readRunModel } from '../src/flowmodel.js';
41
41
  import { configDoorHome } from '../src/config.js';
42
42
  import {
43
43
  claimHold, settleHold, nameRunDir, monthlyRefusalText, ConfigError,
@@ -50,8 +50,9 @@ import { panelMain } from '../src/panel/server.js';
50
50
  import { isInteractive, confirmTypedName, NEEDS_TTY } from '../src/sign-confirm.js';
51
51
  import { draftToDir, draftKeyRefusal, signDraft, SIGN_LINE, costText, questionsRefusal } from '../src/authoring.js';
52
52
  import { userInfo } from 'node:os';
53
+ import { pageAddressesOf, pageAddressRefusal } from '../src/pagefetch.js';
53
54
 
54
- // This CLI drives no fixed provider (M4d amendment 6). A job runs with the model recorded beside it (`model.json`, written when it was drafted:
55
+ // This CLI drives no fixed provider (M4d amendment 6). A job runs with the model recorded beside it as its DEFAULT (M4d am33: `run --model` picks any other ticked model for that run) (`model.json`, written when it was drafted:
55
56
  // the provider is the name of a key, its key is read from the env under that name and never printed); `draft` takes `--model` (+ `--provider`).
56
57
  // Whether that model may be used is `resolveUsableModel` (ticked in Settings > Providers with both prices): this file names no model and no price.
57
58
 
@@ -75,7 +76,9 @@ const keyedEnv = () => keyedLoad().env;
75
76
  * that does not fit refuses at $0 with the one refusal text. A hold that fits is given back when this
76
77
  * process ends or parks (the `exit` hook runs on every exit path; a SIGKILL leaves it for the next check,
77
78
  * which settles it as "process gone").
78
- * @returns {{ addRunDir: (d: string) => void, nameRunDir: (d: string) => void }}
79
+ * M4d am32: the draft door also gets `settle(why)`, called when the draft's result is written: the hold is given back then, not at exit. The exit hook calls the same
80
+ * function as a backstop; it settles once (a second call is a no-op), so a hold is never settled twice.
81
+ * @returns {{ addRunDir: (d: string) => void, nameRunDir: (d: string) => void, settle: (why: string) => void }}
79
82
  */
80
83
  const NO_CONFIG_HOME_REFUSAL = 'NODE_ENV=test is set without FWDLOOP_CONFIG_HOME, so the keys file, prices and monthly limit would be skipped. Nothing spent. Unset NODE_ENV, or set FWDLOOP_CONFIG_HOME.';
81
84
 
@@ -90,7 +93,7 @@ function takeMonthlyHold({ what, flow, runId, runDir, holdUsd, spentAtHold = 0 }
90
93
  if (!(process.env.NODE_ENV === 'test' && process.env[hook])) {
91
94
  fail(NO_CONFIG_HOME_REFUSAL);
92
95
  }
93
- return { addRunDir: () => {}, nameRunDir: () => {} };
96
+ return { addRunDir: () => {}, nameRunDir: () => {}, settle: () => {} };
94
97
  }
95
98
  let claim;
96
99
  try {
@@ -102,12 +105,17 @@ function takeMonthlyHold({ what, flow, runId, runDir, holdUsd, spentAtHold = 0 }
102
105
  fail(`${err.message} — refusing to start rather than guess the monthly limit. Nothing spent.`);
103
106
  }
104
107
  if (!claim.ok) fail(monthlyRefusalText(claim.room));
105
- if (claim.holdId !== null) {
106
- process.on('exit', () => settleHold({
107
- holdId: claim.holdId, why: process.exitCode ? 'ended (red)' : 'ended or parked', home, alsoRunDirs: also,
108
- }));
109
- }
108
+ let settled = false;
109
+ const settle = (why) => {
110
+ if (settled || claim.holdId === null) return;
111
+ settled = true;
112
+ settleHold({
113
+ holdId: claim.holdId, why, home, alsoRunDirs: also,
114
+ });
115
+ };
116
+ if (claim.holdId !== null) process.on('exit', () => settle(process.exitCode ? 'ended (red)' : 'ended or parked'));
110
117
  return {
118
+ settle,
111
119
  addRunDir: (d) => also.push(d),
112
120
  // C2: a rerun's new run dir is named in the money record the moment it starts.
113
121
  nameRunDir: (d) => { also.push(d); nameRunDir({ holdId: claim.holdId, runDir: d, home }); },
@@ -160,7 +168,24 @@ function today() {
160
168
  * be hit by a user typing `--something`. This is how the test suite drives
161
169
  * every CLI scenario at $0 with zero chance of a real network call.
162
170
  */
163
- async function resolveModelStep(spendPath, env, flowDir, named = {}, runModel = null) {
171
+ async function resolveModelStep(spendPath, env, flowDir, named = {}, runModel = null, continuing = false) {
172
+ // M4d am33: the ONE decision of which model this run uses. `runModel` is the model the run already has (a continue: the one it started on; a start: the
173
+ // one it was signed with). `--model` picks any ticked model for a NEW run (the job's recorded model is only the default; model.json is never rewritten);
174
+ // a run that already has its model keeps it: naming another is refused by name, never silently swapped.
175
+ const decide = (config) => {
176
+ const rec = runModel ?? readModelRecord(flowDir); // M6 am5/am6 / M4d am33: the model of THIS run, else the one recorded with the job
177
+ if (runModel !== null && named.model !== undefined && (named.model !== runModel.model || (named.provider !== undefined && named.provider !== runModel.slot))) {
178
+ throw new Error(continuing
179
+ ? `This run started on ${runModel.model}; a resume keeps it. Nothing spent.`
180
+ : `This run was signed with its model (${runModel.slot} · ${runModel.model}); --model cannot change it.`);
181
+ }
182
+ if (named.model !== undefined) {
183
+ const p = pickTicked(config, { model: named.model, provider: named.provider ?? (rec !== null && rec.model === named.model ? rec.slot : undefined) });
184
+ if (!p.ok) throw new Error(p.say);
185
+ return p;
186
+ }
187
+ return rec;
188
+ };
164
189
  if (process.env.NODE_ENV === 'test' && process.env.FWDLOOP_TEST_MODEL_STEP) {
165
190
  const modulePath = resolve(process.env.FWDLOOP_TEST_MODEL_STEP);
166
191
  const mod = await import(pathToFileURL(modulePath).href);
@@ -171,33 +196,24 @@ async function resolveModelStep(spendPath, env, flowDir, named = {}, runModel =
171
196
  // is exercised the way a live run's is); with none, the double holds nothing. It is never refused here: it spends nothing.
172
197
  const modelStep = await mod.default({ spendPath });
173
198
  let usable = null;
199
+ let pick = null;
174
200
  try {
175
- const rec = configDoorHome().skip ? null : (runModel ?? readModelRecord(flowDir));
176
- usable = rec === null ? null : resolveUsableModel(rec.slot, { config: readPriceConfig(), model: rec.model });
201
+ pick = configDoorHome().skip ? null : decide(readPriceConfig());
202
+ usable = pick === null ? null : resolveUsableModel(pick.slot, { config: readPriceConfig(), model: pick.model });
177
203
  } catch (err) {
178
204
  if (!(err instanceof ConfigError)) throw err; // a broken config is refused by name at the monthly hold, right after this
179
205
  }
180
- return { modelStep, ...(usable?.ok ? { ceilingUsd: ceilingCostUsd(usable.rates) } : {}) };
206
+ return { modelStep, model: pick === null ? null : { slot: pick.slot, model: pick.model }, ...(usable?.ok ? { ceilingUsd: ceilingCostUsd(usable.rates) } : {}) };
181
207
  }
182
208
  // A test process with no config home reads no Settings: say why, not "tick a model".
183
209
  if (configDoorHome().skip) throw new Error(NO_CONFIG_HOME_REFUSAL);
184
- // The ONE decision of which model runs and at what price (M4d amendments 5 and 6): the model recorded with the job (a job drafted before the record
185
- // existed takes `--model`), refused by name, at $0, before a run dir or a book row exists. The per-round hold is that model's own Settings price times the token bounds.
210
+ // The per-round hold is that model's own Settings price times the token bounds; a refusal comes before a run dir or a book row exists.
186
211
  let usable;
187
212
  let slot;
188
213
  try {
189
214
  const config = readPriceConfig();
190
- const rec = runModel ?? readModelRecord(flowDir); // M6 am5/am6: the model signed for THIS run, else the one recorded with the job
191
- if (rec !== null && named.model !== undefined && (named.model !== rec.model || (named.provider !== undefined && named.provider !== rec.slot))) {
192
- throw new Error(`This job already has its model recorded (${rec.slot} · ${rec.model}); --model cannot change it.`);
193
- }
194
- let pick = rec;
195
- if (pick === null) {
196
- if (named.model === undefined) throw new Error('This job has no model recorded. Name one with --model <id>, a model ticked in Settings > Providers with both prices.');
197
- const p = pickTicked(config, named);
198
- if (!p.ok) throw new Error(p.say);
199
- pick = p;
200
- }
215
+ const pick = decide(config);
216
+ if (pick === null) throw new Error('This job has no model recorded. Name one with --model <id>, a model ticked in Settings > Providers with both prices.');
201
217
  slot = pick.slot;
202
218
  const keyCheck = checkKeyPreflight(slot, env);
203
219
  if (!keyCheck.ok) throw new Error(keyCheck.message);
@@ -209,10 +225,16 @@ async function resolveModelStep(spendPath, env, flowDir, named = {}, runModel =
209
225
  if (!usable.ok) throw new Error(usable.say);
210
226
  return {
211
227
  modelStep: makeLiveModelStep({ slot, model: usable.model, spendPath, env }),
228
+ model: { slot, model: usable.model },
212
229
  ceilingUsd: ceilingCostUsd(usable.rates),
213
230
  };
214
231
  }
215
232
 
233
+ /** M4d am33: the model a run being continued keeps: the one it started on (its record), else the one it was signed with; null = an old run, today's pick. */
234
+ function runModelKept(runDir) {
235
+ return readRunModel(runDir) ?? runModelOf(pickRunValues(runDir));
236
+ }
237
+
216
238
  function parseSourceFlags(list) {
217
239
  const out = {};
218
240
  for (const entry of list ?? []) {
@@ -221,7 +243,7 @@ function parseSourceFlags(list) {
221
243
  const role = entry.slice(0, eq);
222
244
  const value = entry.slice(eq + 1);
223
245
  if (value.length === 0) throw new Error(`--source "${entry}" has an empty path`);
224
- out[role] = resolve(value);
246
+ out[role] = value; // resolved at use: a file role is a path, a signed page role is an address (M10 am3)
225
247
  }
226
248
  return out;
227
249
  }
@@ -324,6 +346,13 @@ async function cmdRun(rest) {
324
346
  return;
325
347
  }
326
348
  const declaredRoles = (read.arbiter.sources ?? []).map((s) => s.role);
349
+ // M10 am3: a web page input's address is signed with the job; the run takes it from there, and naming any other address is refused at $0
350
+ const pages = pageAddressesOf(read.arbiter);
351
+ for (const role of Object.keys(pages)) {
352
+ if (Object.hasOwn(parsedSources, role) && parsedSources[role] !== pages[role]) fail(`run: ${pageAddressRefusal(role, pages[role])}`);
353
+ parsedSources[role] = pages[role];
354
+ }
355
+ for (const role of Object.keys(parsedSources)) if (!Object.hasOwn(pages, role)) parsedSources[role] = resolve(parsedSources[role]);
327
356
  for (const role of declaredRoles) {
328
357
  if (!Object.hasOwn(parsedSources, role)) {
329
358
  fail(`run: flow "${flowName}" declares source role "${role}" — pass --source ${role}=<path>`);
@@ -336,7 +365,7 @@ async function cmdRun(rest) {
336
365
  }
337
366
  const sources = declaredRoles.map((role) => ({ id: role, path: parsedSources[role] }));
338
367
  for (const src of sources) {
339
- if (!existsSync(src.path)) fail(`run: source "${src.id}" is unreadable at ${src.path}`);
368
+ if (!Object.hasOwn(pages, src.id) && !existsSync(src.path)) fail(`run: source "${src.id}" is unreadable at ${src.path}`);
340
369
  }
341
370
 
342
371
  // M4e amendment 3: no --run-id -> the ONE claim (`run-<n>`, the folder created exclusively). A typed id is checked as before; its
@@ -368,8 +397,9 @@ async function cmdRun(rest) {
368
397
  const spendPath = join(runDir, 'spend.jsonl');
369
398
  let modelStep;
370
399
  let ceilingUsd;
400
+ let startedModel;
371
401
  try {
372
- ({ modelStep, ceilingUsd } = await resolveModelStep(spendPath, env, join(root, flowName), values, runModelOf(pickRunValues(runDir))));
402
+ ({ modelStep, ceilingUsd, model: startedModel } = await resolveModelStep(spendPath, env, join(root, flowName), values, runModelOf(pickRunValues(runDir))));
373
403
  } catch (err) {
374
404
  fail(err.message);
375
405
  return;
@@ -398,6 +428,7 @@ async function cmdRun(rest) {
398
428
  root,
399
429
  name: flowName,
400
430
  runId,
431
+ runModel: startedModel ?? undefined,
401
432
  sources,
402
433
  catalogue,
403
434
  modelStep,
@@ -626,7 +657,7 @@ async function cmdResume(rest) {
626
657
  let modelStep;
627
658
  let ceilingUsd;
628
659
  try {
629
- ({ modelStep, ceilingUsd } = await resolveModelStep(spendPath, env, join(root, flowName), values, runModelOf(pickRunValues(runDir))));
660
+ ({ modelStep, ceilingUsd } = await resolveModelStep(spendPath, env, join(root, flowName), values, runModelKept(runDir), true));
630
661
  } catch (err) {
631
662
  fail(err.message);
632
663
  return;
@@ -668,6 +699,7 @@ async function cmdResume(rest) {
668
699
  root,
669
700
  name: flowName,
670
701
  runId,
702
+ runModel: runModelKept(runDir) ?? undefined, // a rerun (a new run made by this resume) records the model the resumed run keeps
671
703
  catalogue,
672
704
  modelStep,
673
705
  ceilingUsd,
@@ -727,7 +759,7 @@ async function cmdContinue(rest) {
727
759
  let modelStep;
728
760
  let ceilingUsd;
729
761
  try {
730
- ({ modelStep, ceilingUsd } = await resolveModelStep(spendPath, env, join(root, flowName), values, runModelOf(pickRunValues(runDir))));
762
+ ({ modelStep, ceilingUsd } = await resolveModelStep(spendPath, env, join(root, flowName), values, runModelKept(runDir), true));
731
763
  } catch (err) {
732
764
  fail(err.message);
733
765
  return;
@@ -818,6 +850,8 @@ async function cmdDraft(rest) {
818
850
  out: { type: 'string' }, root: { type: 'string' }, name: { type: 'string' },
819
851
  // M4e amendment 24 item 4: the redraft after the human's answers never asks (the panel passes this; a plain draft may ask on try 3)
820
852
  'no-questions': { type: 'boolean' },
853
+ // M10 piece 3: the rules the person left Not checked ("drop it"), as `<line>.<rule>` pairs, e.g. `1.2,3.1` (the panel passes this to the redraft after the answers)
854
+ left: { type: 'string' },
821
855
  // M4d amendment 6: the model that drafts (and then runs) the job - a line ticked in Settings > Providers; --provider only if two keys tick the same id.
822
856
  // --thinking is the Chat "Thinking on" tick (drafting only; off unless given).
823
857
  model: { type: 'string' }, provider: { type: 'string' }, thinking: { type: 'boolean' },
@@ -830,6 +864,13 @@ async function cmdDraft(rest) {
830
864
  if (!proseFile) fail('draft: a prose file is required — fwdloop draft <prose.txt> --out <draftDir> --root <flowsDir> --name <flow>');
831
865
  for (const req of ['out', 'root', 'name']) if (!values[req]) fail(`draft: --${req} is required`);
832
866
 
867
+ const leftRules = [];
868
+ for (const pair of values.left === undefined ? [] : values.left.split(',')) {
869
+ const m = /^(\d+)\.(\d+)$/.exec(pair.trim());
870
+ if (m === null || Number(m[1]) < 1 || Number(m[2]) < 1) fail(`draft: --left takes <line>.<rule> pairs like 1.2,3.1, got "${values.left}"`);
871
+ leftRules.push({ line: Number(m[1]), rule: Number(m[2]) });
872
+ }
873
+
833
874
  let injected = {};
834
875
  if (process.env.NODE_ENV === 'test' && process.env.FWDLOOP_TEST_DRAFT_PROVIDER) {
835
876
  const mod = await import(pathToFileURL(resolve(process.env.FWDLOOP_TEST_DRAFT_PROVIDER)).href);
@@ -869,16 +910,25 @@ async function cmdDraft(rest) {
869
910
  fail(`${err.message} — refusing to draft rather than guess the price. Nothing spent.`);
870
911
  }
871
912
  // M4d am19 item 1: the hold is what is left of the cap (cap minus this job's drafting so far), the most the draft may spend, not one round
872
- const proseRead = readFileInside(dirname(resolve(proseFile)), basename(resolve(proseFile)));
873
- takeMonthlyHold({
913
+ // the ONE read of the prose file goes through the safe gateway (a symlink or an outside path is refused); draftToDir is handed this read
914
+ const proseAbs = resolve(proseFile);
915
+ const gate = readFileInside(dirname(proseAbs), basename(proseAbs));
916
+ const proseRead = gate.ok
917
+ ? (gate.text.trim() === '' ? { ok: false, red: `prose: "${proseAbs}" is empty` } : gate)
918
+ : { ok: false, red: gate.missing ? `prose: cannot read "${proseAbs}": ENOENT` : `prose: ${gate.red}` };
919
+ const hold = takeMonthlyHold({
874
920
  what: 'draft', flow: values.name, runId: null, runDir: resolve(values.out), holdUsd: draftHoldUsd(proseRead.ok ? proseRead.text : '', resolve(values.out), ceiling),
875
921
  });
876
922
  const result = await draftToDir({
923
+ // M4d am32: the hold is given back when the draft's result is written, not when this process exits (the exit hook stays as the backstop)
924
+ onResult: ({ ok }) => hold.settle(ok ? 'ended or parked' : 'ended (red)'),
877
925
  proseFile: resolve(proseFile),
926
+ proseRead,
878
927
  dir: resolve(values.out),
879
928
  root: resolve(values.root),
880
929
  name: values.name,
881
930
  noQuestions: values['no-questions'] === true,
931
+ ...(leftRules.length ? { leftRules } : {}),
882
932
  draftThinking: values.thinking === true ? 'on' : 'off',
883
933
  env,
884
934
  keyNames: keysLoad.keyNames,
@@ -892,7 +942,8 @@ async function cmdDraft(rest) {
892
942
  return;
893
943
  }
894
944
  process.stdout.write(`draft dir: ${resolve(values.out)} cost: ${cost}\n`);
895
- if (!result.ok) {
945
+ // M10 piece 3: a draft that stopped to ask what the page look raised is not red: it waits for the person's answers (the panel takes them)
946
+ if (!result.ok && result.stop !== 'look-asks') {
896
947
  process.stderr.write(`fwdloop: draft RED (${result.stop ?? 'scrub'}) — ${result.reds.join('; ')}\n`);
897
948
  process.exitCode = 1;
898
949
  return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fwdloop",
3
- "version": "0.21.0",
3
+ "version": "0.23.0",
4
4
  "description": "Describe a job as steps and guardrails; an agent builds the workflow, pauses for humans where you said, checks every step happened, and reruns it under budgets it cannot touch.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
@@ -32,7 +32,7 @@
32
32
  "bare-suite"
33
33
  ],
34
34
  "engines": {
35
- "node": ">=20"
35
+ "node": ">=22"
36
36
  },
37
37
  "scripts": {
38
38
  "test": "node --test",
@@ -50,7 +50,8 @@
50
50
  ],
51
51
  "dependencies": {
52
52
  "bare-agent": "^0.52.0",
53
- "bareguard": "^0.21.2",
53
+ "barebrowse": "^0.21.0",
54
+ "bareguard": "^0.26.0",
54
55
  "litectx": "^0.32.0"
55
56
  },
56
57
  "devDependencies": {
package/src/ask.js CHANGED
@@ -184,7 +184,7 @@ export function makeFileAskStep({
184
184
  * @param {any} ask the parsed ask.json object (or its `evidence` field's
185
185
  * container — pass the whole ask so a missing `evidence` key is itself a
186
186
  * handled case, not the caller's problem).
187
- * @returns {{ draft: {step?: string, text: string} | null, unjudged: Array<{step: string, emits?: string, text: string}>, why?: string }}
187
+ * @returns {{ draft: {step?: string, text: string} | null, unjudged: Array<{step: string, emits?: string, text: string}>, why?: string, claims?: Record<string, any> }}
188
188
  */
189
189
  export function readAskEvidence(ask) {
190
190
  const evidence = ask && typeof ask === 'object' ? ask.evidence : undefined;
@@ -205,8 +205,8 @@ export function readAskEvidence(ask) {
205
205
  };
206
206
  }
207
207
 
208
- // M3 shape: evidence.artifact.text (+ evidence.unjudged[]).
209
- if (evidence.artifact && typeof evidence.artifact === 'object' && typeof evidence.artifact.text === 'string') {
208
+ // The earlier steps' text carried into the ask (the same for every shape that has an `artifact`).
209
+ const readUnjudged = () => {
210
210
  const rawUnjudged = Array.isArray(evidence.unjudged) ? evidence.unjudged : [];
211
211
  const unjudged = [];
212
212
  for (const item of rawUnjudged) {
@@ -230,7 +230,12 @@ export function readAskEvidence(ask) {
230
230
  // dropped rather than shown as a blank row — the draft itself is
231
231
  // never lost by a malformed sibling entry.
232
232
  }
233
- return { draft: { text: evidence.artifact.text }, unjudged };
233
+ return unjudged;
234
+ };
235
+
236
+ // M3 shape: evidence.artifact.text (+ evidence.unjudged[]).
237
+ if (evidence.artifact && typeof evidence.artifact === 'object' && typeof evidence.artifact.text === 'string') {
238
+ return { draft: { text: evidence.artifact.text }, unjudged: readUnjudged() };
234
239
  }
235
240
 
236
241
  // M2 shape: evidence.text (+ evidence.lines) — no unjudged concept.
@@ -238,6 +243,17 @@ export function readAskEvidence(ask) {
238
243
  return { draft: { text: evidence.text }, unjudged: [] };
239
244
  }
240
245
 
246
+ // M10b am4: a step with sheet checks answers in claim boxes, an object with no text. They are handed on as `claims` (the panel matches them to the step's checks);
247
+ // the `why` stays, for the caller that finds no sheet step for them.
248
+ if (evidence.artifact && typeof evidence.artifact === 'object' && !Array.isArray(evidence.artifact)) {
249
+ return {
250
+ draft: null,
251
+ unjudged: readUnjudged(),
252
+ claims: evidence.artifact,
253
+ why: `ask.json "evidence" has neither ".artifact.text" (M3) nor ".text" (M2) — unrecognised shape: keys ${JSON.stringify(Object.keys(evidence))}`,
254
+ };
255
+ }
256
+
241
257
  // Present but neither recognised shape — never fall through to
242
258
  // `undefined`/`JSON.stringify(undefined)` ("undefined" the string).
243
259
  return {
package/src/audit-fold.js CHANGED
@@ -103,11 +103,15 @@ export function deriveFold(group, d, info = {}) {
103
103
  });
104
104
  }
105
105
  } else {
106
+ // M4d am30: a try's checks are the check row with ITS number. A number is used once per step, so that is exact. A run from before am30 may repeat a number
107
+ // (the old Redo restarted it): those tries are paired in order only when every one of them saved (as many check rows as try rows); otherwise none is guessed.
106
108
  const seen = new Map();
107
109
  tryRows.forEach((r, i) => {
108
110
  const k = seen.get(r.attempt) ?? 0;
109
111
  seen.set(r.attempt, k + 1);
110
- const rec = checkRows.filter((c) => c.try === r.attempt)[k] ?? null;
112
+ const saved = checkRows.filter((c) => c.try === r.attempt);
113
+ const alike = tryRows.filter((t) => t.attempt === r.attempt).length;
114
+ const rec = saved.length === alike ? saved[k] : null;
111
115
  tries.push({
112
116
  n: r.attempt, mark: group.tryMarks[i] ?? '·', thinking: r.thinkingPhrase ?? null, gap: r.gap || null, answer: null, about: null, checks: rec?.checks ?? [], output: rec?.output ?? null,
113
117
  });
package/src/authoring.js CHANGED
@@ -22,6 +22,8 @@ import path from 'node:path';
22
22
  import { draft } from './drafter.js';
23
23
  import { parseSignedText, unsignedAskTtls } from './signed-text.js';
24
24
  import { validateDeclaration } from './declaration.js';
25
+ import { factRows } from './citedcheck.js';
26
+ import { sheetLineBlocks } from './sheetblock.js';
25
27
  import { loadCatalogue } from './catalogue.js';
26
28
  import { WIRED_VERBS } from './primitives.js';
27
29
  import { canonicalBytes } from './signature.js';
@@ -43,6 +45,10 @@ export const LEAK_MARKER_FILE = 'scrub-leak.red';
43
45
  * and the drafter's own "not checked" reading (information only; never in the readout, so never in the hash). */
44
46
  export const QUESTIONS_FILE = 'questions.json';
45
47
  export const NOT_CHECKED_FILE = 'not-checked.json';
48
+ /** M10: the drafting copy of each web page input is kept in this folder of the draft folder (a run freezes its own, never this one). */
49
+ export const PAGES_DIR = 'pages';
50
+ /** M10 item 3: what the page-word look kept and dropped, per page input (the map the AI named, the kept facts with their readings, every drop). Not signed. */
51
+ export const PAGE_LOOK_FILE = 'page-look.json';
46
52
  export const ANSWER_FILE = (k) => `answer-${k}.json`;
47
53
  export const SIGN_LINE = (dir, hash) => `DRAFTED — NOT SIGNED. To sign: fwdloop sign ${dir} --approve ${hash}`;
48
54
 
@@ -77,7 +83,8 @@ export function specHash({
77
83
  * checks and the page all use it). `questions` = [{ k, line, question, answer|null }], `open` = those with no answer. A blank or unreadable
78
84
  * answer file counts as no answer. No questions file = `{ questions: [], open: [] }`.
79
85
  * @param {string} planDir
80
- * @returns {{ questions: {k:number, line:number, question:string, answer:string|null}[], open: {k:number, line:number, question:string, answer:null}[] }}
86
+ * 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`.
87
+ * @returns {{ questions: {k:number, line:number, question:string, answer:string|null, at?:string, rule?:string|null, source?:string, ask?:string, ruleNo?:number, ruleText?:string, proposal?:string|null}[], open: {k:number, line:number, question:string, answer:null}[] }}
81
88
  */
82
89
  export function readQuestions(planDir) {
83
90
  const none = { questions: [], open: [] };
@@ -90,8 +97,20 @@ export function readQuestions(planDir) {
90
97
  const k = i + 1;
91
98
  const a = readFileInside(planDir, ANSWER_FILE(k));
92
99
  let answer = null;
93
- if (a.ok) { try { const t = JSON.parse(a.text)?.answer; if (typeof t === 'string' && t.trim() !== '') answer = t; } catch { /* unreadable = unanswered */ } }
94
- return { k, line: q.line, question: String(q.question), answer };
100
+ let at;
101
+ /** @type {string|null|undefined} the `~` rule the answer added (null = it left the rule Not checked), as the answer file recorded it */
102
+ let rule;
103
+ if (a.ok) {
104
+ try {
105
+ const j = JSON.parse(a.text);
106
+ const t = j?.answer;
107
+ 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; }
108
+ } catch { /* unreadable = unanswered */ }
109
+ }
110
+ return {
111
+ k, line: q.line, question: String(q.question), answer, ...(at === undefined ? {} : { at }), ...(rule === undefined ? {} : { rule }),
112
+ ...(q.source === 'look' ? { source: 'look', ask: q.ask, ruleNo: q.ruleNo, ruleText: q.ruleText, proposal: typeof q.proposal === 'string' ? q.proposal : null } : {}),
113
+ };
95
114
  });
96
115
  return { questions, open: /** @type {any} */ (questions.filter((q) => q.answer === null)) };
97
116
  }
@@ -174,10 +193,17 @@ export function buildReadout({
174
193
  out.push(` ${s.role} = ${s.path}${h ? ` [headings: ${h.join(' | ') || 'none'}]` : ''}`);
175
194
  }
176
195
  out.push('', READOUT_HEADS.steps);
196
+ const sheetBlocks = sheetLineBlocks({ declaration, lines });
177
197
  declaration.steps.forEach((st, i) => {
178
198
  out.push(` ${i + 1}. (line ${st.fromLine}) ${st.goal}`);
179
199
  out.push(` grants: ${st.primitives?.length ? st.primitives.join(', ') : 'none (pure stop)'}`
180
200
  + ` | reads: ${st.reads?.length ? st.reads.join(', ') : '-'} | emits: ${st.emits} | check: ${st.close?.class}`);
201
+ // M10 am7 item 1: the facts a cited step checks its quotes against, signed with the readout (typed fields, never model prose)
202
+ if (st.close?.cited && typeof st.close.cited === 'object') for (const row of factRows(st.close.cited)) out.push(` ${row}`);
203
+ // M10b piece 1: the signed sheet checks, one row each, written by code from the typed fields
204
+ if (Array.isArray(st.close?.sheet)) for (const row of sheetBlocks.find((b) => b.line === st.fromLine)?.checked ?? []) out.push(` sheet check: ${row.text}`);
205
+ // M10 am8 item 2: the column lock, signed with the readout (typed fields)
206
+ if (Array.isArray(st.close?.columns)) for (const c of st.close.columns) if (typeof c?.column === 'string' && typeof c?.source === 'string') out.push(` cells only from column '${c.column}' of ${c.source}`);
181
207
  // M4e amendment 14 item 5: the check's sections in its order (+ word limit); fixed text from typed fields, never model prose.
182
208
  const shape = st.close?.shape;
183
209
  if (Array.isArray(shape?.sections) && shape.sections.length > 0) {
@@ -246,9 +272,10 @@ export function draftKeyRefusal(slot, env) {
246
272
  * writer (appendSpendRow); an unpriced round books null, never 0.
247
273
  *
248
274
  * Test seam: `provider`/`rates`/`modelId` are injected; without them a live provider is built.
275
+ * `onResult({ ok })` (M4d am32): called once, after the spend is booked and just before the result files are written (the CLI gives its monthly hold back there).
249
276
  */
250
277
  export async function draftToDir({
251
- proseFile, dir, root, name, slot, model, draftThinking = /** @type {'on'|'off'} */ ('off'), keyNames, env = process.env, provider, rates, modelId, noQuestions = false,
278
+ proseFile, dir, root, name, slot, model, draftThinking = /** @type {'on'|'off'} */ ('off'), keyNames, env = process.env, provider, rates, modelId, noQuestions = false, onResult, fetchPage, leftRules, proseRead,
252
279
  }) {
253
280
  const refuse = (reds) => ({ ok: false, wrote: false, reds, costUsd: 0 });
254
281
  const nameCheck = checkFlowName(name);
@@ -264,7 +291,7 @@ export async function draftToDir({
264
291
  if (!panelDrafts && (rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel)))) {
265
292
  return refuse([`draft: "${dir}" is inside the flows root "${root}" — an unsigned draft would show as a flow; use a --out outside the flows root`]);
266
293
  }
267
- const read = readProseFile(proseFile);
294
+ const read = proseRead ?? readProseFile(proseFile); // the CLI reads the file once (for its hold) and hands that read in
268
295
  if (!read.ok) return refuse([String(read.red)]);
269
296
  const prose = { text: String(read.text) };
270
297
  const injected = provider != null;
@@ -307,7 +334,7 @@ export async function draftToDir({
307
334
  // M4d am16: a panel draft folder (card.json beside this plan folder) is one job's session: what its earlier plans spent comes off the cap first.
308
335
  const priorSpend = sessionPriorSpend(dir);
309
336
  const result = await draft({
310
- proseText: prose.text, slot, model, provider, rates, modelId, env, onBook, priorSpend, offerQuestions: !noQuestions, draftThinking,
337
+ proseText: prose.text, slot, model, provider, rates, modelId, env, onBook, priorSpend, offerQuestions: !noQuestions, draftThinking, draftDir: path.join(dir, PAGES_DIR), fetchPage, ...(leftRules === undefined ? {} : { leftRules }),
311
338
  });
312
339
  if (result.stop === 'pre-flight') {
313
340
  try { rmdirSync(dir); } catch { /* the claimed dir is still empty; leave it rather than mask the refusal */ }
@@ -332,6 +359,7 @@ export async function draftToDir({
332
359
  // two as "the draft finished"), as their own files: never in the readout, so never in the hash.
333
360
  if (result.questions?.length) files[QUESTIONS_FILE] = scrub(dj({ questions: result.questions }), secrets);
334
361
  files[NOT_CHECKED_FILE] = scrub(dj({ notChecked: result.notChecked ?? [] }), secrets);
362
+ if (result.pageLooks || result.sheetLooks) files[PAGE_LOOK_FILE] = scrub(dj({ pages: result.pageLooks ?? [], ...(result.sheetLooks ? { sheets: result.sheetLooks } : {}), look: result.look ?? { facts: [], dropped: [] } }), secrets);
335
363
  files['log.json'] = scrub(dj({
336
364
  ok: result.ok, stop: result.stop, reds: result.reds, rounds: result.rounds, calls: result.calls, costUsd: result.costUsd, spendComplete: result.spendComplete,
337
365
  modelId: result.modelId, modelReturned: result.modelReturned, structureRetries: result.structureRetries,
@@ -376,6 +404,8 @@ export async function draftToDir({
376
404
  startedAt,
377
405
  wallMs: startedAt === null ? null : Math.max(0, Date.now() - Date.parse(startedAt)),
378
406
  });
407
+ // M4d am32: the spend is booked, and the result files are about to be written: the monthly hold is given back now, so a draft never reads done while its hold is still held
408
+ if (typeof onResult === 'function') onResult({ ok: result.ok });
379
409
  for (const [f, text] of Object.entries(files)) writeFileSync(path.join(dir, f), text);
380
410
  if (pick !== null) writeModelRecord(dir, pick);
381
411
  leaks = sweepForSecrets(dir, secrets);
package/src/canrun.js CHANGED
@@ -70,6 +70,11 @@ export function unbuildableSay(n, shape) {
70
70
  */
71
71
  export function findUnbuildableCheckStep(declaration) {
72
72
  for (const step of declaration.steps) {
73
+ // M10b piece 5 (item 8, hamr's ruling): a green step with neither close.sheet nor close.cited is the old cell cite, which no longer runs. A job signed that
74
+ // way is kept for reference (it still reads and displays) and is refused here, at $0, before any spend.
75
+ if (step.close?.class === 'green' && !step.close.cited && !Array.isArray(step.close.sheet)) {
76
+ return { step, why: 'a green step with no close.sheet or close.cited is the retired cell cite', say: `This flow will not run: Line ${step.fromLine}'s check cannot cite cells any more. Draft it again to run it.` };
77
+ }
73
78
  if (step.close?.class !== 'softgreen') continue;
74
79
  try {
75
80
  buildSoftgreenRubric(step.close.shape ?? {});
package/src/checked.js CHANGED
@@ -11,24 +11,40 @@
11
11
  /** The label that always sits with the "Not checked" list (am41 item 3: the ONE place these words live; the Job tab and the Chat card read it off their payloads). */
12
12
  export const NOT_CHECKED_LABEL = "not checked (the AI's own reading)";
13
13
 
14
+ import { factRows } from './citedcheck.js';
15
+ import { sheetCheckRows } from './sheetchecks.js';
16
+ import { sheetLineBlocks } from './sheetblock.js';
17
+ import { splitReadNotes, signedFactNames } from './pagedropwords.js';
18
+
14
19
  const list = (xs) => xs.join(', ');
15
20
 
16
21
  /**
17
22
  * One entry per step, in plan order: the plain sentences for what its typed close checks.
18
- * @param {{ steps?: any[] }} declaration @param {{ hasAsk?: boolean, askLines?: number[] }} [opts] hasAsk = the job has a signed ask line (so "you check it at the ask" is true);
23
+ * M10b piece 4: with `lines` (the signed job lines) a step that reads a sheet also carries `sheet`, its line's block (src/sheetblock.js `sheetLineBlocks`: guardrails,
24
+ * Checked with `covers`, Not checked), and its sentences are only the lead sentence; the surfaces draw the block. Without `lines` the older one-row-per-check sentences.
25
+ * @param {{ steps?: any[] }} declaration @param {{ hasAsk?: boolean, askLines?: number[], lines?: any[], csvRoles?: string[] }} [opts] hasAsk = the job has a signed ask line (so "you check it at the ask" is true);
19
26
  * askLines = the job lines of the signed asks, which also lets a step after the LAST ask read "you check it after you accept" (am41 item 2, am42: the ONE place for these words)
20
- * @returns {{ step: number, line: number|null, goal: string, class: string, sentences: string[] }[]}
27
+ * @returns {{ step: number, line: number|null, goal: string, class: string, sentences: string[], sheet?: ReturnType<typeof sheetLineBlocks>[number] }[]}
21
28
  */
22
- export function checkedLines(declaration, { hasAsk = true, askLines } = {}) {
29
+ export function checkedLines(declaration, { hasAsk = true, askLines, lines, csvRoles = [] } = {}) {
30
+ const blocks = Array.isArray(lines) ? sheetLineBlocks({ declaration, lines, csvRoles }) : [];
23
31
  const steps = Array.isArray(declaration?.steps) ? declaration.steps : [];
24
32
  if (Array.isArray(askLines)) hasAsk = askLines.length > 0;
25
33
  const lastAsk = Array.isArray(askLines) ? steps.reduce((m, st, i) => (askLines.includes(st?.fromLine) ? i : m), -1) : -1;
26
34
  return steps.map((st, i) => {
27
35
  const cls = st?.close?.class;
36
+ const firstGreen = steps.findIndex((x) => x?.fromLine === st?.fromLine && x?.close?.class === 'green') === i;
37
+ const sheet = firstGreen ? (blocks.find((b) => b.line === st?.fromLine) ?? null) : null;
28
38
  const shape = st?.close?.shape && typeof st.close.shape === 'object' ? st.close.shape : {};
29
39
  /** @type {string[]} */
30
40
  const out = [];
31
- if (cls === 'green') {
41
+ if (cls === 'green' && st.close.cited && typeof st.close.cited === 'object') {
42
+ // M10 am7 item 1: the facts the drafter wrote, as plain rows written by code from the typed fields
43
+ out.push(`Each result must be quoted word for word from the saved page "${st.close.cited.source}", and the machine checks every quote, every value and the count against that copy.`, ...factRows(st.close.cited));
44
+ } else if (cls === 'green' && Array.isArray(st.close.sheet)) {
45
+ // M10b piece 1: the signed sheet checks, one row each, written by code from the typed fields
46
+ out.push('The machine recomputes each of these from the saved sheet and compares it with what the step gave:', ...(sheet ? [] : sheetCheckRows(st.close.sheet)));
47
+ } else if (cls === 'green') {
32
48
  out.push('Every figure must cite its source cell, or a formula over cells, and the machine recomputes it and compares it with its source.');
33
49
  } else if (cls === 'softgreen') {
34
50
  out.push('The reply is checked as plain text only.');
@@ -43,6 +59,7 @@ export function checkedLines(declaration, { hasAsk = true, askLines } = {}) {
43
59
  }
44
60
  return {
45
61
  step: i + 1, line: Number.isInteger(st?.fromLine) ? st.fromLine : null, goal: typeof st?.goal === 'string' ? st.goal : '', class: String(cls), sentences: out,
62
+ ...(sheet && cls === 'green' ? { sheet } : {}),
46
63
  };
47
64
  });
48
65
  }
@@ -52,3 +69,14 @@ export function notCheckedBlock(items) {
52
69
  const clean = Array.isArray(items) ? items.filter((x) => typeof x === 'string' && x.trim() !== '').map((x) => x.trim()) : [];
53
70
  return { label: NOT_CHECKED_LABEL, items: clean };
54
71
  }
72
+
73
+ /**
74
+ * M10 am11: the Not checked block split for showing. The drafter's list and code's drop lines are one list on disk (and in the sign row, unchanged);
75
+ * the page shows code's notes about written forms it did not use apart, as "How the page was read" (`readNotes`). The signed facts decide an s1 note.
76
+ * @param {unknown} items @param {any} declaration the plan's declaration (its cited facts are the signed ones)
77
+ */
78
+ export function notCheckedView(items, declaration) {
79
+ const block = notCheckedBlock(items);
80
+ const { notChecked, readNotes } = splitReadNotes(block.items, signedFactNames(declaration));
81
+ return { label: block.label, items: notChecked, readNotes };
82
+ }