fwdloop 0.20.0 → 0.22.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 (92) hide show
  1. package/README.md +2 -0
  2. package/bin/fwdloop +85 -34
  3. package/package.json +4 -3
  4. package/src/audit-fold.js +181 -0
  5. package/src/authoring.js +33 -7
  6. package/src/books.js +1 -1
  7. package/src/checked.js +18 -1
  8. package/src/cited-record.js +138 -0
  9. package/src/cited-source.js +49 -0
  10. package/src/citedcheck.js +306 -0
  11. package/src/citedwords.js +197 -0
  12. package/src/closers.js +105 -9
  13. package/src/ctx-tools.js +2 -14
  14. package/src/declaration.js +85 -5
  15. package/src/diary.js +49 -0
  16. package/src/docx.js +16 -2
  17. package/src/draft-steps.js +1 -1
  18. package/src/drafter.js +292 -25
  19. package/src/flow.js +33 -7
  20. package/src/flowmodel.js +63 -5
  21. package/src/input-facts.js +20 -3
  22. package/src/model-step.js +132 -9
  23. package/src/pageask.js +136 -0
  24. package/src/pagebits.js +107 -0
  25. package/src/pagedropwords.js +171 -0
  26. package/src/pagedry.js +120 -0
  27. package/src/pagefetch.js +164 -0
  28. package/src/pagelook.js +155 -0
  29. package/src/pagemap.js +55 -0
  30. package/src/pageplace.js +103 -0
  31. package/src/pagerules.js +318 -0
  32. package/src/panel/author.js +41 -20
  33. package/src/panel/authorcard.js +11 -1
  34. package/src/panel/authorflows.js +21 -15
  35. package/src/panel/authorstart.js +2 -4
  36. package/src/panel/authortrigger.js +14 -4
  37. package/src/panel/data.js +130 -10
  38. package/src/panel/index.html +499 -41
  39. package/src/panel/result.js +295 -0
  40. package/src/panel/server.js +27 -3
  41. package/src/primitives.js +43 -2
  42. package/src/provider.js +5 -2
  43. package/src/redact.js +17 -0
  44. package/src/runner.js +128 -21
  45. package/src/schedule.js +3 -3
  46. package/src/setup.js +16 -1
  47. package/src/sheetfind.js +50 -0
  48. package/src/sheetlook.js +157 -0
  49. package/src/signed-text.js +11 -1
  50. package/src/thinking.js +39 -0
  51. package/src/try-checks.js +68 -0
  52. package/src/types.js +4 -2
  53. package/types/audit-fold.d.ts +54 -0
  54. package/types/authoring.d.ts +20 -2
  55. package/types/books.d.ts +17 -0
  56. package/types/checked.d.ts +10 -0
  57. package/types/cited-record.d.ts +21 -0
  58. package/types/cited-source.d.ts +18 -0
  59. package/types/citedcheck.d.ts +95 -0
  60. package/types/citedwords.d.ts +97 -0
  61. package/types/closers.d.ts +55 -3
  62. package/types/declaration.d.ts +15 -1
  63. package/types/diary.d.ts +57 -0
  64. package/types/docx.d.ts +14 -0
  65. package/types/drafter.d.ts +244 -2
  66. package/types/flow.d.ts +21 -0
  67. package/types/flowmodel.d.ts +40 -3
  68. package/types/input-facts.d.ts +12 -2
  69. package/types/model-step.d.ts +38 -3
  70. package/types/pageask.d.ts +75 -0
  71. package/types/pagebits.d.ts +32 -0
  72. package/types/pagedropwords.d.ts +40 -0
  73. package/types/pagedry.d.ts +38 -0
  74. package/types/pagefetch.d.ts +86 -0
  75. package/types/pagelook.d.ts +75 -0
  76. package/types/pagemap.d.ts +31 -0
  77. package/types/pageplace.d.ts +22 -0
  78. package/types/pagerules.d.ts +86 -0
  79. package/types/panel/authorcard.d.ts +2 -0
  80. package/types/panel/authorflows.d.ts +2 -0
  81. package/types/panel/data.d.ts +26 -0
  82. package/types/panel/result.d.ts +156 -0
  83. package/types/provider.d.ts +3 -1
  84. package/types/redact.d.ts +1 -0
  85. package/types/runner.d.ts +156 -7
  86. package/types/schedule.d.ts +0 -11
  87. package/types/setup.d.ts +13 -0
  88. package/types/sheetfind.d.ts +46 -0
  89. package/types/sheetlook.d.ts +120 -0
  90. package/types/thinking.d.ts +31 -0
  91. package/types/try-checks.d.ts +55 -0
  92. package/types/types.d.ts +20 -3
@@ -0,0 +1,197 @@
1
+ // borrowed-from: bareloop src/factwords.js@2f93962 (keptSetOf, checkFactWords: the page-word path, where the label must be one the page-word map KEPT; bareloop's
2
+ // code-made label list (src/labelscan.js) is the other path and is not copied - a source with no look is refused as unread instead)
3
+ // M10 amendment 7 item 1 (docs/wiki/the-module-ladder.md): the facts a cited step checks are WRITTEN by the drafter and CHECKED by code at $0, before
4
+ // anything is signed. Code refuses, naming the job line, when: a label is not one the page-read kept (label-off-list); a word is not on the page
5
+ // (word-missing); a label shows up fewer times than the result count (label-rare, phrase-rare); a page rule dropped that word (word-dropped). Tighter than
6
+ // bareloop (signed): a number rule that is not in the person's own words on that line (their `~` rule, or a reading they agreed to, which is a `~` line
7
+ // too) is refused (number-unsigned). And, from item 2 (R2c), a place the page-read grew to phrases must have every phrase in the part (place-missing).
8
+ //
9
+ // Pure: no I/O, no model. Compared white-space blind. Third outcome, named: a source with no page-read (md text, a page the look never read) is a red
10
+ // `unread` - a check whose words were never proved against the source is never signed. What this throws away: nothing; every red is a sentence.
11
+
12
+ import { asList, countExact, countPhrase, normLabel, wordsSaidOn } from './pagebits.js';
13
+ import { dropSentence } from './pagedropwords.js';
14
+ import { factsOfLook } from './citedcheck.js';
15
+
16
+ /** @typedef {{code: string, detail: string}} WordRed */
17
+
18
+ /**
19
+ * What the page-word map KEPT and DROPPED for one input: the sets the proof reads.
20
+ * @param {{facts?: any[], dropped?: any[]}|null|undefined} look @param {string} source
21
+ * @returns {{labels: Set<string>|null, words: Set<string>, dropped: Map<string, any>}|null} null = the page was not read by the map; `labels: null` = a document (no map, any label in the text)
22
+ */
23
+ export function keptSetOf(look, source) {
24
+ if (!look || !Array.isArray(look.dropped)) return null;
25
+ const facts = (Array.isArray(look.facts) ? look.facts : []).filter((f) => f && f.source === source && Array.isArray(f.words));
26
+ const set = (/** @type {string[]} */ a) => new Set(a.map((w) => normLabel(String(w))));
27
+ /** @type {Map<string, any>} */
28
+ const dropped = new Map();
29
+ for (const d of look.dropped) if (d.source === source && typeof d.word === 'string' && !dropped.has(normLabel(d.word))) dropped.set(normLabel(d.word), d);
30
+ return {
31
+ labels: set(facts.filter((f) => f.shape !== 'phrase').flatMap((f) => f.words)),
32
+ words: set(facts.flatMap((f) => [...f.words, ...(f.phrases ?? []), ...(f.unit ?? []), ...(f.currency ?? [])])),
33
+ dropped,
34
+ };
35
+ }
36
+
37
+ /**
38
+ * The reds for ONE fact part against its frozen source text and what the page-word map kept.
39
+ * @param {{part: any, text: string, line: number, kept: NonNullable<ReturnType<typeof keptSetOf>>}} o
40
+ * @returns {WordRed[]}
41
+ */
42
+ export function factWordReds({
43
+ part, text, line, kept,
44
+ }) {
45
+ /** @type {WordRed[]} */
46
+ const reds = [];
47
+ const src = part.source;
48
+ const red = (/** @type {string} */ code, /** @type {string} */ msg) => reds.push({ code, detail: `line ${line}: ${msg}` });
49
+ for (const f of Array.isArray(part.facts) ? part.facts : []) {
50
+ const who = `fact "${f.name}"`;
51
+ // a word the page rules DROPPED (and no other fact kept) can never come back through the drafter
52
+ const dropRed = (/** @type {string} */ what, /** @type {unknown} */ w) => {
53
+ const n = normLabel(String(w));
54
+ const d = kept.dropped.get(n);
55
+ if (!d || kept.words.has(n)) return false;
56
+ red('word-dropped', `${who}: the ${what} ${JSON.stringify(n)} cannot be used. ${dropSentence(d)}`);
57
+ return true;
58
+ };
59
+ if (f.anchor !== undefined && f.shape !== 'phrase') {
60
+ const label = normLabel(String(f.anchor));
61
+ if (dropRed('label', f.anchor)) { /* said above */ } else if (kept.labels !== null && !kept.labels.has(label)) {
62
+ const some = [...kept.labels].slice(0, 12).map((l) => JSON.stringify(l)).join(', ');
63
+ red('label-off-list', `${who}: the label ${JSON.stringify(label)} is not one of the labels the page words for "${src}" kept. A label is picked from those, never typed${some ? `: ${some}` : ' (there are none - leave the label out)'}.`);
64
+ } else if (countExact(text, label) < 1) {
65
+ red('word-missing', `${who}: the label ${JSON.stringify(label)} is not in the input "${src}".`);
66
+ } else if (Number.isInteger(part.count?.min) && countExact(text, label) < part.count.min) {
67
+ const n = part.count.min;
68
+ const seen = countExact(text, label);
69
+ red('label-rare', `${who}: the label ${JSON.stringify(label)} is in the input "${src}" only ${seen} time${seen === 1 ? '' : 's'}, but this line asks for ${n} results, so a label that sits in each result must be there at least ${n} times. Pick a label that is counted ${n} or more times.`);
70
+ }
71
+ }
72
+ if (f.until !== undefined) dropRed('closing label', f.until);
73
+ if (f.until !== undefined && countExact(text, f.until) < 1) red('word-missing', `${who}: ${JSON.stringify(f.until)} is not in the input "${src}". Copy the closing words from the input, or leave them out.`);
74
+ if (f.shape === 'phrase' && typeof f.phrase === 'string') {
75
+ const seen = countPhrase(text, f.phrase);
76
+ if (seen < 1) red('word-missing', `${who}: ${JSON.stringify(f.phrase)} is not in the input "${src}". Copy the words the input really uses, or remove the check.`);
77
+ else if (Number.isInteger(part.count?.min) && seen < part.count.min) {
78
+ const n = part.count.min;
79
+ red('phrase-rare', `${who}: the words ${JSON.stringify(f.phrase)} are in the input "${src}" only ${seen} time${seen === 1 ? '' : 's'}, but this line asks for ${n} results - each result's own quote must say them. Pick words every result says, or drop this check.`);
80
+ }
81
+ }
82
+ for (const u of asList(f.unit)) dropRed('unit', u);
83
+ for (const c of asList(f.currency)) dropRed('currency', c);
84
+ for (const u of asList(f.unit)) if (countPhrase(text, u) < 1) red('word-missing', `${who}: the unit ${JSON.stringify(u)} is not in the input "${src}". Copy the words the input really uses.`);
85
+ for (const c of asList(f.currency)) if (countExact(text, c) < 1) red('word-missing', `${who}: the currency ${JSON.stringify(c)} is not in the input "${src}". Copy the sign the input really uses.`);
86
+ }
87
+ return reds;
88
+ }
89
+
90
+ /**
91
+ * The numbers a person said in their words, by KIND. A number inside a time (05:00), a date (2026-11-18) or an amount ($150) is part of that token, not
92
+ * a bare number: "5" is not said by "05:00", "15" and "50" are not said by "$150". (bareloop's `boundInWords` is a substring test and accepts all of those; this
93
+ * reader is ours - FINDINGS-worthy, see the commit.) Times compare without a leading zero on the hour ("05:00" = "5:00"), spaces dropped, case folded.
94
+ * @param {string} text
95
+ * @returns {{bare: Set<number>, amount: Set<number>, time: Set<string>, date: Set<string>}}
96
+ */
97
+ export function numbersSaid(text) {
98
+ const out = { bare: new Set(), amount: new Set(), time: new Set(), date: new Set() };
99
+ for (const m of String(text).matchAll(/(\d{1,2}:\d{2}(?:\s?[AaPp][Mm])?)|(\d{1,4}[-/.]\d{1,2}[-/.]\d{1,4})|([$\u20ac\u00a3]\s?\d[\d,]*(?:\.\d+)?)|(\d[\d,]*(?:\.\d+)?)/g)) {
100
+ if (m[1]) out.time.add(timeKey(m[1]));
101
+ else if (m[2]) out.date.add(m[2]);
102
+ else if (m[3]) out.amount.add(Number(m[3].replace(/[^\d.]/g, '')));
103
+ else out.bare.add(Number(m[4].replace(/,/g, '')));
104
+ }
105
+ return out;
106
+ }
107
+ /** @param {string} t @returns {string} a time token as compared: no spaces, lower case, no leading zero on the hour */
108
+ const timeKey = (t) => t.replace(/\s+/g, '').toLowerCase().replace(/^0(?=\d:)/, '');
109
+
110
+ /**
111
+ * Tighter than bareloop (signed, am7 item 1): every number in a fact's rule must be in the person's own words on this job line (the line and its `~` rules;
112
+ * an agreed reading is a `~` line too), as the right KIND of token: a money or number bound is a bare number or an amount, a time bound is a time, a date bound
113
+ * is a date. A bound the AI made up, or one that only sits inside another token, is refused.
114
+ * @param {{part: any, jobLine: {n: number, text?: string, rule?: string, rules?: string[]}}} o @returns {WordRed[]}
115
+ */
116
+ export function numberRuleReds({ part, jobLine }) {
117
+ /** @type {WordRed[]} */
118
+ const reds = [];
119
+ const said = numbersSaid(wordsSaidOn(jobLine));
120
+ const isSaid = (/** @type {string} */ shape, /** @type {unknown} */ b) => {
121
+ if (shape === 'money' || shape === 'number') return typeof b === 'number' && (said.bare.has(b) || said.amount.has(b));
122
+ if (shape === 'time') return typeof b === 'string' && said.time.has(timeKey(b));
123
+ if (shape === 'date') return typeof b === 'string' && said.date.has(b);
124
+ return false;
125
+ };
126
+ for (const f of Array.isArray(part.facts) ? part.facts : []) {
127
+ if (!f.rule || typeof f.rule !== 'object') continue;
128
+ const bounds = f.rule.op === 'between' ? [f.rule.lo, f.rule.hi] : [f.rule.value];
129
+ for (const b of bounds) {
130
+ if (!isSaid(f.shape, b)) {
131
+ reds.push({
132
+ code: 'number-unsigned',
133
+ detail: `line ${jobLine.n}: fact "${f.name}" has the number ${b} in its rule, but ${b} is not in your words on line ${jobLine.n}. A number rule must come from a ~ rule you wrote or a reading you agreed to. Change the ~ rule on line ${jobLine.n} to say it, or leave this rule out.`,
134
+ });
135
+ }
136
+ }
137
+ }
138
+ return reds;
139
+ }
140
+
141
+ const NUMBER_WORDS = Object.freeze({ one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10 });
142
+
143
+ /**
144
+ * Signed (am7 item 1): "List 3 ..." is the count, 3 results. A count the person never said as a bare number or a word number (not inside a time, a date or an
145
+ * amount) is refused. Same reader as the number rules.
146
+ * @param {{part: any, jobLine: {n: number, text?: string, rule?: string, rules?: string[]}}} o @returns {WordRed[]}
147
+ */
148
+ export function countReds({ part, jobLine }) {
149
+ /** @type {WordRed[]} */
150
+ const reds = [];
151
+ const text = wordsSaidOn(jobLine);
152
+ const said = numbersSaid(text).bare;
153
+ for (const w of text.toLowerCase().split(/[^\p{L}\p{N}]+/u)) { const n = NUMBER_WORDS[/** @type {'one'} */ (w)]; if (n !== undefined) said.add(n); }
154
+ const c = part.count && typeof part.count === 'object' ? part.count : {};
155
+ for (const k of ['min', 'max']) {
156
+ if (c[k] === undefined || said.has(c[k])) continue;
157
+ reds.push({ code: 'count-unsigned', detail: `line ${jobLine.n}: the result count has the number ${c[k]}, but ${c[k]} is not in your words on line ${jobLine.n}. The count is the number you asked for ("List 3" is 3 results); say it on the line, or leave the count out.` });
158
+ }
159
+ return reds;
160
+ }
161
+
162
+ /**
163
+ * R2c (am7 item 2): a place the page-read grew to phrases must have EVERY phrase as a phrase fact of the part, or a flipped route passes.
164
+ * @param {{part: any, line: number, look: {facts?: any[]}|null|undefined}} o @returns {WordRed[]}
165
+ */
166
+ export function placeReds({ part, line, look }) {
167
+ /** @type {WordRed[]} */
168
+ const reds = [];
169
+ const have = new Set((Array.isArray(part.facts) ? part.facts : []).filter((/** @type {any} */ f) => f.shape === 'phrase').map((/** @type {any} */ f) => String(f.phrase)));
170
+ for (const k of Array.isArray(look?.facts) ? look.facts : []) {
171
+ if (k.line !== line || k.source !== part.source || !Array.isArray(k.phrases)) continue;
172
+ for (const f of factsOfLook(k)) {
173
+ if (!have.has(f.phrase)) {
174
+ reds.push({
175
+ code: 'place-missing',
176
+ detail: `line ${line}: the place ${JSON.stringify(k.name)} must be checked with the words ${JSON.stringify(f.phrase)} (the page writes the place with its role: a result that leaves the other way does not say them). Add a phrase fact with exactly those words${k.phrases.length > 1 ? `, and one for each of: ${k.phrases.map((/** @type {string} */ p) => JSON.stringify(p)).join(', ')}` : ''}.`,
177
+ });
178
+ }
179
+ }
180
+ }
181
+ return reds;
182
+ }
183
+
184
+ /**
185
+ * Every word red for one cited part, in the order a person fixes them.
186
+ * @param {{part: any, text: string|undefined, line: number, jobLine: any, look: {facts?: any[], dropped?: any[]}|null|undefined, doc?: boolean}} o @returns {WordRed[]}
187
+ */
188
+ export function citedWordReds({
189
+ part, text, line, jobLine, look, doc = false,
190
+ }) {
191
+ // M10 piece 5 (item 2): a DOCUMENT has no page-word map; its words are proved on its text alone (a label need not be one a map kept)
192
+ const kept = doc ? { labels: null, words: new Set(), dropped: new Map() } : keptSetOf(look, part.source);
193
+ if (typeof text !== 'string' || kept === null) {
194
+ return [{ code: 'unread', detail: `line ${line}: the input "${part.source}" was not read here to prove the words against it, so a check on it cannot be drafted. A check on quotes works on a saved web page.` }];
195
+ }
196
+ return [...factWordReds({ part, text, line, kept }), ...numberRuleReds({ part, jobLine }), ...countReds({ part, jobLine }), ...placeReds({ part, line, look })];
197
+ }
package/src/closers.js CHANGED
@@ -63,10 +63,11 @@
63
63
  // signed text).
64
64
 
65
65
  import { createRubric, checkStep } from 'bareguard';
66
+ import { checkCited } from './citedcheck.js';
66
67
 
67
68
  /** @typedef {import('./types.js').CloseVerdict} CloseVerdict */
68
69
 
69
- const FORMULAS = Object.freeze({
70
+ export const FORMULAS = Object.freeze({
70
71
  sum: (vals) => vals.reduce((a, b) => a + b, 0),
71
72
  count: (vals) => vals.length,
72
73
  min: (vals) => Math.min(...vals),
@@ -74,6 +75,14 @@ const FORMULAS = Object.freeze({
74
75
  sub: (vals) => vals[0] - vals[1],
75
76
  });
76
77
 
78
+ /**
79
+ * M10 am10: the one description of the cite forms, told to a step whose check cites cells and named in the red when a cite fits none.
80
+ * Built from the checker's own formula list (FORMULAS keys + daysBetween, which is handled apart), so the text cannot drift from what is accepted.
81
+ */
82
+ export function citeForms(names = [...Object.keys(FORMULAS), 'daysBetween']) {
83
+ return `one cell (\`<input>!C3\`), a field above it (\`#name\`), or ${names.join(', ')} over those`;
84
+ }
85
+
77
86
  /** An input with cells (M4d amendment 8): a file whose name ends `.csv`. The one decider for "this input can be cited". */
78
87
  export function isCellsPath(p) {
79
88
  return typeof p === 'string' && p.toLowerCase().endsWith('.csv');
@@ -135,6 +144,12 @@ function resolveCite(cite, ctx) {
135
144
  const row = Number(rowStr);
136
145
  const raw = getCellRaw(artifact, col, row);
137
146
  if (raw === null) return { ok: false, red: `cite "${cite}": cell ${col}${row} does not exist in "${artifactId}"` };
147
+ // M10 am8 item 2: the step's check names the column(s) its facts come from; a cell from any other column is red, naming it
148
+ const locked = (Array.isArray(ctx.lock) ? ctx.lock : []).filter((l) => l?.source === artifactId).map((l) => l.column);
149
+ if (locked.length > 0) {
150
+ const name = artifact.header?.[colIndexOf(col)];
151
+ if (!locked.includes(name)) return { ok: false, red: `cite "${cite}": the cell ${col}${row} is in column '${name ?? col}', but this step is locked to column ${locked.map((c) => `'${c}'`).join(' and ')}` };
152
+ }
138
153
  return { ok: true, raw };
139
154
  }
140
155
 
@@ -184,7 +199,7 @@ function resolveCite(cite, ctx) {
184
199
  return { ok: true, computed: fn(vals) };
185
200
  }
186
201
 
187
- return { ok: false, red: `cite "${cite}" does not match the cell or formula grammar` };
202
+ return { ok: false, red: `cite "${cite}" does not match the cell or formula grammar - the forms are: ${citeForms()}` };
188
203
  }
189
204
 
190
205
  function checkField(name, field, ctx) {
@@ -226,7 +241,7 @@ function checkField(name, field, ctx) {
226
241
  * resolves and matches its cite. First red wins.
227
242
  *
228
243
  * @param {any} artifact
229
- * @param {{ reads: Record<string, any>, businessDate: string }} ctx
244
+ * @param {{ reads: Record<string, any>, businessDate: string, lock?: {source: string, column: string}[] }} ctx `lock` (M10 am8): the columns the step's check names
230
245
  * @returns {CloseVerdict}
231
246
  */
232
247
  export function closeGreen(artifact, ctx) {
@@ -241,7 +256,7 @@ export function closeGreen(artifact, ctx) {
241
256
  /** @type {Record<string, any>} */
242
257
  const fieldsSoFar = {};
243
258
  for (const name of names) {
244
- const result = checkField(name, artifact.fields[name], { reads: ctx.reads, fieldsSoFar, businessDate: ctx.businessDate });
259
+ const result = checkField(name, artifact.fields[name], { reads: ctx.reads, fieldsSoFar, businessDate: ctx.businessDate, lock: ctx.lock });
245
260
  if (result.verdict === 'red') return /** @type {CloseVerdict} */ (result);
246
261
  fieldsSoFar[name] = artifact.fields[name];
247
262
  }
@@ -251,6 +266,38 @@ export function closeGreen(artifact, ctx) {
251
266
  }
252
267
  }
253
268
 
269
+ /**
270
+ * M10 piece 4 (item 2, "green grows"): the green close of a step that cites quotes instead of cells. `part` is the step's fact part (`close.cited`, set by
271
+ * code from the page look's kept facts, never by the model); `source` is the run's OWN frozen copy of the page or doc (`readRunSource`); the artifact is
272
+ * `{ results: [{ quote, values: { <fact name>: "<value as the quote writes it>" } }] }`. bareguard's `cited` check proves each quote is word for word in
273
+ * the frozen text, each value is in its quote and passes its rule, and the number of results is as signed. No model grades.
274
+ * Third outcomes, each named, never green: no readable source or an artifact that is not an object (`unparseable`, a casualty), a part bareguard cannot sign
275
+ * (`crash`). `cited` carries what the runner writes to the run's cited-check record: the part and the check's own answer.
276
+ *
277
+ * @param {any} part
278
+ * @param {any} artifact
279
+ * @param {{ok: true, text: string, sha256: string}|{ok: false, red: string}|null|undefined} source
280
+ * @returns {Promise<CloseVerdict>}
281
+ */
282
+ export async function closeCited(part, artifact, source) {
283
+ try {
284
+ if (!source || source.ok !== true) {
285
+ const red = source && source.ok === false ? source.red : `input "${part?.source}": the run gave the check no saved copy to read`;
286
+ return /** @type {CloseVerdict} */ ({ verdict: 'unparseable', red: `cited close: ${red}`, cited: { part, check: { verdict: 'stopped', gapLines: [], fault: red, sha256: '', claims: [], evidence: [] } } });
287
+ }
288
+ if (!artifact || typeof artifact !== 'object' || Array.isArray(artifact)) {
289
+ return /** @type {CloseVerdict} */ ({ verdict: 'unparseable', red: 'cited artifact must be an object shaped {results: [{quote, values}]}' });
290
+ }
291
+ const check = await checkCited({ part, text: source.text, results: artifact.results });
292
+ const cited = { part, check, results: artifact.results };
293
+ if (check.verdict === 'green') return /** @type {CloseVerdict} */ ({ verdict: 'green', red: null, cited });
294
+ if (check.verdict === 'red') return /** @type {CloseVerdict} */ ({ verdict: 'red', red: check.gapLines.join('\n'), cited });
295
+ return /** @type {CloseVerdict} */ ({ verdict: 'crash', red: `cited close stopped: ${check.fault}`, cited });
296
+ } catch (err) {
297
+ return /** @type {CloseVerdict} */ ({ verdict: 'crash', red: `cited close crashed: ${err.message}` });
298
+ }
299
+ }
300
+
254
301
  /**
255
302
  * M4e amendment 18: the soft checks run on bareguard 0.21.0. `softgreenSpec(shape)` is the ONE place a declared shape
256
303
  * becomes a rubric spec (signing and the run both build through `buildSoftgreenRubric`, so a shape that signs is a shape
@@ -338,6 +385,52 @@ export function renderSoftgreenGaps(gaps, shape) {
338
385
  return { red: reds.join('; '), reds };
339
386
  }
340
387
 
388
+ /** The words each softgreen check is listed under (M4d am29 item 2), by its rubric id; the numbers and names come from the signed shape. @param {Record<string, any>} c a check of `softgreenSpec` */
389
+ function softgreenCheckText(c) {
390
+ if (c.id === 'keys') return 'the answer has only a "text" field';
391
+ if (c.id === 'words') return `at most ${c.value} words`;
392
+ if (c.id === 'sections') return `the sections are there, in order: ${c.names.join(', ')}`;
393
+ if (c.id === 'perSection') return `each section is about ${c.wordsPerSection} words`;
394
+ return `${c.size ?? 'its'} lines per block, each carrying: ${(c.phrases ?? []).join(', ')}`;
395
+ }
396
+
397
+ /**
398
+ * How many words bareguard counts in `text`, asked of bareguard itself (a `minWords` check no text can meet, whose gap carries the measured count) so the
399
+ * number listed beside a passing `maxWords` check is the one the check used. `null` when it cannot be read.
400
+ * @param {string} text @returns {Promise<number|null>}
401
+ */
402
+ async function countWordsWithBareguard(text) {
403
+ try {
404
+ const rubric = createRubric({ schema: 1, goal: 'count', checkpoints: { count: { gating: true, checks: [{ id: 'n', rule: 'minWords', field: 'text', value: 100_000_000 }] } } });
405
+ const res = await checkStep(rubric, 'count', { text });
406
+ const measured = res.gaps?.[0]?.measured;
407
+ return typeof measured === 'number' ? measured : null;
408
+ } catch { return null; }
409
+ }
410
+
411
+ /**
412
+ * M4d am29 item 2: every check the softgreen close ran, in the order of `softgreenSpec`, each `{ id, text, ok, result }`. `result` is the word count beside the
413
+ * words check (met or not), the plain-English reason beside any other check that failed, and `null` beside a check that passed with nothing to measure.
414
+ * @param {Record<string, any>} shape @param {any[]} gaps bareguard's gaps (empty when green) @param {string} text
415
+ */
416
+ async function softgreenCheckResults(shape, gaps, text) {
417
+ const out = [];
418
+ for (const c of softgreenSpec(shape).checkpoints.close.checks) {
419
+ const mine = gaps.filter((g) => g.id === c.id);
420
+ let result = null;
421
+ if (c.id === 'words') {
422
+ const n = mine[0]?.measured ?? await countWordsWithBareguard(text);
423
+ result = typeof n === 'number' ? `${n} words` : null;
424
+ } else if (mine.length > 0) {
425
+ result = renderSoftgreenGaps(mine, shape).reds.join('; ');
426
+ }
427
+ out.push({
428
+ id: c.id, text: softgreenCheckText(c), ok: mine.length === 0, result,
429
+ });
430
+ }
431
+ return out;
432
+ }
433
+
341
434
  /** What the artifact looks like in a message, without ever throwing on a hostile object. */
342
435
  function describeArtifact(artifact) {
343
436
  try { return JSON.stringify(artifact); } catch { return '[an object that cannot be read]'; }
@@ -372,8 +465,9 @@ export async function closeSoftgreen(artifact, shape) {
372
465
  const fault = /** @type {NonNullable<typeof res.fault>} */ (res.fault);
373
466
  return { verdict: 'crash', red: `softgreen close crashed: the ${fault.id} check stopped (${fault.kind}${fault.detail ? `: ${fault.detail}` : ''})` };
374
467
  }
375
- if (res.verdict === 'red') return { verdict: 'red', ...renderSoftgreenGaps(res.gaps, shape) };
376
- return { verdict: 'green', red: null, reds: [] };
468
+ const checks = await softgreenCheckResults(shape, res.verdict === 'red' ? res.gaps : [], text);
469
+ if (res.verdict === 'red') return { verdict: 'red', ...renderSoftgreenGaps(res.gaps, shape), checks };
470
+ return { verdict: 'green', red: null, reds: [], checks };
377
471
  } catch (err) {
378
472
  return { verdict: 'crash', red: `softgreen close crashed: ${err.message}` };
379
473
  }
@@ -382,14 +476,16 @@ export async function closeSoftgreen(artifact, shape) {
382
476
  /**
383
477
  * The one dispatcher — `close by declared class` (M2 scope item 4).
384
478
  *
385
- * @param {{ close?: { class?: string, shape?: Record<string, any> } }} step
479
+ * @param {{ close?: { class?: string, shape?: Record<string, any>, cited?: any, columns?: {source: string, column: string}[] } }} step
386
480
  * @param {unknown} artifact
387
- * @param {{ reads: Record<string, any>, businessDate: string }} ctx
481
+ * @param {{ reads: Record<string, any>, businessDate: string, source?: {ok: true, text: string, sha256: string}|{ok: false, red: string}|null }} ctx
482
+ * `source` (M10 piece 4) = the run's own frozen copy a cited step reads, from `readRunSource`; only a step whose close carries `cited` reads it
388
483
  * @returns {Promise<CloseVerdict>}
389
484
  */
390
485
  export async function closeByClass(step, artifact, ctx) {
391
486
  const cls = step?.close?.class;
392
- if (cls === 'green') return closeGreen(artifact, ctx);
487
+ if (cls === 'green' && step?.close?.cited) return await closeCited(step.close.cited, artifact, ctx.source);
488
+ if (cls === 'green') return closeGreen(artifact, { ...ctx, lock: step?.close?.columns });
393
489
  if (cls === 'softgreen') return await closeSoftgreen(artifact, step?.close?.shape ?? {});
394
490
  if (cls === 'hitl') return { verdict: 'hitl', red: null };
395
491
  return { verdict: 'crash', red: `closeByClass: unknown close class ${JSON.stringify(cls)}` };
package/src/ctx-tools.js CHANGED
@@ -14,11 +14,11 @@
14
14
  // - no spine `emit`: model-step already tallies each tool a step called;
15
15
  // - `remember`/`forget` are NOT here: memory lasts one run (PRD: no learning
16
16
  // between flows), so they stay refused.
17
- // - redactSecrets is bareloop's src/validate.js@07215d6 inventory (SECRET_PATTERNS).
17
+ // - redactSecrets lives in src/redact.js (bareloop's src/validate.js@07215d6 inventory).
18
18
 
19
19
  import path from 'node:path';
20
20
  import { createRequire } from 'node:module';
21
- import { redact } from 'bareguard';
21
+ import { redactSecrets } from './redact.js';
22
22
  import { withRunStore } from './run-store.js';
23
23
 
24
24
  const require = createRequire(import.meta.url);
@@ -28,18 +28,6 @@ const { compress: compressNode, StalePointerError } = require('litectx');
28
28
  * because that is what enters the store). Bareloop's number, signed in M7 item 3. */
29
29
  export const ISOLATE_MAX_BYTES = 65536;
30
30
 
31
- const SECRET_PATTERNS = [
32
- /(?<![A-Za-z0-9_-])sk-[A-Za-z0-9_-]{16,}/,
33
- /(?<![A-Za-z0-9_-])ghp_[A-Za-z0-9]{20,}/,
34
- /(?<![A-Za-z0-9_-])github_pat_[A-Za-z0-9_]{20,}/,
35
- /(?<![A-Za-z0-9_-])AKIA[0-9A-Z]{16}/,
36
- /(?<![A-Za-z0-9_-])xox[bap]-[A-Za-z0-9-]{10,}/,
37
- /(?<![A-Za-z0-9_-])AIza[0-9A-Za-z_-]{35}/,
38
- ];
39
-
40
- /** Mask known secret shapes. @param {unknown} raw */
41
- const redactSecrets = (raw) => redact(String(raw ?? ''), { patterns: SECRET_PATTERNS });
42
-
43
31
  const LINE_SPACE = 'Line numbers are 0-based; copy them between recall and get as printed.';
44
32
 
45
33
  /**
@@ -37,6 +37,8 @@
37
37
  // greps all of src/ for that, and it must keep passing with this file added.
38
38
 
39
39
  import { buildSoftgreenRubric, isCellsPath } from './closers.js';
40
+ import { factPartReds } from './citedcheck.js';
41
+ import { numberRuleReds, countReds, citedWordReds } from './citedwords.js';
40
42
 
41
43
  /** @typedef {import('./types.js').Arbiter} Arbiter */
42
44
  /** @typedef {import('./types.js').SignedLine} SignedLine */
@@ -64,6 +66,8 @@ export const DECLARATION_FIELDS = Object.freeze([
64
66
  // close level
65
67
  'class',
66
68
  'shape',
69
+ 'cited',
70
+ 'columns',
67
71
  ]);
68
72
 
69
73
  const VALID_CLASSES = Object.freeze(['green', 'softgreen', 'hitl']);
@@ -76,7 +80,7 @@ const ARBITER_KEYS = Object.freeze(['cap', 'ask', 'ttl', 'send', 'source', 'trig
76
80
 
77
81
  const TOP_LEVEL_ALLOWED = Object.freeze(['steps', 'guardrailClasses', 'unjudgeable', 'refused', 'inputFacts']);
78
82
  const STEP_ALLOWED = Object.freeze(['goal', 'primitives', 'reads', 'emits', 'fromLine', 'close', 'picks']);
79
- const CLOSE_ALLOWED = Object.freeze(['class', 'shape']);
83
+ const CLOSE_ALLOWED = Object.freeze(['class', 'shape', 'cited', 'columns']);
80
84
 
81
85
  /** @returns {value is Record<string, any>} */
82
86
  function isPlainObject(value) {
@@ -403,6 +407,68 @@ function checkShapeBuilds(shape, label, reds, redsBefore) {
403
407
  }
404
408
  }
405
409
 
410
+ /**
411
+ * M10 amendment 7 item 1: `close.cited` is the facts a green step checks its quotes against, written by the drafter (a fact part:
412
+ * `{source, facts, count?}`, src/citedcheck.js). Its SHAPE is checked in every mode (a signed flow is read the same way). With `fitJobLine` the number rules
413
+ * must be the person's own words on the job line; with `pageWords` (the drafting copy of each page and what the page-word map kept) every word is proved on
414
+ * the page at $0 (src/citedwords.js). Each red names the job line, so a redraft can be told which line.
415
+ * @param {any} step @param {string} label @param {{sourceRoles: any[], reads: string[]|null, effectiveClass: string, lines: SignedLine[], fitJobLine?: boolean, pageWords?: {texts: Record<string, string>, look: any, docs?: string[]}}} c @param {string[]} reds
416
+ */
417
+ function checkCitedKey(step, label, c, reds) {
418
+ const at = `declaration: ${label}.close.cited`;
419
+ const part = step.close.cited;
420
+ if (!isPlainObject(part)) { reds.push(`${at} must be an object {source, facts, count}`); return; }
421
+ if (step.close.class !== 'green' || c.effectiveClass !== 'green') reds.push(`${at} is for a green step only (its quotes are checked against the page); this step's check is "${step.close.class ?? c.effectiveClass}"`);
422
+ for (const r of factPartReds(part)) reds.push(`${at}: ${r}`);
423
+ if (typeof part.source === 'string' && part.source.trim() !== '') {
424
+ if (!c.sourceRoles.includes(part.source)) reds.push(`${at}.source "${part.source}" is not one of the signed source roles`);
425
+ else if (c.reads !== null && !c.reads.includes(part.source)) reds.push(`${at}.source "${part.source}" is not in ${label}.reads - the step must read the input its quotes come from`);
426
+ }
427
+ if (c.fitJobLine !== true || !Number.isInteger(step.fromLine)) return;
428
+ const jobLine = c.lines.find((l) => l.n === step.fromLine);
429
+ if (!jobLine) return;
430
+ const jl = { n: jobLine.n, text: jobLine.text, ...(jobLine.guardrail ? { rule: jobLine.guardrail } : {}) };
431
+ // a part that is not valid is not read further: its words would only repeat the same red
432
+ if (factPartReds(part).length) return;
433
+ const words = c.pageWords ? citedWordReds({ part, text: c.pageWords.texts[part.source], line: jl.n, jobLine: jl, look: c.pageWords.look, doc: Array.isArray(c.pageWords.docs) && c.pageWords.docs.includes(part.source) }) : [...numberRuleReds({ part, jobLine: jl }), ...countReds({ part, jobLine: jl })];
434
+ for (const r of words) reds.push(`declaration: ${r.detail}`);
435
+ }
436
+
437
+ /**
438
+ * M10 am8 item 2: `close.columns` is the column lock of a green step that cites cells: `[{source, column}]`, written by the drafter and checked by code. Its SHAPE is
439
+ * checked in every mode; with `sheetWords` (draft time) every column is proved to be a real column of its sheet and a column the sheet look kept for this step's
440
+ * line must be in the list. At run time every cited cell must come from one of these columns (src/closers.js).
441
+ * @param {any} step @param {string} label @param {{cellsRoles: string[], reads: string[]|null, effectiveClass: string, sheetWords?: {headers: Record<string, string[]>, facts: any[]}}} c @param {string[]} reds
442
+ */
443
+ function checkColumnsKey(step, label, c, reds) {
444
+ const at = `declaration: ${label}.close.columns`;
445
+ const cols = step.close.columns;
446
+ if (cols !== undefined) {
447
+ if (step.close.class !== 'green' || c.effectiveClass !== 'green') reds.push(`${at} is for a green step only (its cells are checked); this step's check is "${step.close.class ?? c.effectiveClass}"`);
448
+ if (!Array.isArray(cols) || cols.length === 0 || cols.length > 10) { reds.push(`${at} must be a list of 1 to 10 {source, column}`); return; }
449
+ for (const [j, e] of cols.entries()) {
450
+ if (!isPlainObject(e) || Object.keys(e).some((k) => k !== 'source' && k !== 'column') || typeof e.source !== 'string' || typeof e.column !== 'string' || e.column.trim() === '') {
451
+ reds.push(`${at}[${j}] must be {source, column}, both words`);
452
+ } else if (!c.cellsRoles.includes(e.source)) {
453
+ reds.push(`${at}[${j}].source "${e.source}" is not a signed spreadsheet input`);
454
+ } else if (c.reads !== null && !c.reads.includes(e.source)) {
455
+ reds.push(`${at}[${j}].source "${e.source}" is not in ${label}.reads - the step must read the sheet its cells come from`);
456
+ }
457
+ }
458
+ }
459
+ const sw = c.sheetWords;
460
+ if (!sw || !Number.isInteger(step.fromLine)) return;
461
+ const list = Array.isArray(cols) ? cols.filter((e) => isPlainObject(e) && typeof e.column === 'string') : [];
462
+ for (const e of list) {
463
+ const header = sw.headers?.[e.source];
464
+ if (Array.isArray(header) && !header.includes(e.column)) reds.push(`declaration: line ${step.fromLine}: '${e.column}' is not a real column of "${e.source}" (its columns: ${header.map((h) => `'${h}'`).join(', ')}). Copy a column name exactly.`);
465
+ }
466
+ for (const f of sw.facts ?? []) {
467
+ if (f.line !== step.fromLine || f.shape !== 'column') continue;
468
+ if (!list.some((e) => e.source === f.source && e.column === f.column)) reds.push(`declaration: line ${step.fromLine}: the check must name the column '${f.column}' of "${f.source}" in close.columns - the code kept it for this line${f.agreed ? ' (the column you agreed to)' : ''}, and every cell must come from it.`);
469
+ }
470
+ }
471
+
406
472
  /**
407
473
  * Validate a drafter declaration against the M1 closed schema. `arbiter`
408
474
  * and `lines` are `parseSignedText`'s output; `catalogue` is a plain array
@@ -417,11 +483,16 @@ function checkShapeBuilds(shape, label, reds, redsBefore) {
417
483
  * text as its goal, exactly. Off by default so already-signed flows keep running; draft and sign turn it on.
418
484
  * `fitJobLine` (optional boolean; M4e amendment 6): when true, a `close.shape` whose sections/maxWords fight the step's job
419
485
  * line or its guardrail is a red. Draft, change and sign turn it on; readFlow does not (signed flows keep running).
420
- * @param {{ arbiter?: unknown, lines?: unknown, catalogue?: unknown, wired?: Set<string>, verbatimGoals?: boolean, fitJobLine?: boolean }} [context]
486
+ * `pageWords` (optional; M10 am7 item 1): `{texts: {role: drafting copy}, look: {facts, dropped}}`. With `fitJobLine`, the words of every `close.cited` fact are
487
+ * proved on the page at $0; the drafter passes it, sign does not (the draft was already proved, and its files are hash-bound).
488
+ * `pageWords.docs` (M10 piece 5): the roles that are documents (.docx / .md / .txt): their words are proved on their text alone, with no page-word map.
489
+ * `sheetWords` (optional; M10 am8 item 2): `{headers: {role: header names}, facts: the columns the sheet look kept}`. With `fitJobLine`, every column a step's `close.columns` names
490
+ * is proved a real column of its sheet, and a column the code kept for the step's line (an agreed one included) must be in it.
491
+ * @param {{ arbiter?: unknown, lines?: unknown, catalogue?: unknown, wired?: Set<string>, verbatimGoals?: boolean, fitJobLine?: boolean, pageWords?: {texts: Record<string, string>, look: any, docs?: string[]}, sheetWords?: {headers: Record<string, string[]>, facts: any[]} }} [context]
421
492
  * @returns {ValidateDeclarationResult}
422
493
  */
423
494
  export function validateDeclaration(declaration, context = {}) {
424
- const { arbiter, lines, catalogue, wired, verbatimGoals, fitJobLine } = context;
495
+ const { arbiter, lines, catalogue, wired, verbatimGoals, fitJobLine, pageWords, sheetWords } = context;
425
496
  const reds = [];
426
497
 
427
498
  if (!isPlainObject(declaration)) {
@@ -445,6 +516,10 @@ export function validateDeclaration(declaration, context = {}) {
445
516
  // M4d amendment 8: the inputs with cells (a spreadsheet file). A step may read one by its role; a green step must.
446
517
  const cellsRoles = Array.isArray(safeArbiter.sources)
447
518
  ? safeArbiter.sources.filter((s) => s?.kind === 'file' && isCellsPath(s.path)).map((s) => s.role) : [];
519
+ // M10 am7 item 3: a web page is an input too, frozen at run start; a step reads it by its role (its quotes are checked against the run's own copy)
520
+ const pageRoles = Array.isArray(safeArbiter.sources) ? safeArbiter.sources.filter((s) => s?.kind === 'page').map((s) => s.role) : [];
521
+ // M10 piece 5 (item 2): a document (.docx / .md / .txt) may be READ by a step that quotes it (its close.cited.source), and by no other step
522
+ const docRoles = Array.isArray(safeArbiter.sources) ? safeArbiter.sources.filter((s) => s?.kind === 'file' && ['.docx', '.md', '.txt'].some((x) => String(s.path).toLowerCase().endsWith(x))).map((s) => s.role) : [];
448
523
  const asks = Array.isArray(safeArbiter.asks) ? safeArbiter.asks : [];
449
524
  const askLines = asks.map((a) => a.line);
450
525
  const sends = Array.isArray(safeArbiter.sends) ? safeArbiter.sends : [];
@@ -637,6 +712,8 @@ export function validateDeclaration(declaration, context = {}) {
637
712
  if (reads !== null && emits !== null) {
638
713
  for (const readId of reads) {
639
714
  if (cellsRoles.includes(readId) && !declaredEmits.has(readId)) continue; // an input with cells, frozen at run start (M4d amendment 8)
715
+ if (pageRoles.includes(readId) && !declaredEmits.has(readId)) continue; // a web page, frozen at run start (M10 am7 item 3)
716
+ if (docRoles.includes(readId) && !declaredEmits.has(readId) && step.close?.cited?.source === readId) continue; // a document the step quotes (M10 piece 5)
640
717
  if (readId === emits || !declaredEmits.has(readId)) {
641
718
  reds.push(`declaration: ${label} reads artifact "${readId}" that no earlier step declared`);
642
719
  }
@@ -644,7 +721,7 @@ export function validateDeclaration(declaration, context = {}) {
644
721
  }
645
722
  const earlierEmits = [...declaredEmits]; // outputs of EARLIER steps, in order (the nearest is last)
646
723
  if (emits !== null) declaredEmits.add(emits);
647
- if (fitJobLine === true && emits !== null && cellsRoles.includes(emits)) reds.push(`declaration: ${label}.emits "${emits}" is also a signed input — one id, one meaning`);
724
+ if (fitJobLine === true && emits !== null && (cellsRoles.includes(emits) || pageRoles.includes(emits))) reds.push(`declaration: ${label}.emits "${emits}" is also a signed input — one id, one meaning`);
648
725
 
649
726
  // fromLine + class derivation — the key itself is required (value may be
650
727
  // null, meaning "no line"; the key being entirely absent is not the same
@@ -690,6 +767,8 @@ export function validateDeclaration(declaration, context = {}) {
690
767
  if (fitJobLine === true) checkShapeFitsJobLine(step, i, safeLines, reds);
691
768
  }
692
769
  }
770
+ if (step.close.cited !== undefined) checkCitedKey(step, label, { sourceRoles, reads, effectiveClass, lines: safeLines, fitJobLine, pageWords }, reds);
771
+ if (step.close.columns !== undefined || (fitJobLine === true && sheetWords)) checkColumnsKey(step, label, { cellsRoles, reads, effectiveClass, sheetWords }, reds);
693
772
  }
694
773
  }
695
774
 
@@ -701,7 +780,8 @@ export function validateDeclaration(declaration, context = {}) {
701
780
 
702
781
  // M4d amendment 8: a step whose check is green (every figure cites a source cell) must read an input with cells; a text
703
782
  // output of an earlier step has no cells to cite.
704
- if (fitJobLine === true && effectiveClass === 'green' && reads !== null && !reads.some((r) => cellsRoles.includes(r))) {
783
+ // M10 am7: a green step that cites quotes (`close.cited`) reads a web page, which has no cells; its source is checked above.
784
+ if (fitJobLine === true && effectiveClass === 'green' && reads !== null && !reads.some((r) => cellsRoles.includes(r)) && !isPlainObject(step.close?.cited)) {
705
785
  const n = fromLine;
706
786
  const reading = reads.length === 0 ? 'it reads nothing' : `it reads only ${reads.join(', ')}`;
707
787
  const want = cellsRoles.length === 0 ? 'a spreadsheet input, and this job signs none' : cellsRoles.join(' or ');
package/src/diary.js ADDED
@@ -0,0 +1,49 @@
1
+ // M4d am29 item 1-3: the run's three add-only diaries, in the run's own folder, the way bareloop keeps its gate audit sidecar
2
+ // (src/planrun.js: `new Gate({ audit: { path } })`, the path denied to the worker with `fs.deny`).
3
+ // calls.jsonl one row per MODEL CALL: step, try, round, cost, tokens, time, stop reason, thinking asked and status
4
+ // tools.jsonl one row per TOOL CALL: step, try, round, tool, path, the guard's decision (allow / deny + rule / no check)
5
+ // checks.jsonl one row per TRY that ran checks: each check numbered, ✓/✗, its result, where it comes from, and the output it judged
6
+ // Never saved: what the model said, what was in any file (a tool row names a path, never its content). Every string is scrubbed with the
7
+ // ONE secret inventory (`redactSecrets`, src/redact.js) before the row is written. The model can never read these files: the step's
8
+ // bareguard Gate denies them (src/primitives.js) and a grep over the run folder drops their hits.
9
+ // Rounds count from 1 in EACH STEP (they keep counting across that step's tries); `nextRound` reads the count off the diary.
10
+ //
11
+ // borrowed-from: bareloop src/planrun.js@fd78723 (the gate audit sidecar + fs.deny of its path; the per-round rows emitted from the onLlmResult wrapper)
12
+ import { join } from 'node:path';
13
+ import { appendRow } from './jsonl-append.js';
14
+ import { readLines } from './books.js';
15
+ import { redactSecrets } from './redact.js';
16
+
17
+ export const DIARY_FILES = Object.freeze({ calls: 'calls.jsonl', tools: 'tools.jsonl', checks: 'checks.jsonl' });
18
+
19
+ /** Every diary's absolute path for a run, for the model's deny list. @param {string} runDir @returns {string[]} */
20
+ export const diaryPaths = (runDir) => Object.values(DIARY_FILES).map((f) => join(runDir, f));
21
+
22
+ /** A copy of a JSON value with every string scrubbed. @param {any} v @returns {any} */
23
+ function scrub(v) {
24
+ if (typeof v === 'string') return redactSecrets(v);
25
+ if (Array.isArray(v)) return v.map(scrub);
26
+ if (v !== null && typeof v === 'object') return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, scrub(x)]));
27
+ return v;
28
+ }
29
+
30
+ /** The ONE writer of a diary row. @param {string} runDir @param {keyof typeof DIARY_FILES} kind @param {Record<string, any>} row */
31
+ function write(runDir, kind, row) { appendRow(join(runDir, DIARY_FILES[kind]), scrub(row)); }
32
+
33
+ /** @param {string} runDir @param {{step:string|null, try:number|null, round:number, at:string, model:string|null, costUsd:number|null, tokens:{in:number,out:number,cache:number}|null, ms:number|null, stopReason:string|null, thinking:{asked:string|null,status:string|null}}} row */
34
+ export const appendCall = (runDir, row) => write(runDir, 'calls', row);
35
+ /** @param {string} runDir @param {{step:string|null, try:number|null, round:number, at:string, tool:string, path:string|null, decision:'allow'|'deny'|'no check', rule:string|null}} row */
36
+ export const appendTool = (runDir, row) => write(runDir, 'tools', row);
37
+ /** @param {string} runDir @param {{step:string|null, try:number, at:string, lastRound:number, checks:Array<{n:number, text:string, ok:boolean, result:string|null, source:string}>, output:{file:string, bytes:number, sha256:string}|null}} row */
38
+ export const appendChecks = (runDir, row) => write(runDir, 'checks', row);
39
+
40
+ /** @param {string} runDir @returns {any[]} */
41
+ export const readCalls = (runDir) => readLines(runDir, DIARY_FILES.calls);
42
+ /** @param {string} runDir @returns {any[]} */
43
+ export const readTools = (runDir) => readLines(runDir, DIARY_FILES.tools);
44
+ /** @param {string} runDir @returns {any[]} */
45
+ export const readChecks = (runDir) => readLines(runDir, DIARY_FILES.checks);
46
+
47
+ /** The round number of this step's next model call: one more than the highest round it has in the diary, so it counts on across tries and across resumes.
48
+ * Read off the file each time (the diary is the one record), never a copy held in memory. @param {string} runDir @param {string|null} step */
49
+ export const nextRound = (runDir, step) => readCalls(runDir).filter((r) => r.step === step).reduce((m, r) => Math.max(m, r.round), 0) + 1;