fwdloop 0.33.0 → 0.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/README.md +14 -0
  2. package/bin/fwdloop +18 -2
  3. package/package.json +1 -1
  4. package/src/action-line.js +100 -0
  5. package/src/action-stop.js +44 -0
  6. package/src/ask.js +9 -2
  7. package/src/auditchecks.js +6 -4
  8. package/src/authoring.js +28 -14
  9. package/src/blockasks.js +3 -2
  10. package/src/blockassemble.js +40 -21
  11. package/src/blockdraft.js +8 -13
  12. package/src/blockpick.js +11 -1
  13. package/src/checkblock.js +102 -58
  14. package/src/checked.js +7 -2
  15. package/src/checklist.js +1 -3
  16. package/src/checklistsign.js +1 -1
  17. package/src/checkpick.js +7 -73
  18. package/src/declaration.js +20 -35
  19. package/src/drafter.js +281 -208
  20. package/src/jobkey.js +2 -3
  21. package/src/noteask.js +62 -0
  22. package/src/pageask.js +24 -69
  23. package/src/pagedry.js +27 -4
  24. package/src/pagemap.js +8 -2
  25. package/src/pagerules.js +19 -3
  26. package/src/panel/author.js +63 -36
  27. package/src/panel/authorcard.js +36 -20
  28. package/src/panel/data.js +5 -1
  29. package/src/panel/index.html +66 -37
  30. package/src/pickrecord.js +42 -54
  31. package/src/planrebuild.js +16 -6
  32. package/src/rowedit.js +35 -5
  33. package/src/rubricstep.js +9 -1
  34. package/src/runner.js +87 -41
  35. package/src/runvalues.js +9 -1
  36. package/src/setup.js +3 -1
  37. package/src/sheetblock.js +17 -7
  38. package/src/sheetbuild.js +148 -0
  39. package/src/sheetchecks.js +3 -2
  40. package/src/sheetfind.js +4 -4
  41. package/src/sheetlook.js +15 -4
  42. package/src/sheetoffer.js +50 -5
  43. package/src/sheetrows.js +18 -2
  44. package/src/signed-text.js +1 -5
  45. package/src/ticket-draft.js +4 -21
  46. package/src/ticketrows.js +100 -0
  47. package/src/whole-job.js +27 -11
  48. package/types/action-line.d.ts +71 -0
  49. package/types/action-stop.d.ts +36 -0
  50. package/types/ask.d.ts +3 -2
  51. package/types/auditchecks.d.ts +2 -1
  52. package/types/authoring.d.ts +8 -3
  53. package/types/blockasks.d.ts +1 -2
  54. package/types/blockassemble.d.ts +20 -3
  55. package/types/blockdraft.d.ts +4 -12
  56. package/types/blockpick.d.ts +5 -0
  57. package/types/checkblock.d.ts +33 -17
  58. package/types/checked.d.ts +2 -0
  59. package/types/checklist.d.ts +3 -5
  60. package/types/checkpick.d.ts +4 -34
  61. package/types/declaration.d.ts +7 -0
  62. package/types/drafter.d.ts +23 -356
  63. package/types/noteask.d.ts +52 -0
  64. package/types/pageask.d.ts +12 -36
  65. package/types/pagedry.d.ts +13 -0
  66. package/types/pagerules.d.ts +7 -0
  67. package/types/panel/author.d.ts +1 -1
  68. package/types/panel/authorcard.d.ts +13 -8
  69. package/types/panel/authorflows.d.ts +4 -4
  70. package/types/panel/data.d.ts +2 -2
  71. package/types/panel/jobgrid.d.ts +1 -1
  72. package/types/pickrecord.d.ts +47 -13
  73. package/types/rowedit.d.ts +16 -1
  74. package/types/rubricstep.d.ts +3 -0
  75. package/types/sheetblock.d.ts +11 -4
  76. package/types/sheetbuild.d.ts +82 -0
  77. package/types/sheetchecks.d.ts +2 -1
  78. package/types/sheetfind.d.ts +2 -2
  79. package/types/sheetoffer.d.ts +26 -1
  80. package/types/sheetrows.d.ts +8 -0
  81. package/types/ticket-draft.d.ts +3 -49
  82. package/types/ticketrows.d.ts +61 -0
  83. package/types/whole-job.d.ts +3 -3
  84. package/src/added-end.js +0 -60
  85. package/src/repairs.js +0 -38
  86. package/types/added-end.d.ts +0 -62
  87. package/types/repairs.d.ts +0 -13
package/src/rowedit.js CHANGED
@@ -12,6 +12,34 @@ import { rubricVocabulary } from 'bareguard';
12
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
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
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
+
15
43
  /** the tool a row-edit reply is delivered through */
16
44
  export const ROW_EDIT_TOOL = 'submit_edits';
17
45
  /** what an acknowledged reply returns (the loop ends the call the moment the tool fires) */
@@ -77,8 +105,8 @@ export function rowEditUserText({ jobLines, look, texts }) {
77
105
  return out.join('\n');
78
106
  }
79
107
 
80
- /** @param {boolean} ticket @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 */
81
- const rowEditSchema = (ticket) => ({
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) => ({
82
110
  type: 'object',
83
111
  properties: {
84
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' },
@@ -92,21 +120,23 @@ const rowEditSchema = (ticket) => ({
92
120
  additionalProperties: false,
93
121
  description: TICKET_FILTER_SCHEMA_WORDS,
94
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' },
95
124
  } : {}),
125
+ ...(sheetChecks ? { sheetChecks } : {}),
96
126
  },
97
127
  required: ['edits'],
98
128
  additionalProperties: false,
99
129
  });
100
130
 
101
- /** @param {boolean} ticket the channel `askStructured` reads (src/authorflow.js) */
102
- export const rowEditChannel = (ticket = false) => ({
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) => ({
103
133
  name: ROW_EDIT_TOOL,
104
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.`,
105
135
  textPath: 'edits',
106
136
  tool: (/** @type {{calls: any[]}} */ box) => ({
107
137
  name: ROW_EDIT_TOOL,
108
138
  description: 'Deliver your row edits (or an empty list). Call this exactly once.',
109
- parameters: rowEditSchema(ticket),
139
+ parameters: rowEditSchema(ticket, sheetChecks),
110
140
  execute: async (/** @type {any} */ args) => { box.calls.push(args); return ROW_EDIT_ACK; },
111
141
  }),
112
142
  });
package/src/rubricstep.js CHANGED
@@ -197,6 +197,10 @@ export function holdsManyBounds(shape, text) {
197
197
  return false;
198
198
  }
199
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
+
200
204
  /**
201
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).
202
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)
@@ -219,7 +223,7 @@ export function readLimit(shape, text, fact = {}) {
219
223
  if (/\b(?:not|never|outside|except|without)\b/i.test(t)) return { why: 'a negated limit (not, except, without) is not read' };
220
224
  const amts = [...t.matchAll(AMOUNT_ALL_RE)];
221
225
  if (!amts.length) return { why: 'no amount with a currency sign or word in the rule' };
222
- for (const a of amts) if (!currencyFits(a[0], fact)) return { why: 'the amount is in another currency than the page fact' };
226
+ for (const a of amts) if (!currencyFits(a[0], fact)) return { why: WHY_OTHER_CURRENCY };
223
227
  if (holdsManyBounds('money', t)) return { why: 'more than one amount in the rule' };
224
228
  const b = MONEY_BETWEEN_RE.exec(t);
225
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' }; }
@@ -235,6 +239,10 @@ export function readLimit(shape, text, fact = {}) {
235
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} */
236
240
  export const defaultCitedText = (label) => `every claim is backed by a quote copied from "${label}"`;
237
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
+
238
246
 
239
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)
240
248
  /**
package/src/runner.js CHANGED
@@ -80,6 +80,7 @@ import { readRunInputs, readRunRecord, writeRunStart } from './runfile.js';
80
80
  import { citedPlaceFactsOf, bindCitedPlaceValues, readPlaceRules, valueInWords, stopWords, placeValuesOfEvents, lastRunPlaceRead, PLACE_EVENT, NO_PLACE_RECORD_WORDS } from './placerule.js';
81
81
  import { buildMemo } from './memo.js';
82
82
  import { wholeJobAskIndex, wholeJobText } from './whole-job.js';
83
+ import { ACTION_STOP_KIND, decideAction, lastAcceptedSha, stopWaitMs } from './action-stop.js';
83
84
  import { fetchPageText, isWebUrl } from './pagefetch.js';
84
85
  import { readTicketMcp, configForServer, remoteRefusal, mcpStartOpts, startRefusal, firstLine } from './ticket-mcp.js';
85
86
  import { createMCPBridge, discoverServers } from 'bare-agent/mcp';
@@ -1693,7 +1694,7 @@ async function runAskSlot({
1693
1694
  // `currentPrior` is the just-redrafted artifact), so this write always
1694
1695
  // carries the CURRENT evidence, not a stale first-park copy.
1695
1696
  writeFileSync(join(runDir, 'ask.json'), JSON.stringify({
1696
- askId, question: askSlot?.question ?? step.goal, askedAt, expiresAt, evidence,
1697
+ askId, question: askSlot?.question ?? step.goal, askedAt, expiresAt, evidence, ...(askSlot?.kind ? { kind: askSlot.kind } : {}),
1697
1698
  }, null, 2));
1698
1699
  // Amendment M4a-1 — SIGNED by hamr 2026-09-27 ("sign m4a1"): a
1699
1700
  // PERMANENT copy of this same park, `asks/<askId>.json`, written right
@@ -1707,7 +1708,7 @@ async function runAskSlot({
1707
1708
  // is a genuine invariant violation, not a race to recover from — it
1708
1709
  // halts the run rather than silently dropping the archive duty.
1709
1710
  const archived = writeAskArchive({
1710
- runDir, askId, question: askSlot?.question ?? step.goal, askedAt, expiresAt, evidence, emits: step.emits,
1711
+ runDir, askId, question: askSlot?.question ?? step.goal, askedAt, expiresAt, evidence, emits: step.emits, ...(askSlot?.kind ? { kind: askSlot.kind } : {}),
1711
1712
  });
1712
1713
  if (!archived.ok) {
1713
1714
  throw new Error(archived.red);
@@ -1889,6 +1890,8 @@ async function foldFromStep({
1889
1890
  // `@param {object} opts` this function's block comment never declared)
1890
1891
  // is what keeps every OTHER destructured field's inferred type intact.
1891
1892
  firstStepGap = /** @type {string|null} */ (null),
1893
+ // M13 am11: set by a resume that took the Accept of the stop before the action at step `i0`: the sha256 the person accepted (what was shown)
1894
+ stopAcceptedSha = /** @type {string|null} */ (null),
1892
1895
  // Amendment 7 item 8: a run Resumed after a Stop that cut step `i0` mid-way re-enters it as a NEW try — `numbered` tries already
1893
1896
  // wear numbers (the new one is numbered after them), `done` of them closed and count against the step's limit.
1894
1897
  resumeTries = { numbered: 0, done: 0 },
@@ -1926,15 +1929,10 @@ async function foldFromStep({
1926
1929
  });
1927
1930
  }
1928
1931
 
1929
- // --- the signed send slot: never through modelStep, only after an
1930
- // accept THIS run, re-checked at write time. ---
1932
+ // --- the signed send slot = the job's action (M13 am11): never through modelStep. It ships the output of the step right before it. Before it writes, what goes
1933
+ // out is compared by sha256 with what was accepted at the last Ask IN THIS RUN: the same goes; a change, or no accept this run, stops the run once and asks
1934
+ // (Accept / Not now, the Ask's own park). The same rule for every Destination. ---
1931
1935
  if (sendLines.has(step.fromLine)) {
1932
- if (!runAcceptedThisRun) {
1933
- return haltRun({
1934
- flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts,
1935
- outcome: 'red', red: `send: step "${step.goal}" reached with no accept this run`,
1936
- });
1937
- }
1938
1936
  const sendSlot = sendLines.get(step.fromLine);
1939
1937
  if (!sendSlot) {
1940
1938
  return haltRun({
@@ -1942,43 +1940,86 @@ async function foldFromStep({
1942
1940
  });
1943
1941
  }
1944
1942
  const target = `${sendSlot.target.kind}:${sendSlot.target.path}`;
1945
- // The send's content is identified by IDENTITY (the artifact emitted
1946
- // by the ONE earlier signed ask step this send reads) — never by
1947
- // position in `reads`. `readFlow`/`validateDeclaration` already
1948
- // refuse, at signing time, any declaration whose send step doesn't
1949
- // read the emits of exactly one earlier signed ask (M3 item 8); every
1950
- // path into this fold goes through `readFlow` first, so `askIdsInReads`
1951
- // is always exactly 1 here.
1952
- const [askArtifactId] = (step.reads ?? []).filter((id) => askStepEmits.has(id));
1953
- if (!acceptedAskEmitsThisRun.has(askArtifactId)) {
1943
+ const before = i > 0 ? steps[i - 1] : null;
1944
+ const outId = before?.emits;
1945
+ if (typeof outId !== 'string') {
1954
1946
  return haltRun({
1955
- flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts,
1956
- outcome: 'red', red: `send: step "${step.goal}" reads ask artifact "${askArtifactId}" that was not accepted this run`,
1947
+ flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts, outcome: 'red', red: `send: step "${step.goal}" has no step before it to write out`,
1957
1948
  });
1958
1949
  }
1959
- // F48 round 4 (redesign): ONLY an `ok:true` read ships — a missing OR
1960
- // refused (symlink swap / outside the run dir / unparseable JSON)
1961
- // accepted artifact halts the run BY NAME, before `sendStep` is ever
1962
- // called, so nothing reaches the signed destination. This is the exact
1963
- // gap the round 3 fix left open: `readArtifact` returning `undefined`
1964
- // for both shapes let a swapped/deleted artifact reach `sendStep` as
1965
- // `undefined`, get `?? null`-ed by src/send.js, and ship as a
1966
- // recorded-green `null` — a silent "success" for content that was
1967
- // never verified.
1968
- const contentResult = readArtifactResult(runDir, askArtifactId);
1950
+ // F48 round 4 (redesign): ONLY an `ok:true` read ships — a missing OR refused (symlink swap / outside the run dir / unparseable JSON) artifact halts the
1951
+ // run BY NAME, before `sendStep` is ever called, so nothing reaches the signed destination.
1952
+ const contentResult = readArtifactResult(runDir, outId);
1969
1953
  if (!contentResult.ok) {
1970
1954
  return haltRun({
1971
1955
  flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts,
1972
1956
  outcome: 'red',
1973
1957
  red: contentResult.missing
1974
- ? `send: accepted artifact "${askArtifactId}" is missing for step "${step.goal}" — refusing to send`
1975
- : `send: accepted artifact "${askArtifactId}" for step "${step.goal}" — ${contentResult.red}`,
1958
+ ? `send: artifact "${outId}" is missing for step "${step.goal}" — refusing to send`
1959
+ : `send: artifact "${outId}" for step "${step.goal}" — ${contentResult.red} — refusing to send`,
1976
1960
  });
1977
1961
  }
1978
- const content = contentResult.value;
1962
+ let content = contentResult.value;
1963
+ const decided = decideAction({ acceptedSha: lastAcceptedSha(steps, i, acceptedAskEmitsThisRun), outgoing: content });
1964
+ let shaToSend = decided.outgoingSha;
1965
+ if (!decided.go) {
1966
+ if (stopAcceptedSha !== null && i === i0) {
1967
+ shaToSend = stopAcceptedSha; // the person accepted the stop for this very step: sendViaPrimitive re-hashes what is on disk against it
1968
+ stopAcceptedSha = null;
1969
+ } else {
1970
+ // eslint-disable-next-line no-await-in-loop
1971
+ const stop = await runAskSlot({
1972
+ mcpServer,
1973
+ checkList,
1974
+ step,
1975
+ stepIndex: i,
1976
+ askSlot: { question: decided.question, ttlMs: stopWaitMs(steps, i, askLines, sendSlot.waitMs), kind: ACTION_STOP_KIND },
1977
+ priorId: outId,
1978
+ priorStep: before,
1979
+ priorStepNo: i,
1980
+ priorPrevStepId: i > 1 ? (steps[i - 2].emits ?? null) : null,
1981
+ priorArtifact: content,
1982
+ redoCap,
1983
+ effectiveCeilingUsd,
1984
+ capUsd,
1985
+ primitives,
1986
+ businessDate,
1987
+ modelStep,
1988
+ askStep,
1989
+ spent,
1990
+ spendComplete,
1991
+ recordAudit,
1992
+ evidenceUnjudged: runUnjudged,
1993
+ unjudgedCount: runUnjudged.length,
1994
+ redone: 0,
1995
+ runDir,
1996
+ flowDir,
1997
+ runId,
1998
+ flowRoot,
1999
+ flowName,
2000
+ signatureHash,
2001
+ inputsManifest,
2002
+ attemptsLog,
2003
+ artifacts,
2004
+ now,
2005
+ startedAt,
2006
+ runStartedAt,
2007
+ });
2008
+ if (stop.type === 'paused' || stop.type === 'stopped') return stop.result;
2009
+ if (stop.type === 'halted') {
2010
+ return haltRun({
2011
+ flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts, outcome: stop.outcome, red: stop.red,
2012
+ ...(stop.stop ? { stop: stop.stop } : {}),
2013
+ resumeAt: { stepIndex: i, flowRoot, flowName, inputsManifest, unjudged: runUnjudged, redone: stop.redone },
2014
+ });
2015
+ }
2016
+ content = stop.artifact;
2017
+ shaToSend = typeof stop.acceptedSha256 === 'string' ? stop.acceptedSha256 : decided.outgoingSha;
2018
+ }
2019
+ }
1979
2020
  const filename = `${flowName}-${runId}-${step.emits}.md`;
1980
2021
  // eslint-disable-next-line no-await-in-loop
1981
- const sendResult = await sendStep(target, filename, content, acceptedAskEmitsThisRun.get(askArtifactId), { root: flowRoot, runDir });
2022
+ const sendResult = await sendStep(target, filename, content, shaToSend, { root: flowRoot, runDir });
1982
2023
  const sendRow = makeAuditRow({
1983
2024
  step, attempt: 1, verdict: sendResult.ok ? 'green' : 'red', gap: sendResult.ok ? null : sendResult.red, usd: 0, spendComplete: true, wallMs: 0, strike: false, at: now(),
1984
2025
  ...(sendResult.ok && typeof sendResult.sha256 === 'string' ? { sentSha256: sendResult.sha256 } : {}),
@@ -2704,8 +2745,10 @@ export async function resumeRun({
2704
2745
  const effectiveCeilingUsd = holdOf(ceilingUsd);
2705
2746
 
2706
2747
  const step = steps[state.stepIndex];
2707
- const askSlot = askLines.get(step.fromLine);
2708
- const priorId = (step.reads ?? [])[0];
2748
+ // M13 am11: a run parked at the stop before the action (a signed send step): the one thing shown is the output of the step right before it
2749
+ const isStop = sendLines.has(step.fromLine);
2750
+ const askSlot = isStop ? { question: 'stop before the action', ttlMs: 0, kind: ACTION_STOP_KIND } : askLines.get(step.fromLine);
2751
+ const priorId = isStop ? steps[state.stepIndex - 1]?.emits : (step.reads ?? [])[0];
2709
2752
  const priorStepIndex = steps.findIndex((s) => s.emits === priorId);
2710
2753
  // `priorId` names a step strictly earlier than the parked ask
2711
2754
  // (state.stepIndex), so i < state.stepIndex — already proven `ok` by the
@@ -2781,14 +2824,17 @@ export async function resumeRun({
2781
2824
  // accepted — write the ask step's own artifact, then fold on to
2782
2825
  // whatever comes next (another signed ask parks again; the ordinary
2783
2826
  // send/step path completes exactly as `runFlow` would have, in-process).
2784
- writeArtifact(runDir, step.emits, askResult.artifact);
2785
- artifacts[step.emits] = askResult.artifact;
2786
- acceptedAskEmitsThisRun.set(step.emits, askResult.acceptedSha256 ?? null);
2827
+ if (!isStop) {
2828
+ writeArtifact(runDir, step.emits, askResult.artifact);
2829
+ artifacts[step.emits] = askResult.artifact;
2830
+ acceptedAskEmitsThisRun.set(step.emits, askResult.acceptedSha256 ?? null);
2831
+ }
2787
2832
 
2788
2833
  const result = await foldFromStep({
2789
2834
  mcpServer: declaration.mcp?.server ?? null,
2790
2835
  checkList: declaration.checkList,
2791
- i0: state.stepIndex + 1,
2836
+ i0: isStop ? state.stepIndex : state.stepIndex + 1,
2837
+ ...(isStop ? { stopAcceptedSha: typeof askResult.acceptedSha256 === 'string' ? askResult.acceptedSha256 : null } : {}),
2792
2838
  steps,
2793
2839
  askLines,
2794
2840
  sendLines,
package/src/runvalues.js CHANGED
@@ -19,6 +19,7 @@ import { join } from 'node:path';
19
19
 
20
20
  import { readFileInside, readdirInside } from './flow.js';
21
21
  import { TRIGGER_RECORD_FILE } from './trigger-line.js';
22
+ import { DEFAULT_ACTION_WAIT_MS } from './action-stop.js';
22
23
 
23
24
  export const VALUES_FILE_RE = /^signed-values(?:-r(\d+))?\.json$/;
24
25
 
@@ -50,6 +51,8 @@ export function flowValues(arbiter) {
50
51
  const sends = arbiter.sends ?? [];
51
52
  const destination = sends.length === 1 && sends[0].target?.kind === 'file' ? String(sends[0].target.path) : null;
52
53
  const askWaits = Object.fromEntries((arbiter.asks ?? []).map((a) => [String(a.line), waitText(a.ttlMs)]));
54
+ // M13 am11a 2: a job with an action and no Ask line keeps the card's Ask wait (1h unless changed) under the action's line, signed with the Destination and the Cap in the same two clicks
55
+ if ((arbiter.asks ?? []).length === 0 && sends.length === 1) askWaits[String(sends[0].line)] = waitText(DEFAULT_ACTION_WAIT_MS);
53
56
  return { capUsd: arbiter.capUsd, destination, askWaits };
54
57
  }
55
58
 
@@ -169,7 +172,12 @@ export function applyRunValues(arbiter, flow, flowSignatureHash, picked) {
169
172
  arbiter: {
170
173
  ...arbiter,
171
174
  capUsd: v.capUsd,
172
- sends: (arbiter.sends ?? []).map((s) => (v.destination === null ? s : { ...s, target: { ...s.target, path: v.destination } })),
175
+ sends: (arbiter.sends ?? []).map((s) => ({
176
+ ...s,
177
+ ...(v.destination === null ? {} : { target: { ...s.target, path: v.destination } }),
178
+ // M13 am11a: the stop before the action waits this long when the job has no Ask line
179
+ ...((arbiter.asks ?? []).length === 0 && v.askWaits[String(s.line)] !== undefined ? { waitMs: parseWaitMs(v.askWaits[String(s.line)]) } : {}),
180
+ })),
173
181
  asks: (arbiter.asks ?? []).map((a) => ({ ...a, ttlMs: parseWaitMs(v.askWaits[String(a.line)]), ttlSigned: true })),
174
182
  },
175
183
  };
package/src/setup.js CHANGED
@@ -72,6 +72,8 @@ function humanRows(sessionDir, rel) {
72
72
  const answered = readQuestions(join(sessionDir, rel)).questions.filter((q) => q.answer !== null).map((q) => (q.source === 'look' ? {
73
73
  kind: 'human', n: q.k, at: q.at ?? null, source: 'look', ask: q.ask, question: q.question, answer: q.answer, line: q.line,
74
74
  ruleNo: q.ruleNo, ruleText: q.ruleText, proposal: q.proposal ?? null, rule: q.rule ?? null, ...(q.choice === undefined ? {} : { choice: q.choice }),
75
+ // M17 am8: the decided words ride the row (the signed rule on Agree, the typed text on a new rule, none on Drop it), so the Audit never reads the question
76
+ ...(q.choice === 'agree' && typeof q.rule === 'string' ? { words: q.rule } : q.choice === 'rule' ? { words: q.answer } : {}),
75
77
  } : {
76
78
  // M14 am3: a question the drafter raised and the person answered is the same row, with no look-only fields (so no picked label)
77
79
  kind: 'human', n: q.k, at: q.at ?? null, question: q.question, answer: q.answer, line: q.line,
@@ -84,7 +86,7 @@ function humanRows(sessionDir, rel) {
84
86
  const [ask] = checkAsks([{ line: k.line, rule: k.rule, text: k.ruleText, check: k.check ?? null, why: null }]);
85
87
  return {
86
88
  kind: 'human', n: lookAnswered + i + 1, at: null, source: 'look', ask: ask.ask, question: ask.question, answer: KEPT_WORDS, line: k.line,
87
- ruleNo: k.rule, ruleText: k.ruleText, proposal: ask.reading ?? null, rule: k.added ?? null,
89
+ ruleNo: k.rule, ruleText: k.ruleText, proposal: ask.reading ?? null, rule: k.ruleText ?? null,
88
90
  };
89
91
  });
90
92
  return [...answered, ...keptRows];
package/src/sheetblock.js CHANGED
@@ -13,6 +13,7 @@ import { rubricVocabulary } from 'bareguard';
13
13
  import { lineRules } from './pagebits.js';
14
14
  import { sheetCheckSentence } from './sheetchecks.js';
15
15
  import { isColumnChoiceRule } from './sheetoffer.js';
16
+ import { NO_VALUE_WHY } from './ticketrows.js';
16
17
 
17
18
  const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
18
19
 
@@ -56,6 +57,12 @@ export function sheetFoundWords(check, claims) {
56
57
  return null;
57
58
  }
58
59
 
60
+ /** M17 am2: a check code built has code's own name: `l<line>r<rules>` (a rule row's) or `l<line>a<k>` (an `[agent]` row's); a plan whose checks all have one is an M17 plan (its card shows the list only) @param {unknown} id */
61
+ export const isCodeBuiltId = (id) => typeof id === 'string' && /^l\d+[ra]\d+(_\d+)*$/.test(id);
62
+
63
+ /** M17 am3: who a sheet check comes from: code's `row: 'agent'` (a second check on a rule, its own `[agent]` row) is `agent` whatever it shows; else the one rule (`sheetByOf`) @param {any} c @param {string[]} rules */
64
+ export const sheetByCheck = (c, rules) => (c?.row === 'agent' ? 'agent' : sheetByOf(rules));
65
+
59
66
  /** @param {any} l a job line `{rules?, guardrail?, rule?}` @returns {string[]} its `~` rules, numbered from 1 by position */
60
67
  export const rulesOfLine = (l) => lineRules({ ...(Array.isArray(l?.rules) ? { rules: l.rules } : {}), rule: l?.guardrail ?? l?.rule });
61
68
 
@@ -70,7 +77,7 @@ export const coversWords = (rules) => rules.map((r) => `covers "${r}"`).join('
70
77
  * older `close.columns` / `close.cited` check (then every guardrail is Not checked).
71
78
  * @param {{declaration: any, lines: Array<{n: number, rules?: string[], guardrail?: string, rule?: string}>, csvRoles?: string[], record?: any}} o
72
79
  * `record` = the `sheet` section of `line-checks.json` (`{lines: [...]}`), only after a run
73
- * @returns {Array<{line: number, guardrails: string[], checked: Array<{id: string, name: string, words: string, covers: string[], coversWords: string, text: string, ok?: boolean, found?: string}>, notChecked: string[]|'none'}>}
80
+ * @returns {Array<{line: number, codeBuilt: boolean, guardrails: string[], checked: Array<{id: string, name: string, words: string, covers: string[], coversWords: string, by: 'you'|'agent', text: string, ok?: boolean, found?: string}>, notChecked: string[]|'none'}>}
74
81
  */
75
82
  export function sheetLineBlocks({ declaration, lines, csvRoles = [], record }) {
76
83
  const out = [];
@@ -95,7 +102,8 @@ export function sheetLineBlocks({ declaration, lines, csvRoles = [], record }) {
95
102
  const words = sheetCheckSentence(c);
96
103
  const cw = coversWords(rules);
97
104
  /** @type {any} */
98
- const e = { id: typeof c.id === 'string' ? c.id : '', name, words, covers: rules, coversWords: cw, text: onList ? tagged(sheetPlainText(name, words, cw), sheetByOf(rules)) : labelled(sheetPlainText(name, words, cw), 'agent') }; // hamr 2026-11-14: a plan whose list has sheet rows tags a check by where it comes from; an older plan keeps M10 am22 (4)'s `[agent]`
105
+ const by = sheetByCheck(c, rules);
106
+ const e = { id: typeof c.id === 'string' ? c.id : '', name, words, covers: rules, coversWords: cw, by, text: onList ? tagged(sheetPlainText(name, words, cw), by) : labelled(sheetPlainText(name, words, cw), 'agent') }; // hamr 2026-11-14: a plan whose list has sheet rows tags a check by where it comes from; an older plan keeps M10 am22 (4)'s `[agent]`
99
107
  const res = newest && Array.isArray(newest.results) ? newest.results.find((/** @type {any} */ r) => isRec(r) && r.id === c.id) : undefined;
100
108
  if (isRec(res) && typeof res.ok === 'boolean') {
101
109
  e.ok = res.ok;
@@ -110,19 +118,21 @@ export function sheetLineBlocks({ declaration, lines, csvRoles = [], record }) {
110
118
  return e;
111
119
  });
112
120
  const notChecked = guardrails.filter((r, i) => !isColumnChoiceRule(r) && !covered.has(i + 1));
113
- out.push({ line: st.fromLine, guardrails, checked, notChecked: notChecked.length === 0 ? /** @type {'none'} */ ('none') : notChecked });
121
+ out.push({ line: st.fromLine, guardrails, checked, codeBuilt: hasSheet && st.close.sheet.every((/** @type {any} */ c) => isCodeBuiltId(c?.id)), notChecked: notChecked.length === 0 ? /** @type {'none'} */ ('none') : notChecked });
114
122
  }
115
123
  return out;
116
124
  }
117
125
 
118
126
  /**
119
- * The guardrail rules of a sheet step that no check covers, as the drafter's Not-checked lines (`line N: "rule" - no sheet check covers it`): the block's own
127
+ * The guardrail rules of a sheet step that no check covers, as the drafter's Not-checked lines (`line N: "rule" - <reason>`): the block's own
120
128
  * `notChecked`, one list for the plan card and the drafter's saved record.
121
- * @param {any} declaration @param {Array<{n: number, rules?: string[], guardrail?: string, rule?: string}>} lines @param {string[]} csvRoles @returns {string[]}
129
+ * M17 am2: `built` (the builder's answer, src/sheetbuild.js) gives the reason a rule is Not checked (the refusal that named it).
130
+ * @param {any} declaration @param {Array<{n: number, rules?: string[], guardrail?: string, rule?: string}>} lines @param {string[]} csvRoles @param {{notChecked: Record<string, string>}} [built] @returns {string[]}
122
131
  */
123
- export function uncoveredRules(declaration, lines, csvRoles) {
132
+ export function uncoveredRules(declaration, lines, csvRoles, built) {
124
133
  if (csvRoles.length === 0) return [];
125
- return sheetLineBlocks({ declaration, lines, csvRoles }).flatMap((b) => (b.notChecked === 'none' ? [] : b.notChecked.map((r) => `line ${b.line}: "${r}" \u2014 no sheet check covers it`)));
134
+ return sheetLineBlocks({ declaration, lines, csvRoles }).flatMap((b) => (b.notChecked === 'none' ? [] : b.notChecked
135
+ .map((r) => `line ${b.line}: "${r}" \u2014 ${built?.notChecked[`line ${b.line}: "${r}"`] ?? NO_VALUE_WHY}`)));
126
136
  }
127
137
 
128
138
  /** @param {any} arbiter @returns {string[]} the roles of the signed sources that are a CSV file (the sheets a check reads) */
@@ -0,0 +1,148 @@
1
+ // M17 am2 + am3 (docs/wiki/the-module-ladder.md "M17 am2", "M17 am3"): the ONE builder of the sheet checks of a line. The AI never writes a sheet check: what it sends in the declaration round's
2
+ // `close.sheet` is read here only as a typed SUGGESTION (bareguard's rule fields plus the `covers` numbers); code refuses or builds every one on bareguard's shapes and writes the check itself.
3
+ // Ported from poc/f195-agentrows/build.mjs (F195 PASS, $0); no class code, no send-back loop, no word-to-column guess, no per-case validator patch.
4
+ // refusals (each by bareguard, in this order): the vocabulary (rule, op), the line's sheets, the schema (a field of the rule), `columnAt` (a column of the sheet's header), `checkTables`
5
+ // (and its problems), `groundedLiterals` (a number or date in the person's own words), `claimSchema` (an answer box), and for a `table` check `runTableChecks` on the sheet frozen at draft time.
6
+ // placement (am3 item 1): every suggestion that passes all of them is BUILT. A cells (answer) check is placed before a table check, then in the order sent. A cells check is a RULE ROW's check when none of the
7
+ // rules it covers is held by an earlier rule row, else (or when it covers no rule) its own `[agent]` row. M17 am7: a `table` check reads only the input sheet, so it is never a rule row: it is always
8
+ // its own `[agent]` row, on by default, and covers no rule (a rule only a table check named is Not checked). Nothing is hidden; nothing sits beside a rule's row.
9
+ // One writer per field: `id`, `claim`, `covers` and `table` (when absent and the line reads one sheet) are assigned here. A rule row's id is `l<line>r<rules>`, an agent row's `l<line>a<k>`; the claim is the id.
10
+ // What this throws away: a suggestion's `id`, `claim`, `text` (and its `covers`: an agent row's is only the rule no rule row holds); a refused suggestion's check (only its reason is kept, on the rules it named).
11
+ // Third outcomes, named: a suggestion that is not an object, names no rule or op bareguard has, a table it cannot read, a column that is no header: refused with that helper's words; a rule that no
12
+ // check holds is Not checked with the last refusal that named it, or the no-pick sentence (`NO_VALUE_WHY`).
13
+ import { rubricVocabulary, claimSchema, groundedLiterals } from 'bareguard';
14
+ import { SHEET_RULES, sheetCheckColumns, sheetCheckReds, bareguardChecks } from './sheetchecks.js';
15
+ import { tableChecksFailingOnInput } from './sheetrun.js';
16
+ import { isColumnChoiceRule } from './sheetoffer.js';
17
+ import { rulesOfLine } from './sheetblock.js';
18
+ import { wordsSaidOn } from './pagebits.js';
19
+ import { NO_VALUE_WHY } from './ticketrows.js';
20
+
21
+ const V = /** @type {any} */ (rubricVocabulary);
22
+ const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
23
+
24
+ /** the fields of a suggestion code does not read: it names every check itself */
25
+ export const SUGGESTION_DROPPED = Object.freeze(['id', 'claim', 'text', 'covers']);
26
+
27
+ /**
28
+ * @param {any} ai a suggestion as the AI sent it @returns {{covers: number[], fields: Record<string, any>}}
29
+ */
30
+ export function toSuggestion(ai) {
31
+ /** @type {Record<string, any>} */
32
+ const fields = {};
33
+ if (isRec(ai)) for (const [k, v] of Object.entries(ai)) if (!SUGGESTION_DROPPED.includes(k)) fields[k] = v;
34
+ return { covers: isRec(ai) && Array.isArray(ai.covers) ? ai.covers : [], fields };
35
+ }
36
+
37
+ /**
38
+ * @typedef {{check: any, covers: number[]}} Placed
39
+ * @typedef {{rule: number, text: string, state: 'built'|'column'|'agent-row'|'not-checked', reason: string|null, id: string|null}} RuleState
40
+ * @param {{line: {n: number, text?: string, rules?: string[], guardrail?: string, rule?: string}, tables: Record<string, {header: string[], rows: any[]}>, suggestions: any[]}} o
41
+ * @returns {Promise<{rows: RuleState[], ruleRows: Placed[], agentRows: Placed[], checks: any[], refused: {helper: string, why: string}[]}>}
42
+ */
43
+ export async function buildSheetLine({ line, tables, suggestions }) {
44
+ const rules = rulesOfLine(line);
45
+ const roles = Object.keys(tables);
46
+ const words = wordsSaidOn({ text: line.text, rules });
47
+ /** @type {{helper: string, why: string}[]} */
48
+ const refused = [];
49
+ /** @type {Map<number, string>} */
50
+ const refusedFor = new Map();
51
+ /** @type {{nums: number[], fields: Record<string, any>}[]} */
52
+ const buildable = [];
53
+ for (const src of suggestions) {
54
+ const s = toSuggestion(src);
55
+ const nums = [...new Set(s.covers)].filter((n) => Number.isInteger(n) && n >= 1 && n <= rules.length && !isColumnChoiceRule(rules[n - 1])).sort((a, b) => a - b);
56
+ const refuse = (/** @type {string} */ helper, /** @type {string} */ why) => { refused.push({ helper, why }); for (const n of nums) if (!refusedFor.has(n)) refusedFor.set(n, `suggestion refused: ${helper}: ${why}`); };
57
+ const f = s.fields;
58
+ if (!SHEET_RULES.includes(f.rule) || !isRec(V.rules[f.rule]?.ops) || !Object.hasOwn(V.rules[f.rule].ops, f.op)) { refuse('vocabulary', `no ${String(f.rule)} op "${String(f.op)}"`); continue; }
59
+ const role = typeof f.table === 'string' ? f.table : roles.length === 1 ? roles[0] : null;
60
+ if (role === null || !roles.includes(role)) { refuse('tables', `"${String(f.table)}" is not one of the line's sheets`); continue; }
61
+ const check = { ...f, table: role };
62
+ const bad = Object.keys(check).filter((k) => k !== 'rule' && !Object.hasOwn(V.rules[f.rule].fields, k));
63
+ if (bad.length > 0) { refuse('schema', `field ${bad.join(', ')} is not a ${f.rule} field`); continue; }
64
+ const probe = { id: 'probe', ...check, ...(f.rule === 'cells' ? { claim: 'probe' } : {}) };
65
+ const cols = sheetCheckColumns(probe).filter((c) => !tables[role].header.includes(c));
66
+ if (cols.length > 0) { refuse('columnAt', `'${cols[0]}' is not a column of "${role}"`); continue; }
67
+ const reds = sheetCheckReds([probe], line.n, tables);
68
+ if (reds.length > 0) { refuse('checkTables', reds[0].replace(/^declaration: line \d+: /, '')); continue; }
69
+ const miss = groundedLiterals(bareguardChecks([probe])[0], words).missing;
70
+ if (miss.length > 0) { refuse('groundedLiterals', `${miss[0].kind} ${JSON.stringify(miss[0].value)} (${miss[0].path}) is not in your words`); continue; }
71
+ if (f.rule === 'cells' && claimSchema(bareguardChecks([probe])[0]) === null) { refuse('claimSchema', 'no answer box for this check'); continue; }
72
+ if (f.rule === 'table') {
73
+ const fails = await tableChecksFailingOnInput({ steps: [{ fromLine: line.n, close: { class: 'green', sheet: [probe] } }] }, tables);
74
+ if (fails.length > 0) { refuse('runTableChecks', 'the table check already fails on the sheet'); continue; }
75
+ }
76
+ buildable.push({ nums, fields: check });
77
+ }
78
+ // placement: answer (cells) checks first, then the order sent (a stable sort)
79
+ const order = buildable.map((b, i) => ({ b, i })).sort((x, y) => (x.b.fields.rule === 'cells' ? 0 : 1) - (y.b.fields.rule === 'cells' ? 0 : 1) || x.i - y.i).map((x) => x.b);
80
+ /** @type {Map<number, string>} */
81
+ const held = new Map();
82
+ /** @type {Map<number, string>} */
83
+ const coveredByAgent = new Map();
84
+ /** @type {Placed[]} */
85
+ const ruleRows = [];
86
+ /** @type {Placed[]} */
87
+ const agentRows = [];
88
+ for (const b of order) {
89
+ const asRule = b.fields.rule !== 'table' && b.nums.length > 0 && b.nums.every((n) => !held.has(n) && !coveredByAgent.has(n));
90
+ const id = asRule ? `l${line.n}r${b.nums.join('_')}` : `l${line.n}a${agentRows.length + 1}`;
91
+ // an [agent] row shows only a rule no rule row holds and no earlier [agent] row shows (F195's rule: never shown nowhere, never two rows); `row: 'agent'` is the tag's own typed field (src/sheetblock.js)
92
+ const shown = asRule ? b.nums : b.fields.rule === 'table' ? [] : b.nums.filter((n) => !held.has(n) && !coveredByAgent.has(n));
93
+ const check = { id, ...b.fields, ...(b.fields.rule === 'cells' ? { claim: id } : {}), covers: shown, ...(asRule ? {} : { row: 'agent' }) };
94
+ if (asRule) { for (const n of b.nums) held.set(n, id); ruleRows.push({ check, covers: b.nums }); } else { for (const n of shown) coveredByAgent.set(n, id); agentRows.push({ check, covers: shown }); }
95
+ }
96
+ /** @type {RuleState[]} */
97
+ const rows = rules.map((text, i) => {
98
+ const n = i + 1;
99
+ if (isColumnChoiceRule(text)) return { rule: n, text, state: 'column', reason: null, id: null };
100
+ if (held.has(n)) return { rule: n, text, state: 'built', reason: null, id: /** @type {string} */ (held.get(n)) };
101
+ if (coveredByAgent.has(n)) return { rule: n, text, state: 'agent-row', reason: null, id: /** @type {string} */ (coveredByAgent.get(n)) };
102
+ return { rule: n, text, state: 'not-checked', reason: refusedFor.get(n) ?? NO_VALUE_WHY, id: null };
103
+ });
104
+ return { rows, ruleRows, agentRows, checks: [...ruleRows, ...agentRows].map((p) => p.check), refused };
105
+ }
106
+
107
+ /**
108
+ * The declaration with every green sheet step's `close.sheet` REWRITTEN by code from what the AI suggested there (`buildSheetLine`). A step with no suggestion is left alone; a step none of whose
109
+ * suggestions can be built loses `close.sheet` (its rules are Not checked with their reasons). Pure over the declaration it is given (a copy is returned).
110
+ * @param {{declaration: any, lines: {n: number, text?: string, rules?: string[], guardrail?: string, rule?: string}[], tables: Record<string, {header: string[], rows: any[]}>}} o
111
+ * @returns {Promise<{declaration: any, notChecked: Record<string, string>, refused: {line: number, helper: string, why: string}[], unbuilt: {line: number, lost: string[]}[]}>} `unbuilt`: the green sheet steps left with no check, each with its rules as Not-checked lines. `notChecked`: `line N: "rule"` -> the refusal that named it (or `NO_VALUE_WHY`), for each rule of a
112
+ * rewritten line that no check holds
113
+ */
114
+ export async function buildSheetChecks({ declaration, lines, tables }) {
115
+ /** @type {Record<string, string>} */
116
+ const notChecked = {};
117
+ /** @type {{line: number, helper: string, why: string}[]} */
118
+ const refused = [];
119
+ if (!isRec(declaration) || !Array.isArray(declaration.steps)) return { declaration, notChecked, refused, unbuilt: [] };
120
+ /** @type {Set<number>} */
121
+ const done = new Set();
122
+ const steps = [];
123
+ for (const st of declaration.steps) {
124
+ if (!isRec(st) || !isRec(st.close) || st.close.class !== 'green' || !Array.isArray(st.close.sheet) || !Number.isInteger(st.fromLine) || done.has(st.fromLine)) { steps.push(st); continue; }
125
+ done.add(st.fromLine);
126
+ const line = lines.find((l) => l.n === st.fromLine);
127
+ if (!line) { steps.push(st); continue; }
128
+ const built = await buildSheetLine({ line, tables, suggestions: st.close.sheet });
129
+ for (const x of built.refused) refused.push({ line: st.fromLine, ...x });
130
+ for (const r of built.rows) if (r.state === 'not-checked') notChecked[`line ${st.fromLine}: "${r.text}"`] = /** @type {string} */ (r.reason);
131
+ const { sheet: _suggested, ...close } = st.close;
132
+ steps.push({ ...st, close: built.checks.length > 0 ? { ...close, sheet: built.checks } : close });
133
+ }
134
+ // M17 am5 / P5: a green step that reads a sheet and holds no check after the build (no suggestion, or none code could build) is REPORTED here, with each of its rules and the refusal that named it
135
+ // (else the no-pick sentence). What class such a step gets is the caller's to decide (src/blockassemble.js closeUnbuiltSheetSteps); this file writes no class.
136
+ /** @type {{line: number, lost: string[]}[]} */
137
+ const unbuilt = [];
138
+ const roles = Object.keys(tables);
139
+ for (const st of steps) {
140
+ if (!isRec(st) || !isRec(st.close) || st.close.class !== 'green' || (Array.isArray(st.close.sheet) && st.close.sheet.length > 0) || isRec(st.close.cited) || !Number.isInteger(st.fromLine)) continue;
141
+ if (!Array.isArray(st.reads) || !st.reads.some((/** @type {string} */ r) => roles.includes(r)) || unbuilt.some((u) => u.line === st.fromLine)) continue;
142
+ const line = lines.find((l) => l.n === st.fromLine);
143
+ const rules = line ? rulesOfLine(line).filter((r) => !isColumnChoiceRule(r)) : [];
144
+ if (rules.length === 0) continue;
145
+ unbuilt.push({ line: st.fromLine, lost: rules.map((r) => `line ${st.fromLine}: "${r}" \u2014 ${notChecked[`line ${st.fromLine}: "${r}"`] ?? NO_VALUE_WHY}`) });
146
+ }
147
+ return { declaration: { ...declaration, steps }, notChecked, refused, unbuilt };
148
+ }
@@ -91,10 +91,11 @@ export function sheetCheckSentence(check) {
91
91
  /**
92
92
  * M10b piece 4: a signed check may carry fwdloop's own `covers` (the numbers of the job line's `~` rules the drafter tagged it to; signed, so the person sees it).
93
93
  * bareguard does not know it, so the checks are cleaned HERE, the ONE place, on the way into bareguard (`createRubric` at sign time and at run time).
94
- * @param {any[]} checks @returns {any[]} a copy without `covers`
94
+ * M17 am3: `row` (fwdloop's own typed tag of a check code made an `[agent]` row) is cleaned here too.
95
+ * @param {any[]} checks @returns {any[]} a copy without `covers` and `row`
95
96
  */
96
97
  export function bareguardChecks(checks) {
97
- return checks.map((c) => { if (!isRec(c) || !('covers' in c)) return c; const { covers: _kept, ...rest } = c; return rest; });
98
+ return checks.map((c) => { if (!isRec(c) || !('covers' in c || 'row' in c)) return c; const { covers: _kept, row: _row, ...rest } = c; return rest; });
98
99
  }
99
100
 
100
101
  /**
package/src/sheetfind.js CHANGED
@@ -44,9 +44,9 @@ export function findColumn(csvText, word) {
44
44
 
45
45
  /**
46
46
  * The question, as signed (item 7's example, then am8 item 1's answer words):
47
- * `no column 'Price'; 'Amount' has numbers in 40 of 40 rows. Use it? Answer "agree", or type your own words (your answer is added as a new ~ rule on line N).`
47
+ * `no column 'Price'; 'Amount' has numbers in 40 of 40 rows. Use it? Answer "agree", or type your own words (your answer becomes the agent's check on line N).`
48
48
  * @param {string} word @param {FoundAsk} found @param {number} line @returns {string}
49
49
  */
50
- export const columnQuestion = (word, found, line) => `no column '${word}'; '${found.column}' has numbers in ${found.numbers} of ${found.rows} rows. Use it?${columnTail(line)}`;
51
- /** @param {number} line @returns {string} the answer words the column question ends with (M10 am29: the panel cuts exactly this) */
52
- export const columnTail = (line) => ` Answer "agree", or type your own words (your answer is added as a new ~ rule on line ${line}).`;
50
+ export const columnQuestion = (word, found, line, tied = false) => `no column '${word}'; '${found.column}' has numbers in ${found.numbers} of ${found.rows} rows. Use it?${columnTail(line, tied)}`;
51
+ /** @param {number} line @param {boolean} [tied] the question is about one of the person's `~` rules (M17 ruling 1: the answer replaces that rule; the words are the page asks' own) @returns {string} the answer words the column question ends with (M10 am29: the panel cuts exactly this) */
52
+ export const columnTail = (line, tied = false) => (tied ? ` Answer "agree", or type your own words (your answer replaces that ~ rule on line ${line}).` : ` Answer "agree", or type your own words (your answer becomes the agent's check on line ${line}).`);