fwdloop 0.31.0 → 0.33.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 (96) hide show
  1. package/bin/fwdloop +8 -2
  2. package/package.json +2 -2
  3. package/src/auditchecks.js +53 -0
  4. package/src/authoring.js +52 -12
  5. package/src/blockasks.js +44 -0
  6. package/src/blockassemble.js +140 -0
  7. package/src/blockdraft.js +91 -0
  8. package/src/blocklines.js +30 -0
  9. package/src/blockpick.js +165 -0
  10. package/src/cardlist.js +19 -0
  11. package/src/checkblock.js +804 -0
  12. package/src/checked.js +48 -9
  13. package/src/checklist.js +99 -0
  14. package/src/checklistsign.js +93 -0
  15. package/src/checkwords.js +20 -1
  16. package/src/cited-record.js +21 -1
  17. package/src/citedcheck.js +162 -7
  18. package/src/closers.js +41 -3
  19. package/src/declaration.js +25 -2
  20. package/src/declaredclose.js +4 -0
  21. package/src/draft-steps.js +3 -1
  22. package/src/drafter.js +244 -134
  23. package/src/factwords.js +112 -0
  24. package/src/inputlook.js +53 -0
  25. package/src/jsonbrace.js +21 -0
  26. package/src/labelscan.js +162 -0
  27. package/src/pageask.js +4 -1
  28. package/src/pagedropwords.js +11 -1
  29. package/src/panel/author.js +76 -5
  30. package/src/panel/authorcard.js +9 -6
  31. package/src/panel/data.js +41 -9
  32. package/src/panel/index.html +202 -13
  33. package/src/panel/result.js +4 -3
  34. package/src/panel/server.js +3 -1
  35. package/src/pickrecord.js +28 -0
  36. package/src/placerule.js +398 -0
  37. package/src/planrebuild.js +206 -0
  38. package/src/rowedit.js +118 -0
  39. package/src/rubricstep.js +264 -0
  40. package/src/runfile.js +4 -2
  41. package/src/runner.js +67 -10
  42. package/src/setup.js +10 -4
  43. package/src/sheetblock.js +6 -2
  44. package/src/sheetchecks.js +49 -64
  45. package/src/sheetclaims.js +12 -32
  46. package/src/sheetlook.js +2 -2
  47. package/src/sheetoffer.js +25 -53
  48. package/src/sheetrows.js +107 -0
  49. package/src/sheetrun.js +31 -1
  50. package/src/summary-words.js +3 -3
  51. package/src/try-checks.js +31 -12
  52. package/src/types.js +1 -0
  53. package/types/auditchecks.d.ts +24 -0
  54. package/types/authoring.d.ts +18 -1
  55. package/types/blockasks.d.ts +37 -0
  56. package/types/blockassemble.d.ts +33 -0
  57. package/types/blockdraft.d.ts +83 -0
  58. package/types/blocklines.d.ts +31 -0
  59. package/types/blockpick.d.ts +41 -0
  60. package/types/cardlist.d.ts +21 -0
  61. package/types/checkblock.d.ts +363 -0
  62. package/types/checked.d.ts +16 -2
  63. package/types/checklist.d.ts +115 -0
  64. package/types/checklistsign.d.ts +27 -0
  65. package/types/checkwords.d.ts +5 -0
  66. package/types/cited-record.d.ts +9 -0
  67. package/types/citedcheck.d.ts +33 -2
  68. package/types/closers.d.ts +24 -2
  69. package/types/declaredclose.d.ts +2 -0
  70. package/types/drafter.d.ts +15 -361
  71. package/types/factwords.d.ts +38 -0
  72. package/types/inputlook.d.ts +49 -0
  73. package/types/jsonbrace.d.ts +8 -0
  74. package/types/labelscan.d.ts +35 -0
  75. package/types/pageask.d.ts +2 -0
  76. package/types/panel/author.d.ts +41 -0
  77. package/types/panel/authorcard.d.ts +1 -1
  78. package/types/panel/data.d.ts +4 -2
  79. package/types/panel/jobgrid.d.ts +1 -1
  80. package/types/pickrecord.d.ts +22 -0
  81. package/types/placerule.d.ts +208 -0
  82. package/types/planrebuild.d.ts +52 -0
  83. package/types/provider.d.ts +1 -1
  84. package/types/rowedit.d.ts +33 -0
  85. package/types/rubricstep.d.ts +60 -0
  86. package/types/runfile.d.ts +5 -2
  87. package/types/runner.d.ts +45 -1
  88. package/types/sheetblock.d.ts +1 -0
  89. package/types/sheetchecks.d.ts +10 -17
  90. package/types/sheetclaims.d.ts +2 -1
  91. package/types/sheetoffer.d.ts +5 -5
  92. package/types/sheetrows.d.ts +73 -0
  93. package/types/sheetrun.d.ts +12 -0
  94. package/types/summary-words.d.ts +2 -1
  95. package/types/try-checks.d.ts +4 -2
  96. package/types/types.d.ts +8 -0
@@ -0,0 +1,398 @@
1
+ // borrowed-from: bareloop src/placerule.js@v0.56.0 (3383cce) (the two spine reads in lastPlaceRead go through fwd's one safe gateway, readFileInside, instead of node:fs)
2
+ // PLACE RULES (docs/product/ITEM33-BUILD.md, "Place rules build spec (hamr go 2026-11-11)").
3
+ //
4
+ // A check whose words hold a version or a date ("the newest release is 0.55.0") is true only while the input stays as it is, so code refuses
5
+ // it as week-only. A PLACE RULE keeps it: it names WHERE the value sits (the first heading at one level of a changelog) instead of WHAT the
6
+ // value is. The signed fact carries the rule; at run start, before any provider call, CODE reads the run's own copy of the input with the rule
7
+ // and the value it finds is bound, in memory only, as that fact's phrase for the planner and the close. No model chooses or reads anything here.
8
+ //
9
+ // This module is the graduation (a REWRITE, never a copy) of the round-3 POC (F321). Pure except `lastPlaceRead`, which reads earlier runs' spines.
10
+
11
+ import path from 'node:path';
12
+ import { readFileInside, readdirInside } from './flow.js';
13
+ import { readRunRecord } from './runfile.js';
14
+
15
+ /** the two rule kinds on the menu: the version in a heading, and the date on the same heading line */
16
+ export const PLACE_KINDS = Object.freeze(['headingBetween', 'headingDateAfter']);
17
+ /** the end-of-line end mark */
18
+ export const EOL = '$EOL';
19
+ /** the field a place rule may carry */
20
+ export const PLACE_FIELDS = Object.freeze(['kind', 'prefix', 'end', 'shape', 'skip']);
21
+ /** the closed list of reasons a read can end not found */
22
+ export const PLACE_REASONS = Object.freeze(['mixed-levels', 'no-heading-line', 'first-heading-mismatch', 'end-mark-missing', 'capture-not-shape', 'only-skipped-headings', 'no-date-on-line', 'no-file', 'empty-text']);
23
+ /** plain words for each reason, from code (the person never reads a raw code) */
24
+ export const PLAIN_REASONS = Object.freeze({
25
+ 'mixed-levels': 'the file writes its version headings at more than one level',
26
+ 'no-heading-line': 'the file has no heading at the level the rule reads',
27
+ 'first-heading-mismatch': 'the newest heading does not start the way the rule says',
28
+ 'end-mark-missing': 'the newest heading does not have the mark the rule reads up to',
29
+ 'capture-not-shape': 'the newest heading does not carry a version number',
30
+ 'only-skipped-headings': 'the file has only an Unreleased heading and no release after it',
31
+ 'no-date-on-line': 'the newest heading line carries no date',
32
+ 'no-file': 'the input could not be read',
33
+ 'empty-text': 'the input is empty',
34
+ });
35
+
36
+ const SHAPES = /** @type {Record<string, RegExp>} */ ({ semver: /^\d+\.\d+\.\d+$/, 'iso-date': /^\d{4}-\d{2}-\d{2}$/ });
37
+ const DATE_FIND = /\d{4}-\d{2}-\d{2}/;
38
+ const FENCE = /^\s{0,3}(```|~~~)/;
39
+ /** a heading carries a semver iff its text starts with an optional "[", an optional "v", then X.Y.Z (token-bounded) */
40
+ const SEMVER_HEADING = /^(#{1,6}) \[?v?(\d+\.\d+\.\d+)(?!\d|\.\d)/;
41
+
42
+ /**
43
+ * @typedef {{kind: 'headingBetween'|'headingDateAfter', prefix: string, end: string, shape: string, skip: string[]}} PlaceRule
44
+ * @typedef {{found: true, value: string, lineIndex: number}|{found: false, reason: string}} PlaceRead
45
+ */
46
+
47
+ /**
48
+ * Why a rule is not a legal place rule, or null when it is. Pure.
49
+ * @param {unknown} rule @returns {string|null}
50
+ */
51
+ export function placeRuleProblem(rule) {
52
+ if (rule === null || typeof rule !== 'object' || Array.isArray(rule)) return 'a place rule is {kind, prefix, end, shape, skip}';
53
+ const r = /** @type {Record<string, any>} */ (rule);
54
+ for (const k of Object.keys(r)) if (!PLACE_FIELDS.includes(k)) return `"${k}" is not a field of a place rule (fields: ${PLACE_FIELDS.join(', ')})`;
55
+ if (!PLACE_KINDS.includes(r.kind)) return `kind is one of ${PLACE_KINDS.join(' | ')}`;
56
+ if (typeof r.prefix !== 'string' || !/^#+ /.test(r.prefix)) return 'prefix starts with # marks and a space';
57
+ if (typeof r.end !== 'string' || r.end === '') return 'end is the mark the value is read up to (or $EOL)';
58
+ if (typeof r.shape !== 'string' || !Object.hasOwn(SHAPES, r.shape)) return `shape is one of ${Object.keys(SHAPES).join(' | ')}`;
59
+ if (!Array.isArray(r.skip) || r.skip.some((/** @type {unknown} */ s) => typeof s !== 'string')) return 'skip is a list of words';
60
+ return null;
61
+ }
62
+
63
+ /**
64
+ * Heading lines at the rule's level: lines outside ``` / ~~~ fences that start with the level mark (for example "## "). Pure.
65
+ * @param {string} text @param {string} prefix @returns {{i: number, line: string}[]}
66
+ */
67
+ export function levelLines(text, prefix) {
68
+ const mark = `${/^#+/.exec(prefix)?.[0] ?? '#'} `;
69
+ let fenced = false;
70
+ /** @type {{i: number, line: string}[]} */
71
+ const out = [];
72
+ text.split(/\r?\n/).forEach((line, i) => {
73
+ if (FENCE.test(line)) { fenced = !fenced; return; }
74
+ if (!fenced && line.startsWith(mark)) out.push({ i, line });
75
+ });
76
+ return out;
77
+ }
78
+
79
+ /**
80
+ * The mixed-level guard: every non-fenced heading line is scanned; semver-carrying headings at MORE THAN ONE level mean mixed. A heading with no
81
+ * semver (a "# Changelog" title, "### Fixed") is ignored. It only ever turns a read into not found, never into a value.
82
+ * @param {string} text @returns {boolean}
83
+ */
84
+ export function mixedLevels(text) {
85
+ let fenced = false;
86
+ /** @type {Set<number>} */
87
+ const levels = new Set();
88
+ for (const line of text.split(/\r?\n/)) {
89
+ if (FENCE.test(line)) { fenced = !fenced; continue; }
90
+ if (fenced) continue;
91
+ const m = SEMVER_HEADING.exec(line);
92
+ if (m) levels.add(m[1].length);
93
+ }
94
+ return levels.size > 1;
95
+ }
96
+
97
+ /** @param {string} reason @returns {{found: false, reason: string}} */
98
+ const nf = (reason) => ({ found: false, reason });
99
+
100
+ /**
101
+ * The STRICT first-heading read. It reads only the first heading line at the rule's level; it must match prefix + end + shape, else not found, and
102
+ * it never looks further down. One exception: a capture that is exactly a skip word ("Unreleased") moves to the NEXT heading at that level,
103
+ * ONCE (a second skip word is not found). Pure.
104
+ * @param {PlaceRule} rule @param {string} text
105
+ * @returns {{found: true, cap: string, after: string, lineIndex: number}|{found: false, reason: string}}
106
+ */
107
+ function selectFirst(rule, text) {
108
+ if (!text || !text.trim()) return nf('empty-text');
109
+ if (mixedLevels(text)) return nf('mixed-levels');
110
+ const hs = levelLines(text, rule.prefix);
111
+ if (!hs.length) return nf('no-heading-line');
112
+ let k = 0;
113
+ let skipped = false;
114
+ for (;;) {
115
+ const { i, line } = hs[k];
116
+ if (!line.startsWith(rule.prefix)) return nf('first-heading-mismatch');
117
+ const rest = line.slice(rule.prefix.length);
118
+ const e = rule.end === EOL ? rest.length : rest.indexOf(rule.end);
119
+ if (e < 0) return nf('end-mark-missing');
120
+ const cap = rest.slice(0, e).trim();
121
+ if (rule.skip.some((s) => s.toLowerCase() === cap.toLowerCase())) {
122
+ if (skipped) return nf('only-skipped-headings');
123
+ skipped = true;
124
+ k += 1;
125
+ if (k >= hs.length) return nf('only-skipped-headings');
126
+ continue;
127
+ }
128
+ if (!SHAPES[rule.shape].test(cap)) return nf('capture-not-shape');
129
+ return { found: true, cap, after: rule.end === EOL ? '' : rest.slice(e + rule.end.length), lineIndex: i };
130
+ }
131
+ }
132
+
133
+ /**
134
+ * Read one rule against one input text: the run-start function, code only. A rule that is not legal throws (the signed spec was validated, so a bad one
135
+ * is a defect, never a read).
136
+ * @param {PlaceRule} rule @param {string} text @returns {PlaceRead}
137
+ */
138
+ export function readPlace(rule, text) {
139
+ const bad = placeRuleProblem(rule);
140
+ if (bad !== null) throw new Error(`place rule: ${bad}`);
141
+ const sel = selectFirst(rule, text);
142
+ if (!sel.found) return sel;
143
+ if (rule.kind === 'headingBetween') return { found: true, value: sel.cap, lineIndex: sel.lineIndex };
144
+ const m = DATE_FIND.exec(sel.after);
145
+ if (!m || !SHAPES['iso-date'].test(m[0])) return nf('no-date-on-line');
146
+ return { found: true, value: m[0], lineIndex: sel.lineIndex };
147
+ }
148
+
149
+ // ---- drafting: fit a rule ---------------------------------------------------------------------------------------------------------------
150
+
151
+ const CANDIDATE_PREFIXES = ['## [', '## v', '## ', '# [', '# v', '# ', '### [', '### v', '### '];
152
+ const CANDIDATE_ENDS = [']', ' ', EOL];
153
+ /** the frozen candidate list: 9 prefixes crossed with 3 ends, prefix-major (27) */
154
+ export const PLACE_CANDIDATES = Object.freeze(CANDIDATE_PREFIXES.flatMap((prefix) => CANDIDATE_ENDS.map((end) => Object.freeze({ prefix, end }))));
155
+ /** the one skip word of a fitted rule: an "Unreleased" heading above the newest release */
156
+ const FIT_SKIP = Object.freeze(['Unreleased']);
157
+
158
+ /**
159
+ * Fit a place rule to a fact's own words, by CODE, at drafting. The words must be exactly one version (X.Y.Z) or exactly one ISO date; the frozen
160
+ * candidates are walked in order, and the first whose strict first-heading read on the input's own text returns exactly those words wins. Null =
161
+ * no fit (a version and a date together, any other words, another date form, a mixed-level file, no text, or no candidate reading them): the caller
162
+ * refuses the words as week-only exactly as before. Only the two kinds are handled. Pure.
163
+ * @param {string} words @param {string|null|undefined} text
164
+ * @returns {PlaceRule|null}
165
+ */
166
+ export function fitPlaceRule(words, text) {
167
+ if (typeof text !== 'string' || text.trim() === '') return null;
168
+ const w = String(words ?? '').trim();
169
+ const kind = SHAPES.semver.test(w) ? 'headingBetween' : (SHAPES['iso-date'].test(w) ? 'headingDateAfter' : null);
170
+ if (kind === null) return null;
171
+ for (const c of PLACE_CANDIDATES) {
172
+ /** @type {PlaceRule} */
173
+ const rule = { kind, prefix: c.prefix, end: c.end, shape: 'semver', skip: [...FIT_SKIP] };
174
+ const r = readPlace(rule, text);
175
+ if (r.found && r.value === w) return rule;
176
+ }
177
+ return null;
178
+ }
179
+
180
+ /** the only marks a heading piece may carry around its value: heading hashes, brackets, a dash, parentheses and spaces */
181
+ const HEADING_FURNITURE = /^[\s#[\]()\-\u2013\u2014]*$/;
182
+
183
+ /**
184
+ * STRIP (P1b, hamr 2026-11-11): the words of a phrase fact that are a piece of the newest release heading ("## [0.54.1]", "[0.54.1] -", "0.54.1",
185
+ * "2026-11-04", "## [0.54.1] - 2026-11-04") are stripped by code to their value(s). The words hold exactly one version (X.Y.Z, an optional leading v) and/or
186
+ * exactly one ISO date and nothing else but heading marks; each value is fitted with {@link fitPlaceRule} on the input's own text, and when both are
187
+ * present both must sit on the SAME first release heading line. Returns the values (version first) each with its rule, or null: two versions, two dates,
188
+ * any other word, another date form, a value that is not at the first release heading, no text. Pure.
189
+ * @param {string} words @param {string|null|undefined} text
190
+ * @returns {{kind: 'version'|'date', value: string, rule: PlaceRule}[]|null}
191
+ */
192
+ export function fitPlacePhrase(words, text) {
193
+ if (typeof text !== 'string' || text.trim() === '') return null;
194
+ const w = String(words ?? '');
195
+ const dates = w.match(/(?<![\w.])\d{4}-\d{2}-\d{2}(?!\d)/g) ?? [];
196
+ const noDates = w.replace(/(?<![\w.])\d{4}-\d{2}-\d{2}(?!\d)/g, ' ');
197
+ const versions = [...noDates.matchAll(/(?<![\w.])v?(\d+\.\d+\.\d+)(?!\d|\.\d)/g)].map((m) => m[1]);
198
+ if (dates.length > 1 || versions.length > 1 || dates.length + versions.length === 0) return null;
199
+ if (!HEADING_FURNITURE.test(noDates.replace(/(?<![\w.])v?\d+\.\d+\.\d+(?!\d|\.\d)/g, ' '))) return null;
200
+ /** @type {{kind: 'version'|'date', value: string, rule: PlaceRule}[]} */
201
+ const out = [];
202
+ for (const [kind, value] of /** @type {['version'|'date', string][]} */ ([...versions.map((v) => ['version', v]), ...dates.map((d) => ['date', d])])) {
203
+ const rule = fitPlaceRule(value, text);
204
+ if (rule === null) return null;
205
+ out.push({ kind, value, rule });
206
+ }
207
+ if (out.length === 2) {
208
+ const [a, b] = out.map((x) => readPlace(x.rule, text));
209
+ if (!a.found || !b.found || a.lineIndex !== b.lineIndex) return null;
210
+ }
211
+ return out;
212
+ }
213
+
214
+ // ---- the facts a spec carries -----------------------------------------------------------------------------------------------------------
215
+
216
+ /** @param {unknown} v @returns {v is Record<string, any>} */
217
+ const isRec = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
218
+
219
+ /**
220
+ * @typedef {{key: string, name: string, source: string, stage: number, part: number, fact: number, place: PlaceRule, phrase: string}} PlaceFact
221
+ */
222
+
223
+ /**
224
+ * Every place-rule fact of a spec, in stage / part / fact order. The key is the stage's name and the fact's name (both stable across the runs of one
225
+ * workflow), so an earlier run's record finds the same fact. Pure.
226
+ * @param {any} spec @returns {PlaceFact[]}
227
+ */
228
+ export function placeFactsOf(spec) {
229
+ /** @type {PlaceFact[]} */
230
+ const out = [];
231
+ const stages = Array.isArray(spec?.closeDecl?.stages) ? spec.closeDecl.stages : [];
232
+ stages.forEach((/** @type {any} */ st, /** @type {number} */ si) => {
233
+ if (!isRec(st) || st.kind !== 'rubric-step' || !isRec(st.params) || !Array.isArray(st.params.parts)) return;
234
+ st.params.parts.forEach((/** @type {any} */ p, /** @type {number} */ pi) => {
235
+ if (!isRec(p) || p.class !== 'fact' || !Array.isArray(p.facts)) return;
236
+ p.facts.forEach((/** @type {any} */ f, /** @type {number} */ fi) => {
237
+ if (!isRec(f) || f.shape !== 'phrase' || !isRec(f.place)) return;
238
+ out.push({ key: `${String(st.name)}/${String(f.name)}`, name: String(f.name), source: String(p.source), stage: si, part: pi, fact: fi, place: /** @type {PlaceRule} */ (f.place), phrase: String(f.phrase) });
239
+ });
240
+ });
241
+ });
242
+ return out;
243
+ }
244
+
245
+ /**
246
+ * fwd's shape of {@link placeFactsOf}: a place fact lives on a step's `close.cited.facts[]` (the fact part of a green step that quotes an input), not in a
247
+ * bareloop closeDecl stage. Same PlaceFact record (`stage` = the step's index, `part` = 0, `fact` = the fact's index); the key is the step's `emits` and the fact's name.
248
+ * Pure. @param {any[]} steps @returns {PlaceFact[]}
249
+ */
250
+ export function citedPlaceFactsOf(steps) {
251
+ /** @type {PlaceFact[]} */
252
+ const out = [];
253
+ (Array.isArray(steps) ? steps : []).forEach((/** @type {any} */ st, /** @type {number} */ si) => {
254
+ const cited = st?.close?.class === 'green' ? st.close.cited : undefined;
255
+ if (!isRec(cited) || !Array.isArray(cited.facts)) return;
256
+ cited.facts.forEach((/** @type {any} */ f, /** @type {number} */ fi) => {
257
+ if (!isRec(f) || f.shape !== 'phrase' || !isRec(f.place)) return;
258
+ out.push({ key: `${String(st.emits ?? st.goal)}/${String(f.name)}`, name: String(f.name), source: String(cited.source), stage: si, part: 0, fact: fi, place: /** @type {PlaceRule} */ (f.place), phrase: String(f.phrase) });
259
+ });
260
+ });
261
+ return out;
262
+ }
263
+
264
+ /**
265
+ * A copy of the steps with each place fact's phrase replaced by the value the run read (fwd's shape of {@link bindPlaceValues}). The input is never touched, so the
266
+ * signed declaration and its hash stay as signed. A key with no value keeps the signed drafting words. @param {any[]} steps @param {Record<string, string>} values @returns {any[]}
267
+ */
268
+ export function bindCitedPlaceValues(steps, values) {
269
+ const bound = structuredClone(steps);
270
+ for (const f of citedPlaceFactsOf(bound)) {
271
+ if (Object.hasOwn(values, f.key)) bound[f.stage].close.cited.facts[f.fact].phrase = values[f.key];
272
+ }
273
+ return bound;
274
+ }
275
+
276
+ /**
277
+ * A copy of the spec with each place fact's phrase replaced by the value the run read. The input spec is never touched (the signed spec and its hash
278
+ * stay as signed); the copy is for this run's planner and close only. A key with no value is left as the signed drafting words.
279
+ * @param {any} spec @param {Record<string, string>} values place-fact key to the value read @returns {any}
280
+ */
281
+ export function bindPlaceValues(spec, values) {
282
+ const bound = structuredClone(spec);
283
+ for (const f of placeFactsOf(bound)) {
284
+ if (Object.hasOwn(values, f.key)) bound.closeDecl.stages[f.stage].params.parts[f.part].facts[f.fact].phrase = values[f.key];
285
+ }
286
+ return bound;
287
+ }
288
+
289
+ /**
290
+ * The value the drafting words themselves hold for this rule: the first version for headingBetween, the first ISO date for headingDateAfter. Null when
291
+ * the words hold none. Used as "last read" when no earlier run has one.
292
+ * @param {PlaceRule} rule @param {string} words @returns {string|null}
293
+ */
294
+ export function valueInWords(rule, words) {
295
+ const m = rule.kind === 'headingBetween' ? /(?<![\d.])\d+\.\d+\.\d+(?!\d|\.\d)/.exec(words) : /(?<!\d)\d{4}-\d{2}-\d{2}(?!\d)/.exec(words);
296
+ return m === null ? null : m[0];
297
+ }
298
+
299
+ /**
300
+ * Re-read EVERY place fact against the run's own input text, one by one, before any spend. A row is same / new / notfound. Any notfound stops the run;
301
+ * otherwise the run proceeds with the new words.
302
+ * @param {{fact: PlaceFact, text: string|null, was: string|null}[]} items `text` null = the input could not be read
303
+ * @returns {{proceed: boolean, rows: {key: string, name: string, kind: string, found: boolean, value: string|null, was: string|null, reason: string|null}[], values: Record<string, string>}}
304
+ */
305
+ export function readPlaceRules(items) {
306
+ const rows = items.map(({ fact, text, was }) => {
307
+ const r = text === null ? /** @type {PlaceRead} */ ({ found: false, reason: 'no-file' }) : readPlace(fact.place, text);
308
+ return r.found
309
+ ? { key: fact.key, name: fact.name, kind: fact.place.kind, found: true, value: r.value, was, reason: null }
310
+ : { key: fact.key, name: fact.name, kind: fact.place.kind, found: false, value: null, was, reason: r.reason };
311
+ });
312
+ /** @type {Record<string, string>} */
313
+ const values = {};
314
+ for (const r of rows) if (r.found && r.value !== null) values[r.key] = r.value;
315
+ return { proceed: rows.every((r) => r.found), rows, values };
316
+ }
317
+
318
+ /** the end of the stop words: what the person can do, and that nothing ran or was spent */
319
+ export const STOP_TAIL = 'Reuse workflow and adjust the rules, or check the input. The run did not start. Nothing spent.';
320
+
321
+ /**
322
+ * The words of the $0 stop, plain words from code. Every rule is listed, found or not: "<name>: found <value>" (with "(was <last>)" when the value is
323
+ * new) or "<name>: not found (<plain reason>)", then the closing line. The reasons come only from the closed list.
324
+ * @param {{name: string, found: boolean, value: string|null, was: string|null, reason: string|null}[]} rows @returns {string}
325
+ */
326
+ export function stopWords(rows) {
327
+ const lines = rows.map((r) => {
328
+ if (!r.found) return `${r.name}: not found (${PLAIN_REASONS[/** @type {keyof typeof PLAIN_REASONS} */ (r.reason ?? 'no-file')] ?? 'the input could not be read'})`;
329
+ return `${r.name}: found ${r.value}${r.was !== null && r.was !== r.value ? ` (was ${r.was})` : ''}`;
330
+ });
331
+ return `${lines.join('\n')}\n${STOP_TAIL}`;
332
+ }
333
+
334
+ // ---- the record of a run: what was read, and what the last run read ---------------------------------------------------------------------
335
+
336
+ /** the plain words of the door's refusal when a place-rule run has no record of the values it read */
337
+ export const NO_PLACE_RECORD_WORDS = 'This run has no record of the values it read, so it cannot be checked again. Use Reuse workflow.';
338
+
339
+ /** the spine event a run writes, once, after job-start */
340
+ export const PLACE_EVENT = 'place-rules';
341
+
342
+ /**
343
+ * The values of the LAST `place-rules` record in a run's own events (key to value): what a RESUME of that run rebinds, since a resume does not re-read. Null when
344
+ * there is no record, or any of its rows was not found.
345
+ * @param {any[]} events @returns {Record<string, string>|null}
346
+ */
347
+ export function placeValuesOfEvents(events) {
348
+ const rec = Array.isArray(events) ? events.findLast((e) => isRec(e) && e.type === PLACE_EVENT && Array.isArray(e.rows)) : undefined;
349
+ if (rec === undefined || rec.rows.length === 0 || rec.rows.some((/** @type {any} */ r) => !isRec(r) || r.found !== true || typeof r.value !== 'string')) return null;
350
+ return Object.fromEntries(rec.rows.map((/** @type {any} */ r) => [String(r.key), r.value]));
351
+ }
352
+
353
+ /**
354
+ * What the newest EARLIER run of the same workflow read, per fact key: "last read". `rows` are the run list's rows (file order, oldest first). Candidates are
355
+ * the rows of the same job, newest first, at most {@link LAST_READ_LOOK} of them; the first whose spine holds a `place-rules` record of the same workflow key
356
+ * answers. An unreadable spine is skipped. Empty when there is none (the caller falls back to the drafting words).
357
+ * @param {{rows: {runid: string, job: string, spine: string}[], job: string, workflowKey: string, runid: string}} o @returns {Record<string, string>}
358
+ */
359
+ export function lastPlaceRead({ rows, job, workflowKey, runid }) {
360
+ let looked = 0;
361
+ for (const row of [...rows].reverse()) {
362
+ if (row.runid === runid || row.job !== job || typeof row.spine !== 'string') continue;
363
+ // one read through the gateway: a missing spine is skipped WITHOUT counting (as `existsSync` did); one that exists but cannot be read (or is a symlink: the gateway refuses it) counts and is skipped
364
+ const spine = readFileInside(path.dirname(row.spine), path.basename(row.spine));
365
+ if (!spine.ok && spine.missing) continue;
366
+ if (looked >= LAST_READ_LOOK) break;
367
+ looked += 1;
368
+ if (!spine.ok) continue;
369
+ /** @type {any[]} */
370
+ let events = [];
371
+ try { events = spine.text.split('\n').filter((l) => l.includes(`"${PLACE_EVENT}"`)).map((l) => JSON.parse(l)); } catch { continue; }
372
+ const rec = events.findLast((e) => isRec(e) && e.type === PLACE_EVENT && e.workflowKey === workflowKey && Array.isArray(e.rows));
373
+ if (rec !== undefined) return Object.fromEntries(rec.rows.filter((/** @type {any} */ r) => isRec(r) && r.found === true && typeof r.value === 'string').map((/** @type {any} */ r) => [String(r.key), r.value]));
374
+ }
375
+ return {};
376
+ }
377
+ /** how many earlier runs of the job are looked at for "last read" */
378
+ export const LAST_READ_LOOK = 25;
379
+
380
+ /**
381
+ * fwd's "last read" (bareloop's lastPlaceRead reads spines; fwd has none): per fact key, the value the newest EARLIER run of the same flow recorded in its run.json
382
+ * `placeRules` (runs are `run-<n>`; at most {@link LAST_READ_LOOK} earlier runs are looked at; a run with no record, or an unreadable one, is skipped). Empty when none.
383
+ * @param {{flowDir: string, runId: string}} o @returns {Record<string, string>}
384
+ */
385
+ export function lastRunPlaceRead({ flowDir, runId }) {
386
+ const num = (/** @type {string} */ id) => { const m = /^run-(\d+)$/.exec(id); return m === null ? null : Number(m[1]); };
387
+ const me = num(runId);
388
+ const earlier = readdirInside(flowDir, 'runs').map((id) => ({ id, n: num(id) })).filter((r) => r.n !== null && (me === null || /** @type {number} */ (r.n) < me))
389
+ .sort((a, b) => /** @type {number} */ (b.n) - /** @type {number} */ (a.n)).slice(0, LAST_READ_LOOK);
390
+ /** @type {Record<string, string>} */
391
+ const out = {};
392
+ for (const r of earlier) {
393
+ const got = readRunRecord(path.join(flowDir, 'runs', r.id));
394
+ const rows = got.ok && Array.isArray(got.rec.placeRules?.rows) ? got.rec.placeRules.rows : [];
395
+ for (const row of rows) if (isRec(row) && row.found === true && typeof row.value === 'string' && !Object.hasOwn(out, String(row.key))) out[String(row.key)] = row.value;
396
+ }
397
+ return out;
398
+ }
@@ -0,0 +1,206 @@
1
+ // borrowed-from: bareloop src/panel/authorroutes.js@v0.56.0 (3383cce) (the row-edit route: op drop|add and a row key, the choice goes through the block's own rowChoice; the live session is replaced by the rebuild below)
2
+ // borrowed-from: bareloop src/panel/authorsession.js@v0.56.0 (3383cce) (rowEdit: the refusal words are the block's own, the choices are kept as rowChoices in the picks record)
3
+ // M16 P4 item 3 (docs/wiki/the-module-ladder.md, "M16" am3 (4)): Drop and Add on the plan card. fwd drafts in a child process, so no live check block outlives a draft: the panel REBUILDS the list at $0
4
+ // from what the draft saved (its prose, the frozen page copies and the document inputs, page-look.json, picks-record.json, and the AI's edit replies in log.json), applies the person's choice through
5
+ // the block's own `rowChoice`, assembles the checks again and hands back the files of a NEW plan. It makes no provider call, builds no provider, spawns nothing. The rebuild is only trusted when,
6
+ // before the choice, it reproduces the saved plan's list exactly; if an input changed since the draft the person is told so and nothing is written.
7
+ // What this throws away: nothing of the old plan (it is never rewritten, records are write-once).
8
+ import path from 'node:path';
9
+ import { parseSignedText } from './signed-text.js';
10
+ import { readFileInside, readdirInside } from './flow.js';
11
+ import { readInputFacts } from './input-facts.js';
12
+ import { blockJobLines } from './blocklines.js';
13
+ import { setUpBlock, ticketLeaveOut, pickEdits, ledgerEdits } from './blockdraft.js';
14
+ import { assembleFromBlock } from './blockassemble.js';
15
+ import { cardOfBlock } from './cardlist.js';
16
+ import { editsOf } from './rowedit.js';
17
+ import { offerRules, rowsFromAnswer, codeScope } from './checkpick.js';
18
+ import { matchRecord, readRowChoices, RECORD_FILE } from './pickrecord.js';
19
+ import { listLinesOf, cardLinesOf } from './checklistsign.js';
20
+ import { csvRolesOf } from './sheetblock.js';
21
+ import { isSheetKey, sheetChoice, withSheetRows, withSheetCard, droppedSheetOf } from './sheetrows.js';
22
+ import { validateDeclaration } from './declaration.js';
23
+ import { loadCatalogue } from './catalogue.js';
24
+ import { WIRED_VERBS } from './primitives.js';
25
+ import { ticketSourcesOf } from './ticket-draft.js';
26
+ import { docRolesOf } from './drafter.js';
27
+ import { buildReadout, specHash, PAGES_DIR, NOT_CHECKED_FILE } from './authoring.js';
28
+
29
+ /** what a person is told when the saved inputs no longer give the saved list: nothing is written */
30
+ export const REBUILD_CHANGED_SAY = 'The inputs of this plan have changed since it was drafted, so its checks cannot be changed here. Draft again from the card. Nothing was changed.';
31
+ /** a plan that has no list (drafted before M16) */
32
+ export const NO_LIST_SAY = 'This plan has no list of checks to change. Nothing was changed.';
33
+
34
+ const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
35
+ const readJson = (/** @type {string} */ dir, /** @type {string} */ rel) => { const r = readFileInside(dir, rel); if (!r.ok) return null; try { return JSON.parse(r.text); } catch { return null; } };
36
+
37
+ /**
38
+ * Rebuild the block of a saved plan at $0. `choices` = the Drop/Add choices the plan was made with (its record's `rowChoices`).
39
+ * @param {{planDir: string, asks: boolean}} o
40
+ * @returns {{ok: true, block: import('./checkblock.js').CheckBlock, declaration: any, lines: any[], lineSet: Set<number>, parsed: any, texts: Record<string, string>, look: {facts: any[], dropped: any[]}, record: any, log: any, proseText: string}|{ok: false, say: string}}
41
+ */
42
+ export function rebuildBlock({ planDir, asks }) {
43
+ const no = (/** @type {string} */ say) => ({ ok: /** @type {const} */ (false), say });
44
+ const prose = readFileInside(planDir, 'prose.txt');
45
+ const parsed = prose.ok ? parseSignedText(prose.text) : null;
46
+ const declaration = readJson(planDir, 'declaration.json');
47
+ if (!prose.ok || !parsed || !parsed.ok || !isRec(declaration)) return no('This plan could not be read. Nothing was changed.');
48
+ // the lines the block was given; a CSV job's sheet lines (M16 am4) have rows on the list too, but the block never had them
49
+ const lineSet = listLinesOf(declaration);
50
+ if (cardLinesOf(declaration).size === 0) return no(NO_LIST_SAY);
51
+ const log = readJson(planDir, 'log.json');
52
+ const pageLook = readJson(planDir, 'page-look.json');
53
+ const look = isRec(pageLook?.look) ? { facts: Array.isArray(pageLook.look.facts) ? pageLook.look.facts : [], dropped: Array.isArray(pageLook.look.dropped) ? pageLook.look.dropped : [] } : { facts: [], dropped: [] };
54
+ const record = readJson(planDir, RECORD_FILE) ?? {};
55
+ // the frozen copies of the page inputs, then the document inputs as the draft read them (they are not copied into the folder: an input that changed is caught below)
56
+ /** @type {Record<string, {text: string}>} */
57
+ const pages = {};
58
+ for (const p of Array.isArray(pageLook?.pages) ? pageLook.pages : []) {
59
+ const f = readFileInside(planDir, path.join(PAGES_DIR, String(p.frozen)));
60
+ if (f.ok && typeof p.role === 'string') pages[p.role] = { text: f.text };
61
+ }
62
+ const ticketSources = declaration.flowType === 'tickets' ? ticketSourcesOf(parsed.arbiter.sources) : [];
63
+ const facts = readInputFacts((parsed.arbiter.sources ?? []).filter((/** @type {any} */ s) => !ticketSources.includes(s)), { pages });
64
+ if (!facts.ok) return no(REBUILD_CHANGED_SAY);
65
+ const texts = { ...(facts.docs ?? {}), ...Object.fromEntries(Object.entries(pages).map(([role, pg]) => [role, pg.text])) };
66
+ // the lines the block was given are the lines the saved list has rows on
67
+ const all = blockJobLines(prose.text, undefined, []);
68
+ if (!all.ok) return no('This plan could not be read. Nothing was changed.');
69
+ const tied = all.jobLines.filter((l) => !lineSet.has(l.n)).map((l) => l.n);
70
+ const plan = blockJobLines(prose.text, undefined, tied);
71
+ if (!plan.ok) return no('This plan could not be read. Nothing was changed.');
72
+ const blockLineNums = new Set(plan.jobLines.map((l) => l.n));
73
+ const inBlock = (/** @type {{line: number}} */ x) => blockLineNums.has(x.line);
74
+ const lines = parsed.lines;
75
+ const allShape = offerRules(lines, parsed.arbiter, look.facts);
76
+ const matched = matchRecord(Array.isArray(record.picks) ? record.picks : [], lines, allShape);
77
+ const keptKeys = new Set((Array.isArray(record.kept) ? record.kept : []).map((/** @type {any} */ k) => `${k.line}:${k.rule}`));
78
+ const isKept = (/** @type {{line: number, rule: number}} */ x) => keptKeys.has(`${x.line}:${x.rule}`);
79
+ // a rule the person answered Drop it: the draft was told it as `leftRules` and saved it as a `person-left` drop in page-look.json (its record holds no entry for a rule the look served);
80
+ // the rebuild reads that same saved drop, so the rule is the block's own `left` row again and its note keeps the person's words
81
+ const leftSaved = look.dropped.filter((/** @type {any} */ d) => d?.reason === 'person-left' && Number.isInteger(d.line) && Number.isInteger(d.rule)).map((/** @type {any} */ d) => ({ line: d.line, rule: d.rule }));
82
+ const leftFresh = [...matched.left.filter((x) => !isKept(x)), ...leftSaved.filter((x) => !matched.left.some((m) => m.line === x.line && m.rule === x.rule))].filter(inBlock);
83
+ const block = setUpBlock({
84
+ texts, jobLines: plan.jobLines, look,
85
+ kept: { picks: matched.picks.filter(inBlock).filter(isKept), left: matched.left.filter(inBlock).filter(isKept), askRules: matched.askRules.filter(inBlock) },
86
+ fresh: { picks: matched.picks.filter(inBlock).filter((x) => !isKept(x)), left: leftFresh },
87
+ asks, countScope: (t) => codeScope(parsed.arbiter.sources, t) === 'in', scoped: allShape.filter(inBlock), leaveOut: ticketLeaveOut(declaration.flowType, plan.jobLines, look.facts),
88
+ });
89
+ // the AI's replies, in the order the draft took them (log.json keeps each reply as sent)
90
+ const askRules = allShape.filter((r) => !isKept(r));
91
+ for (const e of Array.isArray(log?.log) ? log.log : []) {
92
+ if (!isRec(e) || e.outcome !== 'answered' || !isRec(e.args)) continue;
93
+ if (e.kind === 'check-suggest') block.applyDelta({ label: 'pre:check-suggest', pre: true, edits: pickEdits(rowsFromAnswer(askRules, e.args), blockLineNums) });
94
+ else if (e.kind === 'ledger-suggest') block.applyDelta({ label: 'pre:ledger-suggest', pre: true, edits: ledgerEdits(e.args.extra) });
95
+ else if (e.kind === 'row-edit' || e.kind === 'row-edit-revision') block.applyDelta({ label: `${e.kind}-${e.round}`, edits: editsOf(e.args) });
96
+ else continue;
97
+ block.reconcile();
98
+ }
99
+ // the choices the plan was made with (a Drop or an Add of an earlier edit), judged by the block again
100
+ const choices = readRowChoices(path.join(planDir, RECORD_FILE));
101
+ if (choices) block.carryChoices(choices);
102
+ block.reconcile();
103
+ return { ok: true, block, declaration, lines, lineSet, parsed, texts, look, record, log, proseText: prose.text };
104
+ }
105
+
106
+ /**
107
+ * The checks of a rebuilt block put back into the saved plan's declaration (the same assembly the draft used), re-proved by the validator.
108
+ * @param {any} b @param {any} [from] the declaration to assemble over (a sheet Drop or Add changes its `close.sheet`); the saved one by default
109
+ * @returns {{ok: true, declaration: any, notChecked: string[], notCheckedBy: Record<string, string>, sheet: ReturnType<typeof withSheetRows>['sheet']}|{ok: false, say: string}}
110
+ */
111
+ function assembleAgain(b, from = b.declaration) {
112
+ const { checkList: _c, pickedLines: _p, ...saved } = from;
113
+ // a document input is listed in a step's reads only by the step that quotes it, and the assembly put it there: take it out first, the assembly adds it again while the fact is still built
114
+ const docs = new Set(docRolesOf(b.parsed.arbiter.sources));
115
+ const rest = { ...saved, steps: (saved.steps ?? []).map((/** @type {any} */ st) => {
116
+ const src = b.lineSet.has(st?.fromLine) && isRec(st.close) && isRec(st.close.cited) ? st.close.cited.source : undefined;
117
+ return typeof src === 'string' && docs.has(src) && Array.isArray(st.reads) ? { ...st, reads: st.reads.filter((/** @type {string} */ r) => r !== src) } : st;
118
+ }) };
119
+ const built = assembleFromBlock({ declaration: rest, block: b.block, lines: b.lines, lineSet: b.lineSet });
120
+ // M16 am4: the sheet checks are rows on the list too, read from the steps the same way the draft read them
121
+ const withSheet = withSheetRows({ declaration: built.declaration, lines: b.lines, csvRoles: csvRolesOf(b.parsed.arbiter) });
122
+ const a = { ...built, declaration: withSheet.declaration };
123
+ const cat = loadCatalogue();
124
+ if (!cat.ok) return { ok: false, say: 'The catalogue could not be read. Nothing was changed.' };
125
+ const inPlan = new Set(b.block.rows.filter((r) => r.state === 'built').flatMap((r) => (r.factNames ?? []).map((/** @type {string} */ nm) => `${r.line}:${nm}`)));
126
+ const planFacts = b.look.facts.filter((f) => !b.lineSet.has(f.line) || inPlan.has(`${f.line}:${f.name}`));
127
+ const pageSources = (b.parsed.arbiter.sources ?? []).some((/** @type {any} */ s) => s.kind === 'page');
128
+ const verdict = validateDeclaration(a.declaration, {
129
+ arbiter: b.parsed.arbiter, lines: b.lines, catalogue: cat.primitives, wired: WIRED_VERBS, verbatimGoals: true, fitJobLine: true,
130
+ pageWords: { texts: b.texts, look: pageSources ? { facts: planFacts, dropped: b.look.dropped } : null, docs: docRolesOf(b.parsed.arbiter.sources) },
131
+ });
132
+ if (!verdict.ok) return { ok: false, say: `The changed list did not pass the plan's checks (${String(verdict.reds[0])}). Nothing was changed.` };
133
+ return { ok: true, declaration: a.declaration, notChecked: a.notChecked, notCheckedBy: a.notCheckedBy, sheet: withSheet.sheet };
134
+ }
135
+
136
+ /** the plan's list and the closes it checks, as one comparable string (the proof that the rebuild is the saved plan) @param {any} d */
137
+ const fingerprint = (d) => JSON.stringify([d.checkList ?? null, (d.steps ?? []).map((/** @type {any} */ s) => [s?.fromLine, s?.close])]);
138
+
139
+ /**
140
+ * Drop or Add a row of a saved plan, at $0. Returns the files of the NEW plan folder (the caller writes them once); the old plan is never touched.
141
+ * @param {{planDir: string, op: 'drop'|'add', key: string, asks?: boolean}} o
142
+ * @returns {{ok: true, files: Record<string, string>, pages: Record<string, string>, logRow: Record<string, any>, hash: string}|{ok: false, say: string, refused?: string}}
143
+ */
144
+ export function rowEditPlan({ planDir, op, key, asks = true }) {
145
+ const b = rebuildBlock({ planDir, asks });
146
+ if (!b.ok) return { ok: false, say: b.say, refused: 'no-list' };
147
+ const dropped = droppedSheetOf(b.record);
148
+ const before = assembleAgain(b);
149
+ if (!before.ok) return { ok: false, say: before.say, refused: 'rebuild' };
150
+ if (fingerprint(before.declaration) !== fingerprint(b.declaration)) return { ok: false, say: REBUILD_CHANGED_SAY, refused: 'changed' };
151
+ // a sheet row is a check of the AI's own sheet step: its Drop or Add changes `close.sheet` (src/sheetrows.js); any other row is the block's
152
+ const sheetDone = isSheetKey(key) ? sheetChoice({ declaration: b.declaration, lines: b.lines, csvRoles: csvRolesOf(b.parsed.arbiter), op, key, dropped }) : null;
153
+ const done = sheetDone ?? b.block.rowChoice(key, op);
154
+ if (!done.ok) return { ok: false, say: `${done.why[0].toUpperCase()}${done.why.slice(1)}${/[.!?]$/.test(done.why) ? '' : '.'} Nothing was changed.`, refused: 'bad-row' };
155
+ const droppedNow = sheetDone && sheetDone.ok ? sheetDone.dropped : dropped;
156
+ const after = assembleAgain(b, sheetDone && sheetDone.ok ? sheetDone.declaration : b.declaration);
157
+ if (!after.ok) return { ok: false, say: after.say, refused: 'rebuild' };
158
+ const target = readJson(planDir, 'target.json');
159
+ const inputFactsText = readFileInside(planDir, 'input-facts.json');
160
+ const targetText = readFileInside(planDir, 'target.json');
161
+ if (!targetText.ok || !inputFactsText.ok || !isRec(target)) return { ok: false, say: 'This plan could not be read. Nothing was changed.', refused: 'rebuild' };
162
+ const dj = (/** @type {unknown} */ o) => `${JSON.stringify(o, null, 2)}\n`;
163
+ const declarationText = dj(after.declaration);
164
+ const readoutText = buildReadout({
165
+ declaration: after.declaration, arbiter: b.parsed.arbiter, lines: b.lines, name: target.name, modelId: b.log?.modelId, costUsd: b.log?.costUsd ?? null, rounds: b.log?.rounds ?? 0, spendComplete: b.log?.spendComplete !== false, root: target.root,
166
+ });
167
+ const h = specHash({ proseText: b.proseText, declarationText, inputFactsText: inputFactsText.text, readoutText, targetText: targetText.text });
168
+ if (!h.ok) return { ok: false, say: 'The changed plan could not be hashed. Nothing was changed.', refused: 'rebuild' };
169
+ // the "Not checked" list: what the old plan listed, less what the old list made, plus what the changed list makes (the AI's own list stays)
170
+ const oldNc = readJson(planDir, NOT_CHECKED_FILE)?.notChecked;
171
+ const oldList = Array.isArray(oldNc) ? oldNc.filter((x) => typeof x === 'string') : [];
172
+ const was = new Set(before.notChecked);
173
+ const notChecked = [...new Set([...oldList.filter((x) => !was.has(x)), ...after.notChecked])];
174
+ const oldBy = isRec(readJson(planDir, NOT_CHECKED_FILE)?.by) ? readJson(planDir, NOT_CHECKED_FILE).by : {};
175
+ const by = { ...Object.fromEntries(Object.entries(oldBy).filter(([t]) => !was.has(t))), ...after.notCheckedBy };
176
+ const { sheetDropped: _sd, ...record } = isRec(b.record) ? b.record : {};
177
+ const logRow = { round: (Array.isArray(b.log?.log) ? b.log.log.length : 0) + 1, kind: 'row-edit-human', op, key, outcome: 'answered', at: new Date().toISOString() };
178
+ // the files the new plan keeps as they were (read through the gateway), then the ones it changes; `spec.hash` last, so a folder with one is whole
179
+ /** @type {Record<string, string>} */
180
+ const kept = {};
181
+ for (const f of ['prose.txt', 'target.json', 'input-facts.json', 'page-look.json', 'model.json', 'learnings.json']) {
182
+ const r = readFileInside(planDir, f);
183
+ if (r.ok) kept[f] = r.text;
184
+ }
185
+ /** @type {Record<string, string>} */
186
+ const pages = {};
187
+ for (const f of readdirInside(planDir, PAGES_DIR)) {
188
+ const r = readFileInside(planDir, path.join(PAGES_DIR, f));
189
+ if (r.ok) pages[path.join(PAGES_DIR, f)] = r.text;
190
+ }
191
+ return {
192
+ ok: true,
193
+ hash: h.hash,
194
+ logRow,
195
+ pages,
196
+ files: {
197
+ ...kept,
198
+ 'declaration.json': declarationText,
199
+ 'readout.txt': readoutText,
200
+ [NOT_CHECKED_FILE]: dj({ notChecked, ...(Object.keys(by).length ? { by } : {}) }),
201
+ [RECORD_FILE]: dj({ ...record, rowChoices: b.block.choicesRecord(), ...(droppedNow.length ? { sheetDropped: droppedNow } : {}) }),
202
+ 'log.json': dj({ ...(isRec(b.log) ? b.log : {}), log: [...(Array.isArray(b.log?.log) ? b.log.log : []), logRow], checkCard: withSheetCard(cardOfBlock(b.block), after.sheet, droppedNow) }),
203
+ 'spec.hash': `${h.hash}\n`,
204
+ },
205
+ };
206
+ }