fwdloop 0.21.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 (87) hide show
  1. package/bin/fwdloop +85 -34
  2. package/package.json +4 -3
  3. package/src/audit-fold.js +5 -1
  4. package/src/authoring.js +32 -6
  5. package/src/checked.js +18 -1
  6. package/src/cited-record.js +138 -0
  7. package/src/cited-source.js +49 -0
  8. package/src/citedcheck.js +306 -0
  9. package/src/citedwords.js +197 -0
  10. package/src/closers.js +56 -7
  11. package/src/ctx-tools.js +2 -14
  12. package/src/declaration.js +85 -5
  13. package/src/diary.js +2 -2
  14. package/src/docx.js +16 -2
  15. package/src/draft-steps.js +1 -1
  16. package/src/drafter.js +292 -25
  17. package/src/flow.js +33 -7
  18. package/src/flowmodel.js +21 -0
  19. package/src/input-facts.js +20 -3
  20. package/src/model-step.js +30 -5
  21. package/src/pageask.js +136 -0
  22. package/src/pagebits.js +107 -0
  23. package/src/pagedropwords.js +171 -0
  24. package/src/pagedry.js +120 -0
  25. package/src/pagefetch.js +164 -0
  26. package/src/pagelook.js +155 -0
  27. package/src/pagemap.js +55 -0
  28. package/src/pageplace.js +103 -0
  29. package/src/pagerules.js +318 -0
  30. package/src/panel/author.js +41 -20
  31. package/src/panel/authorcard.js +11 -1
  32. package/src/panel/authorflows.js +21 -15
  33. package/src/panel/authorstart.js +2 -4
  34. package/src/panel/authortrigger.js +14 -4
  35. package/src/panel/data.js +83 -2
  36. package/src/panel/index.html +279 -12
  37. package/src/panel/result.js +295 -0
  38. package/src/panel/server.js +27 -3
  39. package/src/primitives.js +2 -3
  40. package/src/provider.js +5 -2
  41. package/src/redact.js +17 -0
  42. package/src/runner.js +83 -12
  43. package/src/schedule.js +3 -3
  44. package/src/setup.js +16 -1
  45. package/src/sheetfind.js +50 -0
  46. package/src/sheetlook.js +157 -0
  47. package/src/signed-text.js +11 -1
  48. package/src/thinking.js +1 -1
  49. package/src/try-checks.js +6 -0
  50. package/src/types.js +3 -2
  51. package/types/authoring.d.ts +19 -2
  52. package/types/checked.d.ts +10 -0
  53. package/types/cited-record.d.ts +21 -0
  54. package/types/cited-source.d.ts +18 -0
  55. package/types/citedcheck.d.ts +95 -0
  56. package/types/citedwords.d.ts +97 -0
  57. package/types/closers.d.ts +55 -3
  58. package/types/ctx-tools.d.ts +0 -1
  59. package/types/declaration.d.ts +15 -1
  60. package/types/docx.d.ts +14 -0
  61. package/types/drafter.d.ts +244 -2
  62. package/types/flow.d.ts +21 -0
  63. package/types/flowmodel.d.ts +15 -0
  64. package/types/input-facts.d.ts +12 -2
  65. package/types/model-step.d.ts +35 -3
  66. package/types/pageask.d.ts +75 -0
  67. package/types/pagebits.d.ts +32 -0
  68. package/types/pagedropwords.d.ts +40 -0
  69. package/types/pagedry.d.ts +38 -0
  70. package/types/pagefetch.d.ts +86 -0
  71. package/types/pagelook.d.ts +75 -0
  72. package/types/pagemap.d.ts +31 -0
  73. package/types/pageplace.d.ts +22 -0
  74. package/types/pagerules.d.ts +86 -0
  75. package/types/panel/authorcard.d.ts +2 -0
  76. package/types/panel/authorflows.d.ts +2 -0
  77. package/types/panel/data.d.ts +26 -0
  78. package/types/panel/result.d.ts +156 -0
  79. package/types/provider.d.ts +3 -1
  80. package/types/redact.d.ts +1 -0
  81. package/types/runner.d.ts +156 -7
  82. package/types/schedule.d.ts +0 -11
  83. package/types/setup.d.ts +13 -0
  84. package/types/sheetfind.d.ts +46 -0
  85. package/types/sheetlook.d.ts +120 -0
  86. package/types/thinking.d.ts +1 -1
  87. package/types/types.d.ts +11 -3
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
@@ -429,14 +476,16 @@ export async function closeSoftgreen(artifact, shape) {
429
476
  /**
430
477
  * The one dispatcher — `close by declared class` (M2 scope item 4).
431
478
  *
432
- * @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
433
480
  * @param {unknown} artifact
434
- * @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
435
483
  * @returns {Promise<CloseVerdict>}
436
484
  */
437
485
  export async function closeByClass(step, artifact, ctx) {
438
486
  const cls = step?.close?.class;
439
- 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 });
440
489
  if (cls === 'softgreen') return await closeSoftgreen(artifact, step?.close?.shape ?? {});
441
490
  if (cls === 'hitl') return { verdict: 'hitl', red: null };
442
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
- export 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 CHANGED
@@ -4,7 +4,7 @@
4
4
  // tools.jsonl one row per TOOL CALL: step, try, round, tool, path, the guard's decision (allow / deny + rule / no check)
5
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
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/ctx-tools.js) before the row is written. The model can never read these files: the step's
7
+ // ONE secret inventory (`redactSecrets`, src/redact.js) before the row is written. The model can never read these files: the step's
8
8
  // bareguard Gate denies them (src/primitives.js) and a grep over the run folder drops their hits.
9
9
  // Rounds count from 1 in EACH STEP (they keep counting across that step's tries); `nextRound` reads the count off the diary.
10
10
  //
@@ -12,7 +12,7 @@
12
12
  import { join } from 'node:path';
13
13
  import { appendRow } from './jsonl-append.js';
14
14
  import { readLines } from './books.js';
15
- import { redactSecrets } from './ctx-tools.js';
15
+ import { redactSecrets } from './redact.js';
16
16
 
17
17
  export const DIARY_FILES = Object.freeze({ calls: 'calls.jsonl', tools: 'tools.jsonl', checks: 'checks.jsonl' });
18
18
 
package/src/docx.js CHANGED
@@ -12,6 +12,7 @@
12
12
  // is over raw paragraph markup, not a parsed tree).
13
13
 
14
14
  import { readFileSync } from 'node:fs';
15
+ import { createHash } from 'node:crypto';
15
16
  import { inflateRawSync } from 'node:zlib';
16
17
 
17
18
  const EOCD_SIG = 0x06054b50;
@@ -128,7 +129,8 @@ function extractText(xml) {
128
129
  }
129
130
 
130
131
  /** One reader for word/document.xml: the file, the zip entry, the bounded inflate.
131
- * @param {string} path @returns {{ok:true,xml:string}|{ok:false,red:string}} */
132
+ * `sha256` is of the file's bytes, taken from the SAME read the text comes from (so a text and its hash can never be of two different files).
133
+ * @param {string} path @returns {{ok:true,xml:string,sha256:string}|{ok:false,red:string}} */
132
134
  function loadDocumentXml(path) {
133
135
  let buf;
134
136
  try {
@@ -140,7 +142,7 @@ function loadDocumentXml(path) {
140
142
  if (entry.red) return { ok: false, red: entry.red };
141
143
  const read = readEntryBytes(buf, entry);
142
144
  if (read.red || !read.data) return { ok: false, red: read.red ?? 'no data decoded' };
143
- return { ok: true, xml: read.data.toString('utf8') };
145
+ return { ok: true, xml: read.data.toString('utf8'), sha256: createHash('sha256').update(buf).digest('hex') };
144
146
  }
145
147
 
146
148
  /** @param {string} path @returns {{ok:true,text:string,paragraphs:number}|{ok:false,red:string}} */
@@ -151,6 +153,18 @@ export function readDocxText(path) {
151
153
  return { ok: true, text, paragraphs };
152
154
  }
153
155
 
156
+ /**
157
+ * M10 piece 5 (item 2, "a quote in a doc"): the text of a .docx AND the sha256 of its bytes from one read, so a cited check can prove the run's own frozen copy is
158
+ * the file that was frozen. Same text as {@link readDocxText} (what it throws away is declared at the top of this file).
159
+ * @param {string} path @returns {{ok:true,text:string,paragraphs:number,sha256:string}|{ok:false,red:string}}
160
+ */
161
+ export function readDocxSource(path) {
162
+ const doc = loadDocumentXml(path);
163
+ if (!doc.ok) return doc;
164
+ const { text, paragraphs } = extractText(doc.xml);
165
+ return { ok: true, text, paragraphs, sha256: doc.sha256 };
166
+ }
167
+
154
168
  // Heading paragraphs: <w:pStyle w:val="Heading1"/> .. HeadingN, or Title. The
155
169
  // style ID is matched, not styles.xml's display name — Word writes the ID
156
170
  // "Heading1" for the built-in "heading 1"; a custom-named heading style is
@@ -69,7 +69,7 @@ export function draftStepList({ log, declaration, questionOpen = false }) {
69
69
  const reds = Array.isArray(log.reds) ? log.reds.map(String) : [];
70
70
  const facts = ['drafted', who, `${n} round${n === 1 ? '' : 's'}`, money(log)];
71
71
  if (!gotPlan && reds.length > 0) facts.push(reds[0]); // no plan at all (provider red, cut off): its own words, there is no checker text
72
- out.push({ id: 'drafted', label: facts.join(' · '), status: /** @type {'done'|'failed'} */ (gotPlan ? 'done' : 'failed'), details: [] });
72
+ out.push({ id: 'drafted', label: facts.join(' · '), status: /** @type {'done'|'failed'} */ (gotPlan || (questionOpen && reds.length === 0) ? 'done' : 'failed'), details: [] }); // a draft that stopped to ask (the page look's question, no plan yet) has not failed
73
73
 
74
74
  const steps = Array.isArray(declaration?.steps) ? declaration.steps : [];
75
75
  const rubricReds = [];