fwdloop 0.21.0 → 0.22.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 (87) hide show
  1. package/bin/fwdloop +85 -34
  2. package/package.json +4 -3
  3. package/src/audit-fold.js +5 -1
  4. package/src/authoring.js +32 -6
  5. package/src/checked.js +18 -1
  6. package/src/cited-record.js +138 -0
  7. package/src/cited-source.js +49 -0
  8. package/src/citedcheck.js +306 -0
  9. package/src/citedwords.js +197 -0
  10. package/src/closers.js +56 -7
  11. package/src/ctx-tools.js +2 -14
  12. package/src/declaration.js +85 -5
  13. package/src/diary.js +2 -2
  14. package/src/docx.js +16 -2
  15. package/src/draft-steps.js +1 -1
  16. package/src/drafter.js +292 -25
  17. package/src/flow.js +33 -7
  18. package/src/flowmodel.js +21 -0
  19. package/src/input-facts.js +20 -3
  20. package/src/model-step.js +30 -5
  21. package/src/pageask.js +136 -0
  22. package/src/pagebits.js +107 -0
  23. package/src/pagedropwords.js +171 -0
  24. package/src/pagedry.js +120 -0
  25. package/src/pagefetch.js +164 -0
  26. package/src/pagelook.js +155 -0
  27. package/src/pagemap.js +55 -0
  28. package/src/pageplace.js +103 -0
  29. package/src/pagerules.js +318 -0
  30. package/src/panel/author.js +41 -20
  31. package/src/panel/authorcard.js +11 -1
  32. package/src/panel/authorflows.js +21 -15
  33. package/src/panel/authorstart.js +2 -4
  34. package/src/panel/authortrigger.js +14 -4
  35. package/src/panel/data.js +83 -2
  36. package/src/panel/index.html +279 -12
  37. package/src/panel/result.js +295 -0
  38. package/src/panel/server.js +27 -3
  39. package/src/primitives.js +2 -3
  40. package/src/provider.js +5 -2
  41. package/src/redact.js +17 -0
  42. package/src/runner.js +83 -12
  43. package/src/schedule.js +3 -3
  44. package/src/setup.js +16 -1
  45. package/src/sheetfind.js +50 -0
  46. package/src/sheetlook.js +157 -0
  47. package/src/signed-text.js +11 -1
  48. package/src/thinking.js +1 -1
  49. package/src/try-checks.js +6 -0
  50. package/src/types.js +3 -2
  51. package/types/authoring.d.ts +19 -2
  52. package/types/checked.d.ts +10 -0
  53. package/types/cited-record.d.ts +21 -0
  54. package/types/cited-source.d.ts +18 -0
  55. package/types/citedcheck.d.ts +95 -0
  56. package/types/citedwords.d.ts +97 -0
  57. package/types/closers.d.ts +55 -3
  58. package/types/ctx-tools.d.ts +0 -1
  59. package/types/declaration.d.ts +15 -1
  60. package/types/docx.d.ts +14 -0
  61. package/types/drafter.d.ts +244 -2
  62. package/types/flow.d.ts +21 -0
  63. package/types/flowmodel.d.ts +15 -0
  64. package/types/input-facts.d.ts +12 -2
  65. package/types/model-step.d.ts +35 -3
  66. package/types/pageask.d.ts +75 -0
  67. package/types/pagebits.d.ts +32 -0
  68. package/types/pagedropwords.d.ts +40 -0
  69. package/types/pagedry.d.ts +38 -0
  70. package/types/pagefetch.d.ts +86 -0
  71. package/types/pagelook.d.ts +75 -0
  72. package/types/pagemap.d.ts +31 -0
  73. package/types/pageplace.d.ts +22 -0
  74. package/types/pagerules.d.ts +86 -0
  75. package/types/panel/authorcard.d.ts +2 -0
  76. package/types/panel/authorflows.d.ts +2 -0
  77. package/types/panel/data.d.ts +26 -0
  78. package/types/panel/result.d.ts +156 -0
  79. package/types/provider.d.ts +3 -1
  80. package/types/redact.d.ts +1 -0
  81. package/types/runner.d.ts +156 -7
  82. package/types/schedule.d.ts +0 -11
  83. package/types/setup.d.ts +13 -0
  84. package/types/sheetfind.d.ts +46 -0
  85. package/types/sheetlook.d.ts +120 -0
  86. package/types/thinking.d.ts +1 -1
  87. package/types/types.d.ts +11 -3
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.22.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.25.1",
54
55
  "litectx": "^0.32.0"
55
56
  },
56
57
  "devDependencies": {
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,7 @@ 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';
25
26
  import { loadCatalogue } from './catalogue.js';
26
27
  import { WIRED_VERBS } from './primitives.js';
27
28
  import { canonicalBytes } from './signature.js';
@@ -43,6 +44,10 @@ export const LEAK_MARKER_FILE = 'scrub-leak.red';
43
44
  * and the drafter's own "not checked" reading (information only; never in the readout, so never in the hash). */
44
45
  export const QUESTIONS_FILE = 'questions.json';
45
46
  export const NOT_CHECKED_FILE = 'not-checked.json';
47
+ /** 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). */
48
+ export const PAGES_DIR = 'pages';
49
+ /** 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. */
50
+ export const PAGE_LOOK_FILE = 'page-look.json';
46
51
  export const ANSWER_FILE = (k) => `answer-${k}.json`;
47
52
  export const SIGN_LINE = (dir, hash) => `DRAFTED — NOT SIGNED. To sign: fwdloop sign ${dir} --approve ${hash}`;
48
53
 
@@ -77,7 +82,8 @@ export function specHash({
77
82
  * checks and the page all use it). `questions` = [{ k, line, question, answer|null }], `open` = those with no answer. A blank or unreadable
78
83
  * answer file counts as no answer. No questions file = `{ questions: [], open: [] }`.
79
84
  * @param {string} planDir
80
- * @returns {{ questions: {k:number, line:number, question:string, answer:string|null}[], open: {k:number, line:number, question:string, answer:null}[] }}
85
+ * 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`.
86
+ * @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
87
  */
82
88
  export function readQuestions(planDir) {
83
89
  const none = { questions: [], open: [] };
@@ -90,8 +96,20 @@ export function readQuestions(planDir) {
90
96
  const k = i + 1;
91
97
  const a = readFileInside(planDir, ANSWER_FILE(k));
92
98
  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 };
99
+ let at;
100
+ /** @type {string|null|undefined} the `~` rule the answer added (null = it left the rule Not checked), as the answer file recorded it */
101
+ let rule;
102
+ if (a.ok) {
103
+ try {
104
+ const j = JSON.parse(a.text);
105
+ const t = j?.answer;
106
+ 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; }
107
+ } catch { /* unreadable = unanswered */ }
108
+ }
109
+ return {
110
+ k, line: q.line, question: String(q.question), answer, ...(at === undefined ? {} : { at }), ...(rule === undefined ? {} : { rule }),
111
+ ...(q.source === 'look' ? { source: 'look', ask: q.ask, ruleNo: q.ruleNo, ruleText: q.ruleText, proposal: typeof q.proposal === 'string' ? q.proposal : null } : {}),
112
+ };
95
113
  });
96
114
  return { questions, open: /** @type {any} */ (questions.filter((q) => q.answer === null)) };
97
115
  }
@@ -178,6 +196,10 @@ export function buildReadout({
178
196
  out.push(` ${i + 1}. (line ${st.fromLine}) ${st.goal}`);
179
197
  out.push(` grants: ${st.primitives?.length ? st.primitives.join(', ') : 'none (pure stop)'}`
180
198
  + ` | reads: ${st.reads?.length ? st.reads.join(', ') : '-'} | emits: ${st.emits} | check: ${st.close?.class}`);
199
+ // M10 am7 item 1: the facts a cited step checks its quotes against, signed with the readout (typed fields, never model prose)
200
+ if (st.close?.cited && typeof st.close.cited === 'object') for (const row of factRows(st.close.cited)) out.push(` ${row}`);
201
+ // M10 am8 item 2: the column lock, signed with the readout (typed fields)
202
+ 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
203
  // M4e amendment 14 item 5: the check's sections in its order (+ word limit); fixed text from typed fields, never model prose.
182
204
  const shape = st.close?.shape;
183
205
  if (Array.isArray(shape?.sections) && shape.sections.length > 0) {
@@ -246,9 +268,10 @@ export function draftKeyRefusal(slot, env) {
246
268
  * writer (appendSpendRow); an unpriced round books null, never 0.
247
269
  *
248
270
  * Test seam: `provider`/`rates`/`modelId` are injected; without them a live provider is built.
271
+ * `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
272
  */
250
273
  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,
274
+ 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
275
  }) {
253
276
  const refuse = (reds) => ({ ok: false, wrote: false, reds, costUsd: 0 });
254
277
  const nameCheck = checkFlowName(name);
@@ -264,7 +287,7 @@ export async function draftToDir({
264
287
  if (!panelDrafts && (rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel)))) {
265
288
  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
289
  }
267
- const read = readProseFile(proseFile);
290
+ const read = proseRead ?? readProseFile(proseFile); // the CLI reads the file once (for its hold) and hands that read in
268
291
  if (!read.ok) return refuse([String(read.red)]);
269
292
  const prose = { text: String(read.text) };
270
293
  const injected = provider != null;
@@ -307,7 +330,7 @@ export async function draftToDir({
307
330
  // 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
331
  const priorSpend = sessionPriorSpend(dir);
309
332
  const result = await draft({
310
- proseText: prose.text, slot, model, provider, rates, modelId, env, onBook, priorSpend, offerQuestions: !noQuestions, draftThinking,
333
+ 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
334
  });
312
335
  if (result.stop === 'pre-flight') {
313
336
  try { rmdirSync(dir); } catch { /* the claimed dir is still empty; leave it rather than mask the refusal */ }
@@ -332,6 +355,7 @@ export async function draftToDir({
332
355
  // two as "the draft finished"), as their own files: never in the readout, so never in the hash.
333
356
  if (result.questions?.length) files[QUESTIONS_FILE] = scrub(dj({ questions: result.questions }), secrets);
334
357
  files[NOT_CHECKED_FILE] = scrub(dj({ notChecked: result.notChecked ?? [] }), secrets);
358
+ 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
359
  files['log.json'] = scrub(dj({
336
360
  ok: result.ok, stop: result.stop, reds: result.reds, rounds: result.rounds, calls: result.calls, costUsd: result.costUsd, spendComplete: result.spendComplete,
337
361
  modelId: result.modelId, modelReturned: result.modelReturned, structureRetries: result.structureRetries,
@@ -376,6 +400,8 @@ export async function draftToDir({
376
400
  startedAt,
377
401
  wallMs: startedAt === null ? null : Math.max(0, Date.now() - Date.parse(startedAt)),
378
402
  });
403
+ // 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
404
+ if (typeof onResult === 'function') onResult({ ok: result.ok });
379
405
  for (const [f, text] of Object.entries(files)) writeFileSync(path.join(dir, f), text);
380
406
  if (pick !== null) writeModelRecord(dir, pick);
381
407
  leaks = sweepForSecrets(dir, secrets);
package/src/checked.js CHANGED
@@ -11,6 +11,9 @@
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 { splitReadNotes, signedFactNames } from './pagedropwords.js';
16
+
14
17
  const list = (xs) => xs.join(', ');
15
18
 
16
19
  /**
@@ -28,7 +31,10 @@ export function checkedLines(declaration, { hasAsk = true, askLines } = {}) {
28
31
  const shape = st?.close?.shape && typeof st.close.shape === 'object' ? st.close.shape : {};
29
32
  /** @type {string[]} */
30
33
  const out = [];
31
- if (cls === 'green') {
34
+ if (cls === 'green' && st.close.cited && typeof st.close.cited === 'object') {
35
+ // M10 am7 item 1: the facts the drafter wrote, as plain rows written by code from the typed fields
36
+ 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));
37
+ } else if (cls === 'green') {
32
38
  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
39
  } else if (cls === 'softgreen') {
34
40
  out.push('The reply is checked as plain text only.');
@@ -52,3 +58,14 @@ export function notCheckedBlock(items) {
52
58
  const clean = Array.isArray(items) ? items.filter((x) => typeof x === 'string' && x.trim() !== '').map((x) => x.trim()) : [];
53
59
  return { label: NOT_CHECKED_LABEL, items: clean };
54
60
  }
61
+
62
+ /**
63
+ * 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);
64
+ * 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.
65
+ * @param {unknown} items @param {any} declaration the plan's declaration (its cited facts are the signed ones)
66
+ */
67
+ export function notCheckedView(items, declaration) {
68
+ const block = notCheckedBlock(items);
69
+ const { notChecked, readNotes } = splitReadNotes(block.items, signedFactNames(declaration));
70
+ return { label: block.label, items: notChecked, readNotes };
71
+ }
@@ -0,0 +1,138 @@
1
+ // borrowed-from: bareloop src/panel/server.js@2959217 (proofOf, moneyAsRead, resultCell - the row a Result tab shows, read off bareguard's evidence)
2
+ // M10 piece 4: the ONE writer of `<run>/cited-checks.json`, the record the Result tab's reader (`readCitedChecks`, src/panel/result.js) takes. One line per
3
+ // job line, written the moment that line's cited check has run, from the check's own answer: nothing here decides a verdict.
4
+ //
5
+ // Shape (the reader's, copied from bareloop): { lines: [ { n, source, passed, facts: [{name, kind: 'phrase'|'value', sentence}],
6
+ // rows: [{n, quote, cells: [one text per fact], proof?: {text, marks}}] | null, notChecked: string[] } ] }.
7
+ // Extra keys the reader ignores and the separate checker (scripts/check-cited-run.mjs) reads: per line `check` {sha256 of the frozen text, the signed facts,
8
+ // the count} and per row `values`.
9
+ // Throws away: bareguard's evidence beyond the marks of the claim's own spans; nothing: a red line keeps its judged rows (am9); only a stopped check has none.
10
+ import { writeFileSync, renameSync } from 'node:fs';
11
+ import { join } from 'node:path';
12
+ import { readFileInside } from './flow.js';
13
+ import { moneyAs } from './pageask.js';
14
+ import { factSentence, countSentence, CITED_ID } from './citedcheck.js';
15
+
16
+ /** the record's name in the run's own folder; the Result tab's reader takes it from here */
17
+ export const CITED_CHECKS_FILE = 'cited-checks.json';
18
+
19
+ const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
20
+
21
+ /**
22
+ * What a result's check read, from bareguard's `full.evidence` entry for the claim, for the proof fold. `null` = no evidence, or an entry that is not about
23
+ * this quote: the page then shows the plain quote. `text` is bareguard's normalized quote; `marks` are `[start, end]` UTF-16 offsets into it, sorted,
24
+ * overlaps merged. Every span the check read EXCEPT a bind-only membership token that is not this claim's (`canon` present, `matched` absent).
25
+ * @param {any} ev @param {unknown} quote @returns {{text: string, marks: number[][]}|null}
26
+ */
27
+ function proofOf(ev, quote) {
28
+ if (!ev || typeof ev.text !== 'string' || !Array.isArray(ev.spans) || typeof quote !== 'string') return null;
29
+ if (quote.replace(/\*\*|__/g, '').replace(/\s+/g, ' ').trim() !== ev.text) return null;
30
+ const spans = ev.spans
31
+ .filter((/** @type {any} */ sp) => sp && Number.isInteger(sp.start) && Number.isInteger(sp.end) && sp.start >= 0 && sp.end > sp.start && sp.end <= ev.text.length
32
+ && !(sp.canon !== undefined && sp.matched !== true))
33
+ .map((/** @type {any} */ sp) => [sp.start, sp.end])
34
+ .sort((/** @type {number[]} */ x, /** @type {number[]} */ y) => x[0] - y[0] || x[1] - y[1]);
35
+ /** @type {number[][]} */
36
+ const marks = [];
37
+ for (const sp of spans) {
38
+ const last = marks[marks.length - 1];
39
+ if (last && sp[0] < last[1]) last[1] = Math.max(last[1], sp[1]);
40
+ else marks.push([sp[0], sp[1]]);
41
+ }
42
+ return { text: ev.text, marks };
43
+ }
44
+
45
+ /**
46
+ * A money fact's amount as the page wrote it ("144 US dollars"): the quote's text from the first to the last of the value's own currency / unit / value spans
47
+ * in bareguard's evidence for this claim. `null` = nothing located, or more than a short run (the caller keeps the fact's own spelling).
48
+ * @param {any} ev @param {number} j the fact's index (bareguard's decide index) @returns {string|null}
49
+ */
50
+ function moneyAsRead(ev, j) {
51
+ const own = ev.spans.filter((/** @type {any} */ sp) => sp && sp.decide === j && ['value', 'currency', 'unit'].includes(sp.role)
52
+ && Number.isInteger(sp.start) && Number.isInteger(sp.end) && sp.start >= 0 && sp.end > sp.start && sp.end <= ev.text.length
53
+ && !(sp.canon !== undefined && sp.matched !== true));
54
+ if (own.length === 0) return null;
55
+ const t = ev.text.slice(Math.min(...own.map((/** @type {any} */ sp) => sp.start)), Math.max(...own.map((/** @type {any} */ sp) => sp.end))).trim();
56
+ return t !== '' && t.length <= 40 ? t : null;
57
+ }
58
+
59
+ /** a result value as the step wrote it, for a table cell */
60
+ function cellText(/** @type {unknown} */ v) {
61
+ if (typeof v === 'string') return v;
62
+ if (typeof v === 'number' && Number.isFinite(v)) return String(v);
63
+ return '';
64
+ }
65
+
66
+ /**
67
+ * One job line's record from the check's own answer.
68
+ * @param {{n: number, part: any, results: unknown, check: Awaited<ReturnType<typeof import('./citedcheck.js').checkCited>>, confirmed?: string[]}} o
69
+ * `confirmed` = names of facts whose limit the person agreed to (the Result tab's "(you confirmed)")
70
+ * @returns {Record<string, any>}
71
+ */
72
+ export function citedLineOf({
73
+ n, part, results, check, confirmed = [],
74
+ }) {
75
+ const passed = check.verdict === 'green';
76
+ const list = Array.isArray(results) ? results : [];
77
+ /** @type {any[]|null} */
78
+ let rows = null;
79
+ // M10 am9 item 1: a red line keeps the results the check judged (bareloop's readJudged); `passed` stays false, so the page never ticks it. A stopped check
80
+ // judged nothing: no rows.
81
+ if (passed || check.verdict === 'red') {
82
+ rows = list.map((/** @type {any} */ r, /** @type {number} */ k) => {
83
+ const values = isRec(r) && isRec(r.values) ? r.values : {};
84
+ const quote = isRec(r) && typeof r.quote === 'string' ? r.quote : '';
85
+ const ev = check.evidence.find((/** @type {any} */ e) => e && e.check === CITED_ID && e.claim === k) ?? null;
86
+ const proof = proofOf(ev, quote);
87
+ return {
88
+ n: k + 1,
89
+ quote,
90
+ ...(proof ? { proof } : {}),
91
+ cells: part.facts.map((/** @type {any} */ f, /** @type {number} */ j) => {
92
+ if (f.shape === 'phrase') return String(f.phrase);
93
+ const v = cellText(values[f.name]);
94
+ if (f.shape === 'money') return (proof ? moneyAsRead(ev, j) : null) ?? (/^\d[\d.,]*$/.test(v.trim()) ? moneyAs(f, v.trim(), true) : v);
95
+ return v;
96
+ }),
97
+ values: Object.fromEntries(part.facts.filter((/** @type {any} */ f) => f.shape !== 'phrase').map((/** @type {any} */ f) => [f.name, cellText(values[f.name])])),
98
+ };
99
+ });
100
+ }
101
+ const countRow = countSentence(part);
102
+ return {
103
+ n,
104
+ source: part.source,
105
+ passed,
106
+ facts: part.facts.map((/** @type {any} */ f) => ({
107
+ name: f.name, kind: f.shape === 'phrase' ? 'phrase' : 'value', sentence: factSentence(f, part.source), ...(confirmed.includes(f.name) ? { confirmed: true } : {}),
108
+ })),
109
+ rows,
110
+ notChecked: check.verdict === 'stopped' && check.fault ? [check.fault] : [],
111
+ check: {
112
+ sha256: check.sha256, facts: part.facts.map((/** @type {any} */ f) => ({ ...f })), ...(part.count === undefined ? {} : { count: { ...part.count } }), ...(countRow ? { countSentence: countRow } : {}),
113
+ },
114
+ };
115
+ }
116
+
117
+ /**
118
+ * Write one job line into the run's record: the line with the same `n` is replaced (a later try of the same step wins), the others stay, lines are kept in
119
+ * order. An unreadable existing record is started again (this function is its only writer). Atomic: a reader sees the old file or the new one.
120
+ * @param {string} runDir @param {Record<string, any>} line @returns {void}
121
+ */
122
+ export function writeCitedLine(runDir, line) {
123
+ const file = join(runDir, CITED_CHECKS_FILE);
124
+ /** @type {Record<string, any>[]} */
125
+ let lines = [];
126
+ const had = readFileInside(runDir, CITED_CHECKS_FILE);
127
+ if (had.ok) {
128
+ try {
129
+ const rec = JSON.parse(had.text);
130
+ if (rec && Array.isArray(rec.lines)) lines = rec.lines.filter((/** @type {any} */ l) => isRec(l) && l.n !== line.n);
131
+ } catch { lines = []; }
132
+ }
133
+ lines.push(line);
134
+ lines.sort((a, b) => a.n - b.n);
135
+ const tmp = `${file}.tmp`;
136
+ writeFileSync(tmp, `${JSON.stringify({ lines }, null, 2)}\n`);
137
+ renameSync(tmp, file);
138
+ }