fwdloop 0.28.0 → 0.30.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 (74) hide show
  1. package/README.md +1 -1
  2. package/bin/fwdloop +27 -5
  3. package/package.json +3 -3
  4. package/src/added-end.js +60 -0
  5. package/src/ask.js +1 -1
  6. package/src/audit-fold.js +9 -1
  7. package/src/authoring.js +18 -7
  8. package/src/checked.js +14 -9
  9. package/src/checkpick.js +318 -0
  10. package/src/checkwords.js +29 -0
  11. package/src/citedcheck.js +14 -0
  12. package/src/closers.js +40 -3
  13. package/src/declaration.js +102 -5
  14. package/src/draft-steps.js +3 -3
  15. package/src/drafter.js +151 -38
  16. package/src/jobkey.js +3 -1
  17. package/src/learn.js +1 -1
  18. package/src/learnstore.js +6 -6
  19. package/src/memo.js +120 -0
  20. package/src/model-step.js +103 -25
  21. package/src/pageask.js +12 -6
  22. package/src/pagedropwords.js +9 -0
  23. package/src/panel/author.js +33 -10
  24. package/src/panel/authorcard.js +59 -6
  25. package/src/panel/data.js +16 -10
  26. package/src/panel/index.html +151 -59
  27. package/src/panel/result.js +28 -7
  28. package/src/panel/server.js +2 -1
  29. package/src/pickrecord.js +146 -0
  30. package/src/plain-checks.js +16 -3
  31. package/src/provider.js +4 -1
  32. package/src/repairs.js +38 -0
  33. package/src/runfile.js +4 -2
  34. package/src/runner.js +129 -40
  35. package/src/send.js +71 -4
  36. package/src/setup.js +13 -1
  37. package/src/sheetblock.js +2 -1
  38. package/src/ticket-draft.js +2 -2
  39. package/src/ticket-labels.js +2 -2
  40. package/src/try-checks.js +13 -3
  41. package/src/whole-job.js +71 -0
  42. package/types/added-end.d.ts +62 -0
  43. package/types/ask.d.ts +2 -1
  44. package/types/audit-fold.d.ts +13 -2
  45. package/types/authoring.d.ts +6 -2
  46. package/types/checked.d.ts +7 -2
  47. package/types/checkpick.d.ts +183 -0
  48. package/types/checkwords.d.ts +18 -0
  49. package/types/citedcheck.d.ts +6 -0
  50. package/types/closers.d.ts +6 -3
  51. package/types/declaration.d.ts +12 -0
  52. package/types/drafter.d.ts +28 -25
  53. package/types/learn.d.ts +1 -0
  54. package/types/learnstore.d.ts +2 -3
  55. package/types/memo.d.ts +15 -0
  56. package/types/model-step.d.ts +23 -3
  57. package/types/pageask.d.ts +9 -2
  58. package/types/pagedropwords.d.ts +1 -0
  59. package/types/panel/author.d.ts +1 -1
  60. package/types/panel/authorcard.d.ts +41 -0
  61. package/types/panel/data.d.ts +1 -1
  62. package/types/panel/jobgrid.d.ts +1 -1
  63. package/types/panel/result.d.ts +9 -3
  64. package/types/pickrecord.d.ts +88 -0
  65. package/types/plain-checks.d.ts +9 -1
  66. package/types/repairs.d.ts +13 -0
  67. package/types/runfile.d.ts +7 -2
  68. package/types/runner.d.ts +16 -5
  69. package/types/send.d.ts +10 -2
  70. package/types/setup.d.ts +1 -56
  71. package/types/try-checks.d.ts +1 -7
  72. package/types/whole-job.d.ts +70 -0
  73. package/src/attemptdiff.js +0 -118
  74. package/types/attemptdiff.d.ts +0 -38
@@ -644,7 +644,8 @@ export function handleRequest(req, res, opts) {
644
644
  res.writeHead(200, {
645
645
  'content-type': `${got.type}; charset=utf-8`,
646
646
  'content-length': got.buf.length,
647
- 'content-disposition': `attachment; filename="${plain}"; filename*=UTF-8''${encodeURIComponent(got.name)}`,
647
+ // M15 item 5: `?view=1` (the top card's file link) opens the saved file in the tab; its type is text/plain or a download type, nosniff stays
648
+ 'content-disposition': `${url.searchParams.get('view') === '1' && /^(text\/plain|text\/csv|application\/json)$/.test(got.type) ? 'inline' : 'attachment'}; filename="${plain}"; filename*=UTF-8''${encodeURIComponent(got.name)}`,
648
649
  'x-content-type-options': 'nosniff',
649
650
  });
650
651
  if (method === 'HEAD') res.end(); else res.end(got.buf);
@@ -0,0 +1,146 @@
1
+ // M10 am17 + am18: the ONE record of check picks, carried from plan to plan. A pick is tied to its job line's WORDS (plus its order among lines with the same words)
2
+ // and to its guardrail's exact words, never to a line or rule number: both are recomputed on the new card. This file is the only writer of a record's entries
3
+ // (`entriesFromAnswers`) and the only reader that decides keep-or-ask (`matchRecord`); the logic is the one F146 / F146b proved (poc/m10-am17/keep-picks-am18.mjs).
4
+ // Throws away: line and rule numbers (recomputed), the model's words (it never sees a pick), a pick whose line or guardrail words no longer match.
5
+ import path from 'node:path';
6
+ import { readFileInside } from './flow.js';
7
+
8
+ /** the record's file, inside a drafting folder only (never a run folder) */
9
+ export const RECORD_FILE = 'picks-record.json';
10
+ /** the exact words a kept pick is marked with in the draft log, the Audit and the plan card (M10 am17 (6)) */
11
+ export const KEPT_WORDS = 'kept from last draft';
12
+
13
+ /** @typedef {{lineWords: string, occurrence: number, ruleText: string, added: string|null, check: Record<string, any>|null, own: boolean, left: boolean}} Entry */
14
+ /** @typedef {{line: number, rule: number, text: string}} Rule */
15
+
16
+ const norm = (/** @type {unknown} */ t) => String(t).toLowerCase().replace(/\s+/g, ' ').trim();
17
+ /** @param {unknown} a @param {unknown} b the two texts are the same words (case and spacing aside) */
18
+ export const sameWords = (a, b) => norm(a) === norm(b);
19
+ const id = (/** @type {Rule} */ r) => `${r.line}:${r.rule}`;
20
+
21
+ /**
22
+ * The key of every job line: its own words, plus how many lines before it have the same words (equal lines match in their order).
23
+ * @param {{n: number, text: string}[]} lines @returns {Map<number, {lineWords: string, occurrence: number}>}
24
+ */
25
+ export function lineKeys(lines) {
26
+ /** @type {Map<string, number>} */
27
+ const seen = new Map();
28
+ return new Map(lines.map((l) => {
29
+ const w = norm(l.text);
30
+ const occurrence = seen.get(w) ?? 0;
31
+ seen.set(w, occurrence + 1);
32
+ return [l.n, { lineWords: w, occurrence }];
33
+ }));
34
+ }
35
+
36
+ /**
37
+ * The entries for answers just given, numbered on THIS card (the answer redraft's card: its line and rule numbers are the ones the asks carried).
38
+ * @param {{n: number, text: string}[]} lines @param {Rule[]} rules
39
+ * @param {{line: number, rule: number, check?: Record<string, any>|null, added?: string|null, own?: boolean}[]} picks @param {{line: number, rule: number}[]} left
40
+ * @returns {Entry[]}
41
+ */
42
+ export function entriesFromAnswers(lines, rules, picks, left) {
43
+ const keys = lineKeys(lines);
44
+ /** @param {number} line @param {number} rule */
45
+ const base = (line, rule) => {
46
+ const r = rules.find((x) => x.line === line && x.rule === rule);
47
+ const k = keys.get(line);
48
+ return r === undefined || k === undefined ? null : { ...k, ruleText: r.text };
49
+ };
50
+ /** @type {Entry[]} */
51
+ const out = [];
52
+ for (const p of picks) {
53
+ const b = base(p.line, p.rule);
54
+ if (b) out.push({ ...b, added: typeof p.added === 'string' ? p.added : null, check: p.check ?? null, own: p.own === true, left: false });
55
+ }
56
+ for (const l of left) {
57
+ const b = base(l.line, l.rule);
58
+ if (b) out.push({ ...b, added: null, check: null, own: false, left: true });
59
+ }
60
+ return out;
61
+ }
62
+
63
+ /**
64
+ * Decide, for the card in hand, which stored picks are kept and which guardrails must be asked.
65
+ * A pick is KEPT when the job line with its words (same order among equal lines) still has its source guardrail with the exact words and, if the pick wrote a `~` line,
66
+ * that line with its exact words too. Otherwise the pick is dropped (never partly kept) and its guardrails are asked: a pair broken on one side is ONE ask, so the
67
+ * partner left on the card is folded (neither asked nor given the old check) - except an EDITED added line (M10 am21): that one is asked (`pairRule` = its source's number) and the source is folded. Pure.
68
+ * @param {Entry[]} entries @param {{n: number, text: string}[]} lines @param {Rule[]} rules every guardrail the call settles
69
+ * @returns {{picks: {line: number, rule: number, check: Record<string, any>|null, added?: string, own?: boolean}[], left: {line: number, rule: number}[],
70
+ * kept: {line: number, rule: number, entry: Entry}[], askRules: (Rule & {pairRule?: number})[]}}
71
+ */
72
+ export function matchRecord(entries, lines, rules) {
73
+ const byKey = new Map([...lineKeys(lines)].map(([n, k]) => [`${k.lineWords}#${k.occurrence}`, n]));
74
+ /** @type {Set<string>} */
75
+ const claimed = new Set();
76
+ /** @type {Set<string>} */
77
+ const folded = new Set();
78
+ /** @type {Map<string, number>} an edited added line (by id) -> the rule number of the source it was paired with (M10 am21) */
79
+ const edited = new Map();
80
+ const free = (/** @type {number} */ n, /** @type {string} */ text) => rules.find((r) => r.line === n && !claimed.has(id(r)) && !folded.has(id(r)) && norm(r.text) === norm(text));
81
+ const kept = [];
82
+ /** @type {{e: Entry, n: number|undefined}[]} */
83
+ const broken = [];
84
+ for (const e of Array.isArray(entries) ? entries : []) {
85
+ const n = byKey.get(`${e.lineWords}#${e.occurrence}`);
86
+ const src = n === undefined ? undefined : free(n, e.ruleText);
87
+ if (src) claimed.add(id(src)); // held while the partner is looked for, so a pair never takes one rule twice
88
+ const add = n === undefined || !src || e.added === null ? undefined : free(n, e.added);
89
+ if (n !== undefined && src && (e.added === null || add)) {
90
+ if (add) claimed.add(id(add));
91
+ kept.push({ line: n, rule: src.rule, entry: e });
92
+ } else {
93
+ if (src) claimed.delete(id(src));
94
+ broken.push({ e, n });
95
+ }
96
+ }
97
+ // a pair broken on one side is ONE pick, so ONE ask: the partner that is left folds into it (it keeps no old check and is not asked on its own)
98
+ for (const { e, n } of broken) {
99
+ if (e.added === null) continue;
100
+ if (n === undefined) {
101
+ // the line's own words changed: it is a new line, all its guardrails are asked; its old `~` line with its source still there rides the source's ask
102
+ for (const l of lines) {
103
+ const s = free(l.n, e.ruleText);
104
+ const a = s ? rules.find((r) => r.line === l.n && r !== s && !claimed.has(id(r)) && !folded.has(id(r)) && norm(r.text) === norm(e.added ?? '')) : undefined;
105
+ if (a) { folded.add(id(a)); break; }
106
+ }
107
+ continue;
108
+ }
109
+ const src = free(n, e.ruleText);
110
+ const add = free(n, e.added);
111
+ if (src && !add) {
112
+ // the added line was edited (or deleted): the unclaimed rule right after the source on that line is it. M10 am21: the ONE ask is about THAT line's words
113
+ // (it carries the source's number as `pairRule`, the rule its pick is kept under); the source rides it and is not asked on its own
114
+ const p = rules.find((r) => r.line === n && r.rule > src.rule && !claimed.has(id(r)) && !folded.has(id(r)));
115
+ if (p) { folded.add(id(src)); edited.set(id(p), src.rule); }
116
+ } else if (add && !src) {
117
+ // the source was edited: the unclaimed rule right before the added line is it; the old added line rides that ask
118
+ const p = [...rules].reverse().find((r) => r.line === n && r.rule < add.rule && !claimed.has(id(r)) && !folded.has(id(r)));
119
+ if (p) folded.add(id(add));
120
+ }
121
+ }
122
+ const picks = [];
123
+ const left = [];
124
+ for (const k of kept) {
125
+ const e = k.entry;
126
+ if (e.left) left.push({ line: k.line, rule: k.rule });
127
+ else picks.push({ line: k.line, rule: k.rule, check: e.check, ...(e.added === null ? {} : { added: e.added }), ...(e.own ? { own: true } : {}) });
128
+ }
129
+ return { picks, left, kept, askRules: rules.filter((r) => !claimed.has(id(r)) && !folded.has(id(r))).map((r) => (edited.has(id(r)) ? { ...r, pairRule: edited.get(id(r)) } : r)) };
130
+ }
131
+
132
+ /**
133
+ * Read a carried record (the folder's file). A missing or unreadable file is no record (a plan from before am17 has none).
134
+ * @param {string} file @returns {Entry[]|null}
135
+ */
136
+ export function readRecordFile(file) {
137
+ try {
138
+ const g = readFileInside(path.dirname(file), path.basename(file));
139
+ if (!g.ok) return null;
140
+ const j = JSON.parse(g.text);
141
+ return Array.isArray(j?.picks) ? j.picks.filter((/** @type {any} */ e) => e && typeof e.lineWords === 'string' && Number.isInteger(e.occurrence) && typeof e.ruleText === 'string') : null;
142
+ } catch { return null; }
143
+ }
144
+
145
+ /** where a plan folder keeps its record @param {string} planDir */
146
+ export const recordPath = (planDir) => path.join(planDir, RECORD_FILE);
@@ -6,7 +6,7 @@
6
6
  // change (the job line, the guardrail, the inputs, the destination) or to Draft again when it is the AI's own form error; every rule has one (am15 item 3).
7
7
  // The first two rules' `say` already ends with their fix, as the page has always shown them.
8
8
 
9
- /** @type {ReadonlyArray<{re: RegExp, say: string|null, fix: string}>} `say` null = the checker's own sentence, as it is without its "declaration: " prefix */
9
+ /** @type {ReadonlyArray<{re: RegExp, say: string|null, fix: string, first?: boolean}>} `say` null = the checker's own sentence, as it is without its "declaration: " prefix */
10
10
  export const PLAN_CHECK_RULES = Object.freeze([
11
11
  { re: /which is not in the job line's words/, say: "A section name in the plan's check is not in your job line. Change the job line to use the section words you want.", fix: 'Change the job line to use the section words you want.' },
12
12
  { re: /the job line says .*; the check says/, say: "The sections in the plan's check come in a different order than your job line. Change the job line to change the order.", fix: 'Change the job line to change the order.' },
@@ -21,6 +21,8 @@ export const PLAN_CHECK_RULES = Object.freeze([
21
21
  { re: /not in the catalogue|not wired|which is not signed|checkpoint/, say: 'A step uses a tool that is not available for this job.', fix: 'Draft again; if it repeats, say in the job line what that step should do.' },
22
22
  { re: /reads artifact|is a duplicate|\.reads must|\.emits must/, say: 'The steps do not pass their results to each other in a workable order.', fix: 'Draft again.' },
23
23
  { re: /ask at line \d+|signed ask at line|ask slot/, say: 'The ask on one of your lines is not set up as a plain stop where you decide.', fix: 'Check the line that starts with Ask in your job, then Draft again.' },
24
+ // M4d am38 item 1: `first: true` = this red is the one explained whenever it is among the reds (pickPlanRed), not only when it comes first.
25
+ { re: /send at line \d+ .* is not granted a catalogue primitive of class "write"/, say: 'Your last line sends to your Destination, but your job puts other work on it. Make your last line the one that sends, or move that work above it, then Draft again.', fix: 'Make your last line the one that sends, or move that work above it, then Draft again.', first: true },
24
26
  { re: /send at line \d+|signed send at line|send slot/, say: 'The send step is not set up to follow your accept and write only to your destination.', fix: 'Check the Destination on the card, then Draft again.' },
25
27
  { re: /hitl after the last signed ask/, say: 'A step after your last ask would leave without your seeing it, so it is refused.', fix: 'Move the lines you want to check before your last Ask line, then Draft again.' },
26
28
  { re: /is a pause .* unsigned line/, say: 'A step pauses at a line you did not sign as an ask.', fix: 'Mark the line you want to stop at with Ask, then Draft again.' },
@@ -28,14 +30,25 @@ export const PLAN_CHECK_RULES = Object.freeze([
28
30
  { re: /picks|inputFacts|invented name/, say: 'The plan names a field that is not in your input.', fix: 'Check the names in your Inputs and job line, then Draft again.' },
29
31
  { re: /guardrailClasses|unjudgeable|refused/, say: "The AI's notes on which lines it can check are not in a form the checker accepts.", fix: 'Draft again.' },
30
32
  { re: /^line \d+'s (guardrail|check)|can't write files/, say: null, fix: 'Change the guardrail on that line the way the sentence says, then Draft again.' },
33
+ { re: /^Input ".+" is read by no step\.$/, say: null, fix: 'Draft again.' },
31
34
  { re: /must be an? |is required|must name|does not name/, say: 'The plan the AI wrote is not in the shape the checker needs.', fix: 'Draft again.' },
32
35
  ]);
33
36
 
34
37
  export const GENERIC_SAY = 'One of the checks on the plan failed.';
35
38
  export const GENERIC_FIX = 'Draft again.';
36
39
 
37
- /** The rules as the page takes them: JSON, the regex as its source text. */
38
- export const pageRules = () => PLAN_CHECK_RULES.map((r) => ({ re: r.re.source, say: r.say }));
40
+ /** The rules as the page takes them: JSON, the regex as its source text. `first` rides along so a page that picks a red reads the same rule data. */
41
+ export const pageRules = () => PLAN_CHECK_RULES.map((r) => ({ re: r.re.source, say: r.say, ...(r.first === true ? { first: true } : {}) }));
42
+
43
+ /**
44
+ * M4d amendment 38 item 1: the ONE decision of which red is explained: the first red a `first` rule matches, else the first red (am15 item 3).
45
+ * @param {ReadonlyArray<string>} reds
46
+ * @returns {string|undefined}
47
+ */
48
+ export function pickPlanRed(reds) {
49
+ const list = Array.isArray(reds) ? reds : [];
50
+ return list.find((t) => PLAN_CHECK_RULES.some((r) => r.first === true && r.re.test(String(t)))) ?? list[0];
51
+ }
39
52
 
40
53
  /**
41
54
  * @param {unknown} raw one raw refusal text
package/src/provider.js CHANGED
@@ -41,7 +41,7 @@ import { OpenAI, Anthropic, Gemini } from 'bare-agent/providers';
41
41
  * marker on the instance (`this.lastMalformedToolCall`, reset at the top of
42
42
  * every `generate()` call) — the one channel `runModelStepOnPrimitives`
43
43
  * (same provider reference) can read after `loop.run()` returns. We require
44
- * bare-agent >=0.50 (package.json `^0.52.0`) and never patch around its
44
+ * bare-agent >=0.50 (package.json `^0.59.0`) and never patch around its
45
45
  * private response internals.
46
46
  */
47
47
  class MalformedToolCallTolerantOpenAI extends OpenAI {
@@ -443,6 +443,9 @@ export function makeProvider(slotName, options = {}) {
443
443
  exposeMalformedArgs: true,
444
444
  });
445
445
 
446
+ // M4d am37: only the OpenAI-shaped provider sends `toolChoice`; the other shapes ignore it, so a forced call there would be a force that was never sent
447
+ /** @type {any} */ (provider).honoursToolChoice = slot.shape === DEFAULT_SHAPE;
448
+
446
449
  return {
447
450
  provider, rates, modelId, slot: slotName, prices,
448
451
  };
package/src/repairs.js ADDED
@@ -0,0 +1,38 @@
1
+ // M10 am27 (2): code repairs of the two mechanical plan mistakes F169 found in 13 of 20 F168 drafts. Each repair is returned as a line of text and logged on the draft
2
+ // entry (`repaired`), so it is visible. Neither repair grants a primitive, changes a class, or writes a check.
3
+ // (1) a green step whose `close.cited.source` is a declared source role the step does not read: the role is added to its `reads`.
4
+ // (2) an `unjudgeable` entry for a line whose guardrailClasses says green: the entry is dropped and the line stays green.
5
+ // Throws away: the `unjudgeable` reason text of a dropped entry (kept only inside the `repaired` line).
6
+ /**
7
+ * @param {any} declaration the drafter's declaration (not changed) @param {{sources?: {role?: string, kind?: string}[]}} arbiter
8
+ * @returns {{declaration: any, repaired: string[]}}
9
+ */
10
+ export function repairDeclaration(declaration, arbiter) {
11
+ const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
12
+ if (!isRec(declaration)) return { declaration, repaired: [] };
13
+ /** @type {string[]} */
14
+ const repaired = [];
15
+ const roles = new Set((arbiter?.sources ?? []).filter((s) => typeof s?.role === 'string').map((s) => /** @type {string} */ (s.role)));
16
+ let out = declaration;
17
+ if (Array.isArray(declaration.steps)) {
18
+ out = {
19
+ ...out,
20
+ steps: declaration.steps.map((/** @type {any} */ st, /** @type {number} */ i) => {
21
+ const src = isRec(st) && isRec(st.close) && st.close.class === 'green' && isRec(st.close.cited) ? st.close.cited.source : undefined;
22
+ if (typeof src !== 'string' || !roles.has(src) || !Array.isArray(st.reads) || st.reads.includes(src)) return st;
23
+ repaired.push(`steps[${i}].reads: added "${src}" (its cited check reads it)`);
24
+ return { ...st, reads: [...st.reads, src] };
25
+ }),
26
+ };
27
+ }
28
+ if (isRec(declaration.unjudgeable) && isRec(declaration.guardrailClasses)) {
29
+ const un = { ...declaration.unjudgeable };
30
+ for (const key of Object.keys(un)) {
31
+ if (declaration.guardrailClasses[key] !== 'green') continue;
32
+ repaired.push(`unjudgeable: dropped the entry for line ${key} (its class is green; reason was: ${String(un[key]).slice(0, 160)})`);
33
+ delete un[key];
34
+ }
35
+ out = { ...out, unjudgeable: un };
36
+ }
37
+ return { declaration: repaired.length ? out : declaration, repaired };
38
+ }
package/src/runfile.js CHANGED
@@ -50,10 +50,12 @@ export function readRunInputs(runDir) {
50
50
  * M8b item 1: the ONE writer of `run.json`, called once when a fresh run has frozen its inputs (`runFlow`); never over an existing record. `model` is the pick
51
51
  * the run started on (M4d am33; null = the section is left out), `thinking` the job's "Thinking on" box as it was at the start (M4d am25: written for every fresh
52
52
  * run, ticked or not), `inputs` the manifest `freezeInputs` returned. A fresh run always has `thinking` and `inputs`.
53
- * @param {string} runDir @param {{ model: { slot: string, model: string }|null, thinking: boolean, inputs: any[] }} start
53
+ * @param {string} runDir @param {{ model: { slot: string, model: string }|null, thinking: boolean, inputs: any[], rerun?: {decision: 'rerun', words: string, afterStep: string|null}|null }} start
54
54
  */
55
- export function writeRunStart(runDir, { model, thinking, inputs }) {
55
+ export function writeRunStart(runDir, { model, thinking, inputs, rerun = null }) {
56
56
  writeFileSync(join(runDir, RUN_FILE), `${JSON.stringify({
57
57
  ...(model ? { model: { slot: model.slot, model: model.model } } : {}), thinking, inputs,
58
+ // M14 am1 item 1: a rerun keeps the reason it was started with (the decision, the human's words, the step the old run's ask followed); a fresh run has no such key
59
+ ...(rerun ? { rerun: { decision: rerun.decision, words: rerun.words, afterStep: rerun.afterStep } } : {}),
58
60
  }, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
59
61
  }