fwdloop 0.20.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 (92) hide show
  1. package/README.md +2 -0
  2. package/bin/fwdloop +85 -34
  3. package/package.json +4 -3
  4. package/src/audit-fold.js +181 -0
  5. package/src/authoring.js +33 -7
  6. package/src/books.js +1 -1
  7. package/src/checked.js +18 -1
  8. package/src/cited-record.js +138 -0
  9. package/src/cited-source.js +49 -0
  10. package/src/citedcheck.js +306 -0
  11. package/src/citedwords.js +197 -0
  12. package/src/closers.js +105 -9
  13. package/src/ctx-tools.js +2 -14
  14. package/src/declaration.js +85 -5
  15. package/src/diary.js +49 -0
  16. package/src/docx.js +16 -2
  17. package/src/draft-steps.js +1 -1
  18. package/src/drafter.js +292 -25
  19. package/src/flow.js +33 -7
  20. package/src/flowmodel.js +63 -5
  21. package/src/input-facts.js +20 -3
  22. package/src/model-step.js +132 -9
  23. package/src/pageask.js +136 -0
  24. package/src/pagebits.js +107 -0
  25. package/src/pagedropwords.js +171 -0
  26. package/src/pagedry.js +120 -0
  27. package/src/pagefetch.js +164 -0
  28. package/src/pagelook.js +155 -0
  29. package/src/pagemap.js +55 -0
  30. package/src/pageplace.js +103 -0
  31. package/src/pagerules.js +318 -0
  32. package/src/panel/author.js +41 -20
  33. package/src/panel/authorcard.js +11 -1
  34. package/src/panel/authorflows.js +21 -15
  35. package/src/panel/authorstart.js +2 -4
  36. package/src/panel/authortrigger.js +14 -4
  37. package/src/panel/data.js +130 -10
  38. package/src/panel/index.html +499 -41
  39. package/src/panel/result.js +295 -0
  40. package/src/panel/server.js +27 -3
  41. package/src/primitives.js +43 -2
  42. package/src/provider.js +5 -2
  43. package/src/redact.js +17 -0
  44. package/src/runner.js +128 -21
  45. package/src/schedule.js +3 -3
  46. package/src/setup.js +16 -1
  47. package/src/sheetfind.js +50 -0
  48. package/src/sheetlook.js +157 -0
  49. package/src/signed-text.js +11 -1
  50. package/src/thinking.js +39 -0
  51. package/src/try-checks.js +68 -0
  52. package/src/types.js +4 -2
  53. package/types/audit-fold.d.ts +54 -0
  54. package/types/authoring.d.ts +20 -2
  55. package/types/books.d.ts +17 -0
  56. package/types/checked.d.ts +10 -0
  57. package/types/cited-record.d.ts +21 -0
  58. package/types/cited-source.d.ts +18 -0
  59. package/types/citedcheck.d.ts +95 -0
  60. package/types/citedwords.d.ts +97 -0
  61. package/types/closers.d.ts +55 -3
  62. package/types/declaration.d.ts +15 -1
  63. package/types/diary.d.ts +57 -0
  64. package/types/docx.d.ts +14 -0
  65. package/types/drafter.d.ts +244 -2
  66. package/types/flow.d.ts +21 -0
  67. package/types/flowmodel.d.ts +40 -3
  68. package/types/input-facts.d.ts +12 -2
  69. package/types/model-step.d.ts +38 -3
  70. package/types/pageask.d.ts +75 -0
  71. package/types/pagebits.d.ts +32 -0
  72. package/types/pagedropwords.d.ts +40 -0
  73. package/types/pagedry.d.ts +38 -0
  74. package/types/pagefetch.d.ts +86 -0
  75. package/types/pagelook.d.ts +75 -0
  76. package/types/pagemap.d.ts +31 -0
  77. package/types/pageplace.d.ts +22 -0
  78. package/types/pagerules.d.ts +86 -0
  79. package/types/panel/authorcard.d.ts +2 -0
  80. package/types/panel/authorflows.d.ts +2 -0
  81. package/types/panel/data.d.ts +26 -0
  82. package/types/panel/result.d.ts +156 -0
  83. package/types/provider.d.ts +3 -1
  84. package/types/redact.d.ts +1 -0
  85. package/types/runner.d.ts +156 -7
  86. package/types/schedule.d.ts +0 -11
  87. package/types/setup.d.ts +13 -0
  88. package/types/sheetfind.d.ts +46 -0
  89. package/types/sheetlook.d.ts +120 -0
  90. package/types/thinking.d.ts +31 -0
  91. package/types/try-checks.d.ts +55 -0
  92. package/types/types.d.ts +20 -3
@@ -17,17 +17,32 @@ import { parseCsv } from './csv.js';
17
17
 
18
18
  /**
19
19
  * @param {Array<{kind?:string, role:string, path:string}>} sources arbiter.sources
20
+ * @param {{pages?: Record<string, {text: string}>}} [o] `pages` (M10 item 1): the drafting copy of each web page input, role -> its frozen text, fetched by the caller. A page
21
+ * source with no copy here is a named red (never skipped); it adds no heading facts (a page has none), only its line for the drafter and the Chat card.
20
22
  * `list` (M4d am10) is one `{role, detail}` per readable input for the Chat card's list (a CSV: its columns; text: its headings); never hashed.
21
- * @returns {{ok:boolean, inputFacts:Record<string,string[]>, info:string[], list:Array<{role:string, detail:string}>, reds:string[]}}
23
+ * `sheets` (M10 piece 5): role -> the text of each CSV input, for the sheet-word look (the same read, not a second one).
24
+ * `docs` (M10 piece 5, item 2): role -> the text of each document input (.docx paragraphs, .md / .txt as is), the drafting copy a cited fact part's words are proved on.
25
+ * @returns {{ok:boolean, inputFacts:Record<string,string[]>, info:string[], list:Array<{role:string, detail:string}>, reds:string[], sheets:Record<string,string>, docs:Record<string,string>}}
22
26
  */
23
- export function readInputFacts(sources) {
27
+ export function readInputFacts(sources, { pages = {} } = {}) {
24
28
  /** @type {Record<string,string[]>} */
25
29
  const inputFacts = {};
30
+ /** @type {Record<string,string>} */
31
+ const sheets = {};
32
+ /** @type {Record<string,string>} */
33
+ const docs = {};
26
34
  const info = [];
27
35
  const list = [];
28
36
  const headingsDetail = (n) => `${n} heading${n === 1 ? '' : 's'}`;
29
37
  const reds = [];
30
38
  for (const s of sources ?? []) {
39
+ if (s.kind === 'page') {
40
+ const page = pages[s.role];
41
+ if (!page) { reds.push(`input "${s.role}": the web page was not fetched`); continue; }
42
+ list.push({ role: s.role, detail: `a web page, ${page.text.length} characters` });
43
+ info.push(`- ${s.role}: a web page (${s.path}), saved at drafting, ${page.text.length} characters`);
44
+ continue;
45
+ }
31
46
  if (s.kind !== 'file') continue;
32
47
  if (String(s.path).toLowerCase().endsWith('.docx')) {
33
48
  const r = readDocxText(s.path);
@@ -36,6 +51,7 @@ export function readInputFacts(sources) {
36
51
  if (!h.ok) { reds.push(`input "${s.role}": ${h.red}`); continue; }
37
52
  const words = r.text.trim() === '' ? 0 : r.text.trim().split(/\s+/).length;
38
53
  inputFacts[s.role] = h.headings;
54
+ docs[s.role] = r.text;
39
55
  list.push({ role: s.role, detail: headingsDetail(h.headings.length) });
40
56
  info.push(`- ${s.role}: a .docx file, ${r.paragraphs} paragraphs, ~${words} words, headings: ${h.headings.join(', ') || '(none)'} (read it with "readDocx")`);
41
57
  } else {
@@ -44,11 +60,12 @@ export function readInputFacts(sources) {
44
60
  if (raw.trim() === '') { reds.push(`input "${s.role}": "${s.path}" is empty`); continue; }
45
61
  const headings = raw.split(/\r?\n/).filter((l) => /^#{1,6}\s+\S/.test(l)).map((l) => l.replace(/^#{1,6}\s*/, '').trim());
46
62
  inputFacts[s.role] = headings;
63
+ if (isCellsPath(s.path)) sheets[s.role] = raw; else docs[s.role] = raw;
47
64
  list.push({ role: s.role, detail: isCellsPath(s.path) ? `${parseCsv(raw).header.length} columns` : headingsDetail(headings.length) });
48
65
  info.push(isCellsPath(s.path)
49
66
  ? `- ${s.role}: a CSV file with cells (a step reads it by listing "${s.role}" in its reads; or with "read")`
50
67
  : `- ${s.role}: a text/markdown file, ~${raw.trim().split(/\s+/).length} words, headings: ${headings.join(', ') || '(none)'} (read it with "read")`);
51
68
  }
52
69
  }
53
- return { ok: reds.length === 0, inputFacts, info, list, reds };
70
+ return { ok: reds.length === 0, inputFacts, info, list, reds, sheets, docs };
54
71
  }
package/src/model-step.js CHANGED
@@ -24,9 +24,14 @@
24
24
  // (green/softgreen/anything else) — never from the step's `shape` — the
25
25
  // executor context (M2 scope item 3) carries neither.
26
26
 
27
+ import { dirname } from 'node:path';
27
28
  import { Loop, HaltError } from 'bare-agent';
28
29
  import { GateRefusal } from './primitives.js';
30
+ import { appendCall, appendTool, nextRound } from './diary.js';
29
31
  import { ConfigError } from './config.js';
32
+ import { worstThinkingStatus } from './thinking.js';
33
+ import { citedBrief } from './citedcheck.js';
34
+ import { citeForms } from './closers.js';
30
35
 
31
36
  import {
32
37
  makeProvider, ModelRefusal, sumMeterings, appendSpendRow, classifyModelId, priceRecord,
@@ -95,7 +100,7 @@ const GREEN_SCHEMA = Object.freeze({
95
100
  type: 'object',
96
101
  additionalProperties: {
97
102
  type: 'object',
98
- properties: { value: {}, cite: { type: 'string' } },
103
+ properties: { value: {}, cite: { type: 'string', description: `Where the value comes from: ${citeForms()}.` } },
99
104
  required: ['value', 'cite'],
100
105
  },
101
106
  },
@@ -130,11 +135,32 @@ const HITL_SCHEMA = Object.freeze({
130
135
  additionalProperties: true,
131
136
  });
132
137
 
138
+ // M10 am7 item 3: a green step that quotes a saved web page (its close carries `cited`) answers with the quotes it found, each with the values it read from
139
+ // that quote. The check (src/closers.js closeCited) reads exactly this; nothing else in the artifact is trusted.
140
+ const CITED_SCHEMA = Object.freeze({
141
+ type: 'object',
142
+ properties: {
143
+ results: {
144
+ type: 'array',
145
+ items: {
146
+ type: 'object',
147
+ properties: { quote: { type: 'string' }, values: { type: 'object' } },
148
+ required: ['quote', 'values'],
149
+ },
150
+ },
151
+ ...DONE_PROPS,
152
+ },
153
+ required: ['results', 'done'],
154
+ additionalProperties: false,
155
+ });
156
+
133
157
  /**
134
158
  * Build the `emit_artifact` tool schema from a step's declared close CLASS
135
- * only. `stepClass` is `'green' | 'softgreen' | 'hitl' | null | undefined`.
159
+ * only (plus, for a green step that quotes a saved page, the form of its answer).
160
+ * `stepClass` is `'green' | 'softgreen' | 'hitl' | null | undefined`; `cited` is true for that green step.
136
161
  */
137
- export function buildEmitArtifactSchema(stepClass) {
162
+ export function buildEmitArtifactSchema(stepClass, cited = false) {
163
+ if (stepClass === 'green' && cited) return CITED_SCHEMA;
138
164
  if (stepClass === 'green') return GREEN_SCHEMA;
139
165
  if (stepClass === 'softgreen') return SOFTGREEN_SCHEMA;
140
166
  return HITL_SCHEMA;
@@ -173,7 +199,7 @@ function addMeter(cumulative, metered) {
173
199
  // faulted — caught live: `toolFields` threw on `cumulative.ungranted`
174
200
  // being undefined the very first time a transport fault hit round 1.
175
201
  return {
176
- costUsd, rounds, tokens, tools: cumulative.tools, ungranted: cumulative.ungranted, refused: cumulative.refused,
202
+ costUsd, rounds, tokens, tools: cumulative.tools, ungranted: cumulative.ungranted, refused: cumulative.refused, thinking: cumulative.thinking,
177
203
  };
178
204
  }
179
205
 
@@ -223,6 +249,7 @@ function toolFields(cumulative) {
223
249
  // M4e amendment 7 item 8: model calls (turns) this attempt made, so a Stop can say "after turn T of try K".
224
250
  turns: cumulative.rounds,
225
251
  tools: cumulative.tools,
252
+ thinking: cumulative.thinking,
226
253
  // Gate refusals this attempt — always present (empty array when none) so
227
254
  // absence can never be confused with "none".
228
255
  refused: cumulative.refused,
@@ -230,6 +257,42 @@ function toolFields(cumulative) {
230
257
  };
231
258
  }
232
259
 
260
+ /**
261
+ * M4d am29 item 1: the thinking status of ONE provider result, read the way bare-agent's Loop reads it for the whole run (`thinkingStatus`; a custom
262
+ * provider's legacy `thinkingApplied` true/false/null maps to applied/ignored/unknown); `null` when the result carried neither.
263
+ * @param {any} r
264
+ */
265
+ function thinkingStatusOf(r) {
266
+ if (typeof r?.thinkingStatus === 'string') return r.thinkingStatus;
267
+ if (r?.thinkingApplied === true) return 'applied';
268
+ if (r?.thinkingApplied === false) return 'ignored';
269
+ if (r?.thinkingApplied === null) return 'unknown';
270
+ return null;
271
+ }
272
+
273
+ /**
274
+ * The provider with one addition: each `generate` result is handed to `seen` before the Loop meters that call, so the call's diary row can say what bare-agent
275
+ * reported for THAT call (thinking status, the tool names it asked for); the Loop's own `onLlmResult` payload carries neither. Everything else reads through.
276
+ * @param {any} provider @param {(result: any) => void} seen
277
+ */
278
+ function watchCalls(provider, seen) {
279
+ const watched = Object.create(provider);
280
+ watched.generate = async (...a) => {
281
+ const r = await provider.generate(...a);
282
+ seen(r);
283
+ return r;
284
+ };
285
+ return watched;
286
+ }
287
+
288
+ /** The path a tool call's diary row names: the path it was given, else the frozen input role, else the stash key. Never a query, a text or a symbol. @param {any} args */
289
+ function toolRowPath(args) {
290
+ if (typeof args?.path === 'string') return args.path;
291
+ if (typeof args?.role === 'string') return args.role;
292
+ if (typeof args?.id === 'string') return `stash: ${args.id}`;
293
+ return null;
294
+ }
295
+
233
296
  const STOP_RULE = 'stop-requested';
234
297
 
235
298
  /** The attempt result for a Stop that landed mid-attempt: every call made is already summed into `cumulative`. */
@@ -248,7 +311,7 @@ function stoppedResult(cumulative, modelId, modelMatch) {
248
311
  * @param {{in:number,out:number}} [opts.rates]
249
312
  * @param {string} [opts.modelId]
250
313
  * @param {Record<string,string|undefined>} [opts.env] - the merged shell+keys-file env the key is read from (default process.env).
251
- * @returns {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class?:string}, seam?:{stopRequested?:() => boolean}) => Promise<any>}
314
+ * @returns {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class?:string, attempt?:number, step?:string|null, cited?:any, thinkingMode?:'on'|'off'}, seam?:{stopRequested?:() => boolean}) => Promise<any>}
252
315
  */
253
316
  export function makeLiveModelStep({
254
317
  slot, model, spendPath, provider: injectedProvider, rates: injectedRates, modelId: injectedModelId, env,
@@ -285,7 +348,12 @@ export function makeLiveModelStep({
285
348
  }
286
349
  }
287
350
 
288
- const toolSchema = buildEmitArtifactSchema(stepMeta.class);
351
+ // M4d am29: the three diaries live in the run's own folder, beside spend.jsonl; a row names its step and try from the runner's `stepMeta`
352
+ const runDir = dirname(spendPath);
353
+ const diaryStep = stepMeta.step ?? null;
354
+ const diaryTry = typeof stepMeta.attempt === 'number' ? stepMeta.attempt : null;
355
+ const toolSchema = buildEmitArtifactSchema(stepMeta.class, stepMeta.class === 'green' && Boolean(stepMeta.cited));
356
+ const thinkingMode = stepMeta.thinkingMode === 'on' || stepMeta.thinkingMode === 'off' ? stepMeta.thinkingMode : null;
289
357
  const systemPrompt = 'You are executing one step of a signed, human-authored automation. '
290
358
  + 'Call emit_artifact exactly once with this step\'s result. Ground every value in the '
291
359
  + 'reads you were handed or the tools you were granted — never invent a figure.';
@@ -293,6 +361,8 @@ export function makeLiveModelStep({
293
361
  goal: executorContext.goal,
294
362
  reads: executorContext.reads,
295
363
  gap: executorContext.gap,
364
+ // M10 am7 item 3: a step that quotes a saved page is told the form of its answer and what each result must hold
365
+ ...(stepMeta.class === 'green' && stepMeta.cited ? { quoting: citedBrief(stepMeta.cited) } : {}),
296
366
  });
297
367
  const messages = [
298
368
  { role: 'system', content: systemPrompt },
@@ -303,12 +373,32 @@ export function makeLiveModelStep({
303
373
  // wrapped so a typed GateRefusal is recorded, then rethrown unchanged so
304
374
  // the model still sees the refusal as its tool result.
305
375
  const refused = /** @type {Array<{verb:string, path:string, rule:string}>} */ ([]);
376
+ // M4d am29 item 1: every call a granted tool takes also gets its diary row - the guard's decision (`allow`, the `deny` and its rule, or `no check` for a
377
+ // call that never reached the gate) - written whether the call worked or not. `round` is the model call that asked for it (set by onLlmResult below).
378
+ let currentRound = 0;
306
379
  const primitiveTools = Object.values(grantedTools ?? {}).filter(Boolean).map((tool) => ({
307
380
  ...tool,
308
381
  execute: async (...a) => {
382
+ const askedBefore = tool.gateSeen?.n ?? 0;
383
+ /** @type {GateRefusal|null} */
384
+ let refusal = null;
309
385
  try { return await tool.execute(...a); } catch (err) {
310
- if (err instanceof GateRefusal) refused.push({ verb: err.verb, path: err.path, rule: err.rule });
386
+ if (err instanceof GateRefusal) {
387
+ refusal = err;
388
+ refused.push({ verb: err.verb, path: err.path, rule: err.rule });
389
+ }
311
390
  throw err;
391
+ } finally {
392
+ appendTool(runDir, {
393
+ step: diaryStep,
394
+ try: diaryTry,
395
+ round: currentRound,
396
+ at: new Date().toISOString(),
397
+ tool: tool.name,
398
+ path: toolRowPath(a[0]),
399
+ decision: refusal ? 'deny' : ((tool.gateSeen?.n ?? 0) > askedBefore ? 'allow' : 'no check'),
400
+ rule: refusal ? refusal.rule : null,
401
+ });
312
402
  }
313
403
  },
314
404
  }));
@@ -329,6 +419,9 @@ export function makeLiveModelStep({
329
419
  tools: /** @type {Record<string, number>} */ ({}),
330
420
  ungranted: /** @type {string[]} */ ([]),
331
421
  refused,
422
+ // M4d am25 item 4: what this attempt asked of thinking (the runner's decision, `stepMeta.thinkingMode`; null = it asked nothing) and the WORST status
423
+ // bareagent reported across its rounds (null = none reported). The ONE place this record is built; `toolFields` hands it to every return.
424
+ thinking: /** @type {{asked: string|null, status: string|null}} */ ({ asked: thinkingMode ?? null, status: null }),
332
425
  };
333
426
  let noToolCallStreak = 0;
334
427
 
@@ -342,17 +435,46 @@ export function makeLiveModelStep({
342
435
  };
343
436
  const tools = [...primitiveTools, emitTool];
344
437
  const roundMeterings = [];
438
+ let lastCall = /** @type {any} */ (null);
345
439
  const stopRequested = seam?.stopRequested;
346
440
  const stopSeam = typeof stopRequested === 'function'
347
441
  ? { assemble: async (msgs) => { if (stopRequested()) throw new HaltError('stop requested', { rule: STOP_RULE }); return msgs; } }
348
442
  : {};
349
- const loop = new Loop({ provider, rates, onLlmResult: async (ev) => { roundMeterings.push(ev); }, ...stopSeam });
443
+ // M4d am29 item 1: each model call gets its diary row the moment it is metered (round = this step's next, counted across its tries)
444
+ const onLlmResult = async (ev) => {
445
+ roundMeterings.push(ev);
446
+ currentRound = nextRound(runDir, diaryStep);
447
+ appendCall(runDir, {
448
+ step: diaryStep,
449
+ try: diaryTry,
450
+ round: currentRound,
451
+ at: new Date().toISOString(),
452
+ model: typeof ev?.model === 'string' ? ev.model : null,
453
+ costUsd: typeof ev?.costUsd === 'number' ? ev.costUsd : null, // an unpriced call stays null, never 0
454
+ tokens: ev?.usage ? { in: ev.usage.inputTokens ?? 0, out: ev.usage.outputTokens ?? 0, cache: ev.usage.cacheReadTokens ?? 0 } : null,
455
+ ms: typeof ev?.durationMs === 'number' ? ev.durationMs : null,
456
+ stopReason: typeof ev?.stopReason === 'string' ? ev.stopReason : null,
457
+ thinking: { asked: thinkingMode, status: thinkingStatusOf(lastCall) },
458
+ });
459
+ // a name the model asked for that was never offered reaches no tool (the Loop answers "Unknown tool"): it still gets its own denied row.
460
+ // A call cut at the output cap runs none of its tool calls, so it gets none.
461
+ if (ev?.stopReason !== 'max_tokens') {
462
+ for (const tc of lastCall?.toolCalls ?? []) {
463
+ if (tc?.name === 'emit_artifact' || primitiveTools.some((t) => t.name === tc?.name)) continue;
464
+ appendTool(runDir, {
465
+ step: diaryStep, try: diaryTry, round: currentRound, at: new Date().toISOString(), tool: String(tc?.name), path: null, decision: 'deny', rule: 'not granted',
466
+ });
467
+ }
468
+ }
469
+ };
470
+ const loop = new Loop({ provider: watchCalls(provider, (r) => { lastCall = r; }), rates, onLlmResult, ...stopSeam });
350
471
 
351
472
  const startedAt = Date.now();
352
473
  let result;
353
474
  try {
354
475
  // eslint-disable-next-line no-await-in-loop
355
- result = await loop.run(messages, tools, { maxTokens: 16000 });
476
+ // M4d am25: the thinking switch is the runner's decision (`stepMeta.thinkingMode`, 'on' | 'off'); bareagent sends it. Absent = send none (a caller that decides nothing).
477
+ result = await loop.run(messages, tools, { maxTokens: 16000, ...(thinkingMode ? { thinkingMode } : {}) });
356
478
  } catch (err) {
357
479
  const wallMs = Date.now() - startedAt;
358
480
  const partial = sumMeterings(roundMeterings);
@@ -419,6 +541,7 @@ export function makeLiveModelStep({
419
541
  const metered = sumMeterings(roundMeterings);
420
542
  cumulative = addMeter(cumulative, metered);
421
543
  cumulative = { ...cumulative, ...addToolCounts(cumulative, result.metrics?.byTool, grantedNames) };
544
+ if (result.thinkingStatus !== undefined) cumulative.thinking = { asked: cumulative.thinking.asked, status: worstThinkingStatus([cumulative.thinking.status, result.thinkingStatus]) };
422
545
  appendSpendRow(spendPath, {
423
546
  provider: slot ?? null,
424
547
  price: priceRecord(prices, rates),
package/src/pageask.js ADDED
@@ -0,0 +1,136 @@
1
+ // borrowed-from: bareloop src/pagemap.js@0a34846 (DROP_IT, isDropIt, isAgree, readingQuestion, readingOfQuestion, askableFromLook, ruleBounds, tooManyAsksText)
2
+ // borrowed-from: bareloop src/facts.js@0a34846 (ruleWords, sayBound, moneyAs)
3
+ // M10 piece 3 (docs/wiki/the-module-ladder.md "M10", item 4, am1, am2, am5): the early asks CODE forces before any paid drafting, from the page look's own
4
+ // result. The model never decides whether to ask: this file reads a kept fact's own keys (line, forRule, name, shape, unit, currency, reading) and the job
5
+ // lines, and nothing else (test/m10-pageask.test.js greps for it). The question words are bareloop's, verbatim (am5 item 1); the answer words are
6
+ // agree / yes (code's reading), your own words, and, for a can't-check ask only, "drop it" (am2 item 2).
7
+ // Every rule is one of three kinds:
8
+ // PAGE: a kept page word carries it: no ask.
9
+ // READING: a kept fact carries it with a `reading` (a limit the page cannot hold in words, e.g. "not a red-eye"). Asked only when a bound of the
10
+ // reading is NOT in the words the person wrote; a bound they wrote themselves is theirs and nothing is asked.
11
+ // CAN'T CHECK: no kept fact carries it.
12
+ // Throws away: a fact's name, words and source (only its reading and the rule it serves are used).
13
+ import { redactSecrets } from './redact.js';
14
+ import { lineRules, boundInWords, wordsSaidOn } from './pagebits.js';
15
+ import { validReading } from './pagerules.js';
16
+
17
+ /** the most asks before drafting; more than this is a job to rewrite, not a questionnaire (am1) */
18
+ export const MAX_LOOK_ASKS = 3;
19
+ /** the answer that drops a `~` rule the page cannot check: the person types it (any case, a closing full stop allowed) */
20
+ export const DROP_IT = 'drop it';
21
+ /** @param {unknown} text @returns {boolean} */
22
+ export const isDropIt = (text) => String(text ?? '').trim().replace(/\.$/, '').toLowerCase() === DROP_IT;
23
+ /** the answers that accept the code's reading of a rule; anything else the person types is their own reading */
24
+ const AGREE_WORDS = ['agree', 'yes'];
25
+ /** @param {unknown} text @returns {boolean} */
26
+ export const isAgree = (text) => AGREE_WORDS.includes(String(text ?? '').trim().replace(/[.!]$/, '').toLowerCase());
27
+
28
+ /** @typedef {{line: number, rule: number, source: 'look', question: string, ask: 'reading'|'cant-check', ruleText: string, reading?: string}} LookAsk
29
+ * `reading` = the plain words an `agree` writes as a `~` rule (a reading ask only) */
30
+
31
+ /** @param {unknown} n @param {string} shape @param {any} f @returns {string} one bound, as the person would say it */
32
+ function sayBound(n, shape, f) {
33
+ if (shape === 'money') return moneyAs(f, /** @type {string|number} */ (n), false);
34
+ return String(n);
35
+ }
36
+ const asList = (/** @type {unknown} */ v) => (Array.isArray(v) ? v.map(String) : (typeof v === 'string' ? [v] : []));
37
+ /**
38
+ * One amount of a money fact in the fact's OWN forms, never a hardcoded sign: `symbolFirst` puts the currency sign before the amount when the fact has one.
39
+ * @param {any} f @param {string|number} n @param {boolean} symbolFirst @returns {string}
40
+ */
41
+ export function moneyAs(f, n, symbolFirst) {
42
+ const cur = asList(f.currency)[0];
43
+ const uni = asList(f.unit)[0];
44
+ if (symbolFirst) return cur !== undefined ? `${cur}${n}` : `${n} ${uni}`;
45
+ return uni !== undefined ? `${n} ${uni}` : `${cur}${n}`;
46
+ }
47
+ /** @param {any} f a fact with a rule @returns {string} the rule in words, e.g. "under 450 US dollars" */
48
+ export function ruleWords(f) {
49
+ const r = f.rule;
50
+ return r.op === 'between' ? `between ${sayBound(r.lo, f.shape, f)} and ${sayBound(r.hi, f.shape, f)}`
51
+ : `${{ lt: 'under', lte: 'at most', gt: 'over', gte: 'at least' }[/** @type {'lt'|'lte'|'gt'|'gte'} */ (r.op)]} ${sayBound(r.value, f.shape, f)}`;
52
+ }
53
+
54
+ /** the words of a reading ask: the ONE spelling, and {@link readingOfQuestion} reads it back (the Result tab's "(you confirmed)") */
55
+ const READING_HEAD = ' I read it as: ';
56
+ const READING_TAIL = '. Agree? Answer "agree"';
57
+ /** @param {number} n @param {string} rule @param {string} reading @returns {string} */
58
+ const readingQuestion = (n, rule, reading) => `Your line ${n} says "${rule}".${READING_HEAD}${reading}${READING_TAIL}, or type your own reading (your answer is added as a new ~ rule on line ${n}).`;
59
+ /** @param {unknown} q a recorded question @returns {string|null} the reading a reading ask proposed, or null when it was another kind of question */
60
+ export function readingOfQuestion(q) {
61
+ const s = String(q ?? '');
62
+ const a = s.indexOf(READING_HEAD);
63
+ const b = s.indexOf(READING_TAIL);
64
+ return a >= 0 && b > a ? s.slice(a + READING_HEAD.length, b) : null;
65
+ }
66
+
67
+ /**
68
+ * The early asks CODE forces before any paid drafting, from the look's own result. One ask per rule text on a line; readings first, then can't-check
69
+ * asks, each in line order. The caller applies the cap and the answer gate.
70
+ * @param {{facts?: {line: number, forRule?: number, name?: string, shape?: string, unit?: string[], currency?: string[], reading?: import('./pagerules.js').Reading}[]}|null|undefined} look
71
+ * @param {{n: number, text?: string, rule?: string, rules?: string[]}[]|null|undefined} jobLines
72
+ * @returns {LookAsk[]}
73
+ */
74
+ export function askableFromLook(look, jobLines) {
75
+ const facts = Array.isArray(look?.facts) ? look.facts : [];
76
+ /** @type {LookAsk[]} */
77
+ const readings = [];
78
+ /** @type {LookAsk[]} */
79
+ const cants = [];
80
+ /** @type {Set<string>} */
81
+ const seen = new Set();
82
+ for (const l of Array.isArray(jobLines) ? jobLines : []) {
83
+ lineRules(l).forEach((rule, k) => {
84
+ const n = k + 1;
85
+ const key = `${l.n}\u0000${rule.trim().toLowerCase()}`;
86
+ const tied = facts.filter((f) => f.line === l.n && f.forRule === n);
87
+ if (tied.length > 0) {
88
+ const said = wordsSaidOn(l);
89
+ const f = tied.find((x) => x.reading && validReading(x.shape, x.reading) && ruleBounds(x.reading).some((b) => !boundInWords(b, said)));
90
+ if (f === undefined || seen.has(key)) return;
91
+ seen.add(key);
92
+ const reading = `${f.name} ${ruleWords({ shape: f.shape, unit: f.unit, currency: f.currency, rule: f.reading })}`;
93
+ readings.push({
94
+ line: l.n, rule: n, source: 'look', ask: 'reading', ruleText: rule, reading,
95
+ question: readingQuestion(l.n, rule, reading),
96
+ });
97
+ return;
98
+ }
99
+ if (seen.has(key)) return;
100
+ seen.add(key);
101
+ cants.push({
102
+ line: l.n, rule: n, source: 'look', ask: 'cant-check', ruleText: rule,
103
+ question: `Your line ${l.n} says "${rule}". I can't check this on the page. Drop it? Answer "${DROP_IT}", or type how to check it (your answer is added as a new ~ rule on line ${l.n}).`,
104
+ });
105
+ });
106
+ }
107
+ return [...readings, ...cants];
108
+ }
109
+
110
+ /** @param {import('./pagerules.js').Reading} r @returns {unknown[]} the bounds a reading holds */
111
+ const ruleBounds = (r) => (r.op === 'between' ? [r.lo, r.hi] : [r.value]);
112
+
113
+ /**
114
+ * More asks than the cap means the job needs a rewrite, not a questionnaire. The code-owned stop words list EVERY ask and its reading as the
115
+ * suggestion (no extra paid call). A secret in a rule is masked.
116
+ * @param {{line: number, ruleText: string, reading?: string}[]} asks @returns {string}
117
+ */
118
+ export function tooManyAsksText(asks) {
119
+ const list = asks.map((a) => `line ${a.line} "${a.ruleText}" → ${a.reading ?? "I can't check this on the page"}`).join('; ');
120
+ return redactSecrets(`Your job has ${asks.length} rules I can't check or had to guess. Please rewrite it so each one says what to look for. My readings: ${list}.`);
121
+ }
122
+
123
+ /**
124
+ * What a typed answer to a look ask does, the ONE place that decides (the panel's answer route, the setup record and the Result tab all read it).
125
+ * `agree` / `yes` to a reading ask takes the code's reading; `drop it` to a can't-check ask leaves the rule Not checked (no `~` line); anything else is the
126
+ * person's own words, taken word for word with newlines folded to spaces. A question that is not a look ask is never changed: its answer is its rule.
127
+ * @param {{source?: string, ask?: string, proposal?: string|null}} q @param {unknown} typed
128
+ * @returns {{rule: string|null, left: boolean}} `rule` = the words written as a new `~` rule (null when the rule is left Not checked)
129
+ */
130
+ export function ruleOfAnswer(q, typed) {
131
+ const text = String(typed ?? '').replace(/\s*\n\s*/g, ' ').trim();
132
+ if (q.source !== 'look') return { rule: text, left: false };
133
+ if (q.ask === 'reading' && typeof q.proposal === 'string' && isAgree(text)) return { rule: q.proposal, left: false };
134
+ if (q.ask === 'cant-check' && isDropIt(text)) return { rule: null, left: true };
135
+ return { rule: text, left: false };
136
+ }
@@ -0,0 +1,107 @@
1
+ // The small pieces of bareloop's facts.js, factwords.js, labelscan.js and rubricstep.js that the copied page rules need. Each piece is a copy;
2
+ // the rest of those files (bareguard-facing fact checks, label scans, the rubric step) is not wanted here and is not copied.
3
+
4
+ // borrowed-from: bareloop src/facts.js@b7d3306 (FACT_OPS, MAX_CURRENCIES, MAX_UNITS, MAX_UNIT_CHARS, asList, boundOk)
5
+ export const FACT_OPS = Object.freeze(['lt', 'lte', 'gt', 'gte', 'between']);
6
+ export const MAX_CURRENCIES = 3;
7
+ export const MAX_UNITS = 10;
8
+ export const MAX_UNIT_CHARS = 100;
9
+ export const asList = (/** @type {unknown} */ v) => (Array.isArray(v) ? v.map(String) : (typeof v === 'string' ? [v] : []));
10
+ export const boundOk = (/** @type {string} */ shape, /** @type {unknown} */ v) => (shape === 'number' || shape === 'money' ? typeof v === 'number' && Number.isFinite(v) : typeof v === 'string' && v !== '');
11
+
12
+ // borrowed-from: bareloop src/factwords.js@18ab77c (squash, loose, countExact, countPhrase - rewritten without a built pattern, same count, see test/m10-pagebits.test.js)
13
+ const WS = /[\s   ]+/g;
14
+ /** a letter or a digit (any script); the character right at the start of the string tested */
15
+ const WORD_CHAR = /^[\p{L}\p{N}]/u;
16
+
17
+ /** @param {string} t @returns {string} the source with every run of white space made one space */
18
+ export const squash = (t) => String(t ?? '').replace(WS, ' ');
19
+ /** @param {string} t @returns {string} lower case, markdown marks dropped, white space squashed - how a phrase or unit is compared */
20
+ const loose = (t) => squash(t).replace(/[*_`]/g, '').trim().toLowerCase();
21
+
22
+ /**
23
+ * How many times exact words occur in a source, white space blind. Zero for empty words.
24
+ * @param {string} source the raw source text @param {string} words
25
+ * @returns {number}
26
+ */
27
+ export function countExact(source, words) {
28
+ const w = squash(words).trim();
29
+ if (w === '') return 0;
30
+ const hay = squash(source);
31
+ let n = 0;
32
+ for (let i = hay.indexOf(w); i !== -1; i = hay.indexOf(w, i + w.length)) n += 1;
33
+ return n;
34
+ }
35
+
36
+ /**
37
+ * How many times a phrase or unit occurs as WHOLE words, case and spacing aside ("SFO" is not found inside "sfocus").
38
+ * @param {string} source @param {string} words @returns {number}
39
+ */
40
+ export function countPhrase(source, words) {
41
+ const w = loose(words);
42
+ if (w === '') return 0;
43
+ const hay = loose(source);
44
+ // The original is one dynamic RegExp, `(^|[^\p{L}\p{N}])<w>(?=$|[^\p{L}\p{N}])` over every match; this repo bans built patterns in src/, so the same count is
45
+ // taken by hand: a hit has a non-letter-non-digit (or the start) before it and after it, and a hit may not reuse the character the last hit's end left behind.
46
+ let n = 0;
47
+ let consumedTo = 0;
48
+ for (let i = hay.indexOf(w); i !== -1; i = hay.indexOf(w, i + 1)) {
49
+ const prev = i === 0 ? null : /(.)$/su.exec(hay.slice(Math.max(0, i - 2), i))?.[1] ?? null;
50
+ if (prev !== null && (WORD_CHAR.test(prev) || i - prev.length < consumedTo)) continue;
51
+ if (WORD_CHAR.test(hay.slice(i + w.length, i + w.length + 2))) continue;
52
+ n += 1;
53
+ consumedTo = i + w.length;
54
+ i += w.length - 1;
55
+ }
56
+ return n;
57
+ }
58
+
59
+ /**
60
+ * The forms a word may be written in (hamr's ruling 2026-10-21, "a simple plural matches"): the word, its plural and its singular, case aside. A simple plural is
61
+ * `s`, `es` after s/x/z/ch/sh, or `ies` for a consonant + `y`; nothing wider ("amounted" is not "amount"). The ONE place a word is allowed a plural: the
62
+ * sheet look's own-word check, the column finder and the .docx heading match all take their forms from here. A number, a phrase a guardrail names or a
63
+ * money value is never widened by it.
64
+ * @param {string} word @returns {string[]}
65
+ */
66
+ export function wordForms(word) {
67
+ const w = loose(word);
68
+ if (w === '') return [];
69
+ const forms = new Set([w]);
70
+ if (/[^aeiou]y$/.test(w)) forms.add(`${w.slice(0, -1)}ies`);
71
+ else if (/(s|x|z|ch|sh)$/.test(w)) forms.add(`${w}es`);
72
+ else forms.add(`${w}s`);
73
+ if (w.endsWith('ies') && w.length > 4) forms.add(`${w.slice(0, -3)}y`);
74
+ if (/(s|x|z|ch|sh)es$/.test(w)) forms.add(w.slice(0, -2));
75
+ if (w.endsWith('s') && !w.endsWith('ss') && w.length > 2) forms.add(w.slice(0, -1));
76
+ return [...forms];
77
+ }
78
+
79
+ // borrowed-from: bareloop src/labelscan.js@dda9c8f (normLabel)
80
+ /** @param {string} t @returns {string} white space made one space, quote marks at the edges dropped, trimmed - how a label is compared */
81
+ export function normLabel(t) {
82
+ return String(t ?? '').replace(WS, ' ').trim().replace(/^["'“”]+|["'“”]+$/g, '').trim();
83
+ }
84
+
85
+ // borrowed-from: bareloop src/rubricstep.js@2f93962 (lineRules, boundSpellings, boundInWords, wordsSaidOn)
86
+ const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
87
+ /** the ~ rules of one job line, one string each (`rules` when the line has the array, else the joined `rule` split on "; ") @param {any} l @returns {string[]} */
88
+ export function lineRules(l) {
89
+ if (isRec(l) && Array.isArray(l.rules)) return l.rules.filter((/** @type {unknown} */ r) => typeof r === 'string' && r);
90
+ return isRec(l) && typeof l.rule === 'string' && l.rule ? l.rule.split('; ').filter(Boolean) : [];
91
+ }
92
+
93
+ /** @param {unknown} b @returns {string[]} the spellings a rule bound can have in the person's own words */
94
+ const boundSpellings = (b) => {
95
+ const s = String(b);
96
+ return [s, s.replace(/^0+(?=\d)/, ''), s.replace(/\.0+$/, '')];
97
+ };
98
+
99
+ /**
100
+ * Is this rule bound in the words the person wrote? The ONE test for "a number the AI made" (`rubric-fact-unmarked`, the L3 settle, and
101
+ * the early ask of PRD v1.107 Part 5b all read it; never a second spelling).
102
+ * @param {unknown} b @param {string} said @returns {boolean}
103
+ */
104
+ export const boundInWords = (b, said) => boundSpellings(b).some((sp) => said.includes(sp));
105
+
106
+ /** @param {any} jl one job line @returns {string} the words the person wrote on it: the line and its `~` rules */
107
+ export const wordsSaidOn = (jl) => `${jl.text ?? ''} ${lineRules(jl).join(' ')}`;