fwdloop 0.35.2 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/runner.js CHANGED
@@ -79,7 +79,8 @@ import { readRunInputs, readRunRecord, writeRunStart } from './runfile.js';
79
79
  // borrowed-from: bareloop src/userrun.js@v0.56.0 (3383cce) (the place-rule read at run start and its stop words; fwd keeps the read value in run.json, not a spine)
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
- import { wholeJobAskIndex, wholeJobText } from './whole-job.js';
82
+ import { wholeJobAskIndex, wholeJobText, reportContextOf, sendBodyOf } from './whole-job.js';
83
+ import { runNumberOf } from './report.js';
83
84
  import { ACTION_STOP_KIND, decideAction, lastAcceptedSha, stopWaitMs } from './action-stop.js';
84
85
  import { fetchPageText, isWebUrl } from './pagefetch.js';
85
86
  import { readTicketMcp, configForServer, remoteRefusal, mcpStartOpts, startRefusal, firstLine } from './ticket-mcp.js';
@@ -858,6 +859,8 @@ function makeAuditRow({
858
859
  memoText = /** @type {string|undefined} */ (undefined),
859
860
  badCalls = /** @type {any[]|undefined} */ (undefined),
860
861
  sentSha256 = /** @type {string|undefined} */ (undefined),
862
+ sentName = /** @type {string|undefined} */ (undefined),
863
+ sentTaken = /** @type {string|undefined} */ (undefined),
861
864
  savedBy = /** @type {string|undefined} */ (undefined),
862
865
  forcedRefused = /** @type {string|undefined} */ (undefined),
863
866
  }) {
@@ -891,6 +894,9 @@ function makeAuditRow({
891
894
  if (Array.isArray(badCalls) && badCalls.length > 0) row.badCalls = badCalls;
892
895
  // M15 item 4: the sha256 of the plain-text file a send wrote; the key is only on a green send row. The ONE writer; the Result tab reads it to tell the file changed.
893
896
  if (typeof sentSha256 === 'string') row.sentSha256 = sentSha256;
897
+ // M15 am3 item 1: the name the report was written under, and (only when its first choice was taken) that taken name, so the Result tab can say it. The ONE writer.
898
+ if (typeof sentName === 'string') row.sentName = sentName;
899
+ if (typeof sentTaken === 'string') row.sentTaken = sentTaken;
894
900
  // M4d am37 item 5: which way the model step saved its artifact - `first` (round 1), `forced` (the forced call after the fixed line), `fallback` (the unforced call); absent when it did not save. The ONE writer.
895
901
  if (savedBy === 'first' || savedBy === 'forced' || savedBy === 'fallback') row.savedBy = savedBy;
896
902
  // M4d am37, ruling A: the fixed say of a try whose forced call the provider refused with no usage returned (it booked $0); absent otherwise. The ONE writer.
@@ -1520,6 +1526,7 @@ export async function runFlow({
1520
1526
  const result = await foldFromStep({
1521
1527
  mcpServer: declaration.mcp?.server ?? null,
1522
1528
  checkList: declaration.checkList,
1529
+ jobLines: read.lines,
1523
1530
  i0: 0,
1524
1531
  steps,
1525
1532
  askLines,
@@ -1901,12 +1908,14 @@ async function foldFromStep({
1901
1908
  mcpServer = /** @type {string|null} */ (null),
1902
1909
  // M16 item 5: the signed list (declaration.checkList): a list line's checks are tagged by their row in the Audit
1903
1910
  checkList = /** @type {any[]|undefined} */ (undefined),
1911
+ // M15 am3: the signed job lines (their `~` rules are written in the report)
1912
+ jobLines = /** @type {any[]|undefined} */ (undefined),
1904
1913
  }) {
1905
1914
  let runAcceptedThisRun = acceptedThisRun;
1906
1915
  let runUnjudged = unjudgedSinceLastAsk;
1907
1916
  // M13 am9: the Ask that shows the whole job (-1 = none: a job signed before am8 is unchanged)
1908
1917
  const wholeIdx = wholeJobAskIndex({ steps, askLines, sendLines });
1909
- const rebuildWhole = () => wholeJobText({ steps, askLines, lastAskIndex: wholeIdx, readResult: (id) => readArtifactResult(runDir, id) });
1918
+ const rebuildWhole = () => wholeJobText({ steps, askLines, lastAskIndex: wholeIdx, readResult: (id) => readArtifactResult(runDir, id), context: reportContextOf({ runDir, steps, jobLines, checkList }) });
1910
1919
 
1911
1920
  for (let i = i0; i < steps.length; i += 1) {
1912
1921
  const step = steps[i];
@@ -2017,12 +2026,20 @@ async function foldFromStep({
2017
2026
  shaToSend = typeof stop.acceptedSha256 === 'string' ? stop.acceptedSha256 : decided.outgoingSha;
2018
2027
  }
2019
2028
  }
2020
- const filename = `${flowName}-${runId}-${step.emits}.md`;
2029
+ // M15 am3 item 6: what is written is the accepted body (the whole-job text built at the last Ask) under the title and the Passed line the send adds; the hash check stays on `content`
2030
+ const sendBody = sendBodyOf({ content, wholeIdx, steps, sendIndex: i, askLines, context: reportContextOf({ runDir, steps, jobLines, checkList }) });
2031
+ if (!sendBody.ok) {
2032
+ return haltRun({
2033
+ flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts, outcome: 'red', red: sendBody.red,
2034
+ });
2035
+ }
2021
2036
  // eslint-disable-next-line no-await-in-loop
2022
- const sendResult = await sendStep(target, filename, content, shaToSend, { root: flowRoot, runDir });
2037
+ const sendResult = await sendStep(target, flowName, content, shaToSend, { root: flowRoot, runDir, report: { runNo: runNumberOf(runId), now: new Date(), body: sendBody.body } });
2023
2038
  const sendRow = makeAuditRow({
2024
2039
  step, attempt: 1, verdict: sendResult.ok ? 'green' : 'red', gap: sendResult.ok ? null : sendResult.red, usd: 0, spendComplete: true, wallMs: 0, strike: false, at: now(),
2025
2040
  ...(sendResult.ok && typeof sendResult.sha256 === 'string' ? { sentSha256: sendResult.sha256 } : {}),
2041
+ ...(sendResult.ok && typeof sendResult.name === 'string' ? { sentName: sendResult.name } : {}),
2042
+ ...(sendResult.ok && typeof sendResult.taken === 'string' ? { sentTaken: sendResult.taken } : {}),
2026
2043
  });
2027
2044
  recordAudit(sendRow);
2028
2045
  if (!sendResult.ok) {
@@ -2756,7 +2773,7 @@ export async function resumeRun({
2756
2773
  let priorArtifact = readArtifact(runDir, priorId);
2757
2774
  // M13 am9: the Ask that shows the whole job rebuilds `{text}` from the saved outputs, as the first pass did
2758
2775
  const wholeIdx = wholeJobAskIndex({ steps, askLines, sendLines });
2759
- const rebuildWhole = () => wholeJobText({ steps, askLines, lastAskIndex: wholeIdx, readResult: (id) => readArtifactResult(runDir, id) });
2776
+ const rebuildWhole = () => wholeJobText({ steps, askLines, lastAskIndex: wholeIdx, readResult: (id) => readArtifactResult(runDir, id), context: reportContextOf({ runDir, steps, jobLines: read.lines, checkList: declaration.checkList }) });
2760
2777
  if (state.stepIndex === wholeIdx) {
2761
2778
  const whole = rebuildWhole();
2762
2779
  if (!whole.ok) {
@@ -2833,6 +2850,7 @@ export async function resumeRun({
2833
2850
  const result = await foldFromStep({
2834
2851
  mcpServer: declaration.mcp?.server ?? null,
2835
2852
  checkList: declaration.checkList,
2853
+ jobLines: read.lines,
2836
2854
  i0: isStop ? state.stepIndex : state.stepIndex + 1,
2837
2855
  ...(isStop ? { stopAcceptedSha: typeof askResult.acceptedSha256 === 'string' ? askResult.acceptedSha256 : null } : {}),
2838
2856
  steps,
@@ -3043,6 +3061,7 @@ export async function continueRun({
3043
3061
  const result = await foldFromStep({
3044
3062
  mcpServer: declaration.mcp?.server ?? null,
3045
3063
  checkList: declaration.checkList,
3064
+ jobLines: read.lines,
3046
3065
  i0: halt.stepIndex,
3047
3066
  resumeTries,
3048
3067
  steps,
package/src/send.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // M2 piece 2 (docs/wiki/the-module-ladder.md, "M2 — scope, exit, negative —
2
- // SIGNED"): the live `sendStep(target, filename, content)` `src/runner.js`'s
2
+ // SIGNED"): the live `sendStep(target, jobName, content, sha, ctx)` `src/runner.js`'s
3
3
  // `runFlow` expects. `checkSendDestination` — the containment check
4
4
  // (lexical AND realpath, write-time re-check) — is owned by `src/runner.js`
5
5
  // (piece 1 already wrote it); this module imports it rather than growing a
@@ -12,95 +12,31 @@
12
12
  // bytes reds here, not upstream).
13
13
 
14
14
  import { createHash } from 'node:crypto';
15
- import { lstatSync, readFileSync } from 'node:fs';
15
+ import { readFileSync } from 'node:fs';
16
16
  import { join } from 'node:path';
17
17
  import { createShellTools } from 'bare-agent/tools';
18
18
 
19
19
  import { checkSendDestination } from './runner.js';
20
20
  import { serializeArtifact, sha256Hex } from './ask.js';
21
+ import { nextFreeName, reportFileText, MAX_SAME_DAY } from './report.js';
21
22
 
22
23
  const { tools: SHELL_TOOLS } = createShellTools();
23
24
  const FOUND_WRITE_TOOL = SHELL_TOOLS.find((t) => t.name === 'shell_write');
24
25
  if (!FOUND_WRITE_TOOL) throw new Error('send: bare-agent/tools does not export a "shell_write" tool');
25
26
  const WRITE_TOOL = FOUND_WRITE_TOOL;
26
27
 
27
- const SCALAR = ['string', 'number', 'boolean'];
28
-
29
- /** one value as leaf lines `{parts, text}`: parts are the names on the way in; text is a string as it is, a number or boolean written out; a list of plain values joined by ", "; null as empty */
30
- /** @param {string[]} parts @param {any} v @returns {{parts: string[], text: string}[]} */
31
- function leaves(parts, v) {
32
- if (v === null || v === undefined) return [{ parts, text: '' }];
33
- if (SCALAR.includes(typeof v)) return [{ parts, text: `${v}` }];
34
- if (Array.isArray(v) && v.every((x) => x === null || SCALAR.includes(typeof x))) return [{ parts, text: v.join(', ') }];
35
- if (Array.isArray(v)) return v.flatMap((x, i) => leaves([...parts, `${i + 1}`], x));
36
- return Object.entries(v).flatMap(([k, x]) => leaves([...parts, k], x));
37
- }
38
-
39
- /** @param {string} name split only at a lowercase-to-capital boundary, `_` and `-`, so `ID` stays one word */
40
- const words = (name) => name.replace(/([a-z0-9])([A-Z])/g, '$1 $2').split(/[_\-\s]+/).filter(Boolean);
41
-
42
- /** M15 am2 (1): the names as plain words; a last name of `value` or `rows` is left out; the first letter capital, the later words lowercase */
43
- /** @param {string[]} parts */
44
- function friendlyName(parts) {
45
- const p = parts.length > 1 && (parts[parts.length - 1] === 'value' || parts[parts.length - 1] === 'rows') ? parts.slice(0, -1) : parts;
46
- const w = p.flatMap(words).map((x) => x.toLowerCase());
47
- if (!w.length) return parts.join('.');
48
- return w[0][0].toUpperCase() + w[0].slice(1) + (w.length > 1 ? ` ${w.slice(1).join(' ')}` : '');
49
- }
50
-
51
- /** the lines of one block (the flat part, or one result); two lines with the same words both keep today's `a.b` form */
52
- /** @param {{parts: string[], text: string}[]} ls */
53
- function blockLines(ls) {
54
- const f = ls.map((l) => friendlyName(l.parts));
55
- /** @type {Record<string, number>} */
56
- const n = {};
57
- for (const x of f) n[x] = (n[x] || 0) + 1;
58
- return ls.map((l, i) => `${n[f[i]] > 1 ? l.parts.join('.') : f[i]}: ${l.text}`);
59
- }
60
-
61
- /** a list of results: every item an object holding a `values` object (flights' `results`, with a `quote` written as its last line) */
62
- /** @param {any} v */
63
- const isResultList = (v) => Array.isArray(v) && v.length > 0 && v.every((r) => r && typeof r === 'object' && !Array.isArray(r) && r.values && typeof r.values === 'object' && !Array.isArray(r.values));
64
-
65
- /**
66
- * M15 items 3 and am1, am2: the accepted answer as the plain-text file the send writes. `{text}` alone is the text exactly; any other flat object is one
67
- * `Name words: value` line per field; a list of results is one `## Result k` block per result with one line per value, in the order the answer holds
68
- * them, then `from the page: "<quote>"`. Never JSON braces, never check marks. What it throws away: a result's keys other than `quote` and `values`.
69
- * @param {Record<string, any>} content @returns {string}
70
- */
71
- export function renderSentMd(content) {
72
- const keys = Object.keys(content);
73
- if (keys.length === 1 && keys[0] === 'text' && typeof content.text === 'string') return content.text;
74
- /** @type {string[]} */
75
- const parts = [];
76
- /** @type {{parts: string[], text: string}[]} */
77
- let flat = [];
78
- const flush = () => { if (flat.length) parts.push(blockLines(flat).join('\n')); flat = []; };
79
- for (const [k, v] of Object.entries(content)) {
80
- if (isResultList(v)) {
81
- flush();
82
- v.forEach((r, i) => {
83
- const lines = blockLines(Object.entries(r.values).flatMap(([n, x]) => leaves([n], x)));
84
- if (typeof r.quote === 'string') lines.push(`from the page: "${r.quote}"`);
85
- parts.push([`## Result ${i + 1}`, ...lines].join('\n'));
86
- });
87
- } else flat.push(...leaves([k], v));
88
- }
89
- flush();
90
- return parts.join('\n\n');
91
- }
92
-
93
28
  /**
29
+ * M15 am3: the send writes ONE markdown report per run, `<job name>-YYYY-MM-DD.md` (then `-2`, `-3`, ... when that name is taken, never over a taken file): the title, the `Passed` line and the accepted
94
30
  * @param {string} target - a signed arbiter target, e.g. `file:poc/m0/out`.
95
- * @param {string} filename
96
- * @param {unknown} content - the accepted artifact; hash-checked as its JSON, written as plain text (`renderSentMd`).
31
+ * @param {string} jobName - the job's name: the file's name starts with it
32
+ * @param {unknown} content - the accepted artifact; hash-checked as its JSON (M4b item 4).
97
33
  * @param {string|null} [acceptedSha256] - the sha256 the human's accept recorded
98
34
  * (`answerAsk`, M4b piece 3). Required: none recorded (an answer written by an
99
35
  * older version, or no accept in this process) refuses by name.
100
- * @param {{root?: string, runDir?: string}} [ctx] the flow root and this run's folder, for the destination refusals
101
- * @returns {Promise<{ok:true, path:string, bytes:number, sha256:string} | {ok:false, red:string}>}
36
+ * @param {{root?: string, runDir?: string, report?: {runNo: number|null, now?: Date, body: string}}} [ctx] the flow root and this run's folder, for the destination refusals; the report's body, run number and day
37
+ * @returns {Promise<{ok:true, path:string, name:string, bytes:number, sha256:string, taken:string|null} | {ok:false, red:string}>}
102
38
  */
103
- export async function sendViaPrimitive(target, filename, content, acceptedSha256, ctx = {}) {
39
+ export async function sendViaPrimitive(target, jobName, content, acceptedSha256, ctx = {}) {
104
40
  const destination = checkSendDestination(target, ctx);
105
41
  if (!destination.ok) return { ok: false, red: destination.red };
106
42
 
@@ -137,18 +73,19 @@ export async function sendViaPrimitive(target, filename, content, acceptedSha256
137
73
  return { ok: false, red: `send: the artifact changed after it was accepted (accepted sha256 ${acceptedSha256}, about to send ${actualSha256}) — refused (nothing shipped)` };
138
74
  }
139
75
 
140
- const path = join(destination.dir, filename);
141
- // M4e amendment 1: never overwrite. `shell_write` has no exclusive-create mode, so this is an
142
- // existence check immediately before the write (lstat: a dangling symlink at the name counts as
143
- // present). A file created in the instants between this check and the write is still overwritten.
144
- let present = true;
145
- try { lstatSync(path); } catch (err) { if (err.code === 'ENOENT') present = false; }
146
- if (present) return { ok: false, red: `send: "${path}" already exists — never overwritten (nothing shipped)` };
147
- await WRITE_TOOL.execute({ path, content: renderSentMd(/** @type {Record<string, unknown>} */ (content)) });
76
+ const report = ctx.report;
77
+ if (!report || typeof report.body !== 'string') return { ok: false, red: 'send: no report body was given for this send — refused (nothing shipped)' };
78
+ // M15 am3 item 1 (replaces M4e amendment 1's refusal for this file): a taken name is never written over; the report lands under the next free same-day name. `shell_write` has no exclusive-create
79
+ // mode, so this is an existence check immediately before the write (a dangling symlink at the name counts as present); a file created in the instants between the check and the write is still overwritten.
80
+ const now = report.now ?? new Date();
81
+ const pick = nextFreeName(destination.dir, jobName, now);
82
+ if (pick.name === null) return { ok: false, red: `send: every same-day name for "${jobName}" is taken (up to -${MAX_SAME_DAY}) — never overwritten (nothing shipped)` };
83
+ const path = join(destination.dir, pick.name);
84
+ await WRITE_TOOL.execute({ path, content: reportFileText(jobName, report.runNo, now, report.body) });
148
85
 
149
86
  const bytes = readFileSync(path);
150
87
  if (bytes.byteLength === 0) {
151
88
  return { ok: false, red: `send: "${path}" wrote 0 bytes` };
152
89
  }
153
- return { ok: true, path, bytes: bytes.byteLength, sha256: createHash('sha256').update(bytes).digest('hex') };
90
+ return { ok: true, path, name: pick.name, bytes: bytes.byteLength, sha256: createHash('sha256').update(bytes).digest('hex'), taken: pick.taken };
154
91
  }
@@ -56,3 +56,51 @@ export function sheetBrief(checks) {
56
56
  fields: Object.fromEntries(sheetClaims(checks).map(({ claim, example }) => [claim, example])),
57
57
  };
58
58
  }
59
+
60
+ // borrowed-from: bareloop src/sheetclaims.js@v0.60.0 (sheetTotalLines, PLAIN_CELL_NUMBER, ROW_MATH_OPS, fmt; the F356 strict number test). Adapted (M15 am3a): fwd's boxes are separate, so the rows come from the line's `rows` check of the same table and `where`.
61
+ export const ROW_MATH_OPS = Object.freeze(['sumIf', 'countIf']);
62
+
63
+ /** A strict plain number: optional sign, digits (commas only as thousands groups of three), optional decimals. `12,50`, `1e3`, `0x10` are not numbers. */
64
+ const PLAIN_CELL_NUMBER = /^[+-]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?$/;
65
+ const fmt = (/** @type {number} */ n, /** @type {number} */ d) => Number(n.toFixed(d)).toLocaleString('en-US', { minimumFractionDigits: d, maximumFractionDigits: d });
66
+ const sameWhere = (/** @type {any} */ a, /** @type {any} */ b) => a.table === b.table && JSON.stringify(a.where ?? null) === JSON.stringify(b.where ?? null);
67
+
68
+ /**
69
+ * The plain lines the report carries for each sumIf / countIf check: `Count of rows 3, 5, 9: 3 (computed by code from the rows named)` and `Total of rows 3, 5, 9: 1,234.50 (computed by code from the rows named)`.
70
+ * Computed from the FROZEN table and the rows the step named in the `rows` check of the same table and `where` (M15 am3a), never from a number the step wrote. A check with no such `rows` check, or whose box holds no list
71
+ * of integers, writes no line. A named row that is no row of the sheet adds nothing; a blank cell is skipped; a cell that is no strict number makes the total "not computed", naming the row and the column.
72
+ * @param {any[]} checks the step's sheet checks as signed @param {any} claims the step's boxes by claim name @param {Record<string, {header: string[], rows: {rowNumber: number, cells: string[]}[]}>} tables by input label
73
+ * @returns {string[]}
74
+ */
75
+ export function sheetTotalLines(checks, claims, tables) {
76
+ /** @type {string[]} */
77
+ const out = [];
78
+ for (const c of checks) {
79
+ if (!isRec(c) || c.rule !== 'cells' || !ROW_MATH_OPS.includes(c.op)) continue;
80
+ const rowsCheck = checks.find((x) => isRec(x) && x.rule === 'cells' && x.op === 'rows' && typeof x.claim === 'string' && sameWhere(x, c));
81
+ const box = rowsCheck && isRec(claims) && isRec(claims[rowsCheck.claim]) ? claims[rowsCheck.claim].rows : undefined;
82
+ const table = tables[c.table];
83
+ if (!table || !Array.isArray(box) || !box.every((/** @type {unknown} */ x) => Number.isInteger(x))) continue;
84
+ const named = [...new Set(/** @type {number[]} */ (box))].sort((a, b) => a - b);
85
+ const byRow = new Map(table.rows.map((r) => [r.rowNumber, r]));
86
+ const rows = named.filter((n) => byRow.has(n));
87
+ const list = rows.length > 0 ? `rows ${rows.join(', ')}` : 'no rows';
88
+ if (c.op === 'countIf') { out.push(`Count of ${list}: ${rows.length} (computed by code from the rows named)`); continue; }
89
+ const col = table.header.indexOf(c.column);
90
+ let sum = 0;
91
+ let decimals = 0;
92
+ /** @type {number|null} */
93
+ let bad = null;
94
+ for (const n of rows) {
95
+ const cell = String(byRow.get(n)?.cells[col] ?? '').trim();
96
+ if (cell === '') continue;
97
+ if (!PLAIN_CELL_NUMBER.test(cell)) { bad = n; break; }
98
+ sum += Number(cell.replaceAll(',', ''));
99
+ decimals = Math.max(decimals, (cell.split('.')[1] ?? '').length);
100
+ }
101
+ out.push(bad === null
102
+ ? `Total of ${list}: ${fmt(sum, Math.min(decimals, 6))} (computed by code from the rows named)`
103
+ : `Total of ${list}: not computed (row ${bad} has no number in the column "${c.column}")`);
104
+ }
105
+ return out;
106
+ }
package/src/sheetfind.js CHANGED
@@ -48,5 +48,13 @@ export function findColumn(csvText, word) {
48
48
  * @param {string} word @param {FoundAsk} found @param {number} line @returns {string}
49
49
  */
50
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
+
52
+ // borrowed-from: bareloop src/sheetfind.js@v0.60.0 (columnTieQuestion; the tail is fwd's signed M17 am9 item 1, a closed question: no `Answer "agree"`)
53
+ /**
54
+ * The question for a tie (M17 am9): the real count, the columns in sheet order, then the tail of a `~` rule's closed question.
55
+ * @param {string} word @param {string[]} columns @param {number} line @returns {string}
56
+ */
57
+ export const columnTieQuestion = (word, columns, line) => `I found ${columns.length} columns matching '${word}': ${columns.join(', ')}. Choose one. (your answer replaces that ~ rule on line ${line}).`;
58
+
51
59
  /** @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
60
  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}).`);
package/src/sheetlook.js CHANGED
@@ -10,7 +10,7 @@ import { parseCsv } from './csv.js';
10
10
  import { MAP_UNREADABLE } from './pagemap.js';
11
11
  import { tieOf } from './pagerules.js';
12
12
  import { lineRules, countPhrase, wordsSaidOn, wordForms } from './pagebits.js';
13
- import { findColumn, columnQuestion } from './sheetfind.js';
13
+ import { findColumn, columnQuestion, columnTieQuestion } from './sheetfind.js';
14
14
 
15
15
  /** how many data rows the prompt shows (the header is always shown): enough to see what a column holds, never the whole sheet */
16
16
  export const SHEET_PROMPT_ROWS = 5;
@@ -109,6 +109,16 @@ export function applySheetWords(text, words, jobLines, label) {
109
109
  continue;
110
110
  }
111
111
  if (w.kind !== 'number') { dropped.push({ ...rec, reason: 'no-column' }); continue; }
112
+ // M17 am9: a tie on a `~` rule's word asks which column (a closed question: the tied columns and each one's reading); a tie on a line's own prose word stays Not checked
113
+ if (found.kind === 'tie' && at.rule !== undefined) {
114
+ ruleWords.add(`${at.line}\u0000${w.word.toLowerCase()}`);
115
+ if (tiedRules.has(`${at.line}\u0000${at.rule}`)) continue;
116
+ asks.push({
117
+ line: at.line, rule: at.rule, source: 'look', ask: 'reading', ruleText, question: columnTieQuestion(w.word, found.columns, at.line), word: w.word,
118
+ columns: found.columns, readings: Object.fromEntries(found.columns.map((c) => [c, columnRuleWords(w.word, c)])),
119
+ });
120
+ continue;
121
+ }
112
122
  if (found.kind === 'tie') { dropped.push({ ...rec, reason: 'column-tie', other: found.columns.map((c) => `"${c}"`).join(', ') }); continue; }
113
123
  if (found.kind === 'none') { dropped.push({ ...rec, reason: 'no-fit', other: String(found.rows) }); continue; }
114
124
  // the person already named this column in a rule of the line (an answer they gave, or their own words): the word is that column, asked no more
package/src/whole-job.js CHANGED
@@ -1,9 +1,12 @@
1
- // M13 am9: the file holds the whole job. ONE writer of the whole-job text (`wholeJobText`), ONE finder of the Ask that shows it (`wholeJobAskIndex`).
2
- // The last Ask before the added `write it out` shows every step's result in job order, built by code from each step's saved output (never picked by the AI):
3
- // a work step is one section `## Line <n>: <line words>` + `renderSentMd(<its saved output>)` (the M15 form, unchanged); an Ask before it is one line
4
- // `Line <n>: you accepted this at the Ask.`; the last Ask itself and the send line are not sections. The accepted artifact is `{text}`, so the send ships it unchanged.
5
- // Throws away: nothing of a step's saved output beyond what `renderSentMd` already drops. Third outcomes: a work step with no readable saved output refuses, naming the step.
6
- import { renderSentMd } from './send.js';
1
+ // M13 am9 / M15 am3: the file holds the whole job. ONE writer of the whole-job text (`wholeJobText`), ONE finder of the Ask that shows it (`wholeJobAskIndex`).
2
+ // The last Ask before the added `write it out` shows every step's result in job order, built by code from each step's saved output (never picked by the AI). Since M15 am3 that text is the BODY of the
3
+ // run's one markdown report (`renderReportBody`, src/report.js: `## <n>. <line>`, the ~ rules, what code checked, the AI's answer under its heading; an Ask before it is one line
4
+ // `Line <n>: you accepted this at the Ask.`); the last Ask itself and the send line are not sections. The accepted artifact is `{text}`; the send adds the title and the Passed line and writes it.
5
+ // Throws away: what `renderReportBody` throws away. Third outcomes: a work step with no readable saved output refuses, naming the step; a frozen sheet the report needs that cannot be read refuses, naming it.
6
+ import { renderReportBody } from './report.js';
7
+ import { readRunSheets } from './sheetrun.js';
8
+ import { readSheetChecks } from './sheet-record.js';
9
+ import { lineRules } from './pagebits.js';
7
10
 
8
11
  /**
9
12
  * The Ask the action reads: the Ask right before the one signed send (M13 am11: the action ships the step before it). -1 = none.
@@ -39,18 +42,62 @@ export function wholeJobAskIndex({ steps, askLines, sendLines }) {
39
42
  return work.length > 0 && reads.length === work.length && work.every((e) => reads.includes(e)) ? idx : -1;
40
43
  }
41
44
 
45
+ /** the `~` rules of a signed job line, one string each: the parsed line carries them joined by "; " in `guardrail` (several `~` lines under one step are one guardrail), as the Result tab reads it @param {any} jl @returns {string[]} */
46
+ const lineRulesOf = (jl) => (jl && typeof jl.guardrail === 'string' && jl.guardrail !== '' ? jl.guardrail.split('; ').filter(Boolean) : lineRules(jl));
47
+
48
+ /**
49
+ * Is the prose of this step checked by code (M15 am3 item 2: `### The answer` instead of the not-checked heading)? Only when code really checked the step's own text (a green close with a words-per-section
50
+ * or picked check on it) AND the signed list holds no Not checked `~` rule on the line. A non-empty / `happened` check alone is no prose check, nor is a sheet or quote check (they check cells and quotes).
51
+ * @param {any} step @param {any[]|null|undefined} [checkList] the plan's signed list (`declaration.checkList`)
52
+ * @returns {boolean}
53
+ */
54
+ export function proseCheckedOf(step, checkList) {
55
+ const rows = (Array.isArray(checkList) ? checkList : []).filter((r) => r && typeof r === 'object' && r.line === step?.fromLine);
56
+ if (rows.some((r) => r.kind === 'rule' && r.state === 'not-checked')) return false;
57
+ const c = step?.close;
58
+ if (c?.class !== 'green') return false;
59
+ const shape = c.shape && typeof c.shape === 'object' ? c.shape : {};
60
+ return shape.wordsPerSection !== undefined || (Array.isArray(shape.picked) && shape.picked.length > 0) || (Array.isArray(c.picked) && c.picked.length > 0);
61
+ }
62
+
42
63
  /**
43
- * @param {{ steps: { fromLine: number, goal: string, emits?: string }[], askLines: Map<number, any>, lastAskIndex: number,
44
- * readResult: (id: string) => ({ ok: true, value: any } | { ok: false, missing: true } | { ok: false, missing: false, red: string }) }} p
64
+ * What the report needs besides the steps: the signed lines' own words (the `~` rules), the run's frozen sheets and which sheet checks passed. Read once from the run folder.
65
+ * @param {{ runDir: string, steps: any[], jobLines: any[]|null|undefined, checkList?: any[]|null }} p
66
+ * @returns {{ ok: true, jobLines: any[], checkList: any[]|null, tables: Record<string, any>, okIdsOf: (n: number) => Set<string>|null } | { ok: false, red: string }}
67
+ */
68
+ export function reportContextOf({ runDir, steps, jobLines, checkList }) {
69
+ const checks = steps.flatMap((s) => (Array.isArray(s?.close?.sheet) ? s.close.sheet : []));
70
+ /** @type {Record<string, any>} */
71
+ let tables = {};
72
+ if (checks.length > 0) {
73
+ const sheet = readRunSheets(runDir, checks);
74
+ if (!sheet.ok) return { ok: false, red: `ask: the report cannot read the saved sheet — ${sheet.red}` };
75
+ tables = sheet.tables;
76
+ }
77
+ const record = checks.length > 0 ? readSheetChecks(runDir) : null;
78
+ const okIdsOf = (/** @type {number} */ n) => {
79
+ // the newest try of the line that passed: the ids of its checks that passed
80
+ const tries = (record?.lines ?? []).filter((l) => l && l.n === n && l.passed === true && Array.isArray(l.results));
81
+ const last = tries.reduce((m, l) => (m === null || l.try >= m.try ? l : m), /** @type {any} */ (null));
82
+ return last ? new Set(last.results.filter((/** @type {any} */ r) => r && r.ok === true).map((/** @type {any} */ r) => r.id)) : null;
83
+ };
84
+ return { ok: true, jobLines: Array.isArray(jobLines) ? jobLines : [], checkList: Array.isArray(checkList) ? checkList : null, tables, okIdsOf };
85
+ }
86
+
87
+ /**
88
+ * @param {{ steps: { fromLine: number, goal: string, emits?: string, close?: any }[], askLines: Map<number, any>, lastAskIndex: number,
89
+ * readResult: (id: string) => ({ ok: true, value: any } | { ok: false, missing: true } | { ok: false, missing: false, red: string }),
90
+ * context: ReturnType<typeof reportContextOf> }} p
45
91
  * @returns {{ ok: true, value: { text: string } } | { ok: false, red: string }}
46
92
  */
47
- export function wholeJobText({ steps, askLines, lastAskIndex, readResult }) {
48
- /** @type {string[]} */
49
- const parts = [];
93
+ export function wholeJobText({ steps, askLines, lastAskIndex, readResult, context }) {
94
+ if (!context.ok) return { ok: false, red: context.red };
95
+ /** @type {Parameters<typeof renderReportBody>[0]} */
96
+ const lines = [];
50
97
  for (let i = 0; i < lastAskIndex; i += 1) {
51
98
  const s = steps[i];
52
99
  if (askLines.has(s.fromLine)) {
53
- parts.push(`Line ${s.fromLine}: you accepted this at the Ask.`);
100
+ lines.push({ n: s.fromLine, kind: 'ask' });
54
101
  continue;
55
102
  }
56
103
  const r = readResult(/** @type {string} */ (s.emits));
@@ -62,9 +109,38 @@ export function wholeJobText({ steps, askLines, lastAskIndex, readResult }) {
62
109
  : `ask: the saved output "${s.emits}" of step "${s.goal}" — ${r.red}`,
63
110
  };
64
111
  }
65
- parts.push(`## Line ${s.fromLine}: ${s.goal}\n${renderSentMd(r.value)}`);
112
+ const jl = context.jobLines.find((/** @type {any} */ l) => l && l.n === s.fromLine);
113
+ lines.push({
114
+ n: s.fromLine, kind: 'work', text: s.goal, rules: lineRulesOf(jl), artifact: r.value,
115
+ checks: Array.isArray(s.close?.sheet) ? s.close.sheet : [], okIds: context.okIdsOf(s.fromLine), proseChecked: proseCheckedOf(s, context.checkList),
116
+ });
117
+ }
118
+ return { ok: true, value: { text: renderReportBody(lines, context.tables) } };
119
+ }
120
+
121
+ /**
122
+ * M15 am3 item 6: the body the send writes. A plan whose last Ask shows the whole job (`wholeIdx` >= 0) was accepted AS that text: the body is `{text}` exactly, never rebuilt. A plan signed before
123
+ * M13 am9 (or a job with no Ask) sends the one step right before the send: its section is written from the accepted artifact, the line being that step's own (or, past an Ask, the step the Ask read).
124
+ * @param {{ content: any, wholeIdx: number, steps: any[], sendIndex: number, askLines: Map<number, any>, context: ReturnType<typeof reportContextOf> }} p
125
+ * @returns {{ ok: true, body: string } | { ok: false, red: string }}
126
+ */
127
+ export function sendBodyOf({ content, wholeIdx, steps, sendIndex, askLines, context }) {
128
+ if (wholeIdx >= 0) {
129
+ return typeof content?.text === 'string' && Object.keys(content).length === 1
130
+ ? { ok: true, body: content.text }
131
+ : { ok: false, red: 'send: the accepted answer is not the whole-job text — refusing to write a report from it' };
66
132
  }
67
- return { ok: true, value: { text: parts.join('\n\n') } };
133
+ if (!context.ok) return { ok: false, red: context.red };
134
+ const before = steps[sendIndex - 1];
135
+ const made = before && askLines.has(before.fromLine) ? steps.find((x) => x.emits === (before.reads ?? [])[0]) ?? before : before;
136
+ const jl = context.jobLines.find((/** @type {any} */ l) => l && l.n === made?.fromLine);
137
+ return {
138
+ ok: true,
139
+ body: renderReportBody([{
140
+ n: made?.fromLine, kind: 'work', text: made?.goal, rules: lineRulesOf(jl), artifact: content,
141
+ checks: Array.isArray(made?.close?.sheet) ? made.close.sheet : [], okIds: context.okIdsOf(made?.fromLine), proseChecked: proseCheckedOf(made, context.checkList),
142
+ }], context.tables),
143
+ };
68
144
  }
69
145
 
70
146
  /**
@@ -23,7 +23,7 @@ export function specHash({ proseText, declarationText, inputFactsText, readoutTe
23
23
  * answer file counts as no answer. No questions file = `{ questions: [], open: [] }`.
24
24
  * @param {string} planDir
25
25
  * A question the page look raised (M10 piece 3) also carries `source: 'look'`, `ask` ('reading' | 'cant-check'), `ruleNo`, `ruleText` and `proposal`; an answer file carries `at`.
26
- * @returns {{ questions: {k:number, line:number, question:string, answer:string|null, at?:string, rule?:string|null, choice?:'agree'|'drop'|'rule', source?:string, ask?:string, ruleNo?:number, ruleText?:string, proposal?:string|null, check?:Record<string, any>, pairRule?:number}[], open: {k:number, line:number, question:string, answer:null}[] }}
26
+ * @returns {{ questions: {k:number, line:number, question:string, answer:string|null, at?:string, rule?:string|null, choice?:'agree'|'drop'|'rule'|'column', source?:string, ask?:string, ruleNo?:number, ruleText?:string, proposal?:string|null, check?:Record<string, any>, pairRule?:number, columns?:string[], readings?:Record<string,string>}[], open: {k:number, line:number, question:string, answer:null}[] }}
27
27
  */
28
28
  export function readQuestions(planDir: string): {
29
29
  questions: {
@@ -33,7 +33,7 @@ export function readQuestions(planDir: string): {
33
33
  answer: string | null;
34
34
  at?: string;
35
35
  rule?: string | null;
36
- choice?: "agree" | "drop" | "rule";
36
+ choice?: "agree" | "drop" | "rule" | "column";
37
37
  source?: string;
38
38
  ask?: string;
39
39
  ruleNo?: number;
@@ -41,6 +41,8 @@ export function readQuestions(planDir: string): {
41
41
  proposal?: string | null;
42
42
  check?: Record<string, any>;
43
43
  pairRule?: number;
44
+ columns?: string[];
45
+ readings?: Record<string, string>;
44
46
  }[];
45
47
  open: {
46
48
  k: number;
@@ -42,7 +42,7 @@ export function decidedWords(h: {
42
42
  * person's own words, taken word for word with newlines folded to spaces. A question that is not a look ask is never changed: its answer is its rule.
43
43
  * M10 am16: a shape guardrail's ask (`ask: 'check'` proposes a check, `'no-check'` found none) takes the same words: `agree` takes the proposal (and the check it
44
44
  * carries, `check`), `drop it` leaves the rule Not checked (either kind), anything else is the person's own words (`own`: a `~` rule on the line, no check).
45
- * @param {{source?: string, ask?: string, proposal?: string|null, check?: Record<string, any>}} q @param {unknown} typed @param {'agree'|'drop'|'rule'} [choice] M10 am29: the button used; absent = today's words reading (CLI, old files)
45
+ * @param {{source?: string, ask?: string, proposal?: string|null, check?: Record<string, any>, readings?: Record<string, string>}} q @param {unknown} typed @param {'agree'|'drop'|'rule'|'column'} [choice] M10 am29: the button used; absent = today's words reading (CLI, old files)
46
46
  * @returns {{rule: string|null, left: boolean, check?: Record<string, any>, own?: boolean, action?: 'known', actionLine?: string}} `rule` = the words written as a new `~` rule (null when the rule is left Not checked)
47
47
  */
48
48
  export function ruleOfAnswer(q: {
@@ -50,7 +50,8 @@ export function ruleOfAnswer(q: {
50
50
  ask?: string;
51
51
  proposal?: string | null;
52
52
  check?: Record<string, any>;
53
- }, typed: unknown, choice?: "agree" | "drop" | "rule"): {
53
+ readings?: Record<string, string>;
54
+ }, typed: unknown, choice?: "agree" | "drop" | "rule" | "column"): {
54
55
  rule: string | null;
55
56
  left: boolean;
56
57
  check?: Record<string, any>;
@@ -62,6 +63,8 @@ export function ruleOfAnswer(q: {
62
63
  export const MAX_LOOK_ASKS: 3;
63
64
  /** the answer that drops a `~` rule the page cannot check: the person types it (any case, a closing full stop allowed) */
64
65
  export const DROP_IT: "drop it";
66
+ /** M17 am9 item 3: the door's refusal of a wrong answer to a column tie (signed words) */
67
+ export const TIE_PICK_SAY: "This question has a list to choose from: pick one of the columns, or Drop it. Nothing was saved.";
65
68
  export function isDropIt(text: unknown): boolean;
66
69
  /** the answers that accept the code's reading of a rule; anything else the person types is their own reading */
67
70
  export const AGREE_WORDS: string[];
@@ -64,7 +64,7 @@ export function readDelivered(rec: {
64
64
  * The files this run's signed sends wrote: for each signed send whose send step ended green in the audit, the file `<flow>-<runId>-<emits>.md`
65
65
  * in the signed folder with the sha256 the send recorded for it (M15), or, for a send older than M15, `.json` with the sha256 the human's accept recorded for the ask that
66
66
  * send reads (`readAcceptedHashesByEmits`, the same record the send itself checked). No accepted hash = recorded as null, which reads as "changed", never as ok.
67
- * @returns {{path: string, dir: string|null, name: string, sha256: string|null}[]}
67
+ * @returns {{path: string, dir: string|null, name: string, note: string|null, sha256: string|null}[]}
68
68
  */
69
69
  export function deliveredOf({ arbiter, declaration, runDir, root, flow, runId, auditRows, }: {
70
70
  arbiter: any;
@@ -78,6 +78,7 @@ export function deliveredOf({ arbiter, declaration, runDir, root, flow, runId, a
78
78
  path: string;
79
79
  dir: string | null;
80
80
  name: string;
81
+ note: string | null;
81
82
  sha256: string | null;
82
83
  }[];
83
84
  /**
@@ -117,6 +118,7 @@ export function buildResult({ flow, runId, runDir, root, flowRead, arbiter, hist
117
118
  bytes: number | null;
118
119
  state: "ok" | "changed" | "gone";
119
120
  words: string | null;
121
+ note: string | null;
120
122
  }[];
121
123
  gap: {
122
124
  line: string;
@@ -0,0 +1,45 @@
1
+ /**
2
+ * claim id -> the sentence of the first passed non-sumIf/countIf check carrying it; a claim only sumIf/countIf carry is null. `okIds` = the ids of the checks that passed, or null = no record (all count).
3
+ * @param {any[]} checks @param {Set<string>|null} okIds @returns {Record<string, string|null>}
4
+ */
5
+ export function claimWordsOf(checks: any[], okIds: Set<string> | null): Record<string, string | null>;
6
+ /** the date as plain words, `18 Nov 2026`, in the machine's local day (the day the dated file names use) @param {Date} d */
7
+ export function plainDate(d: Date): string;
8
+ /** the run number when the run id reads `run-N`, else null (a rerun id `run-1-rerun-1` has none) @param {string} runId @returns {number|null} */
9
+ export function runNumberOf(runId: string): number | null;
10
+ /**
11
+ * The body: every line before the send, in job order. A work line is `## <n>. <text>`, a `Rule:` per ~ rule, `### Checked by code` (bullets) and the AI's text under its heading; an Ask line is one line
12
+ * in its place; a work line with nothing to write has no section. Pure.
13
+ * @param {{n: number, kind: 'ask'|'work', text?: string, rules?: string[], artifact?: unknown, checks?: any[], okIds?: Set<string>|null, proseChecked?: boolean}[]} lines
14
+ * @param {Record<string, any>} tables the frozen sheets by input name
15
+ * @returns {string}
16
+ */
17
+ export function renderReportBody(lines: {
18
+ n: number;
19
+ kind: "ask" | "work";
20
+ text?: string;
21
+ rules?: string[];
22
+ artifact?: unknown;
23
+ checks?: any[];
24
+ okIds?: Set<string> | null;
25
+ proseChecked?: boolean;
26
+ }[], tables: Record<string, any>): string;
27
+ /**
28
+ * The file name for a report: `<job>-YYYY-MM-DD.md`, then `<job>-YYYY-MM-DD-2.md`, `-3`, ... the first one that is free in `dir` (the machine's local day). Never a taken name. `taken` = the first choice
29
+ * when it was not free (the Result tab's note names it), else null. `name` = null when every name up to -99 is taken.
30
+ * @param {string} dir the Destination folder @param {string} job @param {Date} now
31
+ * @returns {{name: string|null, taken: string|null}}
32
+ */
33
+ export function nextFreeName(dir: string, job: string, now: Date): {
34
+ name: string | null;
35
+ taken: string | null;
36
+ };
37
+ /** the words under a not-checked answer and a checked one (M15 am3 item 2) */
38
+ export const NOT_CHECKED_HEADING: "### The AI's answer (not checked \u2014 you judge it at Accept)";
39
+ export const CHECKED_HEADING: "### The answer";
40
+ export function askLineWords(n: number): string;
41
+ export function REPORT_RENAMED(taken: string): string;
42
+ export function reportHead(job: string, runNo: number | null, now: Date): string;
43
+ export function reportFileText(job: string, runNo: number | null, now: Date, body: string): string;
44
+ /** the most same-day names tried before the send stops (bareloop's MAX_SAME_DAY) */
45
+ export const MAX_SAME_DAY: 99;