fwdloop 0.32.0 → 0.34.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 (114) hide show
  1. package/bin/fwdloop +20 -2
  2. package/package.json +2 -2
  3. package/src/auditchecks.js +55 -0
  4. package/src/authoring.js +53 -12
  5. package/src/blockasks.js +45 -0
  6. package/src/blockassemble.js +159 -0
  7. package/src/blockdraft.js +86 -0
  8. package/src/blocklines.js +30 -0
  9. package/src/blockpick.js +175 -0
  10. package/src/cardlist.js +19 -0
  11. package/src/checkblock.js +843 -0
  12. package/src/checked.js +48 -9
  13. package/src/checklist.js +99 -0
  14. package/src/checklistsign.js +93 -0
  15. package/src/checkpick.js +7 -73
  16. package/src/checkwords.js +20 -1
  17. package/src/cited-record.js +21 -1
  18. package/src/citedcheck.js +162 -7
  19. package/src/closers.js +41 -3
  20. package/src/declaration.js +34 -9
  21. package/src/declaredclose.js +4 -0
  22. package/src/draft-steps.js +3 -1
  23. package/src/drafter.js +311 -206
  24. package/src/factwords.js +112 -0
  25. package/src/inputlook.js +53 -0
  26. package/src/labelscan.js +162 -0
  27. package/src/noteask.js +62 -0
  28. package/src/pageask.js +9 -69
  29. package/src/pagedropwords.js +11 -1
  30. package/src/pagedry.js +27 -4
  31. package/src/pagerules.js +19 -3
  32. package/src/panel/author.js +76 -7
  33. package/src/panel/authorcard.js +43 -17
  34. package/src/panel/data.js +41 -9
  35. package/src/panel/index.html +208 -13
  36. package/src/panel/result.js +4 -3
  37. package/src/panel/server.js +3 -1
  38. package/src/pickrecord.js +70 -54
  39. package/src/placerule.js +398 -0
  40. package/src/planrebuild.js +216 -0
  41. package/src/rowedit.js +148 -0
  42. package/src/rubricstep.js +272 -0
  43. package/src/runfile.js +4 -2
  44. package/src/runner.js +67 -10
  45. package/src/setup.js +11 -5
  46. package/src/sheetblock.js +22 -8
  47. package/src/sheetbuild.js +151 -0
  48. package/src/sheetchecks.js +52 -66
  49. package/src/sheetclaims.js +12 -32
  50. package/src/sheetfind.js +4 -4
  51. package/src/sheetlook.js +14 -3
  52. package/src/sheetoffer.js +74 -57
  53. package/src/sheetrows.js +123 -0
  54. package/src/sheetrun.js +13 -10
  55. package/src/summary-words.js +3 -3
  56. package/src/ticket-draft.js +4 -21
  57. package/src/ticketrows.js +100 -0
  58. package/src/try-checks.js +31 -12
  59. package/src/types.js +1 -0
  60. package/types/auditchecks.d.ts +25 -0
  61. package/types/authoring.d.ts +21 -2
  62. package/types/blockasks.d.ts +36 -0
  63. package/types/blockassemble.d.ts +50 -0
  64. package/types/blockdraft.d.ts +75 -0
  65. package/types/blocklines.d.ts +31 -0
  66. package/types/blockpick.d.ts +46 -0
  67. package/types/cardlist.d.ts +21 -0
  68. package/types/checkblock.d.ts +378 -0
  69. package/types/checked.d.ts +16 -2
  70. package/types/checklist.d.ts +115 -0
  71. package/types/checklistsign.d.ts +27 -0
  72. package/types/checkpick.d.ts +4 -34
  73. package/types/checkwords.d.ts +5 -0
  74. package/types/cited-record.d.ts +9 -0
  75. package/types/citedcheck.d.ts +33 -2
  76. package/types/closers.d.ts +24 -2
  77. package/types/declaration.d.ts +7 -0
  78. package/types/declaredclose.d.ts +2 -0
  79. package/types/drafter.d.ts +29 -715
  80. package/types/factwords.d.ts +38 -0
  81. package/types/inputlook.d.ts +49 -0
  82. package/types/labelscan.d.ts +35 -0
  83. package/types/noteask.d.ts +52 -0
  84. package/types/pageask.d.ts +2 -35
  85. package/types/pagedry.d.ts +13 -0
  86. package/types/pagerules.d.ts +7 -0
  87. package/types/panel/author.d.ts +41 -0
  88. package/types/panel/authorcard.d.ts +14 -9
  89. package/types/panel/authorflows.d.ts +4 -4
  90. package/types/panel/data.d.ts +5 -3
  91. package/types/panel/jobgrid.d.ts +1 -1
  92. package/types/pickrecord.d.ts +69 -13
  93. package/types/placerule.d.ts +208 -0
  94. package/types/planrebuild.d.ts +52 -0
  95. package/types/provider.d.ts +1 -1
  96. package/types/rowedit.d.ts +48 -0
  97. package/types/rubricstep.d.ts +63 -0
  98. package/types/runfile.d.ts +5 -2
  99. package/types/runner.d.ts +45 -1
  100. package/types/sheetblock.d.ts +12 -4
  101. package/types/sheetbuild.d.ts +84 -0
  102. package/types/sheetchecks.d.ts +12 -18
  103. package/types/sheetclaims.d.ts +2 -1
  104. package/types/sheetfind.d.ts +2 -2
  105. package/types/sheetoffer.d.ts +31 -6
  106. package/types/sheetrows.d.ts +81 -0
  107. package/types/sheetrun.d.ts +4 -4
  108. package/types/summary-words.d.ts +2 -1
  109. package/types/ticket-draft.d.ts +3 -49
  110. package/types/ticketrows.d.ts +61 -0
  111. package/types/try-checks.d.ts +4 -2
  112. package/types/types.d.ts +8 -0
  113. package/src/repairs.js +0 -38
  114. package/types/repairs.d.ts +0 -13
package/src/rowedit.js ADDED
@@ -0,0 +1,148 @@
1
+ // borrowed-from: bareloop src/rowedit.js@v0.56.0 (3383cce)
2
+ // THE DRAFTER'S ROW-EDIT TURN of a rubric job (the check block, docs/product/ITEM33-BUILD.md "CHECK BLOCK BUILD SPEC" section 4 and hamr's rulings of 2026-11-12).
3
+ // The AI never writes a part, a check or a declaration: it sends EDITS to the list of checks code keeps in the CheckBlock (src/checkblock.js). Code reads the inputs, proves every
4
+ // word, builds every check and decides what can be checked; every edit is judged on its own. The confirm turn owns the goal (ruling 5), so the reply has none. A Tickets job's reply
5
+ // may also carry the optional `ticketFilter` (ruling 2, R5), checked by its own reader. No text here restates the list of checks (the block's invariant 5): the only list-shaped input is
6
+ // the look's report, an input the drafter already had, and the person's own job lines.
7
+ import { lineRules } from './pagebits.js';
8
+ import { renderLookReport } from './inputlook.js';
9
+ import { OFFERED } from './checkwords.js';
10
+ import { rubricVocabulary } from 'bareguard';
11
+
12
+ // borrowed-from: bareloop src/ticketfilter.js@v0.56.0 (3383cce) (TICKET_FILTER_SCHEMA_WORDS only: the one sentence; fwd's own ticketFilter schema, src/ticket-draft.js, words it another way)
13
+ export const TICKET_FILTER_SCHEMA_WORDS = 'REQUIRED when a job line names a priority or a label (leave it out only when none does). The person signs it; code decides at run start. Listing the line under "refused" does not filter anything: only this key does';
14
+
15
+ // borrowed-from: bareloop src/ticketfilter.js@v0.57.0 (c18df406) (TICKET_FILTER_EXAMPLE, ticketPerRunFacts, TICKET_READ_FACT, ticketFilterBlock: verbatim)
16
+ /** a legal filter, as the drafter is shown it */
17
+ export const TICKET_FILTER_EXAMPLE = '{"priority": ["P1"], "labels": ["bug"]}';
18
+
19
+ /**
20
+ * The facts a person-facing turn must not ask about (R5 finding F285): the confirm turn asked "which ticket, and is it P1?" in 5 of 10 live drafts. ONE owner of these words;
21
+ * the confirm prompt and the drafting prompt both carry them, for a Tickets job only.
22
+ * @returns {string}
23
+ */
24
+ export function ticketPerRunFacts() {
25
+ return 'THIS JOB READS A TICKET. The ticket is picked per run (typed on the run card, later the newest new ticket) and is never known when the job is drafted, so NEVER ask the person which ticket it is, or what its priority or labels are. '
26
+ + 'A job line that names a priority or a label (for example "only priority P1 tickets") is decided by code at run start from the ticket\'s own labels, through the job\'s ticketFilter: it is not a question for the person and not something you can check, so do not turn it into a question.';
27
+ }
28
+
29
+
30
+ export const TICKET_READ_FACT = 'A step that reads the ticket input still lists "read" in its tools: the ticket is already frozen at run start, but reading it is a grant, so a step without "read" cannot see it.';
31
+
32
+ /**
33
+ * What the drafter is told when the job reads tickets (appended to the authoring prompt only then; a plain job's prompt is untouched).
34
+ * Adapted from fwd's `ticketFactsLines` (v0.29.0): the same MUST, the same "never invent a label".
35
+ * @returns {string}
36
+ */
37
+ export function ticketFilterBlock() {
38
+ return `${ticketPerRunFacts()} ${TICKET_READ_FACT}\n\nTHE TICKET FILTER — this job reads one ticket per run. Code, not you, decides at run start whether a ticket runs or is skipped, from the ticket's labels and state; a closed ticket always skips.
39
+ When a job line (or its ~ rule) names a priority or a label (for example "only priority P1 tickets", "only tickets with priority P1 count", "only issues labelled bug"), you MUST add a top-level "ticketFilter" beside "stages": ${TICKET_FILTER_EXAMPLE}. "priority" is a list of values from P0 to P3, "labels" is a list of label names; each key is optional, and at least one is required. Never invent a label: use only the names the job lines give. Leave "ticketFilter" out entirely when no job line names a priority or a label.
40
+ The filter decides whether a run starts, not whether the work is good, so it is not a check. The job line that names the priority or label has no stage: list it under "refused" with the reason "decided by the ticket filter before the run starts" AND add the ticketFilter: the refused entry alone does not filter anything, only the ticketFilter does. A person reads and signs the filter; you never set the job's server or tools.`;
41
+ }
42
+
43
+ /** the tool a row-edit reply is delivered through */
44
+ export const ROW_EDIT_TOOL = 'submit_edits';
45
+ /** what an acknowledged reply returns (the loop ends the call the moment the tool fires) */
46
+ export const ROW_EDIT_ACK = 'edits received';
47
+
48
+ const IGNORED_FIELDS = new Set(['id', 'field', 'text', 'strict']);
49
+ const GLOSS = /** @type {Record<string, string>} */ ({ nonEmpty: 'the output is not empty', maxWords: 'at most value words in all', minWords: 'at least value words in all', maxLines: 'at most value lines', listItems: 'exactly value list items (bullets)', maxListItems: 'at most value list items', minListItems: 'at least value list items', sections: 'the output has sections with these names', sectionOrder: 'the sections come in this order', sectionWords: 'each named section has at most wordsPerSection words', mustCarry: 'the output carries these phrases', blockLines: 'blocks of size lines carry these phrases' });
50
+ /** the checks a `pick` edit may name: the checker's own list (the same bareguard vocabulary src/checkpick.js reads) */
51
+ const pickMenu = () => OFFERED.map((r) => {
52
+ const fields = Object.entries(/** @type {any} */ (rubricVocabulary).rules[r].fields).filter(([k]) => !IGNORED_FIELDS.has(k)).map(([k, v]) => `${k}${/** @type {any} */ (v).required ? '' : '?'}`);
53
+ return `- ${r}${fields.length ? ` { ${fields.join(', ')} }` : ''}: ${GLOSS[r] ?? ''}`;
54
+ }).join('\n');
55
+
56
+ /** the drafter's system text for the row-edit turn (a prompt register: src/promptregisters.js) */
57
+ export const ROW_EDIT_SYSTEM = `You help turn the lines of a job into checks, by sending EDITS to a list of checks that code keeps. You never write a check, a stage, a part or a declaration: code reads the inputs, proves every word, builds every check and decides what can be checked. Each edit you send is judged on its own: a refused edit is dropped and says why, and it never costs your other edits.
58
+
59
+ HOW TO ANSWER
60
+ Deliver ONE reply with an "edits" list (the ${ROW_EDIT_TOOL} tool, or one JSON object {"edits": [ ... ]} and nothing else when no tool is offered). An empty "edits" list is a good answer when you have nothing sure to send.
61
+
62
+ THE FOUR EDITS (each has "op"; the op is exactly one of: add, reading, pick, not-checkable. A count is an add with "kind":"count"; "count" is never an op)
63
+ 1. add - a check the inputs support that the person did not write and the look did not give:
64
+ {"op":"add","kind":"fact","line":N,"name":"price label","shape":"money","words":["words copied exactly from the input"],"unit":["US dollars"],"currency":["$"],"source":"<input label>"}
65
+ {"op":"add","kind":"phrase","line":N,"name":"letters and spaces only","words":["fixed words copied exactly from the input"],"source":"<input label>"}
66
+ {"op":"add","kind":"count","line":N,"min":3,"max":3} (how many results the job line itself asks for; whole numbers of 1 or more; only when the line states it)
67
+ "shape" is one of phrase, money, number, date, time. A name uses letters, spaces, "-" or "_" only (no digits). "words" are copied exactly from the input, never typed from memory; words the input does not hold are refused. At most 3 adds in one reply: the later ones are refused.
68
+ 2. reading - the limit a ~ rule means, for a ~ rule the look tied to a fact ("carries ~ rule N") without giving the limit:
69
+ {"op":"reading","line":N,"rules":[n],"fact":"<that look fact's name>","reading":{"op":"lt","value":450}} (reading op is lt, lte, gt or gte)
70
+ {"op":"reading","line":N,"rules":[n],"fact":"<that look fact's name>","reading":{"op":"between","lo":"05:00","hi":"21:00"}}
71
+ A money limit is a number. A time limit is a 24-hour "HH:MM" string. A limit the person WROTE ("under $450") is a rule that can be checked: give its reading with its number. A number YOU make out of their words ("not a red-eye" becomes a departure time between 06:00 and 21:00) is your proposal for the person to check, and a time limit that you propose is a RANGE (between), never one-sided. A rule that holds more than one amount or range gets no reading.
72
+ 3. pick - for a ~ rule that counts words, bullets, lines or sections: the one check that says exactly what that rule says:
73
+ {"op":"pick","line":N,"rules":[n],"check":{"rule":"<one of the checks below>", ...that check's own fields}}
74
+ Use only numbers the ~ rule itself states and only words it contains. The checks (field? = optional):
75
+ ${pickMenu()}
76
+ 4. not-checkable - a ~ rule no check on the inputs can carry ("the cheapest", "the best", "the newest one"):
77
+ {"op":"not-checkable","line":N,"rule":n,"reason":"plain words, the person's own"}
78
+
79
+ RULES
80
+ - Names, labels and units are the input's own words, copied exactly as the input writes them. When the input does not use the person's word, use the words the input uses; never invent a word the input holds nowhere, and never add a code (like SFO) that the person did not write and the input does not hold.
81
+ - The look (below) is what a read of the inputs already found and code already checks: do not send it again as an add. Use it to name the fact a reading belongs to.
82
+ - Send only what you are sure of. A fact or ~ rule you cannot name from the look and the input is not guessed at.
83
+ - "line" is the job line's number; "rule" and "rules" are the ~ rule numbers shown under that line (1 = the first).`;
84
+
85
+ /** the fixed sentence that follows the refusals in a revise turn (the turn carries each refusal's own reason and nothing else) */
86
+ export const ROW_EDIT_REVISE = 'Send corrected edits only (an empty "edits" list is a good answer).';
87
+
88
+ /** how much of each input the turn is shown (the bound src/checklist.js used) */
89
+ const SHOWN_CHARS = 8000;
90
+
91
+ /**
92
+ * The ONE user message: the person's job lines (their `~` rules numbered), the look, the inputs (bounded).
93
+ * @param {{jobLines: any[], look: any, texts: Record<string, string>}} o
94
+ * @returns {string}
95
+ */
96
+ export function rowEditUserText({ jobLines, look, texts }) {
97
+ const out = ["THE JOB (the person's own words)"];
98
+ for (const l of jobLines) {
99
+ out.push(`${l.n}. ${l.text}`);
100
+ lineRules(l).forEach((r, i) => out.push(` ~ rule ${i + 1}: ${r}`));
101
+ }
102
+ const report = look && typeof look === 'object' ? renderLookReport(look).replace(/^WHAT THE LOOK AT THE INPUTS FOUND[^\n]*/, 'WHAT THE LOOK AT THE INPUTS FOUND - code checks each of these itself; you do not write them') : '';
103
+ if (report) out.push('', report);
104
+ for (const [label, t] of Object.entries(texts)) out.push('', `INPUT "${label}" (first ${SHOWN_CHARS} characters):`, String(t).slice(0, SHOWN_CHARS));
105
+ return out.join('\n');
106
+ }
107
+
108
+ /** @param {boolean} ticket @param {Record<string, any>|null} [sheetChecks] M17 am2: with a CSV input, the optional `sheetChecks` suggestions (src/sheetoffer.js `sheetSuggestProp`) @returns {Record<string, any>} the tool's schema: the edits list (each edit judged by code, so an item is any object), and for a Tickets job the optional ticketFilter */
109
+ const rowEditSchema = (ticket, sheetChecks = null) => ({
110
+ type: 'object',
111
+ properties: {
112
+ edits: { type: 'array', items: { type: 'object', properties: { op: { enum: ['add', 'reading', 'pick', 'not-checkable'] } }, required: ['op'] }, description: 'row edits; each is judged on its own' },
113
+ ...(ticket ? {
114
+ ticketFilter: {
115
+ type: 'object',
116
+ properties: {
117
+ priority: { type: 'array', items: { type: 'string', enum: ['P0', 'P1', 'P2', 'P3'] }, description: 'priorities a ticket must have; only when a job line names them' },
118
+ labels: { type: 'array', items: { type: 'string' }, description: 'label names, one of which a ticket must carry; only when a job line names them' },
119
+ },
120
+ additionalProperties: false,
121
+ description: TICKET_FILTER_SCHEMA_WORDS,
122
+ },
123
+ ticketWatch: { type: 'array', items: { type: 'string', enum: ['state', 'labels'] }, description: 'REQUIRED when a job line says to run a ticket again when its state or its labels change (the fields that change); leave it out otherwise. The person signs it; code runs the look' },
124
+ } : {}),
125
+ ...(sheetChecks ? { sheetChecks } : {}),
126
+ },
127
+ required: ['edits'],
128
+ additionalProperties: false,
129
+ });
130
+
131
+ /** @param {boolean} ticket the channel `askStructured` reads (src/authorflow.js) @param {Record<string, any>|null} [sheetChecks] */
132
+ export const rowEditChannel = (ticket = false, sheetChecks = null) => ({
133
+ name: ROW_EDIT_TOOL,
134
+ instruction: `Your reply did not deliver exactly one ${ROW_EDIT_TOOL} call. Call ${ROW_EDIT_TOOL} exactly once, with the edits list as its arguments. Do not write the answer as text.`,
135
+ textPath: 'edits',
136
+ tool: (/** @type {{calls: any[]}} */ box) => ({
137
+ name: ROW_EDIT_TOOL,
138
+ description: 'Deliver your row edits (or an empty list). Call this exactly once.',
139
+ parameters: rowEditSchema(ticket, sheetChecks),
140
+ execute: async (/** @type {any} */ args) => { box.calls.push(args); return ROW_EDIT_ACK; },
141
+ }),
142
+ });
143
+
144
+ /**
145
+ * The edits a reply holds, as a list (a reply whose `edits` is not a list holds none; each edit is still judged by the block).
146
+ * @param {any} artifact @returns {any[]}
147
+ */
148
+ export const editsOf = (artifact) => (artifact && typeof artifact === 'object' && Array.isArray(artifact.edits) ? artifact.edits : []);
@@ -0,0 +1,272 @@
1
+ // borrowed-from: bareloop src/rubricstep.js@v0.56.0 (3383cce) (rubricStepShapeReds, readLimit, holdsManyBounds, defaultCitedText, NEGATING_RE, boundInWords and what they call; the five patterns built from text are literals here, src/ builds none, test/signed-text.test.js; fwd's own boundInWords and lineRules, src/pagebits.js, are an older copy: boundInWords reads time and date bounds only in this one)
2
+ // The part of the rubric step the check block calls: the shape reds of a step's parts, the limit reader (code reads ONE amount or ONE range from the person's rule words)
3
+ // and the default cited text. The rest of the rubric step (building, grading and reading a step file) is not wanted here.
4
+ import { lineRules } from './pagebits.js';
5
+ import { factShapeReds } from './citedcheck.js';
6
+
7
+ // ── the `rubric-step` stage: its parameters, and the rubric they build ───────────────────────────────────────────────
8
+ //
9
+ // A stage serves exactly ONE job line N and reads exactly one file, output/steps/N.json. Its parameters are
10
+ //
11
+ // step N
12
+ // parts [ { text, class, ... } ] — the person's constraints on that line, each SORTED by the drafter
13
+ //
14
+ // A part's class is one of `countable` (a limit a machine counts, or a quote a claim must show), `judged` (needs the
15
+ // judge — stored, never run in this build), `guard` (a rule about web sources — needs a web input, none exist yet) or
16
+ // `none` (the drafter could not sort it). Only `countable` parts become checks; the others are REDS at drafting
17
+ // (src/authoring.js `checkRubricParts`) so no signed stage ever carries one.
18
+
19
+ /** the closed set of classes a part is sorted into; `none` = "I could not sort this one" (a red, in plain words, never a guess) */
20
+ export const PART_CLASSES = Object.freeze(['countable', 'fact', 'judged', 'guard', 'none']);
21
+
22
+ /**
23
+ * The counted/quoted checks a `countable` part may name, with the fields each needs — read off bareguard's own rule table
24
+ * (`rubricVocabulary`): the names are bareguard's, so a check this build cannot run is inexpressible, not rejected late.
25
+ * (`max`/`min` need a numeric field the step file does not have, so they are not offered.)
26
+ * @type {Readonly<Record<string, readonly string[]>>}
27
+ */
28
+ export const COUNT_CHECKS = Object.freeze({
29
+ maxWords: Object.freeze(['value']),
30
+ minWords: Object.freeze(['value']),
31
+ maxLines: Object.freeze(['value']),
32
+ sections: Object.freeze(['names']),
33
+ sectionWords: Object.freeze(['names', 'wordsPerSection']),
34
+ // R10 (bareguard 0.31, fwdloop v0.29.0 OFFERED): the five text checks a person's pick may carry; the drafter never writes them
35
+ nonEmpty: Object.freeze([]),
36
+ listItems: Object.freeze(['value']),
37
+ maxListItems: Object.freeze(['value']), // bareguard 0.35 (F315): an at-most / at-least bound on the list items, beside the exact listItems
38
+ minListItems: Object.freeze(['value']),
39
+ sectionOrder: Object.freeze(['names']),
40
+ mustCarry: Object.freeze(['phrases']),
41
+ blockLines: Object.freeze(['size', 'phrases']),
42
+ cited: Object.freeze(['source']),
43
+ // a COUNT of the claims listed under an input: the code counts the list (flattenStep), bareguard's own min/max compares it
44
+ minClaims: Object.freeze(['value', 'source']),
45
+ maxClaims: Object.freeze(['value', 'source']),
46
+ // PART 1b: put on every prose step by CODE (`withFactBindings`) when an earlier line is a fact step — every number in the text
47
+ // must be in a checked quote of those lines. The model never writes it; bareguard's `numbersInQuote` reads it (gradeStep).
48
+ numbersFromFacts: Object.freeze(['from']),
49
+ });
50
+
51
+ /** every field a part may carry, whatever its class */
52
+ const PART_FIELDS = Object.freeze(['text', 'class', 'check', 'value', 'names', 'wordsPerSection', 'source', 'domains', 'phrases', 'size', 'covers', 'rules', 'from', 'record', 'facts', 'count', 'tested', 'sample']);
53
+
54
+ /** @typedef {{code: string, path: string, detail: string}} ShapeRed */
55
+
56
+ /** @param {unknown} v @returns {v is Record<string, any>} */
57
+ const isRec = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
58
+
59
+ /** @param {unknown} v @returns {v is string} */
60
+ const nonEmpty = (v) => typeof v === 'string' && v.trim() !== '';
61
+
62
+ /** @param {unknown} v @returns {v is string[]} */
63
+ const nameList = (v) => Array.isArray(v) && v.length > 0 && v.every((x) => nonEmpty(x) && x.length <= 1000);
64
+
65
+ /**
66
+ * The SHAPE of a `rubric-step` stage's parameters — what a part may carry — and nothing about which class is allowed in
67
+ * this build (that is `checkRubricParts`, which also sees the whole job). Pure, never throws.
68
+ * @param {unknown} p the stage's `params`
69
+ * @param {string} at the path prefix for reds, e.g. `stages[1].params`
70
+ * @returns {ShapeRed[]}
71
+ */
72
+ export function rubricStepShapeReds(p, at) {
73
+ /** @type {ShapeRed[]} */
74
+ const reds = [];
75
+ const red = (/** @type {string} */ code, /** @type {string} */ path, /** @type {string} */ detail) => reds.push({ code, path, detail });
76
+ if (!isRec(p)) { red('invalid-value', at, 'an object {step, parts}'); return reds; }
77
+ if (!(Number.isInteger(p.step) && p.step >= 1)) red('invalid-value', `${at}.step`, 'the number of the job line this stage serves (an integer, 1 or more)');
78
+ if (!Array.isArray(p.parts)) { red('invalid-value', `${at}.parts`, 'an array of {text, class, ...} — one entry per constraint the person put on this line (may be empty)'); return reds; }
79
+ p.parts.forEach((/** @type {any} */ part, /** @type {number} */ i) => {
80
+ const w = `${at}.parts[${i}]`;
81
+ if (!isRec(part)) { red('invalid-value', w, '{text, class, ...}'); return; }
82
+ for (const k of Object.keys(part)) {
83
+ if (!PART_FIELDS.includes(k)) red('invalid-value', `${w}.${k}`, `"${k}" is not a field of a part — fields: ${PART_FIELDS.join(', ')}`);
84
+ }
85
+ if (!nonEmpty(part.text)) red('missing-field', `${w}.text`, 'the part, in the person\'s own words (a non-empty string)');
86
+ if (!PART_CLASSES.includes(part.class)) { red('invalid-value', `${w}.class`, `one of ${PART_CLASSES.join(' | ')}`); return; }
87
+ if (Object.hasOwn(part, 'covers') && !(Array.isArray(part.covers) && part.covers.length > 0 && new Set(part.covers).size === part.covers.length
88
+ && part.covers.every((/** @type {unknown} */ x) => Number.isInteger(x) && /** @type {number} */ (x) >= 1))) {
89
+ red('invalid-value', `${w}.covers`, 'the numbers of the confirmed checks this part carries out (distinct integers, 1 or more)');
90
+ }
91
+ if (Object.hasOwn(part, 'rules') && !(Array.isArray(part.rules) && part.rules.length > 0 && new Set(part.rules).size === part.rules.length
92
+ && part.rules.every((/** @type {unknown} */ x) => Number.isInteger(x) && /** @type {number} */ (x) >= 1))) {
93
+ red('invalid-value', `${w}.rules`, 'the numbers of the line\'s ~ rules this part carries out (distinct integers, 1 or more)');
94
+ }
95
+ if (part.class === 'fact') { factShapeReds(part, w, (c, path, d) => red(c, path, d)); return; }
96
+ if (part.class === 'guard') {
97
+ if (!nameList(part.domains)) red('invalid-value', `${w}.domains`, 'a non-empty array of web domains the rule is about');
98
+ return;
99
+ }
100
+ if (part.class !== 'countable') return;
101
+ if (!Object.hasOwn(COUNT_CHECKS, part.check)) { red('invalid-value', `${w}.check`, `one of ${Object.keys(COUNT_CHECKS).join(' | ')}`); return; }
102
+ for (const f of COUNT_CHECKS[part.check]) {
103
+ const ok = f === 'value' || f === 'wordsPerSection' || f === 'size' ? Number.isInteger(part[f]) && part[f] >= 1
104
+ : f === 'names' || f === 'phrases' ? nameList(part[f])
105
+ : f === 'from' ? Array.isArray(part.from) && part.from.length > 0 && new Set(part.from).size === part.from.length && part.from.every((/** @type {unknown} */ x) => Number.isInteger(x) && /** @type {number} */ (x) >= 1)
106
+ : nonEmpty(part.source) && part.source.length <= 128;
107
+ if (!ok) {
108
+ red('invalid-value', `${w}.${f}`, f === 'names' ? 'a non-empty array of section names'
109
+ : f === 'phrases' ? 'a non-empty array of words or phrases'
110
+ : f === 'source' ? 'the label of the input a quote must come from'
111
+ : f === 'from' ? 'the numbers of the earlier fact lines whose checked quotes the text\'s numbers come from (distinct integers, 1 or more)'
112
+ : 'an integer, 1 or more');
113
+ }
114
+ }
115
+ });
116
+ return reds;
117
+ }
118
+
119
+ /** @param {string} t @returns {string} a time token as compared: no spaces, lower case, no leading zero on the hour */
120
+ const timeKey = (t) => t.replace(/\s+/g, '').toLowerCase().replace(/^0(?=\d:)/, '');
121
+
122
+ /**
123
+ * The person's words read by KIND, so a digit inside a time, a date or an amount belongs to that token only (F242).
124
+ * @param {string} text @returns {{bare: Set<number>, amount: Set<number>, time: Set<string>, date: Set<string>}}
125
+ */
126
+ const tokensSaid = (text) => {
127
+ const out = { bare: new Set(), amount: new Set(), time: new Set(), date: new Set() };
128
+ const re = /(\d{1,2}:\d{2}(?:\s?[AaPp][Mm])?)|(\d{4}-\d{1,2}-\d{1,2}|\d{1,2}[/.]\d{1,2}[/.]\d{2,4})|([$\u20ac\u00a3]\s?\d[\d,]*(?:\.\d+)?|\d[\d,]*(?:\.\d+)?\s?(?:US\s)?(?:dollars?|euros?|pounds?|USD|EUR|GBP)\b)|(\d[\d,]*(?:\.\d+)?)/gi;
129
+ for (const m of text.matchAll(re)) {
130
+ if (m[1]) out.time.add(timeKey(m[1]));
131
+ else if (m[2]) out.date.add(m[2]);
132
+ else if (m[3]) out.amount.add(Number(m[3].match(/\d[\d,]*(?:\.\d+)?/)?.[0].replace(/,/g, '')));
133
+ else out.bare.add(Number(m[4].replace(/,/g, '')));
134
+ }
135
+ return out;
136
+ };
137
+
138
+ /**
139
+ * 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
140
+ * the early ask of PRD v1.107 Part 5b all read it; never a second spelling). By kind: a number is said only as a bare number or an
141
+ * amount's number; a time only as a time token (hour leading zero ignored); a date only as a date token. Never a piece of a token.
142
+ * @param {unknown} b @param {string} said @returns {boolean}
143
+ */
144
+ export const boundInWords = (b, said) => {
145
+ const t = tokensSaid(said);
146
+ if (typeof b === 'number') return t.bare.has(b) || t.amount.has(b);
147
+ if (typeof b !== 'string') return false;
148
+ return /^\s*\d{1,2}:\d{2}/.test(b) ? t.time.has(timeKey(b)) : t.date.has(b.trim());
149
+ };
150
+
151
+
152
+ const TIME_RANGE_RE = /\b(?:between|from)\s+(\d{1,2}:\d{2}(?:\s?[AaPp][Mm])?)\s+(?:and|to|-)\s+(\d{1,2}:\d{2}(?:\s?[AaPp][Mm])?)/i;
153
+ const TIME_RANGE_ALL_RE = /\b(?:between|from)\s+(\d{1,2}:\d{2}(?:\s?[AaPp][Mm])?)\s+(?:and|to|-)\s+(\d{1,2}:\d{2}(?:\s?[AaPp][Mm])?)/gi;
154
+
155
+ export const NEGATING_RE = /\b(?:not|no|never|outside|except|before|after|without)\b/i;
156
+
157
+ // The limit reader (hamr ruling A, 2026-11-12): when the look tied a money or time fact to a `~` rule but gave no limit, CODE reads the limit
158
+ // from the person's own rule words. ONE amount or ONE range only; every other text is a plain reason (Not checked), never a wrong check.
159
+ // The direction words are the FACT_OPS words of src/facts.js (lt under, lte at most, gt over, gte at least) plus their plain synonyms.
160
+
161
+ const AMOUNT_ALL_RE = /(?:[$\u20ac\u00a3]\s?(\d[\d,]*(?:\.\d+)?)|(\d[\d,]*(?:\.\d+)?)\s?(?:US\s)?(?:dollars?|euros?|pounds?|USD|EUR|GBP)\b)/gi;
162
+
163
+ const MONEY_BETWEEN_RE = /\bbetween\s+(?:[$\u20ac\u00a3]\s?(\d[\d,]*(?:\.\d+)?)|(\d[\d,]*(?:\.\d+)?)\s?(?:US\s)?(?:dollars?|euros?|pounds?|USD|EUR|GBP)\b)\s+(?:and|to|-)\s+(?:[$\u20ac\u00a3]\s?(\d[\d,]*(?:\.\d+)?)|(\d[\d,]*(?:\.\d+)?)\s?(?:US\s)?(?:dollars?|euros?|pounds?|USD|EUR|GBP)\b)/i;
164
+
165
+ const MONEY_DIRECTION_RE = /\b(under|below|less than|fewer than|at most|up to|no more than|over|above|more than|at least|no less than|no fewer than)\s+(?:[$\u20ac\u00a3]\s?(\d[\d,]*(?:\.\d+)?)|(\d[\d,]*(?:\.\d+)?)\s?(?:US\s)?(?:dollars?|euros?|pounds?|USD|EUR|GBP)\b)/i;
166
+
167
+ const MONEY_OR_LESS_RE = /(?:[$\u20ac\u00a3]\s?(\d[\d,]*(?:\.\d+)?)|(\d[\d,]*(?:\.\d+)?)\s?(?:US\s)?(?:dollars?|euros?|pounds?|USD|EUR|GBP)\b)\s+or\s+(less|fewer|under|below|lower|more|over|above|higher)\b/i;
168
+
169
+ const DIRECTION_OP = /** @type {Record<string, 'lt'|'lte'|'gt'|'gte'>} */ ({ under: 'lt', below: 'lt', 'less than': 'lt', 'fewer than': 'lt', 'at most': 'lte', 'up to': 'lte', 'no more than': 'lte', over: 'gt', above: 'gt', 'more than': 'gt', 'at least': 'gte', 'no less than': 'gte', 'no fewer than': 'gte' });
170
+
171
+ const CURRENCY_STEM = /** @type {Record<string, string>} */ ({ $: 'dollar', '€': 'euro', '£': 'pound', usd: 'dollar', eur: 'euro', gbp: 'pound' });
172
+
173
+ const num = (/** @type {string|undefined} */ a, /** @type {string|undefined} */ b) => Number(String(a ?? b).replace(/,/g, ''));
174
+
175
+ const hhmm = (/** @type {string} */ t) => (/[AaPp][Mm]/.test(t) ? null : t.replace(/\s+/g, '').replace(/^(\d):/, '0$1:'));
176
+
177
+ /** does the amount token's currency (sign or word) fit the look fact's currency and unit lists? A fact with neither list fits anything. */
178
+ function currencyFits(/** @type {string} */ tok, /** @type {any} */ fact) {
179
+ const cur = (Array.isArray(fact?.currency) ? fact.currency : fact?.currency ? [fact.currency] : []).map(String);
180
+ const unit = (Array.isArray(fact?.unit) ? fact.unit : fact?.unit ? [fact.unit] : []).map((/** @type {unknown} */ u) => String(u).toLowerCase());
181
+ if (!cur.length && !unit.length) return true;
182
+ const sym = /^[$€£]/.test(tok) ? tok.charAt(0) : null;
183
+ const last = String(tok.trim().split(/\s+/).at(-1)).toLowerCase();
184
+ const stem = sym ? CURRENCY_STEM[sym] : (CURRENCY_STEM[last] ?? last.replace(/s$/, ''));
185
+ return (sym !== null && cur.includes(sym)) || unit.some((/** @type {string} */ u) => u.includes(String(stem)));
186
+ }
187
+
188
+ /**
189
+ * Does this rule text hold more than one amount (money) or more than one time range (time)? The ONE guard code's own limit read and an AI
190
+ * reading edit both use: "under $450 or over $900" is two limits, and one reading of it would be a wrong check.
191
+ * @param {string} shape @param {string} text @returns {boolean}
192
+ */
193
+ export function holdsManyBounds(shape, text) {
194
+ const t = String(text ?? '');
195
+ if (shape === 'time') return [...t.matchAll(TIME_RANGE_ALL_RE)].length > 1 || (t.match(/\d{1,2}:\d{2}/g) ?? []).length > 2;
196
+ if (shape === 'money') { const amts = [...t.matchAll(AMOUNT_ALL_RE)]; return amts.length > 1 && !(MONEY_BETWEEN_RE.test(t) && amts.length === 2); }
197
+ return false;
198
+ }
199
+
200
+ // borrowed-from: bareloop src/rubricstep.js@v0.57.0 (c18df406) (WHY_OTHER_CURRENCY, fd943e49)
201
+ /** the plain reason a rule's amount is in a currency the page fact does not use; `readLimit` gives it and the check list reads it, one spelling */
202
+ export const WHY_OTHER_CURRENCY = 'the amount is in another currency than the page fact';
203
+
204
+ /**
205
+ * The limit the person's own words give a fact of this shape: `{reading}` or `{why}` (a plain reason; the rule then stays Not checked).
206
+ * @param {string} shape money or time @param {string} text the `~` rule's words @param {any} [fact] the look fact (its currency and unit lists must fit)
207
+ * @returns {{reading: {op: 'lt'|'lte'|'gt'|'gte', value: number} | {op: 'between', lo: number|string, hi: number|string}} | {why: string}}
208
+ */
209
+ export function readLimit(shape, text, fact = {}) {
210
+ const t = String(text ?? '');
211
+ if (shape === 'time') {
212
+ if (NEGATING_RE.test(t)) return { why: 'a one-sided or negated time (before, after, not) is not a range code can read' };
213
+ if (/\b\d{1,2}(?::\d{2})?\s?[ap]\.?m\b/i.test(t)) return { why: 'a 12-hour time (am or pm) is not read, write it like 06:00' };
214
+ if (holdsManyBounds('time', t)) return { why: 'more than one time range in the rule' };
215
+ const m = TIME_RANGE_RE.exec(t);
216
+ if (!m) return { why: 'no range between two times in the rule' };
217
+ const lo = hhmm(String(m[1])), hi = hhmm(String(m[2]));
218
+ if (!lo || !hi) return { why: 'a 12-hour time (am or pm) is not read, write it like 06:00' };
219
+ if (lo >= hi) return { why: 'a range whose end is not after its start is not read' };
220
+ return { reading: { op: 'between', lo, hi } };
221
+ }
222
+ if (shape === 'money') {
223
+ if (/\b(?:not|never|outside|except|without)\b/i.test(t)) return { why: 'a negated limit (not, except, without) is not read' };
224
+ const amts = [...t.matchAll(AMOUNT_ALL_RE)];
225
+ if (!amts.length) return { why: 'no amount with a currency sign or word in the rule' };
226
+ for (const a of amts) if (!currencyFits(a[0], fact)) return { why: WHY_OTHER_CURRENCY };
227
+ if (holdsManyBounds('money', t)) return { why: 'more than one amount in the rule' };
228
+ const b = MONEY_BETWEEN_RE.exec(t);
229
+ if (b) { const lo = num(b[1], b[2]), hi = num(b[3], b[4]); return lo < hi ? { reading: { op: 'between', lo, hi } } : { why: 'a range whose end is not above its start is not read' }; }
230
+ const d = MONEY_DIRECTION_RE.exec(t);
231
+ if (d) return { reading: { op: /** @type {'lt'|'lte'|'gt'|'gte'} */ (DIRECTION_OP[String(d[1]).toLowerCase()]), value: num(d[2], d[3]) } };
232
+ const o = MONEY_OR_LESS_RE.exec(t);
233
+ if (o) return { reading: { op: /^(less|fewer|under|below|lower)$/i.test(String(o[3])) ? 'lte' : 'gte', value: num(o[1], o[2]) } };
234
+ return { why: 'the rule gives an amount but no direction (under, over, at most, at least, between)' };
235
+ }
236
+ return { why: 'code reads a limit only for money or time' };
237
+ }
238
+
239
+ /** the words of the default cited check code adds to a text line of a one-input job (the one list's `$` row); the card reads a part with exactly these words as `[default]` @param {string} label @returns {string} */
240
+ export const defaultCitedText = (label) => `every claim is backed by a quote copied from "${label}"`;
241
+
242
+ // borrowed-from: bareloop src/rubricstep.js@v0.57.0 (c18df406) (defaultNoteText)
243
+ /** the words of the default note check code adds to a facts line that also asks for written words (the one list's `$` row); the card reads a part with exactly these words as `[default]` @param {number} n the job line @returns {string} */
244
+ export const defaultNoteText = (n) => `line ${n} writes a note — the note must be there`;
245
+
246
+
247
+ // borrowed-from: bareloop src/rubricstep.js@v0.56.0 (3383cce) (listMatchesClose: the signing door's test of the list against the close; bareloop's stages shape, the block's own closeCache.stages; fwd's close is shaped differently, so wiring it to fwd's close is a later piece)
248
+ /**
249
+ * The sign-time check of a close that carries the one check list: every BUILT row (the mechanical floor aside) points at a part that is really in the close, and every real check part
250
+ * (countable or fact) has at least one built row pointing at it, so a check cannot be in the close with no row and a row cannot claim a check the close does not run. A close with no list is
251
+ * not examined here. Pure.
252
+ * @param {any} closeDecl @returns {{ok: true}|{ok: false, error: string}}
253
+ */
254
+ export function listMatchesClose(closeDecl) {
255
+ const list = isRec(closeDecl) && Array.isArray(closeDecl.list) ? closeDecl.list : null;
256
+ if (list === null) return { ok: true };
257
+ const stages = Array.isArray(closeDecl.stages) ? closeDecl.stages : [];
258
+ const partsOn = (/** @type {number} */ n) => stages.filter((/** @type {any} */ st) => isRec(st) && st.kind === 'rubric-step' && isRec(st.params) && st.params.step === n && Array.isArray(st.params.parts)).flatMap((/** @type {any} */ st) => st.params.parts);
259
+ const built = list.filter((/** @type {any} */ r) => isRec(r) && r.state === 'built' && r.kind !== 'floor');
260
+ const bad = built.filter((/** @type {any} */ r) => !(isRec(r.part) && r.part.line === r.line && Number.isInteger(r.part.part) && isRec(partsOn(r.line)[r.part.part])));
261
+ const lines = [...new Set(stages.filter((/** @type {any} */ st) => isRec(st) && st.kind === 'rubric-step' && isRec(st.params)).map((/** @type {any} */ st) => st.params.step))];
262
+ const bare = lines.flatMap((/** @type {number} */ n) => partsOn(n).map((/** @type {any} */ p, /** @type {number} */ i) => ({ n, i, p })))
263
+ .filter(({ p }) => isRec(p) && (p.class === 'countable' || p.class === 'fact'))
264
+ // a part has its row when a built row points at it, or when the part lists (in its `rules`) the number of a built `~` row of its line (a row points at ONE part, a rule may be carried by several)
265
+ .filter(({ n, i, p }) => !built.some((/** @type {any} */ r) => (isRec(r.part) && r.part.line === n && r.part.part === i)
266
+ || (r.kind === 'rule' && r.line === n && Array.isArray(p.rules) && p.rules.includes(r.rule))));
267
+ if (bad.length === 0 && bare.length === 0) return { ok: true };
268
+ const parts = [];
269
+ if (bad.length) parts.push(`a row points at a check the close does not run: ${bad.map((/** @type {any} */ r) => r.key).join('; ')}`);
270
+ if (bare.length) parts.push(`a check in the close has no row: line ${bare.map(({ n, i }) => `${n} part ${i + 1}`).join('; ')}`);
271
+ return { ok: false, error: `The list of checks does not match the signed close (${parts.join(' | ')}). Nothing was signed — draft again.` };
272
+ }
package/src/runfile.js CHANGED
@@ -50,12 +50,14 @@ 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[], rerun?: {decision: 'rerun', words: string, afterStep: string|null}|null }} 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, placeRules?: {rows: any[]}|null }} start
54
54
  */
55
- export function writeRunStart(runDir, { model, thinking, inputs, rerun = null }) {
55
+ export function writeRunStart(runDir, { model, thinking, inputs, rerun = null, placeRules = null }) {
56
56
  writeFileSync(join(runDir, RUN_FILE), `${JSON.stringify({
57
57
  ...(model ? { model: { slot: model.slot, model: model.model } } : {}), thinking, inputs,
58
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
59
  ...(rerun ? { rerun: { decision: rerun.decision, words: rerun.words, afterStep: rerun.afterStep } } : {}),
60
+ // M16 item 1 / am3 (3): the values the run read for its place-rule facts at its start (a resume rebinds them from here); a job with no place rule has no such key
61
+ ...(placeRules ? { placeRules } : {}),
60
62
  }, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
61
63
  }