fwdloop 0.37.0 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -57,27 +57,13 @@ last word, and how to make cost and outcome honest. It borrows those solved prob
57
57
  primitives directly, as a sibling of the suite, and adds the part that was missing: the
58
58
  pauses, the checks, and the people.
59
59
 
60
- ## The bare ecosystem
60
+ ## bare suite
61
61
 
62
- Local-first, composable agent infrastructure. Same patterns throughout, each module works
63
- standalone.
62
+ - **Hands** · [barebrowse](https://github.com/hamr0/barebrowse) · [baremobile](https://github.com/hamr0/baremobile) · [beeperbox](https://github.com/hamr0/beeperbox)
63
+ - **Rails** · [bareagent](https://github.com/hamr0/bareagent) · [bareguard](https://github.com/hamr0/bareguard) · [barebox](https://github.com/hamr0/barebox) · [litectx](https://github.com/hamr0/litectx)
64
+ - **Apps** · **fwdloop** · [bareloop](https://github.com/hamr0/bareloop)
64
65
 
65
- **Core** — the brain, the gate, the memory.
66
-
67
- - **[bareagent](https://npmjs.com/package/bare-agent)** — the think→act→observe loop. *Goal in → coordinated actions out.*
68
- - **[bareguard](https://npmjs.com/package/bareguard)** — the single gate every action passes through. *Action in → allow / deny / ask-a-human out.*
69
- - **[litectx](https://npmjs.com/package/litectx)** — memory and context engineering (write · select · compress · isolate). *Query in → ranked context out.*
70
-
71
- **Optional reach** — give the agent hands.
72
-
73
- - **[barebrowse](https://npmjs.com/package/barebrowse)** — a real browser for agents.
74
- - **[baremobile](https://npmjs.com/package/baremobile)** — Android + iOS device control.
75
- - **[beeperbox](https://github.com/hamr0/beeperbox)** — 50+ messaging networks via one MCP server.
76
-
77
- **Siblings** — workflows on top of the rails.
78
-
79
- - **[bareloop](https://github.com/hamr0/bareloop)** — workflows that earn their own design, for repeated, verifiable jobs. Closed loop.
80
- - **fwdloop** — workflows with people in them. Open loop.
66
+ Built from [bareagent](https://github.com/hamr0/bareagent), [barebrowse](https://github.com/hamr0/barebrowse), [bareguard](https://github.com/hamr0/bareguard) and [litectx](https://github.com/hamr0/litectx). → [The whole suite](https://github.com/hamr0)
81
67
 
82
68
  ## Status
83
69
 
package/bin/fwdloop CHANGED
@@ -52,6 +52,7 @@ import { panelMain } from '../src/panel/server.js';
52
52
  import { launcherMain } from '../src/launcher.js';
53
53
  import { isInteractive, confirmTypedName, NEEDS_TTY } from '../src/sign-confirm.js';
54
54
  import { draftToDir, draftKeyRefusal, signDraft, SIGN_LINE, costText, questionsRefusal } from '../src/authoring.js';
55
+ import { minRuleRefusal } from '../src/minrule.js';
55
56
  import { readRecordFile, readRowChoices, readSheetDropped, readShapeDropped, readColumns } from '../src/pickrecord.js';
56
57
  import { userInfo } from 'node:os';
57
58
  import { pageAddressesOf, pageAddressRefusal } from '../src/pagefetch.js';
@@ -110,9 +111,15 @@ function takeMonthlyHold({ what, flow, runId, runDir, holdUsd, spentAtHold = 0 }
110
111
  });
111
112
  } catch (err) {
112
113
  if (!(err instanceof ConfigError)) throw err;
113
- fail(`${err.message} — refusing to start rather than guess the monthly limit. Nothing spent.`);
114
+ const words = `${err.message} — refusing to start rather than guess the monthly limit. Nothing spent.`;
115
+ if (what === 'draft') refuseDraft('capUsd', words, words);
116
+ fail(words);
117
+ }
118
+ if (!claim.ok) {
119
+ const words = monthlyRefusalText(claim.room);
120
+ if (what === 'draft') refuseDraft('capUsd', words, words);
121
+ fail(words);
114
122
  }
115
- if (!claim.ok) fail(monthlyRefusalText(claim.room));
116
123
  let settled = false;
117
124
  const settle = (why) => {
118
125
  if (settled || claim.holdId === null) return;
@@ -142,6 +149,14 @@ function fail(message) {
142
149
  process.exit(1);
143
150
  }
144
151
 
152
+ // F262: the ONE writer of a draft refusal's typed record. `box` is named by the refusing check's own call site (job | capUsd | model | inputs | null), never read from words.
153
+ // The human line is printed first, unchanged; the record is the last line of the log, one JSON line (so words with a newline stay one line).
154
+ function refuseDraft(box, words, printed = `draft refused at $0 — ${words}`) {
155
+ process.stderr.write(`fwdloop: ${printed}\n`);
156
+ process.stderr.write(`fwdloop: refusal-record ${JSON.stringify({ box, words })}\n`);
157
+ process.exit(1);
158
+ }
159
+
145
160
  /**
146
161
  * The ONE place a human-typed `--root` becomes a path (hamr ruling
147
162
  * 2026-09-29): resolved to its real path once, at command start. Nothing
@@ -959,15 +974,16 @@ async function cmdDraft(rest) {
959
974
  if (configDoorHome().skip) fail(NO_CONFIG_HOME_REFUSAL);
960
975
  try {
961
976
  const p = pickTicked(readPriceConfig(), values);
962
- if (!p.ok) fail(`draft refused at $0 — ${p.say}`);
977
+ if (!p.ok) refuseDraft('model', p.say);
963
978
  pick = { slot: p.slot, model: p.model };
964
979
  } catch (err) {
965
980
  if (!(err instanceof ConfigError)) throw err;
966
- fail(`${err.message} — refusing to draft rather than guess the price. Nothing spent.`);
981
+ const words = `${err.message} — refusing to draft rather than guess the price. Nothing spent.`;
982
+ refuseDraft('model', words, words);
967
983
  }
968
984
  // The key preflight (draftToDir repeats it).
969
985
  const refusal = draftKeyRefusal(pick.slot, env);
970
- if (refusal !== null) fail(`draft refused at $0 — ${refusal}`);
986
+ if (refusal !== null) refuseDraft('model', refusal);
971
987
  } else if (values.model !== undefined) pick = { slot: values.provider, model: values.model };
972
988
  // M4d piece 3: the monthly check — one ceiling round, priced from the
973
989
  // picked model's own Settings prices (an injected test provider carries its own rates). A model that is not
@@ -978,13 +994,14 @@ async function cmdDraft(rest) {
978
994
  if (!rates) {
979
995
  if (configDoorHome().skip) fail(NO_CONFIG_HOME_REFUSAL);
980
996
  const usable = resolveUsableModel(pick.slot, { config: readPriceConfig(), model: pick.model });
981
- if (!usable.ok) fail(`draft refused at $0 — ${usable.say}`);
997
+ if (!usable.ok) refuseDraft('model', usable.say);
982
998
  rates = usable.rates;
983
999
  }
984
1000
  ceiling = ceilingCostUsd(rates);
985
1001
  } catch (err) {
986
1002
  if (!(err instanceof ConfigError)) throw err;
987
- fail(`${err.message} — refusing to draft rather than guess the price. Nothing spent.`);
1003
+ const words = `${err.message} — refusing to draft rather than guess the price. Nothing spent.`;
1004
+ refuseDraft('model', words, words);
988
1005
  }
989
1006
  // 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
990
1007
  // 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
@@ -993,6 +1010,11 @@ async function cmdDraft(rest) {
993
1010
  const proseRead = gate.ok
994
1011
  ? (gate.text.trim() === '' ? { ok: false, red: `prose: "${proseAbs}" is empty` } : gate)
995
1012
  : { ok: false, red: gate.missing ? `prose: cannot read "${proseAbs}": ENOENT` : `prose: ${gate.red}` };
1013
+ // M19 am13: a job with no `~` rule of the person's is refused here, at $0, before the hold, the draft folder or any provider call (the panel's Start drafting spawns this command and shows these words)
1014
+ if (proseRead.ok) {
1015
+ const noRule = minRuleRefusal(proseRead.text);
1016
+ if (noRule !== null) refuseDraft('job', noRule);
1017
+ }
996
1018
  const hold = takeMonthlyHold({
997
1019
  what: 'draft', flow: values.name, runId: null, runDir: resolve(values.out), holdUsd: draftHoldUsd(proseRead.ok ? proseRead.text : '', resolve(values.out), ceiling),
998
1020
  });
@@ -1024,9 +1046,7 @@ async function cmdDraft(rest) {
1024
1046
  });
1025
1047
  const cost = result.costUsd === null ? 'UNKNOWN' : costText(Number(result.costUsd), result.spendComplete);
1026
1048
  if (!result.wrote) {
1027
- process.stderr.write(`fwdloop: draft refused at $0 — ${result.reds.join('; ')}\n`);
1028
- process.exitCode = 1;
1029
- return;
1049
+ refuseDraft(result.box ?? null, result.reds.join('; '));
1030
1050
  }
1031
1051
  process.stdout.write(`draft dir: ${resolve(values.out)} cost: ${cost}\n`);
1032
1052
  // 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)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fwdloop",
3
- "version": "0.37.0",
3
+ "version": "0.38.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",
package/src/authoring.js CHANGED
@@ -390,9 +390,9 @@ export async function draftToDir({
390
390
  // M13 am11: what the card's tentative send line is (see draft()); null = the prose file is the truth
391
391
  actionMode = /** @type {null|'check'|'known'} */ (null),
392
392
  }) {
393
- const refuse = (reds) => ({ ok: false, wrote: false, reds, costUsd: 0 });
393
+ const refuse = (reds, box = /** @type {string|null} */ (null)) => ({ ok: false, wrote: false, reds, costUsd: 0, box });
394
394
  const nameCheck = checkFlowName(name);
395
- if (!nameCheck.ok) return refuse([nameCheck.red]);
395
+ if (!nameCheck.ok) return refuse([nameCheck.red], 'flowName');
396
396
  if (typeof root !== 'string' || root === '') return refuse(['draft: --root <flows dir> is required']);
397
397
  // An unsigned draft folder inside the flows root would list as a flow in the panel and Inbox (checked by realpath, at use time).
398
398
  const realRoot = realpathOfNew(root);
@@ -410,7 +410,7 @@ export async function draftToDir({
410
410
  const injected = provider != null;
411
411
  if (!injected) {
412
412
  const refusal = draftKeyRefusal(slot, env);
413
- if (refusal !== null) return refuse([refusal]);
413
+ if (refusal !== null) return refuse([refusal], 'model');
414
414
  }
415
415
  const secrets = keyValues(env, [...new Set([...(keyNames ?? []), ...(typeof slot === 'string' ? [slot] : [])])]);
416
416
  if (secrets.some((s) => s.length >= 8 && prose.text.includes(s))) return refuse(['prose: contains an API key value — refused']);
@@ -478,7 +478,7 @@ export async function draftToDir({
478
478
  });
479
479
  if (result.stop === 'pre-flight') {
480
480
  try { rmdirSync(dir); } catch { /* the claimed dir is still empty; leave it rather than mask the refusal */ }
481
- return refuse(cleanReds(result.reds));
481
+ return refuse(cleanReds(result.reds), result.box ?? null);
482
482
  }
483
483
  // M8 item 5a: what was handed is kept once beside the draft (only when a round was actually sent with it); a failure is recorded, never raised.
484
484
  try {
@@ -18,15 +18,11 @@ export const ASK_LINE_REASON = 'you judge it at the Ask';
18
18
  */
19
19
  export const SHAPE_ONLY_CLASS = 'green';
20
20
 
21
- // fwd (F251): the no-guardrail words are the check block's (src/checkblock.js), the one writer; re-exported for the readers that import them from here
22
- export { NO_GUARDRAIL_WORDS } from './checkblock.js';
23
-
24
21
  import { REASON } from './checkblock.js';
25
22
  import { KEPT_WORDS } from './pickrecord.js';
26
23
  import { lineRules } from './pagebits.js';
27
24
  import { isListedNotChecked, notCheckedItem, ruleTextOf } from './checkrows.js';
28
-
29
- const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
25
+ import { isRec } from './isrec.js';
30
26
 
31
27
  /** a countable part as the picked check the softgreen close runs: its own fields, the rule named `rule` (the inverse of the block's partOfPick) @param {Record<string, any>} part */
32
28
  export function pickedOf(part) {
@@ -67,7 +63,7 @@ export function assembleFromBlock({ declaration, block, lines, lineSet, askLines
67
63
  }
68
64
  if (!isRec(st) || !Number.isInteger(n) || !lineSet.has(n)) return st;
69
65
  const parts = partsOf(n);
70
- // fwd (F251): the check block is the one decider that a line with no ~ guardrail holds no check (src/checkblock.js buildLine), so every part it holds is kept here
66
+ // the check block is the one decider of which parts a line holds (src/checkblock.js buildLine), so every part it holds is kept here
71
67
  const fact = parts.find((p) => p.class === 'fact');
72
68
  // M19 S5: the shape part rides the fact part (facts+shape, class green); a line with no fact part takes it only when a class is ruled for it (`shapeOnlyClass`)
73
69
  const picks = parts.filter((p) => p.class === 'countable' && p.check !== 'cited' && p.check !== 'numbersFromFacts');
@@ -102,7 +98,8 @@ export function assembleFromBlock({ declaration, block, lines, lineSet, askLines
102
98
  for (const n of lineSet) {
103
99
  const mine = steps.find((/** @type {any} */ st) => isRec(st) && st.fromLine === n);
104
100
  // the classes of a list line are code's: a line with no guardrail of the person's has no class entry, whatever the AI sent
105
- if (!guarded(n)) { delete guardrailClasses[String(n)]; continue; }
101
+ // M19 am15 (F257): a line with no guardrail of the person's has a class only when a check the person Added holds it; else no entry (hitl)
102
+ if (!guarded(n) && (!mine || mine.close.class === 'hitl')) { delete guardrailClasses[String(n)]; continue; }
106
103
  if (!mine) continue;
107
104
  guardrailClasses[String(n)] = mine.close.class;
108
105
  }
package/src/checkblock.js CHANGED
@@ -76,9 +76,6 @@ const numberIn = (text, n) => {
76
76
  };
77
77
  const wordSet = (/** @type {unknown} */ t) => new Set(norm(t).match(/[\p{L}\p{N}]+/gu) ?? []);
78
78
 
79
- // fwd (F251): what a row says when its check cannot ride a line that has no guardrail of its own (the class of a line comes from its guardrail); one writer, here (blockassemble.js re-exports it)
80
- export const NO_GUARDRAIL_WORDS = 'This line has no guardrail of yours, so a check on it cannot be signed; you judge it at Accept.';
81
-
82
79
  /** the plain reasons code gives, in one place (the card, the Job tab and the Audit read them from the row) */
83
80
  export const REASON = Object.freeze({
84
81
  left: 'You chose to leave it Not checked, so you judge it at Accept.',
@@ -645,7 +642,7 @@ export class CheckBlock {
645
642
  }
646
643
  // a suggestion code has not built stays off the card (Audit only, F-b); a held one is trialled: shown under Suggested only when code has proved it builds (hamr 2026-11-13)
647
644
  for (const r of this.rows.filter((x) => x.held && x.kind !== 'sheet' && x.kind !== 'shape')) this.trialOffer(r);
648
- if (this.split) for (const r of this.rows) r.hidden = this.isBang(r) && r.state === 'not-checked' && !r.lookWhy && r.reason !== NO_GUARDRAIL_WORDS;
645
+ if (this.split) for (const r of this.rows) r.hidden = this.isBang(r) && r.state === 'not-checked' && !r.lookWhy;
649
646
  this.closeCache = { stages, parts, map };
650
647
  return this.closeCache;
651
648
  }
@@ -659,7 +656,7 @@ export class CheckBlock {
659
656
  r.held = false;
660
657
  /** @type {any[]} */ const parts = [];
661
658
  /** @type {string[][]} */ const rows = [];
662
- this.buildLine(l, parts, rows, new Set(), true);
659
+ this.buildLine(l, parts, rows, new Set());
663
660
  const ok = r.state === 'built';
664
661
  const reason = r.reason;
665
662
  const i = rows.findIndex((k) => k.includes(r.key));
@@ -672,11 +669,8 @@ export class CheckBlock {
672
669
  else { r.offer = null; r.held = false; r.state = 'not-checked'; r.reason = String(reason ?? 'not checked'); }
673
670
  }
674
671
 
675
- // fwd (F251): `offer` = the Suggested trial (trialOffer): it asks whether code can build the row, not whether the line can sign it, so the no-guardrail gate below is skipped
676
672
  /** one line's parts: a pick part per count rule, ONE fact part carrying every fact row of the line (and its result count), then the `$` defaults */
677
- buildLine(/** @type {{n: number, text: string}} */ l, /** @type {any[]} */ lineParts, /** @type {string[][]} */ lineRows, /** @type {Set<number>} */ factLines, /** @type {boolean} */ offer = false) {
678
- // fwd (F251): a line with no ~ guardrail of the person's own holds no signable check; one decider, here
679
- const unguarded = this.ruleRows(l.n).length === 0 && !this.isSheetLine(l.n);
673
+ buildLine(/** @type {{n: number, text: string}} */ l, /** @type {any[]} */ lineParts, /** @type {string[][]} */ lineRows, /** @type {Set<number>} */ factLines) {
680
674
  let foundFact = false;
681
675
  /** @type {any[]} */ const facts = [];
682
676
  /** @type {{r: Row, src: string}[]} */ const factRows = [];
@@ -738,11 +732,8 @@ export class CheckBlock {
738
732
  // facts+shape: the shape part follows the fact part (the same `results` list); its fields are the rules no truth check could take
739
733
  if (shapeRows.length > 0) this.buildShapePartOf(l, shapeRows, lineParts, lineRows);
740
734
  for (const { p, key } of pickParts) { lineParts.push(p); lineRows.push([key]); }
741
- // fwd (F251): the one decider. A line with no ~ guardrail keeps no fact, pick or shape part: its built rows are Not checked in the words the Accept reads, and it is never a fact line (so no numbers tie points at it)
742
- if (unguarded && !offer) {
743
- for (const k of lineRows.flat()) { const row = this.rows.find((x) => x.key === k); if (row) { row.state = 'not-checked'; row.reason = NO_GUARDRAIL_WORDS; row.part = null; } }
744
- lineParts.length = 0; lineRows.length = 0;
745
- } else if (foundFact) factLines.add(l.n);
735
+ // M19 am15 (F257): a line with no ~ of the person's own keeps the parts of the `!` rows the person Added (nothing else builds one there: match() holds every `!` row of such a line), so it may be a fact line
736
+ if (foundFact) factLines.add(l.n);
746
737
  this.buildDefaults(l, lineParts, lineRows, factLines);
747
738
  }
748
739
 
package/src/checked.js CHANGED
@@ -70,10 +70,9 @@ export function checkedLines(declaration, { hasAsk = true, askLines, lines, csvR
70
70
  // M10b piece 1: the signed sheet checks, one row each, written by code from the typed fields
71
71
  lead = 'The machine recomputes each of these from the saved sheet and compares it with what the step gave:';
72
72
  out.push(...(sheet ? [] : sheetCheckRows(st.close.sheet).map((r) => labelled(r, 'agent'))));
73
- } else if (cls === 'green' && st.close.itemShape && typeof st.close.itemShape === 'object') {
74
- // M19 am11 item 6: a list line states no lead sentence; its checks are the rows below (listPartRows)
75
73
  } else if (cls === 'green') {
76
- lead = 'Every figure must cite its source cell, or a formula over cells, and the machine recomputes it and compares it with its source.';
74
+ // M19 am11 item 6: a list line (itemShape) states no lead sentence; its checks are the rows below (listPartRows)
75
+ if (!(st.close.itemShape && typeof st.close.itemShape === 'object')) lead = 'Every figure must cite its source cell, or a formula over cells, and the machine recomputes it and compares it with its source.';
77
76
  } else if (cls === 'softgreen') {
78
77
  lead = 'The reply is checked as plain text only.';
79
78
  if (Number.isInteger(shape.maxWords)) out.push(labelled(`The whole output is under ${shape.maxWords} words.`, 'agent'));
@@ -1,8 +1,7 @@
1
1
  // M16 (docs/wiki/the-module-ladder.md, "M16" item 2, "a check that reaches the plan is not on the list"): the sign-time and run-start proof that the checks of a plan's list lines are the list's.
2
2
  // Equivalent of bareloop src/rubricstep.js@v0.56.0 (3383cce) `listMatchesClose`, read over fwdloop's close fields instead of a rubric-step stage: the checks of one line, in the order the check block
3
3
  // builds them, are [close.cited (the fact part)], [close.itemShape (the shape part, M19 S5)], then each entry of close.picked / close.shape.picked, then close.numbersFrom (the numbers tie). A signed row points at one of them by `part: {line, part: <index>}`.
4
-
5
- const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
4
+ import { isRec } from './isrec.js';
6
5
 
7
6
  /**
8
7
  * The checks of one step's close in the block's part order. M16 am4: with `withSheet` (a plan whose list has sheet rows) each `close.sheet` check is a part too, after the others.
@@ -341,8 +341,8 @@ export function checkShapes(declaration) {
341
341
  * safe); an invented proposal is a red, never normalised to hitl.
342
342
  * Returns `{ ok: true, class }` or `{ ok: false, error }`.
343
343
  */
344
- function resolveGuardrailClass(line, guardrailClasses) {
345
- if (!line || !line.guardrail) {
344
+ function resolveGuardrailClass(line, guardrailClasses, added = new Set()) {
345
+ if (!line || (!line.guardrail && !added.has(line.n))) {
346
346
  return { ok: true, class: 'hitl' };
347
347
  }
348
348
  const key = String(line.n);
@@ -363,7 +363,7 @@ function resolveGuardrailClass(line, guardrailClasses) {
363
363
  /** Same shape as poc/m0/validator.mjs's `deriveFromLine`: a step with no
364
364
  * `fromLine` is silence -> hitl; a malformed or non-existent `fromLine` is
365
365
  * a red; otherwise the class derives from that line's guardrail proposal. */
366
- function deriveFromLine(fromLine, lines, guardrailClasses) {
366
+ function deriveFromLine(fromLine, lines, guardrailClasses, added = new Set()) {
367
367
  if (fromLine === null || fromLine === undefined) {
368
368
  return { ok: true, class: 'hitl', line: null };
369
369
  }
@@ -374,7 +374,7 @@ function deriveFromLine(fromLine, lines, guardrailClasses) {
374
374
  if (!line) {
375
375
  return { ok: false, error: `fromLine ${fromLine} does not name any of the signed numbered lines` };
376
376
  }
377
- const resolved = resolveGuardrailClass(line, guardrailClasses);
377
+ const resolved = resolveGuardrailClass(line, guardrailClasses, added);
378
378
  if (!resolved.ok) return { ok: false, error: resolved.error };
379
379
  return { ok: true, class: resolved.class, line };
380
380
  }
@@ -819,6 +819,8 @@ export function validateDeclaration(declaration, context = {}) {
819
819
 
820
820
  // --- guardrailClasses (REQUIRED — the harness always writes it; empty {}
821
821
  // is fine, missing entirely is not) ------------------------------------
822
+ // M19 am15 (F257): a line with no `~` of the person's own may carry a class only when the plan's list holds a built `!` check on that line (one the person Added, or one code built from the line's own words, M19 am15a)
823
+ const addedLines = new Set((Array.isArray(declaration.checkList) ? declaration.checkList : []).filter((r) => isPlainObject(r) && r.by === 'agent' && r.state === 'built' && r.kind !== 'floor' && Number.isInteger(r.line)).map((r) => r.line));
822
824
  let guardrailClasses = {};
823
825
  if (!Object.prototype.hasOwnProperty.call(declaration, 'guardrailClasses')) {
824
826
  reds.push('declaration: "guardrailClasses" is required (an object keyed by line number; {} is fine)');
@@ -827,7 +829,7 @@ export function validateDeclaration(declaration, context = {}) {
827
829
  for (const key of Object.keys(guardrailClasses)) {
828
830
  const n = Number(key);
829
831
  const line = Number.isInteger(n) ? safeLines.find((l) => l.n === n) : undefined;
830
- if (!line || !line.guardrail) {
832
+ if (!line || (!line.guardrail && !addedLines.has(n))) {
831
833
  reds.push(`declaration: guardrailClasses key "${key}" does not name a signed line with a guardrail`);
832
834
  continue;
833
835
  }
@@ -1032,7 +1034,7 @@ export function validateDeclaration(declaration, context = {}) {
1032
1034
  if (fromLine !== null && typeof fromLine !== 'number') {
1033
1035
  reds.push(`declaration: ${label}.fromLine must be an integer or null`);
1034
1036
  } else {
1035
- const resolved = deriveFromLine(fromLine, safeLines, guardrailClasses);
1037
+ const resolved = deriveFromLine(fromLine, safeLines, guardrailClasses, addedLines);
1036
1038
  if (!resolved.ok) {
1037
1039
  reds.push(`declaration: ${label} ${resolved.error}`);
1038
1040
  } else {
package/src/drafter.js CHANGED
@@ -362,7 +362,7 @@ function isPlainObject(v) { return !!v && typeof v === 'object' && !Array.isArra
362
362
  * @returns {Promise<{ok:boolean, declaration:object|null, reds:string[], rounds:number, calls:number, spendComplete:boolean,
363
363
  * costUsd:number|null, modelReturned:string|null, modelId?:string, price?:object|null, tokens?:object|null, structureRetries:number, revisions:number, stop:string|null, log:object[],
364
364
  * questions?:{line:number, question:string}[], proseText?:string, action?:{line:number, by?:'agent'|'you', dropped?:true}|null, droppedQuestions?:object[], notChecked?:string[], thinking?:{asked:string, status:string|null, say:string|null}, inputs?:{role:string, detail:string}[],
365
- * checkCard?:ReturnType<typeof cardOfPlanBlock>, sheetBuilt?:Awaited<ReturnType<typeof buildSheetChecks>>, notCheckedBy?:Record<string,'you'|'agent'|'default'>, look?:{facts:any[], dropped:any[]}, pageLooks?:{role:string, address:string, sha256:string, bytes:number, frozen:string, attempts:number, mapping:any}[], sheetLooks?:any[]}>}
365
+ * checkCard?:ReturnType<typeof cardOfPlanBlock>, sheetBuilt?:Awaited<ReturnType<typeof buildSheetChecks>>, notCheckedBy?:Record<string,'you'|'agent'|'default'>, look?:{facts:any[], dropped:any[]}, pageLooks?:{role:string, address:string, sha256:string, bytes:number, frozen:string, attempts:number, mapping:any}[], sheetLooks?:any[], box?:string}>}
366
366
  * `learnHints` (M8 item 5a): the earlier runs' notes block (src/learnstore.js hintsForRun), appended to the drafter's system prompt; null = nothing.
367
367
  * `look` / `pageLooks` (M10 item 3) are there when the job signs a web page: the kept facts (with their `reading`, the input a later ask reads), every drop, and per page its address, sha256 and the AI's map. Each drop is also a line in `notChecked`.
368
368
  */
@@ -386,7 +386,7 @@ export async function draft({
386
386
  const status = worstThinkingStatus(log.map((e) => e.thinkingStatus));
387
387
  return { asked: draftThinking, status, say: thinkingSay(status) };
388
388
  };
389
- const fail = (reds, extra = {}) => ({
389
+ const fail = (reds, extra = /** @type {{box?: string}} */ ({})) => ({
390
390
  ok: false, declaration: null, reds, rounds: 0, calls: 0, spendComplete: true, costUsd: 0, modelReturned: null, structureRetries: 0, revisions: 0, stop: 'pre-flight', log: [], ...extra,
391
391
  });
392
392
 
@@ -395,28 +395,29 @@ export async function draft({
395
395
  if (draftThinking !== 'on' && draftThinking !== 'off') return fail([`config: draftThinking must be on | off, got ${JSON.stringify(draftThinking)}`]);
396
396
  if (actionMode !== null && actionMode !== 'check' && actionMode !== 'known') return fail([`config: actionMode must be check | known, got ${JSON.stringify(actionMode)}`]);
397
397
  const parsed = parseSignedText(proseText);
398
- if (!parsed.ok) return fail(parsed.reds.map((r) => `signed-text: ${r}`));
398
+ if (!parsed.ok) return fail(parsed.reds.map((r) => `signed-text: ${r}`), { box: 'job' });
399
399
  const { lines } = parsed;
400
400
  let { arbiter } = parsed;
401
401
  const ttlReds = unsignedAskTtls(arbiter);
402
- if (ttlReds.length) return fail(ttlReds);
402
+ if (ttlReds.length) return fail(ttlReds, { box: 'job' });
403
403
  // M4e amendment 15 item 2: a guardrail that fights itself on words is red at $0, before any provider is built or called.
404
404
  const sumReds = checkGuardrailSums(lines);
405
- if (sumReds.length) return fail(sumReds);
405
+ if (sumReds.length) return fail(sumReds, { box: 'job' });
406
406
  // M10 amendment 14 item 1: a guardrail on the send line is refused at $0 (the card says it first; a prose file straight to `fwdloop draft` is caught here).
407
407
  // M13 am11: with an actionMode the send is the card's tentative one; the refusal is made after the AI says whether the last line is the action (below)
408
408
  const sendReds = actionMode === null ? checkSendLineGuardrail(lines, arbiter) : [];
409
- if (sendReds.length) return fail(sendReds);
409
+ if (sendReds.length) return fail(sendReds, { box: 'job' });
410
410
  const menu = wiredMenu(skills);
411
411
  // The file inputs are read first, at $0, before a provider is built (a page input is fetched only after the price and cap gates, below).
412
412
  const fileFacts = readInputFacts((arbiter.sources ?? []).filter((s) => s.kind !== 'page'));
413
- if (!fileFacts.ok) return fail(fileFacts.reds);
413
+ if (!fileFacts.ok) return fail(fileFacts.reds, { box: 'inputs' });
414
414
  // M13 piece 4: with flow type Tickets, a GitHub issues list is a ticket role, not a page: never fetched at draft; the drafter is told it exists and may suggest a label filter.
415
415
  // The job's flow type and MCP (server + every tool of its newest OK check) come from the card; the refusals are at $0, before any provider is built.
416
416
  const ticketSources = flowType === 'tickets' ? ticketSourcesOf(arbiter.sources) : [];
417
417
  const servers = flowType === 'plain' ? [] : (mcpServers ?? userMcpServers());
418
418
  const flowReds = ticketReds({ flowType, ticketSources, pick: mcp, servers });
419
- if (flowReds.length) return fail(flowReds);
419
+ // M19 am14b: the Tickets list address is an Inputs line; every other flow red is about the picked MCP
420
+ if (flowReds.length) return fail(flowReds, { box: flowType === 'tickets' && ticketSources.length === 0 ? 'inputs' : 'mcp' });
420
421
 
421
422
  let { provider, rates, modelId } = { provider: injected, rates: injectedRates, modelId: injectedModelId };
422
423
  let prices = null; // the one price lookup's result (live provider only); the cap check below uses the SAME price
@@ -426,7 +427,7 @@ export async function draft({
426
427
  provider, rates, modelId, prices = null,
427
428
  } = makeProviderFn(slot, { model, env, ...LIVE_PROVIDER_OPTIONS }));
428
429
  } catch (err) {
429
- return fail([err instanceof ModelRefusal ? err.message : `${err instanceof ConfigError ? 'config' : 'key'}: ${err.message}`]);
430
+ return fail([err instanceof ModelRefusal ? err.message : `${err instanceof ConfigError ? 'config' : 'key'}: ${err.message}`], { box: 'model' });
430
431
  }
431
432
  }
432
433
 
@@ -436,7 +437,7 @@ export async function draft({
436
437
  if (!cat.ok) return fail([`catalogue: ${cat.reds.join('; ')}`]);
437
438
  const validationCatalogue = cat.primitives;
438
439
  // The hold: the picked model's own Settings prices (or the rates a test injected) times the token bounds - never a table.
439
- if (!rates) return fail(['price: this round has no price to hold - tick a model in Settings > Providers with both prices first']);
440
+ if (!rates) return fail(['price: this round has no price to hold - tick a model in Settings > Providers with both prices first'], { box: 'model' });
440
441
  const roundCeiling = ceilingCostUsd(rates);
441
442
  // M4d am13: the draft is capped by the card's Cap $ (the cap signed in the prose), the same number the run is capped at.
442
443
  // One round at its ceiling must fit that cap, or refuse at $0 before any provider call.
@@ -447,7 +448,7 @@ export async function draft({
447
448
  const tooSmall = (ceiling) => (priorUsd > 0
448
449
  ? `Cap ${usdText(arbiter.capUsd)} less ${usdText(priorUsd)} already spent on drafting leaves ${usdText(Math.max(0, budgetUsd))}, below one drafting round's worst case for ${modelId}, $${ceiling.toFixed(4)}. Raise Cap $ or pick another model.`
449
450
  : capTooSmallText('drafting', arbiter.capUsd, ceiling, modelId));
450
- if (roundCeiling > budgetUsd) return fail([tooSmall(roundCeiling)]);
451
+ if (roundCeiling > budgetUsd) return fail([tooSmall(roundCeiling)], { box: 'capUsd' });
451
452
 
452
453
  const meterings = [];
453
454
  const log = [];
@@ -504,7 +505,7 @@ export async function draft({
504
505
  for (let attempt = 1; attempt <= attempts; attempt += 1) {
505
506
  const spentBefore = meterings.reduce((sum, ev) => sum + (ev.costUsd ?? roundCeiling), 0);
506
507
  if (spentBefore + ceilingCostUsd(rates, sys.length + messages.reduce((n, m) => n + m.content.length, 0) + JSON.stringify(spec.schema).length) > budgetUsd) {
507
- if (meterings.length === 0 && calls === 0) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); return { early: fail([tooSmall(roundCeiling)]) }; }
508
+ if (meterings.length === 0 && calls === 0) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); return { early: fail([tooSmall(roundCeiling)], { box: 'capUsd' }) }; }
508
509
  return { early: earlyStop(['the draft budget is spent'], 'budget') };
509
510
  }
510
511
  /** @type {any} */
@@ -638,7 +639,7 @@ export async function draft({
638
639
  const mapCeiling = ceilingCostUsd(rates, mapPrompt({ jobLines: seenLines, label: s.role, text: pg.text }).length + MAP_SYSTEM.length);
639
640
  const spentBefore = meterings.reduce((sum, ev) => sum + (ev.costUsd ?? roundCeiling), 0);
640
641
  if (spentBefore + mapCeiling > budgetUsd) {
641
- if (meterings.length === 0 && calls === 0) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); return fail([tooSmall(mapCeiling)]); }
642
+ if (meterings.length === 0 && calls === 0) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); return fail([tooSmall(mapCeiling)], { box: 'capUsd' }); }
642
643
  }
643
644
  const callModel = makeCallModel('page-map');
644
645
  const got0 = await lookAtPage({ label: s.role, text: pg.text, jobLines: seenLines, callModel });
@@ -698,7 +699,7 @@ export async function draft({
698
699
  const text = headings === undefined ? facts.sheets[role] : '';
699
700
  const spentBefore = meterings.reduce((sum, ev) => sum + (ev.costUsd ?? roundCeiling), 0);
700
701
  const hold = ceilingCostUsd(rates, sheetPrompt({ jobLines: sheetJobLines, label: role, text, headings }).length + MAP_SYSTEM.length);
701
- if (spentBefore + hold > budgetUsd && meterings.length === 0 && calls === 0) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); return fail([tooSmall(hold)]); }
702
+ if (spentBefore + hold > budgetUsd && meterings.length === 0 && calls === 0) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); return fail([tooSmall(hold)], { box: 'capUsd' }); }
702
703
  const got = await lookAtSheet({ label: role, text, headings, jobLines: sheetJobLines, callModel: makeCallModel('sheet-map') });
703
704
  if (!got.ok) {
704
705
  const m = sumMeterings(meterings);
package/src/isrec.js ADDED
@@ -0,0 +1,2 @@
1
+ // one owner for the plain-object predicate (fwd's own files; borrowed copies keep theirs)
2
+ export const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
@@ -5,14 +5,13 @@
5
5
  import { writeFileSync, renameSync } from 'node:fs';
6
6
  import { join } from 'node:path';
7
7
  import { readFileInside } from './flow.js';
8
+ import { isRec } from './isrec.js';
8
9
 
9
10
  /** the record's name in the run's own folder */
10
11
  export const LINE_CHECKS_FILE = 'line-checks.json';
11
12
 
12
13
  /** @typedef {'cited'|'sheet'} LineSection */
13
14
 
14
- const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
15
-
16
15
  /** The whole file as parsed, or why not. @param {string} runDir @returns {{ok: true, rec: Record<string, any>}|{ok: false, missing: boolean, red: string}} */
17
16
  function readWhole(runDir) {
18
17
  const r = readFileInside(runDir, LINE_CHECKS_FILE);
package/src/minrule.js ADDED
@@ -0,0 +1,16 @@
1
+ // M19 amendment 13: a job needs at least one `~` rule of the person's. The ONE writer of the refusal words; the ONE count is the drafter's own reader
2
+ // (parseSignedText) with the block's own splitter (rulesOfLine). `!` and `$` rows are never in the prose, so only typed `~` lines count.
3
+ import { parseSignedText } from './signed-text.js';
4
+ import { rulesOfLine } from './sheetblock.js';
5
+
6
+ export const MIN_RULE_REFUSAL = 'Add at least one rule (~) for this job — for example what the result must include, or what must stay true.';
7
+
8
+ /**
9
+ * @param {string} prose the job prose `fwdloop draft` reads
10
+ * @returns {string|null} the refusal words, or null when the prose carries at least one `~` rule. Prose the reader cannot parse is not this gate's to refuse (the drafter's own red wins).
11
+ */
12
+ export function minRuleRefusal(prose) {
13
+ const p = parseSignedText(prose);
14
+ if (!p.ok) return null;
15
+ return p.lines.reduce((n, l) => n + rulesOfLine(l).length, 0) === 0 ? MIN_RULE_REFUSAL : null;
16
+ }
package/src/model-step.js CHANGED
@@ -33,12 +33,12 @@ import { worstThinkingStatus } from './thinking.js';
33
33
  import { citedBrief, toldPicks } from './citedcheck.js';
34
34
  import { shapeBriefOf, shapeLineBrief } from './rubricstep.js';
35
35
 
36
- const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
37
36
  import { sheetAnswerProps, sheetBrief } from './sheetclaims.js';
38
37
 
39
38
  import {
40
39
  makeProvider, ModelRefusal, sumMeterings, appendSpendRow, classifyModelId, priceRecord,
41
40
  } from './provider.js';
41
+ import { isRec } from './isrec.js';
42
42
 
43
43
  // F27: a provider's `chat/completions` can send HTTP 200 + headers + one byte
44
44
  // then nothing — a "zombie stream" that `timeoutMs`'s idle bound never
@@ -80,6 +80,8 @@ import {
80
80
 
81
81
  const HERE = dirname(fileURLToPath(import.meta.url));
82
82
  const BIN = join(HERE, '..', '..', 'bin', 'fwdloop');
83
+ /** M19 am14b: the prefix of the one log line `bin/fwdloop`'s `refuseDraft` writes (JSON `{box, words}`). */
84
+ const REFUSAL_RECORD = 'fwdloop: refusal-record ';
83
85
 
84
86
  /** A draft id: `d-` + the start time in base 36 (so ids sort oldest to newest) + 4 random hex. */
85
87
  const ID_RE = /^d-[0-9a-z]{10}-[0-9a-f]{4}$/;
@@ -177,13 +179,29 @@ export function createAuthor(opts) {
177
179
  if (first) return { ...base, ...first };
178
180
  // no result yet: the child is the only thing that can still produce one
179
181
  if (running) return { ...base, phase: 'drafting' };
180
- return { ...base, phase: 'stopped', say: logTail(dir, 'child.log', keys) || STOPPED_SAY };
182
+ return { ...base, phase: 'stopped', say: logTail(dir, 'child.log', keys) || STOPPED_SAY, refusal: refusalOf(dir, 'child.log', keys) };
181
183
  }
182
184
 
183
185
  /** The tail of a child's log, scrubbed and without its `fwdloop: ` prefix; '' when there is none. */
184
186
  function logTail(dir, rel, keys) {
185
187
  const logText = readFileInside(dir, rel);
186
- return logText.ok ? scrub(logText.text, keys).trim().slice(-LOG_TAIL_CHARS).replace(/^fwdloop: /, '') : '';
188
+ // the typed refusal record (`refusalOf` reads it) is machine text, never part of what the person is told
189
+ return logText.ok ? scrub(logText.text, keys).split('\n').filter((l) => !l.startsWith(REFUSAL_RECORD)).join('\n').trim().slice(-LOG_TAIL_CHARS).replace(/^fwdloop: /, '') : '';
190
+ }
191
+
192
+ /**
193
+ * M19 am14b: the typed refusal `{box, words}` the child's `refuseDraft` wrote as its last `fwdloop: refusal-record {...}` log line (scrubbed), or null when the child
194
+ * stopped for any other reason. The box is what the refusing check named; the words are never read to find it. `say` stays the whole tail.
195
+ */
196
+ function refusalOf(dir, rel, keys) {
197
+ const log = readFileInside(dir, rel);
198
+ if (!log.ok) return null;
199
+ const lines = scrub(log.text, keys).split('\n').filter((l) => l.startsWith(REFUSAL_RECORD));
200
+ if (lines.length === 0) return null;
201
+ try {
202
+ const r = JSON.parse(lines[lines.length - 1].slice(REFUSAL_RECORD.length));
203
+ return { box: typeof r.box === 'string' ? r.box : null, words: String(r.words) };
204
+ } catch { return null; }
187
205
  }
188
206
 
189
207
  /**
@@ -275,16 +293,17 @@ export function createAuthor(opts) {
275
293
  if (res && res.phase === 'green') return { n, kind, phase: 'green', hash: res.hash, name, lines: scrubbed };
276
294
  if (res) return { n, kind, phase: 'red', reds: res.reds, say: kind === 'answers' ? REDRAFT_RED_SAY : REVISE_RED_SAY, name, lines: scrubbed };
277
295
  if (running) return { n, kind, phase: 'running', name };
278
- return { n, kind, name, phase: 'stopped', say: logTail(dir, `${kind === 'answers' ? 'redraft' : 'revise'}-${n}.log`, keys) || STOPPED_SAY };
296
+ const logRel = `${kind === 'answers' ? 'redraft' : 'revise'}-${n}.log`;
297
+ return { n, kind, name, phase: 'stopped', say: logTail(dir, logRel, keys) || STOPPED_SAY, refusal: refusalOf(dir, logRel, keys) };
279
298
  });
280
- const cur = /** @type {{ phase: string, kind: string, say?: string }} */ (newest > 0 ? revises[revises.length - 1] : { phase: first.phase, kind: 'first' });
299
+ const cur = /** @type {{ phase: string, kind: string, say?: string, refusal?: {box: string|null, words: string} | null }} */ (newest > 0 ? revises[revises.length - 1] : { phase: first.phase, kind: 'first' });
281
300
  // a first plan that asked questions did not end red, it ended by asking (open or answered): its plan-checks line is never the red one (am15 item 3)
282
301
  const firstQs = firstQsRead ?? readQuestions(join(dir, 'draft')); // the first plan's questions, read once per poll
283
302
  const asked = firstQs.questions.length > 0;
284
303
  const shared = { ...base, card, revises, revisesLeft, stepList: asked ? stepListOf(dir, 'draft', keys, true) : (first.stepList ?? null) };
285
304
  const rel = newest > 0 ? `draft-${newest}` : 'draft';
286
305
  if (cur.phase === 'running') return { ...shared, phase: cur.kind === 'answers' ? 'redrafting' : 'revising' };
287
- if (cur.phase === 'stopped') return { ...shared, phase: 'stopped', say: cur.say };
306
+ if (cur.phase === 'stopped') return { ...shared, phase: 'stopped', say: cur.say, refusal: cur.refusal ?? null };
288
307
  const res = newest > 0 ? resultOf(dir, rel, keys) : first;
289
308
  // the plan's questions: any open one makes the phase `questions-open`, whatever colour the plan is (the answers are what it was waiting for)
290
309
  const q = rel === 'draft' ? firstQs : readQuestions(join(dir, rel));
@@ -1253,7 +1253,7 @@
1253
1253
  <div class="jf-gut" id="jf-job-gut" data-testid="jf-job-gut" aria-hidden="true"><div class="jf-gut-in"></div></div>
1254
1254
  <textarea class="jf-wrap" id="jf-job" rows="6" data-testid="jf-job" autocomplete="off" spellcheck="false" placeholder="Read my resume&#10;~keep it under 600 words&#10;Ask: check it with me&#10;Write it out"></textarea>
1255
1255
  </div>
1256
- <div class="hint">One step per line. A line starting with <code>~</code> is a guardrail of the step above it. <code>Ask:</code> stops for you; <code>Ask 2h:</code> sets that ask's own wait. Your last line writes the result to the Destination. Leave it out and fwdloop suggests one.</div>
1256
+ <div class="hint">One step per line. A <code>~</code> line under a step is its rule; add at least one. <code>Ask:</code> stops for you (<code>Ask 2h:</code> waits 2h). The last line writes the result to the Destination.</div>
1257
1257
  <div class="jf-err" id="jf-err-job" data-testid="jf-err-job"></div>
1258
1258
  </div>
1259
1259
  <div class="field">
@@ -1480,6 +1480,8 @@
1480
1480
  <div class="hint" id="chat-action-error" data-testid="chat-action-error"></div>
1481
1481
 
1482
1482
  <button class="btn primary wide" type="button" id="chat-main-btn" data-testid="chat-main" disabled>Draft</button>
1483
+ <!-- M19 am14: POLL-OWNED, written only by renderActions from state.refusal (the words after "draft refused at $0 — "); never by a click handler -->
1484
+ <div class="jf-err" id="chat-draft-refusal" data-testid="chat-draft-refusal"></div>
1483
1485
  <div class="hint" id="chat-main-hint" data-testid="chat-main-hint"></div>
1484
1486
  <!-- M4e amendment 14 item 2: on a green plan, Revise opens every card field (the main button then reads Draft) -->
1485
1487
  <button class="btn wide" type="button" id="chat-revise-btn" data-testid="chat-revise" hidden>Revise</button>
@@ -5814,6 +5816,7 @@
5814
5816
  var startOverBtn = document.getElementById("chat-startover-btn");
5815
5817
  var reviseBtn = document.getElementById("chat-revise-btn");
5816
5818
  var errEl = document.getElementById("chat-card-error"); // POLL-OWNED: the draft's own sentence (red / stopped)
5819
+ var refusalEl = document.getElementById("chat-draft-refusal"); // POLL-OWNED: the pointer to a refusal under a box, or the words of one with no box (M19 am14b)
5817
5820
  var actionErrEl = document.getElementById("chat-action-error"); // ACTION-OWNED: only a click's refusal; the poll never wipes it
5818
5821
  var progressRow = document.getElementById("chat-progress-row");
5819
5822
  var questionBox = document.getElementById("chat-question");
@@ -6436,7 +6439,8 @@
6436
6439
 
6437
6440
  // ---- a refusal shows next to its box ----
6438
6441
  function clearFieldErrors(){
6439
- card.querySelectorAll(".jf-err").forEach(function(e){ e.textContent = ""; });
6442
+ // the painted refusal's box line belongs to paintRefusal / clearRefusal (the one writer): a late flows answer repaints the Run form and must not wipe it
6443
+ card.querySelectorAll(".jf-err").forEach(function(e){ if(e !== refusalBoxEl) e.textContent = ""; });
6440
6444
  }
6441
6445
  function errElFor(field){
6442
6446
  var m = /^inputs\.(\d+)$/.exec(field);
@@ -7051,9 +7055,28 @@
7051
7055
  function syncJobBoxFromSession(state){
7052
7056
  var jt = state && state.card && state.card.job;
7053
7057
  var box = document.getElementById("jf-job");
7054
- if(!sessionLive || reviseOpen || typeof jt !== "string" || jt === box.value) return;
7058
+ // F259: a red or stopped draft has left the boxes to the person (the card is open to fix and draft again); the poll never writes them back
7059
+ if(!sessionLive || reviseOpen || state.phase === "stopped" || state.phase === "red" || typeof jt !== "string" || jt === box.value) return;
7055
7060
  setVal("jf-job", jt); fitCardBoxes();
7056
7061
  }
7062
+ // M19 am14b: the ONE writer of a draft refusal's lines. The box error is painted once per refusal (so a poll never brings back a line the person cleared by pressing Draft).
7063
+ var REFUSAL_POINTER = "Not drafted: fix the red line above.";
7064
+ var refusalKey = ""; // which refusal is painted
7065
+ var refusalBoxEl = null; // the box error line it was painted into (null: none)
7066
+ function clearRefusal(){
7067
+ if(refusalBoxEl) refusalBoxEl.textContent = "";
7068
+ refusalBoxEl = null; refusalKey = ""; refusalEl.textContent = "";
7069
+ }
7070
+ function paintRefusal(state, r){
7071
+ var key = r ? String(state.draftId) + "|" + r.box + "|" + r.words : "";
7072
+ if(key === refusalKey) return;
7073
+ clearRefusal();
7074
+ refusalKey = key;
7075
+ if(!r) return;
7076
+ var boxEl = r.box ? errElFor(r.box) : null;
7077
+ if(boxEl){ boxEl.textContent = r.words; refusalBoxEl = boxEl; refusalEl.textContent = REFUSAL_POINTER; }
7078
+ else refusalEl.textContent = r.words;
7079
+ }
7057
7080
  function renderActions(state){
7058
7081
  lastState = state;
7059
7082
  renderQuestion(state);
@@ -7062,7 +7085,11 @@
7062
7085
  if(signInfo && state.hash && state.hash !== signInfo.hash){ signInfo = null; signClickedOnce = false; }
7063
7086
  // #chat-card-error is POLL-OWNED: it carries only the draft's own sentence (a red plan or a stopped child), written here and
7064
7087
  // nowhere else. A refused click goes to #chat-action-error, which this function never touches.
7065
- errEl.textContent = ((state.phase === "red" || state.phase === "stopped") && state.say) ? state.say : "";
7088
+ // M19 am14b: a draft refused at $0 shows its words under the box it is about (red, like "required") with one pointer by the Draft button; a refusal with no box shows
7089
+ // its words under the button. No grey copy: the grey card line carries every other sentence (a red plan from the AI keeps its own).
7090
+ var refusal = (state.phase === "stopped" && state.refusal && typeof state.refusal === "object") ? state.refusal : null;
7091
+ paintRefusal(state, refusal);
7092
+ errEl.textContent = (!refusal && (state.phase === "red" || state.phase === "stopped") && state.say) ? state.say : "";
7066
7093
  var progressChanged = renderProgress(stepsFor(state, {model: drafterModel, starting: startId !== null, signClicked: signClickedOnce}));
7067
7094
  sessionLive = CLIENT_TERMINAL_PHASES.indexOf(state.phase) === -1;
7068
7095
  refreshStartEnabled();
@@ -7086,6 +7113,7 @@
7086
7113
  threadKey = ""; thread.innerHTML = "";
7087
7114
  renderQuestion(null); renderExtras(null);
7088
7115
  errEl.textContent = "";
7116
+ clearRefusal();
7089
7117
  progressRow.hidden = true; progressRow.innerHTML = ""; progressHtml = "";
7090
7118
  refreshStartEnabled();
7091
7119
  }
@@ -7093,6 +7121,7 @@
7093
7121
  thread.innerHTML = ""; threadKey = "";
7094
7122
  renderQuestion(null); renderExtras(null);
7095
7123
  errEl.textContent = "";
7124
+ clearRefusal();
7096
7125
  actionErrEl.textContent = "";
7097
7126
  clearFieldErrors();
7098
7127
  stopStart();
@@ -7230,6 +7259,7 @@
7230
7259
  }).catch(function(){ qBusy = false; qSend.disabled = false; qAgree.disabled = false; qDrop.disabled = false; qColumn.disabled = false; qError.textContent = NETWORK_SAY; });
7231
7260
  }
7232
7261
  function doDraft(startedOverFrom){
7262
+ clearRefusal();
7233
7263
  clearFieldErrors();
7234
7264
  chatActionOk();
7235
7265
  // disabled from the click until the reply; unlocked below only if the draft is refused
package/src/report.js CHANGED
@@ -7,7 +7,8 @@
7
7
  import { lstatSync } from 'node:fs';
8
8
  import { join } from 'node:path';
9
9
  import { sheetCheckSentence } from './sheetchecks.js';
10
- import { sheetTotalLines, ROW_MATH_OPS, isRec } from './sheetclaims.js';
10
+ import { sheetTotalLines, ROW_MATH_OPS } from './sheetclaims.js';
11
+ import { isRec } from './isrec.js';
11
12
  import { lineRules } from './pagebits.js';
12
13
  import { shapeResultModel, shapeMarkdown } from './shaperesult.js';
13
14
 
@@ -3,8 +3,7 @@
3
3
  // Shape: { lines: [ { n, try, passed, tables: [{name, tableSha}], checks: [the signed check objects], claims: <the step's answer>, results: [{id, text, ok, result}], red } ] }.
4
4
  // `tables[].tableSha` is the one recorded at the run's start (run.json), the one the check used. Throws away: nothing the check saw; no cell text is kept here.
5
5
  import { readLineSection, writeLineSection } from './line-checks.js';
6
-
7
- const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
6
+ import { isRec } from './isrec.js';
8
7
 
9
8
  /**
10
9
  * @param {string} runDir @param {{n: number, try: number, checks: any[], closed: {verdict: string, red?: string|null, sheetRecord?: any}}} o
package/src/sheetblock.js CHANGED
@@ -14,8 +14,7 @@ import { lineRules } from './pagebits.js';
14
14
  import { sheetCheckSentence } from './sheetchecks.js';
15
15
  import { isColumnChoiceRule } from './sheetoffer.js';
16
16
  import { NO_VALUE_WHY } from './ticketrows.js';
17
-
18
- const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
17
+ import { isRec } from './isrec.js';
19
18
 
20
19
  /** the short plain name of each bareguard op (the ONE table; a test fails when bareguard gains an op this table does not name). `noDuplicates` and `noEmpty` add the column. */
21
20
  export const SHEET_OP_NAMES = Object.freeze({
@@ -11,14 +11,13 @@
11
11
 
12
12
  import { checkTables, tableSha, groundedLiterals, rubricVocabulary } from 'bareguard';
13
13
  import { wordsSaidOn, lineRules } from './pagebits.js';
14
+ import { isRec } from './isrec.js';
14
15
 
15
16
  /** the bareguard rules a sheet check may use (`diff` is out of scope for M10b) */
16
17
  export const SHEET_RULES = Object.freeze(['cells', 'table']);
17
18
  /** most checks one step may carry */
18
19
  export const MAX_SHEET_CHECKS = 20;
19
20
 
20
- const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
21
-
22
21
  const V = /** @type {any} */ (rubricVocabulary);
23
22
 
24
23
  /**
@@ -5,8 +5,7 @@
5
5
  // Throws away: a check with no claim (a `table` check judges the sheet itself) adds no box; two checks with the same claim name share one box.
6
6
  import { rubricVocabulary, claimSchema } from 'bareguard';
7
7
  import { bareguardChecks } from './sheetchecks.js';
8
-
9
- export const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
8
+ import { isRec } from './isrec.js';
10
9
 
11
10
  /**
12
11
  * The claim box of every `cells` check in the list: `[{claim, example}]`, one per claim name, in order. `example` is the op's worked-example answer (the box's shape
package/src/sheetoffer.js CHANGED
@@ -10,9 +10,9 @@
10
10
  import { rubricVocabulary, checkSchema } from 'bareguard';
11
11
  import { SHEET_RULES, MAX_SHEET_CHECKS } from './sheetchecks.js';
12
12
  import { columnRuleWords } from './sheetlook.js';
13
+ import { isRec } from './isrec.js';
13
14
 
14
15
  const V = /** @type {any} */ (rubricVocabulary);
15
- const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
16
16
 
17
17
  /** The comparisons of a `where` condition, as bareguard's vocabulary lists them. */
18
18
  export const WHERE_CMPS = Object.freeze([...V.rules.cells.fields.where.cmps]);
package/src/sheetrun.js CHANGED
@@ -12,8 +12,7 @@ import { readFileInside } from './flow.js';
12
12
  import { readRunInputs } from './runfile.js';
13
13
  import { sheetCheckSentence, bareguardChecks } from './sheetchecks.js';
14
14
  import { sheetCheckName, sheetFoundWords } from './sheetblock.js';
15
-
16
- const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
15
+ import { isRec } from './isrec.js';
17
16
 
18
17
  /** The sheet inputs any step's `close.sheet` reads, once each, in order. @param {any[]} steps @returns {string[]} */
19
18
  export function sheetRolesOf(steps) {
package/src/ticketrows.js CHANGED
@@ -4,8 +4,7 @@
4
4
  // its signed fields, its card words and its proof. A job with no ticket rows (a plan signed before M17) is not examined: its filter and watch run exactly as signed.
5
5
  // What this throws away: the filter's and watch's values (they stay in the declaration); a row keeps its line, rule number, tag, state and reason.
6
6
  import { checkTicketFilter, checkTicketWatch, isCountGuardrail } from './declaration.js';
7
-
8
- const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
7
+ import { isRec } from './isrec.js';
9
8
 
10
9
  /** @type {readonly ('ticketFilter'|'ticketWatch')[]} */
11
10
  export const TICKET_FIELDS = Object.freeze(['ticketFilter', 'ticketWatch']);
@@ -167,6 +167,7 @@ export function draftToDir({ proseFile, dir, root, name, slot, model, draftThink
167
167
  wrote: boolean;
168
168
  reds: any;
169
169
  costUsd: number;
170
+ box: string | null;
170
171
  } | {
171
172
  ok: boolean;
172
173
  wrote: boolean;
@@ -47,4 +47,3 @@ export const ASK_LINE_REASON: "you judge it at the Ask";
47
47
  * @type {'green'|null}
48
48
  */
49
49
  export const SHAPE_ONLY_CLASS: "green" | null;
50
- export { NO_GUARDRAIL_WORDS } from "./checkblock.js";
@@ -31,7 +31,6 @@ export function choiceEntries(lines: {
31
31
  /** what `setSheet` is given: code's build of a job's sheet checks, per sheet line @typedef {Awaited<ReturnType<typeof import('./sheetbuild.js').buildSheetChecks>>} SheetBuilt */
32
32
  /** the four row edits an AI reply may hold */
33
33
  export const EDIT_OPS: readonly string[];
34
- export const NO_GUARDRAIL_WORDS: "This line has no guardrail of yours, so a check on it cannot be signed; you judge it at Accept.";
35
34
  /** the plain reasons code gives, in one place (the card, the Job tab and the Audit read them from the row) */
36
35
  export const REASON: Readonly<{
37
36
  left: "You chose to leave it Not checked, so you judge it at Accept.";
@@ -284,7 +283,7 @@ export class CheckBlock {
284
283
  buildLine(l: {
285
284
  n: number;
286
285
  text: string;
287
- }, lineParts: any[], lineRows: string[][], factLines: Set<number>, offer?: boolean): void;
286
+ }, lineParts: any[], lineRows: string[][], factLines: Set<number>): void;
288
287
  /**
289
288
  * S4: ONE sheet part per sheet line, from the checks code built (the `[you]` rule rows' checks, then the `[agent]` checks the person has not dropped). Every row it carries points at it. A part code cannot legally build leaves its rows Not checked
290
289
  * in the stage-shape red's own words; a line whose checks were all dropped has no part and no `[default]` row.
@@ -311,7 +311,7 @@ export function goalForLine(fromLine: any, lines: any): any;
311
311
  * @returns {Promise<{ok:boolean, declaration:object|null, reds:string[], rounds:number, calls:number, spendComplete:boolean,
312
312
  * costUsd:number|null, modelReturned:string|null, modelId?:string, price?:object|null, tokens?:object|null, structureRetries:number, revisions:number, stop:string|null, log:object[],
313
313
  * questions?:{line:number, question:string}[], proseText?:string, action?:{line:number, by?:'agent'|'you', dropped?:true}|null, droppedQuestions?:object[], notChecked?:string[], thinking?:{asked:string, status:string|null, say:string|null}, inputs?:{role:string, detail:string}[],
314
- * checkCard?:ReturnType<typeof cardOfPlanBlock>, sheetBuilt?:Awaited<ReturnType<typeof buildSheetChecks>>, notCheckedBy?:Record<string,'you'|'agent'|'default'>, look?:{facts:any[], dropped:any[]}, pageLooks?:{role:string, address:string, sha256:string, bytes:number, frozen:string, attempts:number, mapping:any}[], sheetLooks?:any[]}>}
314
+ * checkCard?:ReturnType<typeof cardOfPlanBlock>, sheetBuilt?:Awaited<ReturnType<typeof buildSheetChecks>>, notCheckedBy?:Record<string,'you'|'agent'|'default'>, look?:{facts:any[], dropped:any[]}, pageLooks?:{role:string, address:string, sha256:string, bytes:number, frozen:string, attempts:number, mapping:any}[], sheetLooks?:any[], box?:string}>}
315
315
  * `learnHints` (M8 item 5a): the earlier runs' notes block (src/learnstore.js hintsForRun), appended to the drafter's system prompt; null = nothing.
316
316
  * `look` / `pageLooks` (M10 item 3) are there when the job signs a web page: the kept facts (with their `reading`, the input a later ask reads), every drop, and per page its address, sha256 and the AI's map. Each drop is also a line in `notChecked`.
317
317
  */
@@ -421,6 +421,7 @@ export function draft({ proseText, slot, model, provider: injected, rates: injec
421
421
  mapping: any;
422
422
  }[];
423
423
  sheetLooks?: any[];
424
+ box?: string;
424
425
  }>;
425
426
  export const MAX_STRUCTURE_RETRIES: 2;
426
427
  export const MAX_REVISIONS: 2;
@@ -0,0 +1 @@
1
+ export function isRec(v: unknown): boolean;
@@ -0,0 +1,6 @@
1
+ /**
2
+ * @param {string} prose the job prose `fwdloop draft` reads
3
+ * @returns {string|null} the refusal words, or null when the prose carries at least one `~` rule. Prose the reader cannot parse is not this gate's to refuse (the drafter's own red wins).
4
+ */
5
+ export function minRuleRefusal(prose: string): string | null;
6
+ export const MIN_RULE_REFUSAL: "Add at least one rule (~) for this job \u2014 for example what the result must include, or what must stay true.";
@@ -39,5 +39,4 @@ export function sheetTotalLines(checks: any[], claims: any, tables: Record<strin
39
39
  cells: string[];
40
40
  }[];
41
41
  }>): string[];
42
- export function isRec(v: unknown): boolean;
43
42
  export const ROW_MATH_OPS: readonly string[];