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.
- package/bin/fwdloop +8 -2
- package/package.json +2 -2
- package/src/auditchecks.js +53 -0
- package/src/authoring.js +52 -12
- package/src/blockasks.js +44 -0
- package/src/blockassemble.js +140 -0
- package/src/blockdraft.js +91 -0
- package/src/blocklines.js +30 -0
- package/src/blockpick.js +165 -0
- package/src/cardlist.js +19 -0
- package/src/checkblock.js +804 -0
- package/src/checked.js +48 -9
- package/src/checklist.js +99 -0
- package/src/checklistsign.js +93 -0
- package/src/checkwords.js +20 -1
- package/src/cited-record.js +21 -1
- package/src/citedcheck.js +162 -7
- package/src/closers.js +41 -3
- package/src/declaration.js +25 -2
- package/src/declaredclose.js +4 -0
- package/src/draft-steps.js +3 -1
- package/src/drafter.js +244 -134
- package/src/factwords.js +112 -0
- package/src/inputlook.js +53 -0
- package/src/jsonbrace.js +21 -0
- package/src/labelscan.js +162 -0
- package/src/pageask.js +4 -1
- package/src/pagedropwords.js +11 -1
- package/src/panel/author.js +76 -5
- package/src/panel/authorcard.js +9 -6
- package/src/panel/data.js +41 -9
- package/src/panel/index.html +202 -13
- package/src/panel/result.js +4 -3
- package/src/panel/server.js +3 -1
- package/src/pickrecord.js +28 -0
- package/src/placerule.js +398 -0
- package/src/planrebuild.js +206 -0
- package/src/rowedit.js +118 -0
- package/src/rubricstep.js +264 -0
- package/src/runfile.js +4 -2
- package/src/runner.js +67 -10
- package/src/setup.js +10 -4
- package/src/sheetblock.js +6 -2
- package/src/sheetchecks.js +49 -64
- package/src/sheetclaims.js +12 -32
- package/src/sheetlook.js +2 -2
- package/src/sheetoffer.js +25 -53
- package/src/sheetrows.js +107 -0
- package/src/sheetrun.js +31 -1
- package/src/summary-words.js +3 -3
- package/src/try-checks.js +31 -12
- package/src/types.js +1 -0
- package/types/auditchecks.d.ts +24 -0
- package/types/authoring.d.ts +18 -1
- package/types/blockasks.d.ts +37 -0
- package/types/blockassemble.d.ts +33 -0
- package/types/blockdraft.d.ts +83 -0
- package/types/blocklines.d.ts +31 -0
- package/types/blockpick.d.ts +41 -0
- package/types/cardlist.d.ts +21 -0
- package/types/checkblock.d.ts +363 -0
- package/types/checked.d.ts +16 -2
- package/types/checklist.d.ts +115 -0
- package/types/checklistsign.d.ts +27 -0
- package/types/checkwords.d.ts +5 -0
- package/types/cited-record.d.ts +9 -0
- package/types/citedcheck.d.ts +33 -2
- package/types/closers.d.ts +24 -2
- package/types/declaredclose.d.ts +2 -0
- package/types/drafter.d.ts +15 -361
- package/types/factwords.d.ts +38 -0
- package/types/inputlook.d.ts +49 -0
- package/types/jsonbrace.d.ts +8 -0
- package/types/labelscan.d.ts +35 -0
- package/types/pageask.d.ts +2 -0
- package/types/panel/author.d.ts +41 -0
- package/types/panel/authorcard.d.ts +1 -1
- package/types/panel/data.d.ts +4 -2
- package/types/panel/jobgrid.d.ts +1 -1
- package/types/pickrecord.d.ts +22 -0
- package/types/placerule.d.ts +208 -0
- package/types/planrebuild.d.ts +52 -0
- package/types/provider.d.ts +1 -1
- package/types/rowedit.d.ts +33 -0
- package/types/rubricstep.d.ts +60 -0
- package/types/runfile.d.ts +5 -2
- package/types/runner.d.ts +45 -1
- package/types/sheetblock.d.ts +1 -0
- package/types/sheetchecks.d.ts +10 -17
- package/types/sheetclaims.d.ts +2 -1
- package/types/sheetoffer.d.ts +5 -5
- package/types/sheetrows.d.ts +73 -0
- package/types/sheetrun.d.ts +12 -0
- package/types/summary-words.d.ts +2 -1
- package/types/try-checks.d.ts +4 -2
- package/types/types.d.ts +8 -0
package/src/factwords.js
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// borrowed-from: bareloop src/factwords.js@v0.56.0 (3383cce) (checkFactWords, keptSetOf and what they call; squash, countExact and countPhrase are fwd's, src/pagebits.js, the same counts with no built pattern; fwd's own keptSetOf, src/citedwords.js, is a different older copy and stays for the page-word path)
|
|
2
|
+
// THE FOUND-ONCE CHECK: code proves, at $0, that every word a fact check depends on is really in the person's source, and that every label (anchor) is one PICKED
|
|
3
|
+
// from the list code made from that source (src/labelscan.js), never typed. Nothing is graded here and no model is involved.
|
|
4
|
+
import { labelOnList, scanLabels } from './labelscan.js';
|
|
5
|
+
import { asList, normLabel, countExact, countPhrase } from './pagebits.js';
|
|
6
|
+
import { dropSentence } from './pagedropwords.js';
|
|
7
|
+
|
|
8
|
+
/** @param {string} shape @returns {'money'|'number'|'date'|'time'|'text'} the label list a fact's anchor is picked from */
|
|
9
|
+
const listOf = (shape) => /** @type {any} */ (['money', 'number', 'date', 'time'].includes(shape) ? shape : 'text');
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* What the page-word map (src/pagemap.js) KEPT and DROPPED for one input: the sets the second proof reads. A look from the old search-and-read
|
|
13
|
+
* path has no `dropped` list, so it gives null and the label is proved against the code-made list as before.
|
|
14
|
+
* @param {{facts?: any[], dropped?: (import('./pagerules.js').Dropped & {source?: string})[]}|null|undefined} look @param {string} source
|
|
15
|
+
* @returns {{labels: Set<string>, units: Set<string>, currencies: Set<string>, words: Set<string>, dropped: Map<string, import('./pagerules.js').Dropped>, forms: {labels: Set<string>, lang?: string, decimal?: string}[]}|null}
|
|
16
|
+
*/
|
|
17
|
+
export function keptSetOf(look, source) {
|
|
18
|
+
if (!look || !Array.isArray(look.dropped)) return null;
|
|
19
|
+
const facts = (Array.isArray(look.facts) ? look.facts : []).filter((f) => f && f.source === source && Array.isArray(f.words));
|
|
20
|
+
const set = (/** @type {string[]} */ a) => new Set(a.map((w) => normLabel(String(w))));
|
|
21
|
+
/** @type {Map<string, import('./pagerules.js').Dropped>} */
|
|
22
|
+
const dropped = new Map();
|
|
23
|
+
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);
|
|
24
|
+
return {
|
|
25
|
+
labels: set(facts.filter((f) => f.shape !== 'phrase').flatMap((f) => f.words)),
|
|
26
|
+
units: set(facts.flatMap((f) => f.unit ?? [])),
|
|
27
|
+
currencies: set(facts.flatMap((f) => f.currency ?? [])),
|
|
28
|
+
words: set(facts.flatMap((f) => [...f.words, ...(f.unit ?? []), ...(f.currency ?? [])])),
|
|
29
|
+
dropped,
|
|
30
|
+
forms: facts.filter((f) => f.shape !== 'phrase' && (f.lang !== undefined || f.decimal !== undefined))
|
|
31
|
+
.map((f) => ({ labels: new Set(f.words.map((w) => normLabel(String(w)))), lang: f.lang, decimal: f.decimal })),
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The reds for ONE fact part against its frozen source text.
|
|
37
|
+
* @param {{part: any, text: string, line: number|string, scan?: import('./labelscan.js').LabelScan, kept?: ReturnType<typeof keptSetOf>}} o
|
|
38
|
+
* @returns {{code: string, detail: string}[]}
|
|
39
|
+
*/
|
|
40
|
+
export function checkFactWords({ part, text, line, scan = scanLabels(text), kept = null }) {
|
|
41
|
+
/** @type {{code: string, detail: string}[]} */
|
|
42
|
+
const reds = [];
|
|
43
|
+
const src = part.source;
|
|
44
|
+
const red = (/** @type {string} */ code, /** @type {string} */ msg) => reds.push({ code, detail: `line ${line}: ${msg} Nothing was signed.` });
|
|
45
|
+
for (const f of Array.isArray(part.facts) ? part.facts : []) {
|
|
46
|
+
const who = `fact "${f.name}"`;
|
|
47
|
+
// a word the page rules DROPPED (and no other fact kept) can never come back through the drafter (idea A core, spec 4.3)
|
|
48
|
+
const dropRed = (/** @type {string} */ what, /** @type {unknown} */ w) => {
|
|
49
|
+
const n = normLabel(String(w));
|
|
50
|
+
const d = kept?.dropped.get(n);
|
|
51
|
+
if (!kept || !d || kept.words.has(n)) return false;
|
|
52
|
+
red('rubric-fact-word-dropped', `${who}: the ${what} ${JSON.stringify(n)} cannot be used. ${dropSentence(d)}`);
|
|
53
|
+
return true;
|
|
54
|
+
};
|
|
55
|
+
if (f.anchor !== undefined && f.shape !== 'phrase' && kept) {
|
|
56
|
+
// a page input read by the page-word map: the label must be one the map KEPT (the code-made list cannot hold a marker after a number)
|
|
57
|
+
const label = normLabel(String(f.anchor));
|
|
58
|
+
if (dropRed('label', f.anchor)) { /* said above */ } else if (!kept.labels.has(label)) {
|
|
59
|
+
const some = [...kept.labels].slice(0, 12).map((l) => JSON.stringify(l)).join(', ');
|
|
60
|
+
red('rubric-fact-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)'}.`);
|
|
61
|
+
} else if (countExact(text, label) < 1) {
|
|
62
|
+
red('rubric-fact-word-missing', `${who}: the label ${JSON.stringify(label)} is not in the input "${src}".`);
|
|
63
|
+
} else if (Number.isInteger(part.count?.min) && countExact(text, label) < part.count.min) {
|
|
64
|
+
const n = part.count.min;
|
|
65
|
+
const seen = countExact(text, label);
|
|
66
|
+
red('rubric-fact-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.`);
|
|
67
|
+
}
|
|
68
|
+
} else if (f.anchor !== undefined && f.shape !== 'phrase') {
|
|
69
|
+
const list = listOf(f.shape);
|
|
70
|
+
const row = labelOnList(scan, list, f.anchor);
|
|
71
|
+
if (!row) {
|
|
72
|
+
const some = scan[list].slice(0, 12).map((r) => JSON.stringify(r.label)).join(', ');
|
|
73
|
+
red('rubric-fact-label-off-list', `${who}: the label ${JSON.stringify(normLabel(String(f.anchor)))} is not one of the labels the input "${src}" holds before a ${f.shape === 'text' ? 'text value' : f.shape}. A label is picked from that list, never typed${some ? `: ${some}` : ' (the list is empty - leave the label out)'}.`);
|
|
74
|
+
} else if (countExact(text, row.label) < 1) {
|
|
75
|
+
red('rubric-fact-word-missing', `${who}: the label ${JSON.stringify(row.label)} is not in the input "${src}".`);
|
|
76
|
+
} else if (Number.isInteger(part.count?.min) && row.count < part.count.min) {
|
|
77
|
+
// M1: a label that starts each result must repeat as often as results were asked for; one that sits once on the page
|
|
78
|
+
// (a sort tab, a switch) is in no result, so no one-result quote can hold it
|
|
79
|
+
const n = part.count.min;
|
|
80
|
+
red('rubric-fact-label-rare', `${who}: the label ${JSON.stringify(row.label)} is in the input "${src}" only ${row.count} time${row.count === 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 from the list that is counted ${n} or more times.`);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
// a look fact that carries lang / decimal: the signed fact must sign the same, or a drafter that drops it signs a fact that reds at run time
|
|
84
|
+
if (kept && f.anchor !== undefined && f.shape !== 'phrase') {
|
|
85
|
+
const mine = kept.forms.filter((k) => k.labels.has(normLabel(String(f.anchor))));
|
|
86
|
+
if (mine.length && !mine.some((k) => (k.lang === undefined || k.lang === f.lang) && (k.decimal === undefined || k.decimal === (f.decimal ?? '.')))) {
|
|
87
|
+
const k = mine[0];
|
|
88
|
+
const [field, value] = k.lang !== undefined && k.lang !== f.lang ? ['lang', k.lang] : ['decimal', k.decimal];
|
|
89
|
+
reds.push({ code: 'rubric-fact-form-unsigned', detail: `line ${line}: the fact ${JSON.stringify(f.name)} must sign ${field} ${JSON.stringify(value)}, as the page look found. Nothing spent.` });
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (f.until !== undefined) dropRed('closing label', f.until);
|
|
93
|
+
if (f.until !== undefined && countExact(text, f.until) < 1) red('rubric-fact-word-missing', `${who}: ${JSON.stringify(f.until)} is not in the input "${src}". Copy the closing words from the input, or leave them out.`);
|
|
94
|
+
if (f.shape === 'phrase' && typeof f.phrase === 'string') {
|
|
95
|
+
const seen = countPhrase(text, f.phrase);
|
|
96
|
+
if (seen < 1) red('rubric-fact-word-missing', `${who}: ${JSON.stringify(f.phrase)} is not in the input "${src}". Copy the words the input really uses, or remove the check.`);
|
|
97
|
+
else if (Number.isInteger(part.count?.min) && seen < part.count.min) {
|
|
98
|
+
// M4: the words each result's quote must say must repeat as often as results were asked for; page-header words (counted
|
|
99
|
+
// once or twice) are in no result, so no one-result quote can say them
|
|
100
|
+
const n = part.count.min;
|
|
101
|
+
red('rubric-fact-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.`);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
// a unit (one string, or every one of a list) must be found as whole words; a currency sign (each of a list) must be found as written
|
|
105
|
+
for (const u of asList(f.unit)) dropRed('unit', u);
|
|
106
|
+
for (const c of asList(f.currency)) dropRed('currency', c);
|
|
107
|
+
for (const u of asList(f.unit)) if (countPhrase(text, u) < 1) red('rubric-fact-word-missing', `${who}: the unit ${JSON.stringify(u)} is not in the input "${src}". Copy the words the input really uses.`);
|
|
108
|
+
for (const c of asList(f.currency)) if (countExact(text, c) < 1) red('rubric-fact-word-missing', `${who}: the currency ${JSON.stringify(c)} is not in the input "${src}". Copy the sign the input really uses.`);
|
|
109
|
+
}
|
|
110
|
+
return reds;
|
|
111
|
+
}
|
|
112
|
+
|
package/src/inputlook.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// borrowed-from: bareloop src/inputlook.js@v0.56.0 (3383cce) (renderLookReport only: the look itself is fwd's, src/pagelook.js and src/sheetlook.js)
|
|
2
|
+
import { dropRows } from './pagedropwords.js';
|
|
3
|
+
|
|
4
|
+
/** @typedef {{line: number, name: string, shape: string, source: string, label?: string, labelId?: string, value?: string, phrase?: string, example: string, rule?: any, aiProposal?: boolean, forRule?: number, reading?: import('./pagerules.js').Reading,
|
|
5
|
+
* words?: string[], labels?: string[], unit?: string[], currency?: string[], lang?: string, decimal?: string}} LookFact `words` / `labels` / `unit` / `currency`: what the page-word map kept (idea A core) */
|
|
6
|
+
/** @typedef {{line: number, rule?: number, words?: string, why: string}} LookNotFound */
|
|
7
|
+
|
|
8
|
+
/** @typedef {{facts: LookFact[], prose: {line: number, text?: string}[], notFound: LookNotFound[], dropped?: import('./pagerules.js').Dropped[]}} LookReport */
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The look's report as the DRAFTER reads it: one block, per job line, of what can be checked (with the exact words to copy) and what
|
|
12
|
+
* could not be found. Written by code from the verified report.
|
|
13
|
+
* @param {LookReport} report @returns {string}
|
|
14
|
+
*/
|
|
15
|
+
export function renderLookReport(report) {
|
|
16
|
+
const byLine = new Map();
|
|
17
|
+
const add = (/** @type {number} */ n, /** @type {string} */ s) => byLine.set(n, [...(byLine.get(n) ?? []), s]);
|
|
18
|
+
for (const f of report.facts) {
|
|
19
|
+
const bits = [`${f.name} - ${f.shape}`, `from "${f.source}"`];
|
|
20
|
+
if (Array.isArray(f.words)) {
|
|
21
|
+
// a fact the page-word map kept (idea A core): the words the page holds, each one proven by code; the first is the main one
|
|
22
|
+
const quote = (/** @type {string[]|undefined} */ a) => (a ?? []).map((w) => JSON.stringify(w)).join(' or ');
|
|
23
|
+
if (f.shape === 'phrase') bits.push(`the quote must say ${f.words.length > 1 ? 'ONE of these page words, copied exactly' : 'this page word'}: ${quote(f.words)}`);
|
|
24
|
+
else {
|
|
25
|
+
if (f.words.length) bits.push(`label ${quote(f.words)}${f.words.length > 1 ? ' (the first is the main one)' : ''}`);
|
|
26
|
+
else bits.push('no label (read by its unit or sign alone)');
|
|
27
|
+
if (f.unit?.length) bits.push(`unit ${quote(f.unit)}`);
|
|
28
|
+
if (f.currency?.length) bits.push(`currency ${quote(f.currency)}`);
|
|
29
|
+
// a page form the page rules proved is on the page: the drafter signs it as given, never a guess (the run reads that form and no other)
|
|
30
|
+
if (f.lang !== undefined) bits.push(`lang ${JSON.stringify(f.lang)} (the page writes the month name in this language: sign it as the fact's lang)`);
|
|
31
|
+
if (f.decimal !== undefined) bits.push(`decimal ${JSON.stringify(f.decimal)} (the page writes this mark before the decimals: sign it as the fact's decimal)`);
|
|
32
|
+
}
|
|
33
|
+
} else if (f.phrase !== undefined) bits.push(`the quote must say ${JSON.stringify(f.phrase)}`);
|
|
34
|
+
else if (f.label !== undefined) bits.push(`label ${JSON.stringify(f.label)} (id ${f.labelId})`);
|
|
35
|
+
else bits.push('no label (the value as the quote writes it)');
|
|
36
|
+
if (f.example) bits.push(`seen: ${JSON.stringify(f.example)}`);
|
|
37
|
+
if (f.rule) bits.push(`rule ${JSON.stringify(f.rule)}`);
|
|
38
|
+
if (f.aiProposal) bits.push("AI's proposal");
|
|
39
|
+
if (f.forRule !== undefined) bits.push(`carries ~ rule ${f.forRule}`);
|
|
40
|
+
add(f.line, `CAN CHECK: ${bits.join(', ')}`);
|
|
41
|
+
}
|
|
42
|
+
// NO SILENT DROP: a word, fact or rule the page rules removed is said to the drafter too, so it is never written back as a check
|
|
43
|
+
for (const row of dropRows(report.dropped)) {
|
|
44
|
+
add(row.line, row.full
|
|
45
|
+
? `NOT CHECKED${row.rule !== undefined ? ` (rule ${row.rule})` : ''}: "${row.fact}" - ${row.sentences.join(' ')}`
|
|
46
|
+
: `LEFT OUT of "${row.fact}" (the rest is still checked): ${row.sentences.join(' ')}`);
|
|
47
|
+
}
|
|
48
|
+
for (const p of report.prose) add(p.line, 'WRITTEN TEXT (not looked up; keep its word/section counts)');
|
|
49
|
+
for (const n of report.notFound) add(n.line, `NOT FOUND${n.rule ? ` (rule ${n.rule})` : ''}: ${n.words ? `${JSON.stringify(n.words)} - ` : ''}${n.why}`);
|
|
50
|
+
const lines = [...byLine.keys()].sort((a, b) => a - b).map((n) => `line ${n}:\n${byLine.get(n).map((/** @type {string} */ s) => ` ${s}`).join('\n')}`);
|
|
51
|
+
return `WHAT THE LOOK AT THE INPUTS FOUND - write the facts from this; copy the label and phrase words exactly\n\n${lines.join('\n') || '(the look reported nothing)'}`;
|
|
52
|
+
}
|
|
53
|
+
|
package/src/jsonbrace.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// borrowed-from: poc/f183-brace/repair.mjs (the repair rule, M4d am39)
|
|
2
|
+
// A drafting answer that is a complete JSON object followed ONLY by `}` characters and whitespace: drop exactly those
|
|
3
|
+
// trailing characters and parse the rest. Anything else (trailing `]`, text, `}x`, a truncated object, two objects,
|
|
4
|
+
// an array root) returns null. The caller calls this only for a round whose reason is malformed JSON.
|
|
5
|
+
/**
|
|
6
|
+
* @param {unknown} raw
|
|
7
|
+
* @returns {{ value: Record<string, any>, dropped: string } | null}
|
|
8
|
+
*/
|
|
9
|
+
export function repairTrailingBraces(raw) {
|
|
10
|
+
if (typeof raw !== 'string') return null;
|
|
11
|
+
let cut = raw.trimEnd();
|
|
12
|
+
if (!cut.endsWith('}')) return null;
|
|
13
|
+
for (;;) {
|
|
14
|
+
cut = cut.slice(0, -1).trimEnd();
|
|
15
|
+
if (!cut.endsWith('}')) return null;
|
|
16
|
+
let value;
|
|
17
|
+
try { value = JSON.parse(cut); } catch { continue; }
|
|
18
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) return null;
|
|
19
|
+
return { value, dropped: raw.slice(cut.length) };
|
|
20
|
+
}
|
|
21
|
+
}
|
package/src/labelscan.js
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// borrowed-from: bareloop src/labelscan.js@v0.56.0 (3383cce) (scanLabels, labelOnList and what they call; normLabel is fwd's, src/pagebits.js; the date finder is a literal, not a built pattern: src/ builds none, test/signed-text.test.js)
|
|
2
|
+
// THE LABEL LIST: before the look, code scans a source at $0 and lists, per shape (money, number, date, time, text), the words that sit right before a value of
|
|
3
|
+
// that shape, with how often each occurs. A label is picked ONLY from this list. ONE generic scan for every page or file; plain string work, no model.
|
|
4
|
+
import { normLabel } from './pagebits.js';
|
|
5
|
+
|
|
6
|
+
/** @typedef {{id: string, label: string, count: number, example: string}} LabelEntry */
|
|
7
|
+
/** @typedef {Record<'money'|'number'|'date'|'time'|'text', LabelEntry[]>} LabelScan */
|
|
8
|
+
|
|
9
|
+
export const LABEL_SHAPES = Object.freeze(['money', 'number', 'date', 'time', 'text']);
|
|
10
|
+
|
|
11
|
+
/** a label must occur at least this often to be listed (1: a one-page document with one total still has its label; the list is cut to the highest counts) */
|
|
12
|
+
export const MIN_COUNT = 1;
|
|
13
|
+
|
|
14
|
+
/** how many labels one shape's list holds at most (the highest counts first) */
|
|
15
|
+
export const MAX_PER_SHAPE = 40;
|
|
16
|
+
|
|
17
|
+
/** the longest label, in characters */
|
|
18
|
+
const MAX_LABEL = 40;
|
|
19
|
+
|
|
20
|
+
/** the longest whole gap taken as a label when it is short */
|
|
21
|
+
const MAX_GAP_LABEL = 24;
|
|
22
|
+
|
|
23
|
+
/** a phrase must repeat this often to be a repeated phrase */
|
|
24
|
+
const MIN_PHRASE = 3;
|
|
25
|
+
|
|
26
|
+
/** how many repeated phrases are looked behind */
|
|
27
|
+
const MAX_PHRASES = 20;
|
|
28
|
+
|
|
29
|
+
/** a line is scanned up to this many characters, and for this many values (a minified page is one huge line; the bound caps the work per line, each finder's own regex is kept linear below) */
|
|
30
|
+
const MAX_LINE = 20000;
|
|
31
|
+
|
|
32
|
+
const MAX_VALUES_PER_LINE = 400;
|
|
33
|
+
|
|
34
|
+
/** only this much of a source is scanned (a source over it is scanned up to a line end) */
|
|
35
|
+
export const SCAN_MAX_CHARS = 2_000_000;
|
|
36
|
+
|
|
37
|
+
const WS = /[\s ]+/g;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The page reader's bracketed tag (`[ref=549]`), shared by the three places that strip it. The lookahead and lookbehind add no match and drop no
|
|
41
|
+
* match: a `[` that sits inside the run of an earlier `[letters=` (no `]` or white space between) is skipped, because that earlier start reads the same
|
|
42
|
+
* run to the same end - it matches (and consumes this one) or fails (and so does this one). Without them "[a=[a=[a=..." with no `]` is quadratic.
|
|
43
|
+
*/
|
|
44
|
+
export const TAG = /\[(?=[A-Za-z]+=)(?<!\[[A-Za-z]+=[^\]\s]*?)[A-Za-z]+=[^\]\s]*\]/g;
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
/** value finders in priority order: an earlier shape owns a span a later one would also match */
|
|
48
|
+
const FINDERS = /** @type {[string, RegExp][]} */ ([
|
|
49
|
+
['date', /\b\d{4}-\d{2}-\d{2}\b|\b\d{1,2}\/\d{1,2}\/\d{2,4}\b|\b(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:t(?:ember)?)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)\.? \d{1,2}(?:, \d{4})?\b|\b\d{1,2} (?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:t(?:ember)?)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)\.? \d{4}\b/g],
|
|
50
|
+
['time', /\b\d{1,2}:\d{2}(?: ?[AaPp]\.?[Mm]\.?)?(?![\w:])/g],
|
|
51
|
+
// the 2nd shape's leading lookbehind skips a start inside a digit/comma run that an earlier start of the run already covers (that start reads the same
|
|
52
|
+
// run to the same end, so it matches first or fails like this one); without it "1,1,1,...x" is quadratic. The covering start is never one right after
|
|
53
|
+
// a "." - the digits of a decimal can already belong to an earlier match ("$1.5,2 dollars" reads "2 dollars" as its own)
|
|
54
|
+
['money', /[$€£] ?\d[\d,]*(?:\.\d+)?|(?<!(?<!\.)\b\d[\d,]*?)\b\d[\d,]*(?:\.\d+)? ?(?:US dollars?|dollars?|USD|euros?|EUR|pounds?|GBP)\b/g],
|
|
55
|
+
['number', /(?<![\w.,])\d[\d,]*(?:\.\d+)?(?![\w]|\.\d)/g],
|
|
56
|
+
// (?<![A-Za-z]): a start inside a run of letters is covered by the run's first letter (same match, earlier), so a long run of letters with no digit is linear
|
|
57
|
+
['text', /(?<![A-Za-z])[A-Za-z]*\d[\w.\-]*/g],
|
|
58
|
+
]);
|
|
59
|
+
|
|
60
|
+
const PHRASE = /\b[A-Z][a-z]+(?: [A-Z][a-z]+)+\b/g;
|
|
61
|
+
|
|
62
|
+
/** @param {string} gap @returns {string[]} the labels a gap of text before a value offers */
|
|
63
|
+
function candidates(gap) {
|
|
64
|
+
const g = normLabel(gap);
|
|
65
|
+
if (g === '') return [];
|
|
66
|
+
const tokens = g.split(' ');
|
|
67
|
+
/** @type {Set<string>} */
|
|
68
|
+
const out = new Set();
|
|
69
|
+
out.add(normLabel(tokens.at(-1) ?? ''));
|
|
70
|
+
if (tokens.length >= 2) out.add(normLabel(tokens.slice(-2).join(' ')));
|
|
71
|
+
if (g.length <= MAX_GAP_LABEL) out.add(g);
|
|
72
|
+
return [...out].filter((c) => c !== '' && c.length <= MAX_LABEL && !/\d/.test(c) && !/ref=/.test(c));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Scan one source text for the labels that sit before values, per shape.
|
|
77
|
+
* @param {string} text
|
|
78
|
+
* @returns {LabelScan}
|
|
79
|
+
*/
|
|
80
|
+
export function scanLabels(text) {
|
|
81
|
+
let src = String(text ?? '');
|
|
82
|
+
if (src.length > SCAN_MAX_CHARS) { const nl = src.lastIndexOf('\n', SCAN_MAX_CHARS); src = src.slice(0, nl > 0 ? nl : SCAN_MAX_CHARS); }
|
|
83
|
+
/** @type {Record<string, Map<string, {count: number, example: string}>>} */
|
|
84
|
+
const seen = Object.fromEntries(LABEL_SHAPES.map((s) => [s, new Map()]));
|
|
85
|
+
const bump = (/** @type {string} */ shape, /** @type {string} */ label, /** @type {string} */ example) => {
|
|
86
|
+
const m = seen[shape];
|
|
87
|
+
const cur = m.get(label);
|
|
88
|
+
if (cur) cur.count += 1; else m.set(label, { count: 1, example });
|
|
89
|
+
};
|
|
90
|
+
/** @type {Map<string, number>} */
|
|
91
|
+
const phraseCount = new Map();
|
|
92
|
+
/** @type {string[]} */
|
|
93
|
+
const lines = [];
|
|
94
|
+
/** @type {{line: string, at: number, phrase: string}[]} */
|
|
95
|
+
const variants = [];
|
|
96
|
+
for (const raw of src.split('\n')) {
|
|
97
|
+
const line = raw.slice(0, MAX_LINE).replace(TAG, ' ').replace(WS, ' ').trim();
|
|
98
|
+
if (line === '') continue;
|
|
99
|
+
lines.push(line);
|
|
100
|
+
for (const m of line.matchAll(PHRASE)) {
|
|
101
|
+
// a capitalised run may start with a sentence-initial word ("Leaves San Francisco ..."): the run is also read without its first word
|
|
102
|
+
const words = m[0].split(' ');
|
|
103
|
+
let off = m.index ?? 0;
|
|
104
|
+
for (let j = 0; j <= 1 && words.length - j >= 2; j += 1) {
|
|
105
|
+
const phrase = words.slice(j).join(' ');
|
|
106
|
+
phraseCount.set(phrase, (phraseCount.get(phrase) ?? 0) + 1);
|
|
107
|
+
variants.push({ line, at: off, phrase });
|
|
108
|
+
off += words[j].length + 1;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
for (const line of lines) {
|
|
113
|
+
/** @type {{shape: string, s: number, e: number, v: string}[]} */
|
|
114
|
+
const found = [];
|
|
115
|
+
for (const [shape, re] of FINDERS) {
|
|
116
|
+
for (const m of line.matchAll(re)) {
|
|
117
|
+
const s = m.index ?? 0;
|
|
118
|
+
const e = s + m[0].length;
|
|
119
|
+
if (found.length >= MAX_VALUES_PER_LINE) break;
|
|
120
|
+
if (found.some((f) => s < f.e && e > f.s)) continue;
|
|
121
|
+
found.push({ shape, s, e, v: m[0] });
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
found.sort((a, b) => a.s - b.s);
|
|
125
|
+
let prevEnd = 0;
|
|
126
|
+
for (const f of found) {
|
|
127
|
+
for (const c of candidates(line.slice(prevEnd, f.s))) bump(f.shape, c, f.v);
|
|
128
|
+
prevEnd = f.e;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
// the words before each REPEATED capitalised phrase (a place, a name): text facts
|
|
132
|
+
const phrases = new Set([...phraseCount].filter(([, n]) => n >= MIN_PHRASE).sort((a, b) => b[1] - a[1]).slice(0, MAX_PHRASES).map(([p]) => p));
|
|
133
|
+
for (const v of variants) {
|
|
134
|
+
if (!phrases.has(v.phrase)) continue;
|
|
135
|
+
for (const c of candidates(v.line.slice(0, v.at))) bump('text', c, v.phrase);
|
|
136
|
+
}
|
|
137
|
+
/** @type {Record<string, string>} */
|
|
138
|
+
const prefix = { money: 'm', number: 'n', date: 'd', time: 't', text: 'x' };
|
|
139
|
+
return /** @type {LabelScan} */ (Object.fromEntries(LABEL_SHAPES.map((shape) => {
|
|
140
|
+
const rows = [...seen[shape]].filter(([, v]) => v.count >= MIN_COUNT)
|
|
141
|
+
.sort((a, b) => b[1].count - a[1].count || a[0].length - b[0].length || (a[0] < b[0] ? -1 : 1))
|
|
142
|
+
.slice(0, MAX_PER_SHAPE)
|
|
143
|
+
.map(([label, v], i) => ({ id: `${prefix[shape]}${i + 1}`, label, count: v.count, example: v.example }));
|
|
144
|
+
return [shape, rows];
|
|
145
|
+
})));
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Is this label on the list for this shape? Compared the way a label is read: white space of any kind is one space, quote marks at the
|
|
150
|
+
* edges are dropped. `idOrText` may be a list id (`t1`) or the exact words.
|
|
151
|
+
* @param {LabelScan} scan @param {string} shape @param {unknown} idOrText
|
|
152
|
+
* @returns {LabelEntry|null}
|
|
153
|
+
*/
|
|
154
|
+
export function labelOnList(scan, shape, idOrText) {
|
|
155
|
+
const rows = scan[/** @type {'money'} */ (shape)];
|
|
156
|
+
if (!rows || typeof idOrText !== 'string') return null;
|
|
157
|
+
const asId = rows.find((r) => r.id === idOrText.trim());
|
|
158
|
+
if (asId) return asId;
|
|
159
|
+
const want = normLabel(idOrText);
|
|
160
|
+
return rows.find((r) => r.label === want) ?? null;
|
|
161
|
+
}
|
|
162
|
+
|
package/src/pageask.js
CHANGED
|
@@ -81,7 +81,10 @@ const readingRest = (n) => `, or type your own reading (your answer is added as
|
|
|
81
81
|
/** @param {number} n @returns {string} the answer words a can't-check ask ends with (said once, here, and cut in the panel) */
|
|
82
82
|
const cantCheckTail = (n) => ` Answer "${DROP_IT}", or type how to check it (your answer is added as a new ~ rule on line ${n}).`;
|
|
83
83
|
/** @param {number} n @param {string} rule @param {string} reading @returns {string} */
|
|
84
|
-
const readingQuestion = (n, rule, reading) => `Your line ${n} says "${rule}".${READING_HEAD}${reading}${READING_TAIL}${readingRest(n)}`;
|
|
84
|
+
export const readingQuestion = (n, rule, reading) => `Your line ${n} says "${rule}".${READING_HEAD}${reading}${READING_TAIL}${readingRest(n)}`;
|
|
85
|
+
// borrowed-from: bareloop src/pagemap.js@v0.56.0 (3383cce) (cantCheckQuestion; readingQuestion above is exported for the block's asks)
|
|
86
|
+
/** @param {number} n @param {string} rule @returns {string} the can't-check ask in its one spelling */
|
|
87
|
+
export const cantCheckQuestion = (n, rule) => `Your line ${n} says "${rule}". I can't check this on the page. Drop it?${cantCheckTail(n)}`;
|
|
85
88
|
/** @param {unknown} q a recorded question @returns {string|null} the reading a reading ask proposed, or null when it was another kind of question */
|
|
86
89
|
export function readingOfQuestion(q) {
|
|
87
90
|
const s = String(q ?? '');
|
package/src/pagedropwords.js
CHANGED
|
@@ -6,13 +6,20 @@
|
|
|
6
6
|
|
|
7
7
|
/** @typedef {import('./pagerules.js').Dropped} Dropped */
|
|
8
8
|
|
|
9
|
+
// borrowed-from: bareloop src/pagedropwords.js@v0.56.0 (3383cce) (the four reasons the block's drops carry, and the sign-twice sentence by `d.other`; FACT_LANGS lives with the facts in src/citedcheck.js)
|
|
10
|
+
import { FACT_LANGS } from './citedcheck.js';
|
|
11
|
+
|
|
12
|
+
/** the two ways a sign listed twice can be used once (v0.56.0 spells the sentence from `d.other`; no other -> "currency", the sentence fwd has always written) */
|
|
13
|
+
const SIGN_TWICE_AS = ['currency', 'unit'];
|
|
14
|
+
|
|
9
15
|
/** reason code -> the plain sentence (`d.word` = the page's word, `d.fact` = the fact's name, `d.other` = what it was compared to) */
|
|
10
16
|
const WORDS = /** @type {Record<string, (d: Dropped) => string>} */ ({
|
|
11
17
|
'not-on-page': (d) => `"${d.word}" is not written on the page.`,
|
|
12
18
|
'no-value': (d) => `The page never shows a number right after or right before "${d.word}".`,
|
|
19
|
+
'reads-no-amount': (d) => `The page never shows an amount next to "${d.word}", so it was not used to write the price.`,
|
|
13
20
|
'n2': (d) => `"${d.word}" is written more than once inside one line of the page, so one result cannot show it once.`,
|
|
14
21
|
'r1': (d) => `"${d.word}" does not show the same values as "${d.other}", so it was not used as a second way to read it.`,
|
|
15
|
-
'sign-twice': (d) => `"${d.word}" was listed twice, as a unit and as a currency; it is used once, as the currency.`,
|
|
22
|
+
'sign-twice': (d) => `"${d.word}" was listed twice, as a unit and as a currency; it is used once, as the ${SIGN_TWICE_AS.find((kind) => kind === d.other) ?? 'currency'}.`,
|
|
16
23
|
'r1l': (d) => d.word === d.other
|
|
17
24
|
? `"${d.word}" was listed twice, as a unit and as a currency; it is used once, as the first way to write the price.`
|
|
18
25
|
: `"${d.word}" does not show the same amounts as "${d.other}", so it was not used as a second way to write the price.`,
|
|
@@ -23,6 +30,9 @@ const WORDS = /** @type {Record<string, (d: Dropped) => string>} */ ({
|
|
|
23
30
|
'limit-unit': (d) => `Only the first 10 units are used; "${d.word}" was left out.`,
|
|
24
31
|
'unit-too-long': (d) => `"${d.word}" is longer than 100 characters, so it was not used.`,
|
|
25
32
|
'reads-no-result': () => "the price rule could not read a price in the page's results, so it is not checked.",
|
|
33
|
+
'reads-no-time': (d) => `the page never shows a time right after "${d.other}", so it is not checked.`,
|
|
34
|
+
'lang-not-on-page': (d) => `the page shows no month name in ${FACT_LANGS[/** @type {keyof typeof FACT_LANGS} */ (d.other ?? '')] ?? d.other}, so the date is not checked.`,
|
|
35
|
+
'decimal-not-on-page': () => 'the page shows no amount written with a comma before the decimals, so it is not checked.',
|
|
26
36
|
// borrowed-from: bareloop src/pagedropwords.js@c550dc8 (the phrase dry read's sentence)
|
|
27
37
|
'phrase-no-result': (d) => `"${d.other}" is on the page but in none of its results, so it is not checked.`,
|
|
28
38
|
'person-left': () => 'You chose to leave it Not checked.',
|
package/src/panel/author.js
CHANGED
|
@@ -36,8 +36,11 @@ import { dirname, join } from 'node:path';
|
|
|
36
36
|
import { fileURLToPath } from 'node:url';
|
|
37
37
|
|
|
38
38
|
import {
|
|
39
|
-
ANSWER_FILE, NOT_CHECKED_FILE, OPEN_QUESTION_SAY, PANEL_DRAFTS_DIR, readQuestions, readoutHeadIndexes, scrub, signDraft,
|
|
39
|
+
ANSWER_FILE, NOT_CHECKED_FILE, OPEN_QUESTION_SAY, PANEL_DRAFTS_DIR, claimPlanDir, readQuestions, readoutHeadIndexes, scrub, signDraft, writePlanFiles,
|
|
40
40
|
} from '../authoring.js';
|
|
41
|
+
import { rowEditPlan } from '../planrebuild.js';
|
|
42
|
+
import { cardLinesOf } from '../checklistsign.js';
|
|
43
|
+
import { appendSpendRow } from '../provider.js';
|
|
41
44
|
import { ruleOfAnswer, panelQuestionText, DROP_IT } from '../pageask.js';
|
|
42
45
|
import { checkFlowName, nextRunId, readFileInside, readdirInside } from '../flow.js';
|
|
43
46
|
import { readModelRecord } from '../flowmodel.js';
|
|
@@ -49,6 +52,7 @@ import {
|
|
|
49
52
|
applyAnswers, capFloorFor, capFloorOf, capFloorUsd, cardFields, checkCard, checkInputRows, parseInputLines, parseJobBox,
|
|
50
53
|
} from './authorcard.js';
|
|
51
54
|
import { checkedLines, notCheckedView } from '../checked.js';
|
|
55
|
+
import { EVERY_STEP_TEXTS } from '../try-checks.js';
|
|
52
56
|
import { recordPath, RECORD_FILE, KEPT_WORDS } from '../pickrecord.js';
|
|
53
57
|
import { csvRolesOf } from '../sheetblock.js';
|
|
54
58
|
import {
|
|
@@ -132,6 +136,9 @@ export function createAuthor(opts) {
|
|
|
132
136
|
};
|
|
133
137
|
|
|
134
138
|
const readJson = readJsonFile;
|
|
139
|
+
/** every file text scrubbed of the keys, as the draft child writes them @param {Record<string, string>} files @param {string[]} keys */
|
|
140
|
+
const scrubbed = (files, keys) => Object.fromEntries(Object.entries(files).map(([f, t]) => [f, scrub(t, keys)]));
|
|
141
|
+
const isObj = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
135
142
|
|
|
136
143
|
/**
|
|
137
144
|
* The monthly room for a cap, from the ONE read-only check the CLI's door also decides on (`checkMonthlyRoom`, src/monthly.js).
|
|
@@ -255,7 +262,8 @@ export function createAuthor(opts) {
|
|
|
255
262
|
const kind = redrafts.has(n) ? 'answers' : 'revise';
|
|
256
263
|
if (kind === 'revise') reviseNo += 1;
|
|
257
264
|
// M4d am15 (every line of the list): this plan's own line, from its own log, built by `reviseStepList`; the try history is in the Audit Draft group
|
|
258
|
-
const
|
|
265
|
+
const rowEdit = kind === 'answers' ? readJson(dir, `redraft-${n}.json`)?.rowEdit : undefined;
|
|
266
|
+
const name = rowEdit ? (rowEdit.op === 'drop' ? 'a check dropped' : 'a check added') : kind === 'answers' ? 'drafted again with your answers' : `revise ${reviseNo}`;
|
|
259
267
|
const running = n === newest && childRunning(dir); // C9: running first, then the result
|
|
260
268
|
// the result BEFORE the log: the child writes log.json first and the result (spec.hash, or the red log itself) after, so a result we see has its log already on disk
|
|
261
269
|
const res = resultOf(dir, `draft-${n}`, keys);
|
|
@@ -278,6 +286,9 @@ export function createAuthor(opts) {
|
|
|
278
286
|
// the plan's questions: any open one makes the phase `questions-open`, whatever colour the plan is (the answers are what it was waiting for)
|
|
279
287
|
const q = rel === 'draft' ? firstQs : readQuestions(join(dir, rel));
|
|
280
288
|
if (q.open.length > 0) {
|
|
289
|
+
// the child writes its questions, THEN exits; `answer` refuses `draft-live` while it is alive, so a question is offered only once it has ended (one decider: what the phase offers, the answer door takes).
|
|
290
|
+
// A child never comes back to life, so a stale "alive" only delays the offer; asked AFTER the files were read, the questions are already on disk (C9's order is for a missing result)
|
|
291
|
+
if (childRunning(dir)) return { ...shared, phase: newest > 0 ? (cur.kind === 'answers' ? 'redrafting' : 'revising') : 'drafting' };
|
|
281
292
|
const lineText = (line) => parseJobBox(typeof card?.job === 'string' ? card.job : '').steps[line - 1]?.text ?? null;
|
|
282
293
|
const questions = q.questions.map((x) => ({ k: x.k, line: x.line, lineText: lineText(x.line), question: scrub(x.question, keys), answered: x.answer !== null, ...(x.source === 'look' ? { source: 'look', ask: x.ask, proposes: typeof x.proposal === 'string' && (x.ask === 'reading' || x.ask === 'check'), drops: Number.isInteger(x.ruleNo), shown: scrub(panelQuestionText(x), keys) } : {}) }));
|
|
283
294
|
return { ...shared, stepList: stepListOf(dir, rel, keys, true), phase: 'questions-open', plan: rel, questions, openK: q.open[0].k, total: q.questions.length };
|
|
@@ -315,7 +326,16 @@ export function createAuthor(opts) {
|
|
|
315
326
|
...(parsed?.ok === true ? { askLines: parsed.arbiter.asks.map((x) => x.line), lines: parsed.lines, csvRoles: csvRolesOf(parsed.arbiter) } : { hasAsk: true }),
|
|
316
327
|
...(Array.isArray(kept) ? { keptChecks: kept.filter((k) => k && k.check).map((k) => ({ line: k.line, check: k.check })), keptWords: KEPT_WORDS } : {}),
|
|
317
328
|
};
|
|
318
|
-
|
|
329
|
+
const ncFile = readJson(dir, `${rel}/${NOT_CHECKED_FILE}`);
|
|
330
|
+
const view = notCheckedView(ncFile?.notChecked, decl);
|
|
331
|
+
// M16 item 5: the plan card's list - the rows with their tags and Drop, the suggestions with Add - read from the card the draft saved (src/cardlist.js); a plan without a list has none
|
|
332
|
+
const card = cardLinesOf(decl).size > 0 ? readJson(dir, `${rel}/log.json`)?.checkCard : undefined;
|
|
333
|
+
const list = card && Array.isArray(card.rows) && Array.isArray(card.suggested) ? { lines: [...cardLinesOf(decl)].sort((a, b) => a - b), rows: card.rows, suggested: card.suggested } : null;
|
|
334
|
+
// M16 P4c (bareloop's plan view): the job's lines with their `~` rules (the signed text's own, split at its "; " joins) and the two checks every step has; a plan with a list draws them
|
|
335
|
+
const planLines = parsed?.ok === true ? parsed.lines.map((/** @type {any} */ l) => ({ n: l.n, text: l.text, rules: l.guardrail ? l.guardrail.split('; ') : [] })) : [];
|
|
336
|
+
return {
|
|
337
|
+
checked: checkedLines(decl, opts), notChecked: { ...view, ...(isObj(ncFile?.by) ? { by: ncFile.by } : {}) }, ...(list ? { list, planLines, always: [...EVERY_STEP_TEXTS] } : {}),
|
|
338
|
+
};
|
|
319
339
|
}
|
|
320
340
|
|
|
321
341
|
/** The answers an answer-redraft was drafted with, as the marker recorded them: `[{ line, lineText, question, answer }]` (scrubbed). @param {string} dir @param {number} n @param {string[]} keys */
|
|
@@ -752,7 +772,9 @@ export function createAuthor(opts) {
|
|
|
752
772
|
// hamr 2026-11-07 (ruling 2A): a leading `~` the person typed is dropped quietly (the job line adds its own); the ONE place, so a tilde-only answer is a blank answer
|
|
753
773
|
// M10 am29: the button used rides as a typed `choice`; absent = the words reading (CLI and old pages). agree needs a proposal, drop/agree are look asks only.
|
|
754
774
|
const choice = b.choice;
|
|
755
|
-
|
|
775
|
+
// M10 am32 A: every new answer carries its button's choice; an answer with none is refused before anything is written (old answer files are still read by the readers)
|
|
776
|
+
if (choice === undefined) return { status: 400, body: { ok: false, refused: 'bad-choice', say: 'This page is out of date. Reload it and answer again. Nothing was saved.' } };
|
|
777
|
+
{
|
|
756
778
|
const proposes = look && typeof q.proposal === 'string' && (q.ask === 'reading' || q.ask === 'check');
|
|
757
779
|
if (choice !== 'agree' && choice !== 'drop' && choice !== 'rule') return { status: 400, body: { ok: false, refused: 'bad-choice', say: 'That answer is not one of the choices. Nothing was saved.' } };
|
|
758
780
|
if ((choice === 'agree' && !proposes) || (choice === 'drop' && !look)) return { status: 400, body: { ok: false, refused: 'bad-choice', say: 'That choice is not offered for this question. Nothing was saved.' } };
|
|
@@ -781,7 +803,7 @@ export function createAuthor(opts) {
|
|
|
781
803
|
const adds = all.filter((x) => x.rule !== null);
|
|
782
804
|
const grown = applyAnswers(typeof v.card.job === 'string' ? v.card.job : '', all);
|
|
783
805
|
if (grown.added !== adds.length) return { status: 409, body: { ok: false, refused: 'no-such-line', say: 'An answer is about a job line the card no longer has. Draft again from the card. Nothing was signed.' } };
|
|
784
|
-
const vet = vetCard({ ...v.card, job: grown.job }, loaded, draftedSoFar(dir, v.card));
|
|
806
|
+
const vet = vetCard({ ...v.card, job: grown.job }, loaded, draftedSoFar(dir, v.card), readJson(dir, RUN_OF_FILE)?.flow);
|
|
785
807
|
if (!vet.ok) return vet.reply;
|
|
786
808
|
for (const other of listIds()) {
|
|
787
809
|
if (other === id) continue;
|
|
@@ -824,6 +846,55 @@ export function createAuthor(opts) {
|
|
|
824
846
|
return { status: 202, body: { ok: true, draftId: id, n, redrafting: true } };
|
|
825
847
|
},
|
|
826
848
|
|
|
849
|
+
/**
|
|
850
|
+
* `POST /api/author/:id/row-edit` body `{ op: 'drop'|'add', key }` (M16 item 5, am3 (4); hamr 2026-11-13 N-2): the plan card's Drop and Add. $0 and instant: the panel REBUILDS the list from the
|
|
851
|
+
* newest green plan's saved files (src/planrebuild.js), applies the choice through the block's own `rowChoice`, and writes a NEW plan folder `draft-<n>` (records are write-once, the old plan is
|
|
852
|
+
* never touched) booked as a plan of its own with a $0 spend row. It spawns no `fwdloop draft`, builds no provider, makes no call. Signing then reads the new plan (its hash). A refusal is plain
|
|
853
|
+
* words and writes nothing.
|
|
854
|
+
* @param {string} id @param {any} body
|
|
855
|
+
*/
|
|
856
|
+
rowEdit(id, body) {
|
|
857
|
+
const { keys } = keysNow();
|
|
858
|
+
if (!ID_RE.test(id)) return { status: 404, body: { ok: false, refused: 'no-such-draft' } };
|
|
859
|
+
const dd = draftsDir();
|
|
860
|
+
const dir = dd === null ? null : join(dd, id);
|
|
861
|
+
const v = dir === null ? null : /** @type {any} */ (readDraft(dir, id, keys));
|
|
862
|
+
if (dir === null || v === null || v.card === null) return { status: 404, body: { ok: false, refused: 'no-such-draft' } };
|
|
863
|
+
if (v.phase !== 'green' || typeof v.plan !== 'string' || !Array.isArray(v.revises)) return { status: 409, body: { ok: false, refused: 'not-green', say: `This draft is ${v.phase}, not a finished plan, so its checks cannot be changed.` } };
|
|
864
|
+
const b = body && typeof body === 'object' ? body : {};
|
|
865
|
+
if (b.op !== 'drop' && b.op !== 'add') return { status: 400, body: { ok: false, refused: 'bad-choice', say: 'That is not one of the choices. Nothing was changed.' } };
|
|
866
|
+
if (typeof b.key !== 'string' || b.key === '' || b.key.length > 200) return { status: 400, body: { ok: false, refused: 'bad-row', say: 'That check is not on the list. Nothing was changed.' } };
|
|
867
|
+
if (childRunning(dir)) return { status: 409, body: { ok: false, refused: 'draft-live', say: 'The draft process is still finishing. Try again in a moment.' } };
|
|
868
|
+
// the plan was drafted with questions on, unless it is the redraft after answers (it never asks); a plan made by a Drop or an Add keeps the one it came from
|
|
869
|
+
const cur = PLAN_DIR_RE.exec(v.plan)?.[1];
|
|
870
|
+
const marker = cur === undefined ? null : readJson(dir, `redraft-${cur}.json`);
|
|
871
|
+
const asks = marker === null ? true : (marker.rowEdit ? marker.rowEdit.asks !== false : false);
|
|
872
|
+
const planDir = join(dir, v.plan);
|
|
873
|
+
const made = rowEditPlan({ planDir, op: b.op, key: b.key, asks });
|
|
874
|
+
if (!made.ok) return { status: 409, body: { ok: false, refused: made.refused ?? 'row-edit', say: made.say } };
|
|
875
|
+
const n = Math.max(0, ...v.revises.map((x) => x.n)) + 1;
|
|
876
|
+
const at = new Date().toISOString();
|
|
877
|
+
const newDir = join(dir, `draft-${n}`);
|
|
878
|
+
const prose = readFileInside(planDir, 'prose.txt');
|
|
879
|
+
try {
|
|
880
|
+
claimPlanDir(newDir);
|
|
881
|
+
if (Object.keys(made.pages).length > 0) claimPlanDir(join(newDir, 'pages'));
|
|
882
|
+
writePlanFiles(newDir, scrubbed(made.files, keys));
|
|
883
|
+
writePlanFiles(newDir, scrubbed(made.pages, keys));
|
|
884
|
+
// the $0 book of this plan: no call was made, so no round and no cost (a known $0, not an unknown one)
|
|
885
|
+
appendSpendRow(join(newDir, 'spend.jsonl'), {
|
|
886
|
+
kind: 'draft', provider: null, price: null, model: readModelRecord(planDir)?.model ?? null, modelReturned: null, tokens: null, costUsd: 0, rounds: 0, calls: 0, spendComplete: true, stop: null, budgetUsd: null, startedAt: at, wallMs: 0,
|
|
887
|
+
});
|
|
888
|
+
writePlanFiles(dir, {
|
|
889
|
+
[`card-${n}.json`]: `${JSON.stringify(v.card, null, 2)}\n`, [`prose-${n}.txt`]: prose.ok ? prose.text : '',
|
|
890
|
+
[`redraft-${n}.json`]: `${JSON.stringify({ fromPlan: v.plan, answers: [], rowEdit: { op: b.op, key: b.key, at, asks } })}\n`,
|
|
891
|
+
}, { flag: 'wx', mode: 0o600 });
|
|
892
|
+
} catch (e) {
|
|
893
|
+
return { status: 500, body: { ok: false, refused: 'write', say: `The changed plan could not be saved (${/** @type {any} */ (e)?.code ?? 'error'}). Nothing was changed.` } };
|
|
894
|
+
}
|
|
895
|
+
return { status: 200, body: { ok: true, draftId: id, n, plan: `draft-${n}`, hash: made.hash } };
|
|
896
|
+
},
|
|
897
|
+
|
|
827
898
|
/**
|
|
828
899
|
* `GET /api/author/live`: the newest draft that is not abandoned or signed, and the newest panel start the human has not cleared
|
|
829
900
|
* (`starting` or `refused`; a `started` one is in Runs) — read from files, never memory.
|
package/src/panel/authorcard.js
CHANGED
|
@@ -15,6 +15,7 @@ import {
|
|
|
15
15
|
import { isAbsolute, join } from 'node:path';
|
|
16
16
|
|
|
17
17
|
import { checkFlowName } from '../flow.js';
|
|
18
|
+
import { sameRuleWords } from '../blockpick.js';
|
|
18
19
|
import { isWebUrl } from '../pagefetch.js';
|
|
19
20
|
import { checkSendDestination } from '../runner.js';
|
|
20
21
|
import { parseSignedText } from '../signed-text.js';
|
|
@@ -95,7 +96,7 @@ export function parseJobBox(text) {
|
|
|
95
96
|
* that line's own `~` lines (several answers for one line keep their order). The job box's own lines are untouched; the card -> prose path
|
|
96
97
|
* (`cardToProse`) then writes the answer as that line's guardrail, so it reaches the signed text and the hash. Pure. An answer for a line
|
|
97
98
|
* the box does not have is NOT added (the caller sees the count). An answer equal (exact string, after trim) to a `~` rule already on that line is not added
|
|
98
|
-
* again, and still counts: it is taken, the line already says it.
|
|
99
|
+
* again (case, spacing and trailing punctuation aside; also not when it is one `; ` part of a `~` line), and still counts: it is taken, the line already says it.
|
|
99
100
|
* @param {string} job @param {{ line: number, answer: string }[]} answers
|
|
100
101
|
* @returns {{ job: string, added: number }}
|
|
101
102
|
*/
|
|
@@ -103,7 +104,7 @@ export function appendAnswersToJob(job, answers) {
|
|
|
103
104
|
const raw = String(job).split('\n');
|
|
104
105
|
/** @type {Map<number, number>} the index of the last non-empty box line that belongs to each step (its own line or a `~` under it) */
|
|
105
106
|
const lastOf = new Map();
|
|
106
|
-
/** @type {Map<number,
|
|
107
|
+
/** @type {Map<number, string[]>} the `~` rules each step already has: a `~` line's whole words, and each `; ` part of it (a rule of its own) */
|
|
107
108
|
const have = new Map();
|
|
108
109
|
let step = 0;
|
|
109
110
|
raw.forEach((l, i) => {
|
|
@@ -111,7 +112,7 @@ export function appendAnswersToJob(job, answers) {
|
|
|
111
112
|
if (t === '') return;
|
|
112
113
|
if (!t.startsWith('~')) step += 1;
|
|
113
114
|
if (step > 0) lastOf.set(step, i);
|
|
114
|
-
if (step > 0 && t.startsWith('~')) have.set(step, (have.get(step) ??
|
|
115
|
+
if (step > 0 && t.startsWith('~')) { const w = t.slice(1).trim(); have.set(step, [...(have.get(step) ?? []), w, ...w.split('; ').filter(Boolean)]); }
|
|
115
116
|
});
|
|
116
117
|
/** @type {Map<number, string[]>} */
|
|
117
118
|
const after = new Map();
|
|
@@ -120,9 +121,11 @@ export function appendAnswersToJob(job, answers) {
|
|
|
120
121
|
if (!lastOf.has(a.line)) continue;
|
|
121
122
|
const at = /** @type {number} */ (lastOf.get(a.line));
|
|
122
123
|
added += 1;
|
|
123
|
-
const rules = have.get(a.line) ??
|
|
124
|
-
|
|
125
|
-
|
|
124
|
+
const rules = have.get(a.line) ?? [];
|
|
125
|
+
// borrowed-from: bareloop src/panel/authorsession.js@v0.56.0 (3383cce) F318 0291e910
|
|
126
|
+
// words the line already holds as a rule (a whole `~` line or one `; ` part of it) add no second line; different words still add one
|
|
127
|
+
if (rules.some((t) => sameRuleWords(t, a.answer))) continue;
|
|
128
|
+
have.set(a.line, [...rules, a.answer.trim()]);
|
|
126
129
|
after.set(at, [...(after.get(at) ?? []), `~ ${a.answer}`]);
|
|
127
130
|
}
|
|
128
131
|
const out = [];
|