@aglyn/plugins-ai 1.6.0 → 1.8.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/README.md +2 -2
- package/package.json +17 -17
- package/src/lib/components/ai-insight-dialog.component.js +14 -0
- package/src/lib/components/ai-insight-dialog.component.js.map +1 -1
- package/src/lib/insights/ai-figure-readers.d.ts +13 -0
- package/src/lib/insights/ai-figure-readers.js +158 -11
- package/src/lib/insights/ai-figure-readers.js.map +1 -1
- package/src/lib/insights/ai-figure-summaries.js +4 -2
- package/src/lib/insights/ai-figure-summaries.js.map +1 -1
- package/src/lib/insights/ai-insight-digest.d.ts +27 -17
- package/src/lib/insights/ai-insight-digest.js +96 -107
- package/src/lib/insights/ai-insight-digest.js.map +1 -1
- package/src/lib/jobs/ai-job-import-step.d.ts +28 -2
- package/src/lib/jobs/ai-job-import-step.js +170 -14
- package/src/lib/jobs/ai-job-import-step.js.map +1 -1
- package/src/lib/jobs/ai-job-insight-budget.d.ts +19 -3
- package/src/lib/jobs/ai-job-insight-budget.js +18 -4
- package/src/lib/jobs/ai-job-insight-budget.js.map +1 -1
- package/src/lib/jobs/ai-job-insight-step.d.ts +2 -2
- package/src/lib/jobs/ai-job-insight-step.js +17 -7
- package/src/lib/jobs/ai-job-insight-step.js.map +1 -1
- package/src/lib/jobs/ai-job-layout-language.js +2 -0
- package/src/lib/jobs/ai-job-layout-language.js.map +1 -1
- package/src/lib/jobs/ai-job-page-language.js +6 -2
- package/src/lib/jobs/ai-job-page-language.js.map +1 -1
- package/src/lib/jobs/ai-site-import-compile.d.ts +13 -3
- package/src/lib/jobs/ai-site-import-compile.js +336 -27
- package/src/lib/jobs/ai-site-import-compile.js.map +1 -1
- package/src/lib/jobs/ai-site-import-document.d.ts +3 -1
- package/src/lib/jobs/ai-site-import-document.js +36 -0
- package/src/lib/jobs/ai-site-import-document.js.map +1 -1
- package/src/lib/jobs/ai-site-import-look.d.ts +9 -0
- package/src/lib/jobs/ai-site-import-look.js +89 -6
- package/src/lib/jobs/ai-site-import-look.js.map +1 -1
- package/src/lib/layout-language/ai-layout-compiler.d.ts +16 -0
- package/src/lib/layout-language/ai-layout-compiler.js +351 -54
- package/src/lib/layout-language/ai-layout-compiler.js.map +1 -1
- package/src/lib/layout-language/ai-layout-frame-source.d.ts +88 -2
- package/src/lib/layout-language/ai-layout-frame-source.js +591 -30
- package/src/lib/layout-language/ai-layout-frame-source.js.map +1 -1
- package/src/lib/layout-language/ai-layout-frame.js +30 -18
- package/src/lib/layout-language/ai-layout-frame.js.map +1 -1
- package/src/lib/layout-language/ai-layout-language.d.ts +72 -3
- package/src/lib/layout-language/ai-layout-language.js +5 -3
- package/src/lib/layout-language/ai-layout-language.js.map +1 -1
- package/src/lib/layout-language/ai-layout-store.d.ts +8 -0
- package/src/lib/layout-language/ai-layout-store.js +32 -6
- package/src/lib/layout-language/ai-layout-store.js.map +1 -1
- package/src/lib/model/ai-insight.d.ts +23 -3
- package/src/lib/model/ai-insight.js +17 -3
- package/src/lib/model/ai-insight.js.map +1 -1
- package/src/lib/model/ai-site-import-fidelity.d.ts +31 -1
- package/src/lib/model/ai-site-import-fidelity.js +347 -25
- package/src/lib/model/ai-site-import-fidelity.js.map +1 -1
- package/src/lib/model/ai-site-import.d.ts +203 -6
- package/src/lib/model/ai-site-import.js +161 -5
- package/src/lib/model/ai-site-import.js.map +1 -1
- package/src/lib/model/ai-site-look.d.ts +8 -1
- package/src/lib/model/ai-site-look.js +8 -5
- package/src/lib/model/ai-site-look.js.map +1 -1
- package/src/lib/providers/routing.js +3 -1
- package/src/lib/providers/routing.js.map +1 -1
- package/src/lib/runtime/ai-doctrine-validators.d.ts +7 -1
- package/src/lib/runtime/ai-doctrine-validators.js +25 -2
- package/src/lib/runtime/ai-doctrine-validators.js.map +1 -1
- package/src/lib/runtime/ai-insight-check.d.ts +7 -0
- package/src/lib/runtime/ai-insight-check.js +111 -27
- package/src/lib/runtime/ai-insight-check.js.map +1 -1
- package/src/lib/runtime/ai-node-tree.js +19 -2
- package/src/lib/runtime/ai-node-tree.js.map +1 -1
- package/src/lib/runtime/ai-page-links.d.ts +15 -0
- package/src/lib/runtime/ai-page-links.js +48 -0
- package/src/lib/runtime/ai-page-links.js.map +1 -1
- package/src/lib/site-import/fixtures/site-import-fidelity-replay.js +30 -5
- package/src/lib/site-import/fixtures/site-import-fidelity-replay.js.map +1 -1
- package/src/lib/site-import/fixtures/site-layout-recordings.d.ts +9 -0
- package/src/lib/site-import/fixtures/site-layout-recordings.js +24 -5
- package/src/lib/site-import/fixtures/site-layout-recordings.js.map +1 -1
- package/src/lib/site-import/site-import-crawl.d.ts +3 -1
- package/src/lib/site-import/site-import-crawl.js +8 -3
- package/src/lib/site-import/site-import-crawl.js.map +1 -1
- package/src/lib/site-import/site-import-css.d.ts +20 -0
- package/src/lib/site-import/site-import-css.js +106 -0
- package/src/lib/site-import/site-import-css.js.map +1 -1
- package/src/lib/site-import/site-import-html.d.ts +39 -0
- package/src/lib/site-import/site-import-html.js +515 -5
- package/src/lib/site-import/site-import-html.js.map +1 -1
- package/src/lib/site-import/site-import-layout.d.ts +16 -6
- package/src/lib/site-import/site-import-layout.js +524 -52
- package/src/lib/site-import/site-import-layout.js.map +1 -1
- package/src/lib/site-import/site-import-nav.js +286 -24
- package/src/lib/site-import/site-import-nav.js.map +1 -1
- package/src/lib/site-import/site-import-page.js +3 -0
- package/src/lib/site-import/site-import-page.js.map +1 -1
- package/src/lib/tools/ai-insight-tool.js +45 -2
- package/src/lib/tools/ai-insight-tool.js.map +1 -1
|
@@ -34,6 +34,11 @@ import { type AiInsight, type AiInsightAnswer, type AiInsightTable } from '../mo
|
|
|
34
34
|
* whose number cannot be found is exactly the sentence a person must not act
|
|
35
35
|
* on, and rewriting it would be the model's guess again. The rest of the
|
|
36
36
|
* answer stands. What is left out is counted, so the console can say so.
|
|
37
|
+
*
|
|
38
|
+
* A digest's overview, and an insight's reason and next step (AGL-4131), are
|
|
39
|
+
* held to the same rows and dropped alone when they fail: the insight stands.
|
|
40
|
+
* A reason must also cite a row of a table that can hold a cause, and a row
|
|
41
|
+
* whose change shows it held steady is not one.
|
|
37
42
|
*/
|
|
38
43
|
/** Why an insight was left out, as a finding code. */
|
|
39
44
|
export type AiInsightFinding = 'insight-empty' | 'insight-too-long' | 'insight-markup' | 'insight-personal-details' | 'insight-no-citation' | 'insight-unknown-table' | 'insight-unknown-row' | 'insight-number-untraced' | 'insight-direction' | 'insight-too-many';
|
|
@@ -42,6 +47,8 @@ export interface AiInsightVerdict {
|
|
|
42
47
|
findings: string[];
|
|
43
48
|
}
|
|
44
49
|
export interface AiInsightCheck {
|
|
50
|
+
/** A digest's read of the week, when it is one a person may read. */
|
|
51
|
+
overview: string | null;
|
|
45
52
|
/** The insights a person may read, in the order written. */
|
|
46
53
|
kept: AiInsight[];
|
|
47
54
|
/** The insights left out, each with why. */
|
|
@@ -15,7 +15,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
15
15
|
* See the License for the specific language governing permissions and
|
|
16
16
|
* limitations under the License.
|
|
17
17
|
*/ import { hasPersonalDetails } from "@aglyn/aglyn/plugin-manager/plugin-figures";
|
|
18
|
-
import { AI_INSIGHT_GAP_MAX_CHARS, AI_INSIGHT_HEADLINE_MAX_CHARS, AI_INSIGHT_MAX_CHARS, AI_INSIGHT_MAX_CITED_ROWS, AI_INSIGHT_MAX_CITES, AI_INSIGHT_MAX_INSIGHTS } from "../model/ai-insight.js";
|
|
18
|
+
import { AI_INSIGHT_CAUSE_READERS, AI_INSIGHT_GAP_MAX_CHARS, AI_INSIGHT_HEADLINE_MAX_CHARS, AI_INSIGHT_MAX_CHARS, AI_INSIGHT_MAX_CITED_ROWS, AI_INSIGHT_MAX_CITES, AI_INSIGHT_MAX_INSIGHTS, AI_INSIGHT_NEXT_MAX_CHARS, AI_INSIGHT_OVERVIEW_MAX_CHARS, AI_INSIGHT_WHY_MAX_CHARS } from "../model/ai-insight.js";
|
|
19
19
|
const MARKUP = /<\/?[a-z][^>]*>|```|^#{1,6}\s|\*\*/im;
|
|
20
20
|
/**
|
|
21
21
|
* A number as a sentence writes it: an optional sign and currency symbol, the
|
|
@@ -166,29 +166,11 @@ const truncate = (value, decimals)=>{
|
|
|
166
166
|
const headline = typeof (insight == null ? void 0 : insight.headline) === 'string' ? insight.headline.trim() : '';
|
|
167
167
|
return headline.length <= AI_INSIGHT_HEADLINE_MAX_CHARS ? headline : '';
|
|
168
168
|
}
|
|
169
|
-
/**
|
|
170
|
-
const sentences = typeof (insight == null ? void 0 : insight.text) === 'string' ? insight.text.trim() : '';
|
|
171
|
-
if (!sentences) return [
|
|
172
|
-
'insight-empty'
|
|
173
|
-
];
|
|
174
|
-
const findings = [];
|
|
175
|
-
if (sentences.length > AI_INSIGHT_MAX_CHARS) findings.push('insight-too-long');
|
|
176
|
-
// The headline is held to everything the sentence is: it is the part a
|
|
177
|
-
// person reads first, and often the only part.
|
|
178
|
-
const headline = insightHeadline(insight);
|
|
179
|
-
const text = headline ? `${headline}. ${sentences}` : sentences;
|
|
180
|
-
if (MARKUP.test(text)) findings.push('insight-markup');
|
|
181
|
-
if (hasPersonalDetails(text)) findings.push('insight-personal-details');
|
|
182
|
-
const cites = Array.isArray(insight.cites) ? insight.cites.slice(0, AI_INSIGHT_MAX_CITES) : [];
|
|
183
|
-
if (!cites.length || cites.every((cite)=>!Array.isArray(cite == null ? void 0 : cite.rows) || !cite.rows.length)) {
|
|
184
|
-
return [
|
|
185
|
-
...findings,
|
|
186
|
-
'insight-no-citation'
|
|
187
|
-
];
|
|
188
|
-
}
|
|
169
|
+
/** The cells and labels a list of citations opens, and any citation that opens nothing. */ function citedFigures(cites, tables) {
|
|
189
170
|
const cells = [];
|
|
190
171
|
const labels = [];
|
|
191
172
|
const cited = [];
|
|
173
|
+
const findings = [];
|
|
192
174
|
for (const cite of cites){
|
|
193
175
|
var _cite_rows;
|
|
194
176
|
const table = tables.find((entry)=>entry.ref === (cite == null ? void 0 : cite.table));
|
|
@@ -226,7 +208,16 @@ const truncate = (value, decimals)=>{
|
|
|
226
208
|
}
|
|
227
209
|
}
|
|
228
210
|
}
|
|
229
|
-
|
|
211
|
+
return {
|
|
212
|
+
cells,
|
|
213
|
+
labels,
|
|
214
|
+
cited,
|
|
215
|
+
findings
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
/** What a piece of writing says that the rows it cites do not: a figure they do not hold, or a direction they deny. */ function numberFindings(text, cites, figures) {
|
|
219
|
+
const { cells, labels, cited } = figures;
|
|
220
|
+
const findings = [];
|
|
230
221
|
const framing = framingNumbers(cited, cites);
|
|
231
222
|
for (const written of aiInsightNumbers(text)){
|
|
232
223
|
const matched = cells.filter((cell)=>scalesFor(written, cell.kind).some((scale)=>reads(written, cell.value, scale)));
|
|
@@ -246,6 +237,81 @@ const truncate = (value, decimals)=>{
|
|
|
246
237
|
}
|
|
247
238
|
return findings;
|
|
248
239
|
}
|
|
240
|
+
const insightCites = (insight)=>Array.isArray(insight.cites) ? insight.cites.slice(0, AI_INSIGHT_MAX_CITES) : [];
|
|
241
|
+
/** One insight's findings against the tables the job read; empty when it traces. */ export function checkAiInsight(insight, tables) {
|
|
242
|
+
const sentences = typeof (insight == null ? void 0 : insight.text) === 'string' ? insight.text.trim() : '';
|
|
243
|
+
if (!sentences) return [
|
|
244
|
+
'insight-empty'
|
|
245
|
+
];
|
|
246
|
+
const findings = [];
|
|
247
|
+
if (sentences.length > AI_INSIGHT_MAX_CHARS) findings.push('insight-too-long');
|
|
248
|
+
// The headline is held to everything the sentence is: it is the part a
|
|
249
|
+
// person reads first, and often the only part.
|
|
250
|
+
const headline = insightHeadline(insight);
|
|
251
|
+
const text = headline ? `${headline}. ${sentences}` : sentences;
|
|
252
|
+
if (MARKUP.test(text)) findings.push('insight-markup');
|
|
253
|
+
if (hasPersonalDetails(text)) findings.push('insight-personal-details');
|
|
254
|
+
const cites = insightCites(insight);
|
|
255
|
+
if (!cites.length || cites.every((cite)=>!Array.isArray(cite == null ? void 0 : cite.rows) || !cite.rows.length)) {
|
|
256
|
+
return [
|
|
257
|
+
...findings,
|
|
258
|
+
'insight-no-citation'
|
|
259
|
+
];
|
|
260
|
+
}
|
|
261
|
+
const figures = citedFigures(cites, tables);
|
|
262
|
+
findings.push(...figures.findings);
|
|
263
|
+
if (findings.some((finding)=>finding.startsWith('insight-unknown-'))) return findings;
|
|
264
|
+
return [
|
|
265
|
+
...findings,
|
|
266
|
+
...numberFindings(text, cites, figures)
|
|
267
|
+
];
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* A line beside the insights, held to everything an insight is, or `''` with
|
|
271
|
+
* why. It is only dropped: a reason or a next step that cannot be kept says
|
|
272
|
+
* nothing about whether the figures are true (AGL-4131).
|
|
273
|
+
*/ function checkedLine(value, name, maxChars, cites, tables) {
|
|
274
|
+
const line = typeof value === 'string' ? value.replace(/\s+/g, ' ').trim() : '';
|
|
275
|
+
if (!line) return {
|
|
276
|
+
line: '',
|
|
277
|
+
findings: []
|
|
278
|
+
};
|
|
279
|
+
const refused = [
|
|
280
|
+
...line.length > maxChars ? [
|
|
281
|
+
`insight-${name}-too-long`
|
|
282
|
+
] : [],
|
|
283
|
+
...MARKUP.test(line) ? [
|
|
284
|
+
`insight-${name}-markup`
|
|
285
|
+
] : [],
|
|
286
|
+
...hasPersonalDetails(line) ? [
|
|
287
|
+
`insight-${name}-personal-details`
|
|
288
|
+
] : [],
|
|
289
|
+
...numberFindings(line, cites, citedFigures(cites, tables))
|
|
290
|
+
];
|
|
291
|
+
return refused.length ? {
|
|
292
|
+
line: '',
|
|
293
|
+
findings: refused
|
|
294
|
+
} : {
|
|
295
|
+
line,
|
|
296
|
+
findings: []
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Whether an insight cites a row a reason can rest on: a row of a table that
|
|
301
|
+
* can hold a cause, and one that moved. A source or campaign whose change is 0
|
|
302
|
+
* sent the same traffic as the week before, so it cannot explain a move; a
|
|
303
|
+
* dated change has no change column and always can.
|
|
304
|
+
*/ function citesACause(cites, tables) {
|
|
305
|
+
return cites.some((cite)=>{
|
|
306
|
+
const table = tables.find((candidate)=>candidate.ref === cite.table);
|
|
307
|
+
if (!table || !AI_INSIGHT_CAUSE_READERS.includes(table.reader)) return false;
|
|
308
|
+
return cite.rows.some((index)=>{
|
|
309
|
+
const row = table.rows[index];
|
|
310
|
+
return Boolean(row) && row.change !== 0;
|
|
311
|
+
});
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
/** A next step that promises what it would do is left out: nothing here can know. */ const PROMISE = /\b(?:guarantee[sd]?|sure to|will (?:increase|boost|double|grow|raise|improve|bring|get you|rank))\b/i;
|
|
249
315
|
/** The gap sentence a person may read: short, without figures and naming nobody; `null` otherwise. */ export function aiInsightGap(gap) {
|
|
250
316
|
if (typeof gap !== 'string') return null;
|
|
251
317
|
const text = gap.replace(/\s+/g, ' ').trim();
|
|
@@ -273,20 +339,38 @@ const truncate = (value, decimals)=>{
|
|
|
273
339
|
findings.push(...own);
|
|
274
340
|
} else {
|
|
275
341
|
const headline = insightHeadline(insight);
|
|
342
|
+
const cites = insightCites(insight).map((cite)=>({
|
|
343
|
+
table: cite.table,
|
|
344
|
+
rows: cite.rows.slice(0, AI_INSIGHT_MAX_CITED_ROWS)
|
|
345
|
+
}));
|
|
346
|
+
const why = checkedLine(insight.why, 'why', AI_INSIGHT_WHY_MAX_CHARS, cites, tables);
|
|
347
|
+
const reasoned = why.line && citesACause(cites, tables);
|
|
348
|
+
if (why.line && !reasoned) findings.push('insight-why-no-cause');
|
|
349
|
+
const next = checkedLine(insight.next, 'next', AI_INSIGHT_NEXT_MAX_CHARS, cites, tables);
|
|
350
|
+
const promised = PROMISE.test(next.line);
|
|
351
|
+
if (promised) findings.push('insight-next-promise');
|
|
352
|
+
findings.push(...why.findings, ...next.findings);
|
|
276
353
|
kept.push(_extends({}, headline ? {
|
|
277
354
|
headline
|
|
278
355
|
} : {}, {
|
|
279
|
-
text: insight.text.trim()
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
356
|
+
text: insight.text.trim()
|
|
357
|
+
}, reasoned ? {
|
|
358
|
+
why: why.line
|
|
359
|
+
} : {}, next.line && !promised ? {
|
|
360
|
+
next: next.line
|
|
361
|
+
} : {}, {
|
|
362
|
+
cites
|
|
284
363
|
}));
|
|
285
364
|
}
|
|
286
365
|
});
|
|
287
366
|
const gap = aiInsightGap(answer == null ? void 0 : answer.gap);
|
|
288
367
|
if ((answer == null ? void 0 : answer.gap) && !gap) findings.push('insight-gap-unreadable');
|
|
368
|
+
// Held to the rows the kept insights cite: it has no citations of its own,
|
|
369
|
+
// and a figure in it should be one a reader can open just below it.
|
|
370
|
+
const overview = checkedLine(answer == null ? void 0 : answer.overview, 'overview', AI_INSIGHT_OVERVIEW_MAX_CHARS, kept.flatMap((insight)=>insight.cites), tables);
|
|
371
|
+
findings.push(...overview.findings);
|
|
289
372
|
return {
|
|
373
|
+
overview: overview.line || null,
|
|
290
374
|
kept,
|
|
291
375
|
left,
|
|
292
376
|
gap,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/runtime/ai-insight-check.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { hasPersonalDetails } from '@aglyn/aglyn/plugin-manager/plugin-figures'\nimport {\n AI_INSIGHT_GAP_MAX_CHARS,\n AI_INSIGHT_HEADLINE_MAX_CHARS,\n AI_INSIGHT_MAX_CHARS,\n AI_INSIGHT_MAX_CITED_ROWS,\n AI_INSIGHT_MAX_CITES,\n AI_INSIGHT_MAX_INSIGHTS,\n type AiInsight,\n type AiInsightAnswer,\n type AiInsightCitation,\n type AiInsightTable,\n} from '../model/ai-insight'\n\n/**\n * THE TRACE (AGL-2915): whether an insight's words agree with the rows it\n * cites.\n *\n * An insight job hands the model tables that code computed, and the model\n * writes sentences about them. Nothing about a sentence makes it true, so each\n * one is read back against the figures before a person sees it:\n *\n * - it cites at least one row, of a table this job actually read;\n * - every number it writes is a figure in a row it cites — as the table has\n * it, or rounded to the decimals written, in the unit written — or the\n * length of a cited window, a date in it, or a count of the rows cited;\n * - a rise or a fall it names agrees with the sign of the change it quotes;\n * - it names nobody: no email address and no phone number.\n *\n * An insight that fails any of these is LEFT OUT, never repaired: a sentence\n * whose number cannot be found is exactly the sentence a person must not act\n * on, and rewriting it would be the model's guess again. The rest of the\n * answer stands. What is left out is counted, so the console can say so.\n */\n\n/** Why an insight was left out, as a finding code. */\nexport type AiInsightFinding =\n | 'insight-empty'\n | 'insight-too-long'\n | 'insight-markup'\n | 'insight-personal-details'\n | 'insight-no-citation'\n | 'insight-unknown-table'\n | 'insight-unknown-row'\n | 'insight-number-untraced'\n | 'insight-direction'\n | 'insight-too-many'\n\nexport interface AiInsightVerdict {\n insight: AiInsight\n findings: string[]\n}\n\nexport interface AiInsightCheck {\n /** The insights a person may read, in the order written. */\n kept: AiInsight[]\n /** The insights left out, each with why. */\n left: AiInsightVerdict[]\n /** The gap sentence, when it is one a person may read. */\n gap: string | null\n /** Every finding, in order, for the eval harness and the logs. */\n findings: string[]\n}\n\nconst MARKUP = /<\\/?[a-z][^>]*>|```|^#{1,6}\\s|\\*\\*/im\n\n/**\n * A number as a sentence writes it: an optional sign and currency symbol, the\n * digits with their thousands separators, the decimals, and a unit.\n */\nconst NUMBER = /(?<![\\p{L}\\p{N}_.])([+\\-−]?)([$€£¥]?)(\\d{1,3}(?:,\\d{3})+|\\d+)(?:\\.(\\d+))?(?:\\s?(%|percent\\b|k\\b|thousand\\b|m\\b|million\\b|seconds?\\b|secs?\\b|s\\b|minutes?\\b|mins?\\b|hours?\\b|hrs?\\b|h\\b))?/giu\n\n/** Minutes and seconds written together (`2m 04s`), read as one figure in seconds. */\nconst DURATION = /(?<![\\p{L}\\p{N}_.])(?:(\\d+)\\s?h(?:ours?|rs?)?\\s+)?(\\d+)\\s?m(?:in(?:utes?)?)?\\s+(\\d{1,2})\\s?s(?:ec(?:onds?)?)?\\b/giu\n\nconst RISING = /\\b(?:rose|rise[sn]?|rising|grew|grow(?:s|n|ing)?|increas(?:e|ed|es|ing)|up|higher|gain(?:ed|s)?|jump(?:ed|s)?|climb(?:ed|s)?|more)\\b/i\nconst FALLING = /\\b(?:fell|fall(?:s|en|ing)?|drop(?:ped|s)?|declin(?:e|ed|es|ing)|decreas(?:e|ed|es|ing)|down|lower|lost|shr[au]nk|less|fewer)\\b/i\n\ninterface WrittenNumber {\n /** The figure as written, unsigned, in the unit's base (a percent, seconds, a plain count). */\n value: number\n decimals: number\n negative: boolean\n unit: 'percent' | 'thousand' | 'million' | 'seconds' | 'minutes' | 'hours' | 'currency' | null\n /** Where in the text it starts, for the words before it. */\n at: number\n raw: string\n}\n\nfunction unitOf(symbol: string, unit: string | undefined): WrittenNumber['unit'] {\n const word = (unit ?? '').toLowerCase()\n if (word === '%' || word === 'percent') return 'percent'\n if (word === 'k' || word === 'thousand') return 'thousand'\n if (word === 'm' || word === 'million') return 'million'\n if (/^(?:seconds?|secs?|s)$/.test(word)) return 'seconds'\n if (/^(?:minutes?|mins?)$/.test(word)) return 'minutes'\n if (/^(?:hours?|hrs?|h)$/.test(word)) return 'hours'\n return symbol ? 'currency' : null\n}\n\n/** Every figure a sentence writes, durations written as minutes and seconds read as one. */\nexport function aiInsightNumbers(text: string): WrittenNumber[] {\n const found: WrittenNumber[] = []\n const covered: Array<[number, number]> = []\n for (const match of text.matchAll(DURATION)) {\n const hours = Number(match[1] ?? 0)\n const seconds = hours * 3_600 + Number(match[2]) * 60 + Number(match[3])\n const at = match.index ?? 0\n covered.push([at, at + match[0].length])\n found.push({ value: seconds, decimals: 0, negative: false, unit: 'seconds', at, raw: match[0] })\n }\n for (const match of text.matchAll(NUMBER)) {\n const at = match.index ?? 0\n if (covered.some(([start, end]) => at >= start && at < end)) continue\n const whole = match[3].replace(/,/g, '')\n const decimals = match[4] ?? ''\n found.push({\n value: Number(decimals ? `${whole}.${decimals}` : whole),\n decimals: decimals.length,\n negative: match[1] === '-' || match[1] === '−',\n unit: unitOf(match[2], match[5]),\n at,\n raw: match[0],\n })\n }\n return found.sort((a, b) => a.at - b.at)\n}\n\nconst round = (value: number, decimals: number) => {\n const scale = 10 ** decimals\n return Math.round(value * scale) / scale\n}\n\nconst truncate = (value: number, decimals: number) => {\n const scale = 10 ** decimals\n return Math.trunc(value * scale) / scale\n}\n\n/** Whether a written figure reads a cell's value, at the decimals written, rounded or cut. */\nfunction reads(written: WrittenNumber, cell: number, scale: number): boolean {\n const base = Math.abs(cell) / scale\n const value = Math.abs(written.value)\n return round(base, written.decimals) === value || truncate(base, written.decimals) === value\n}\n\n/** The scales a unit may read a column's cells at: a percent is not a count, and seconds are not dollars. */\nfunction scalesFor(written: WrittenNumber, kind: AiInsightTable['columns'][number]['kind']): number[] {\n switch (written.unit) {\n case 'percent':\n return kind === 'percent' || kind === 'change' || kind === 'number' ? [1] : []\n case 'currency':\n return kind === 'money' ? [1] : []\n case 'thousand':\n return kind === 'count' || kind === 'number' || kind === 'money' ? [1_000] : []\n case 'million':\n return kind === 'count' || kind === 'number' || kind === 'money'\n ? [1_000_000]\n : kind === 'duration'\n ? [60]\n : []\n case 'seconds':\n return kind === 'duration' ? [1] : []\n case 'minutes':\n return kind === 'duration' ? [60] : []\n case 'hours':\n return kind === 'duration' ? [3_600] : []\n default:\n return kind === 'date' || kind === 'text' ? [] : kind === 'duration' ? [1, 60] : [1]\n }\n}\n\ninterface CitedCell {\n table: AiInsightTable\n kind: AiInsightTable['columns'][number]['kind']\n value: number\n}\n\n/** The numbers a citation vouches for beyond its cells: the window, its dates, and how many rows. */\nfunction framingNumbers(tables: readonly AiInsightTable[], cites: readonly AiInsightCitation[]): Set<number> {\n const numbers = new Set<number>()\n for (const table of tables) {\n if (table.period) {\n numbers.add(table.period.days)\n for (const day of [table.period.from, table.period.to]) {\n const [year, month, date] = day.split('-').map(Number)\n numbers.add(year).add(month).add(date)\n }\n }\n numbers.add(table.rows.length)\n }\n for (const cite of cites) numbers.add(cite.rows.length)\n numbers.add(cites.reduce((total, cite) => total + cite.rows.length, 0))\n return numbers\n}\n\n/** Whether a figure's digits are written inside a cited label: a year in a campaign's name, a path's number. */\nfunction inLabel(written: WrittenNumber, labels: readonly string[]): boolean {\n if (written.unit !== null || written.negative) return false\n const digits = written.raw.replace(/[^\\d.]/g, '')\n return labels.some((label) => new RegExp(`(?<![\\\\d.])${digits.replace('.', '\\\\.')}(?![\\\\d.])`).test(label))\n}\n\n/** The sign the words just before a figure give it, or `null` when they give none. */\nfunction directionBefore(text: string, at: number): 'rise' | 'fall' | null {\n const before = text.slice(Math.max(0, at - 40), at)\n const words = before.split(/\\s+/).slice(-4).join(' ')\n const rise = RISING.test(words)\n const fall = FALLING.test(words)\n if (rise === fall) return null\n return rise ? 'rise' : 'fall'\n}\n\n/**\n * The headline a person may read. One that runs long is only dropped: the\n * insight keeps its sentence, because length says nothing about whether it is\n * true.\n */\nfunction insightHeadline(insight: AiInsight): string {\n const headline = typeof insight?.headline === 'string' ? insight.headline.trim() : ''\n return headline.length <= AI_INSIGHT_HEADLINE_MAX_CHARS ? headline : ''\n}\n\n/** One insight's findings against the tables the job read; empty when it traces. */\nexport function checkAiInsight(insight: AiInsight, tables: readonly AiInsightTable[]): string[] {\n const sentences = typeof insight?.text === 'string' ? insight.text.trim() : ''\n if (!sentences) return ['insight-empty']\n const findings: string[] = []\n if (sentences.length > AI_INSIGHT_MAX_CHARS) findings.push('insight-too-long')\n // The headline is held to everything the sentence is: it is the part a\n // person reads first, and often the only part.\n const headline = insightHeadline(insight)\n const text = headline ? `${headline}. ${sentences}` : sentences\n if (MARKUP.test(text)) findings.push('insight-markup')\n if (hasPersonalDetails(text)) findings.push('insight-personal-details')\n\n const cites = Array.isArray(insight.cites) ? insight.cites.slice(0, AI_INSIGHT_MAX_CITES) : []\n if (!cites.length || cites.every((cite) => !Array.isArray(cite?.rows) || !cite.rows.length)) {\n return [...findings, 'insight-no-citation']\n }\n const cells: CitedCell[] = []\n const labels: string[] = []\n const cited: AiInsightTable[] = []\n for (const cite of cites) {\n const table = tables.find((entry) => entry.ref === cite?.table)\n if (!table) {\n findings.push(`insight-unknown-table:${String(cite?.table)}`)\n continue\n }\n cited.push(table)\n for (const index of (cite.rows ?? []).slice(0, AI_INSIGHT_MAX_CITED_ROWS)) {\n const row = Number.isInteger(index) ? table.rows[index] : undefined\n if (!row) {\n findings.push(`insight-unknown-row:${table.ref}:${String(index)}`)\n continue\n }\n for (const column of table.columns) {\n const value = row[column.key]\n if (typeof value === 'number' && Number.isFinite(value)) {\n cells.push({ table, kind: column.kind, value })\n } else if (typeof value === 'string') {\n labels.push(value)\n if (column.kind === 'date') {\n for (const part of value.split('-').map(Number)) {\n cells.push({ table, kind: 'count', value: part })\n }\n }\n }\n }\n }\n }\n if (findings.some((finding) => finding.startsWith('insight-unknown-'))) return findings\n\n const framing = framingNumbers(cited, cites)\n for (const written of aiInsightNumbers(text)) {\n const matched = cells.filter((cell) =>\n scalesFor(written, cell.kind).some((scale) => reads(written, cell.value, scale)),\n )\n const framed =\n written.unit === null && written.decimals === 0 && !written.negative && framing.has(written.value)\n if (!matched.length && !framed && !inLabel(written, labels)) {\n findings.push(`insight-number-untraced:${written.raw.trim()}`)\n continue\n }\n // A rise or a fall is checked against the change it quotes, and only then:\n // \"down\" beside a count is not a claim about a sign.\n const changes = matched.filter((cell) => cell.kind === 'change' && cell.value !== 0)\n if (!changes.length || changes.length !== matched.length) continue\n const direction = directionBefore(text, written.at)\n if (!direction) continue\n const agrees = changes.some((cell) => (direction === 'rise' ? cell.value > 0 : cell.value < 0))\n if (!agrees) findings.push(`insight-direction:${written.raw.trim()}`)\n }\n return findings\n}\n\n/** The gap sentence a person may read: short, without figures and naming nobody; `null` otherwise. */\nexport function aiInsightGap(gap: unknown): string | null {\n if (typeof gap !== 'string') return null\n const text = gap.replace(/\\s+/g, ' ').trim()\n if (!text || text.length > AI_INSIGHT_GAP_MAX_CHARS || /\\d/.test(text) || MARKUP.test(text)) return null\n return hasPersonalDetails(text) ? null : text\n}\n\n/**\n * An answer held to the trace: the insights that trace kept in the order\n * written, the rest left out with why, and past `AI_INSIGHT_MAX_INSIGHTS`\n * nothing more is read.\n */\nexport function checkAiInsightAnswer(\n answer: Partial<AiInsightAnswer> | null | undefined,\n tables: readonly AiInsightTable[],\n): AiInsightCheck {\n const insights = Array.isArray(answer?.insights) ? answer.insights : []\n const kept: AiInsight[] = []\n const left: AiInsightVerdict[] = []\n const findings: string[] = []\n insights.forEach((insight, index) => {\n const own =\n index >= AI_INSIGHT_MAX_INSIGHTS ? ['insight-too-many'] : checkAiInsight(insight, tables)\n if (own.length) {\n left.push({ insight, findings: own })\n findings.push(...own)\n } else {\n const headline = insightHeadline(insight)\n kept.push({\n ...(headline ? { headline } : {}),\n text: insight.text.trim(),\n cites: insight.cites.slice(0, AI_INSIGHT_MAX_CITES).map((cite) => ({\n table: cite.table,\n rows: cite.rows.slice(0, AI_INSIGHT_MAX_CITED_ROWS),\n })),\n })\n }\n })\n const gap = aiInsightGap(answer?.gap)\n if (answer?.gap && !gap) findings.push('insight-gap-unreadable')\n return { kept, left, gap, findings }\n}\n"],"names":["hasPersonalDetails","AI_INSIGHT_GAP_MAX_CHARS","AI_INSIGHT_HEADLINE_MAX_CHARS","AI_INSIGHT_MAX_CHARS","AI_INSIGHT_MAX_CITED_ROWS","AI_INSIGHT_MAX_CITES","AI_INSIGHT_MAX_INSIGHTS","MARKUP","NUMBER","DURATION","RISING","FALLING","unitOf","symbol","unit","word","toLowerCase","test","aiInsightNumbers","text","found","covered","match","matchAll","hours","Number","seconds","at","index","push","length","value","decimals","negative","raw","some","start","end","whole","replace","sort","a","b","round","scale","Math","truncate","trunc","reads","written","cell","base","abs","scalesFor","kind","framingNumbers","tables","cites","numbers","Set","table","period","add","days","day","from","to","year","month","date","split","map","rows","cite","reduce","total","inLabel","labels","digits","label","RegExp","directionBefore","before","slice","max","words","join","rise","fall","insightHeadline","insight","headline","trim","checkAiInsight","sentences","findings","Array","isArray","every","cells","cited","find","entry","ref","String","row","isInteger","undefined","column","columns","key","isFinite","part","finding","startsWith","framing","matched","filter","framed","has","changes","direction","agrees","aiInsightGap","gap","checkAiInsightAnswer","answer","insights","kept","left","forEach","own"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,QAAQ,6CAA4C;AAC/E,SACEC,wBAAwB,EACxBC,6BAA6B,EAC7BC,oBAAoB,EACpBC,yBAAyB,EACzBC,oBAAoB,EACpBC,uBAAuB,QAKlB,yBAAqB;AAoD5B,MAAMC,SAAS;AAEf;;;CAGC,GACD,MAAMC,SAAS;AAEf,oFAAoF,GACpF,MAAMC,WAAW;AAEjB,MAAMC,SAAS;AACf,MAAMC,UAAU;AAahB,SAASC,OAAOC,MAAc,EAAEC,IAAwB;IACtD,MAAMC,OAAO,CAACD,eAAAA,OAAQ,IAAIE,WAAW;IACrC,IAAID,SAAS,OAAOA,SAAS,WAAW,OAAO;IAC/C,IAAIA,SAAS,OAAOA,SAAS,YAAY,OAAO;IAChD,IAAIA,SAAS,OAAOA,SAAS,WAAW,OAAO;IAC/C,IAAI,yBAAyBE,IAAI,CAACF,OAAO,OAAO;IAChD,IAAI,uBAAuBE,IAAI,CAACF,OAAO,OAAO;IAC9C,IAAI,sBAAsBE,IAAI,CAACF,OAAO,OAAO;IAC7C,OAAOF,SAAS,aAAa;AAC/B;AAEA,0FAA0F,GAC1F,OAAO,SAASK,iBAAiBC,IAAY;IAC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U,CAAA;wBACjEb,OAAOa,KAAKb,KAAK;wBACjBY,MAAMC,KAAKD,IAAI,CAACW,KAAK,CAAC,GAAG/E;oBAC3B,CAAA;;QAEJ;IACF;IACA,MAAMwH,MAAMD,aAAaG,0BAAAA,OAAQF,GAAG;IACpC,IAAIE,CAAAA,0BAAAA,OAAQF,GAAG,KAAI,CAACA,KAAK7B,SAASlE,IAAI,CAAC;IACvC,OAAO;QAAEmG;QAAMC;QAAML;QAAK7B;IAAS;AACrC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/runtime/ai-insight-check.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { hasPersonalDetails } from '@aglyn/aglyn/plugin-manager/plugin-figures'\nimport {\n AI_INSIGHT_CAUSE_READERS,\n AI_INSIGHT_GAP_MAX_CHARS,\n AI_INSIGHT_HEADLINE_MAX_CHARS,\n AI_INSIGHT_MAX_CHARS,\n AI_INSIGHT_MAX_CITED_ROWS,\n AI_INSIGHT_MAX_CITES,\n AI_INSIGHT_MAX_INSIGHTS,\n AI_INSIGHT_NEXT_MAX_CHARS,\n AI_INSIGHT_OVERVIEW_MAX_CHARS,\n AI_INSIGHT_WHY_MAX_CHARS,\n type AiInsight,\n type AiInsightAnswer,\n type AiInsightCitation,\n type AiInsightTable,\n} from '../model/ai-insight'\n\n/**\n * THE TRACE (AGL-2915): whether an insight's words agree with the rows it\n * cites.\n *\n * An insight job hands the model tables that code computed, and the model\n * writes sentences about them. Nothing about a sentence makes it true, so each\n * one is read back against the figures before a person sees it:\n *\n * - it cites at least one row, of a table this job actually read;\n * - every number it writes is a figure in a row it cites — as the table has\n * it, or rounded to the decimals written, in the unit written — or the\n * length of a cited window, a date in it, or a count of the rows cited;\n * - a rise or a fall it names agrees with the sign of the change it quotes;\n * - it names nobody: no email address and no phone number.\n *\n * An insight that fails any of these is LEFT OUT, never repaired: a sentence\n * whose number cannot be found is exactly the sentence a person must not act\n * on, and rewriting it would be the model's guess again. The rest of the\n * answer stands. What is left out is counted, so the console can say so.\n *\n * A digest's overview, and an insight's reason and next step (AGL-4131), are\n * held to the same rows and dropped alone when they fail: the insight stands.\n * A reason must also cite a row of a table that can hold a cause, and a row\n * whose change shows it held steady is not one.\n */\n\n/** Why an insight was left out, as a finding code. */\nexport type AiInsightFinding =\n | 'insight-empty'\n | 'insight-too-long'\n | 'insight-markup'\n | 'insight-personal-details'\n | 'insight-no-citation'\n | 'insight-unknown-table'\n | 'insight-unknown-row'\n | 'insight-number-untraced'\n | 'insight-direction'\n | 'insight-too-many'\n\nexport interface AiInsightVerdict {\n insight: AiInsight\n findings: string[]\n}\n\nexport interface AiInsightCheck {\n /** A digest's read of the week, when it is one a person may read. */\n overview: string | null\n /** The insights a person may read, in the order written. */\n kept: AiInsight[]\n /** The insights left out, each with why. */\n left: AiInsightVerdict[]\n /** The gap sentence, when it is one a person may read. */\n gap: string | null\n /** Every finding, in order, for the eval harness and the logs. */\n findings: string[]\n}\n\nconst MARKUP = /<\\/?[a-z][^>]*>|```|^#{1,6}\\s|\\*\\*/im\n\n/**\n * A number as a sentence writes it: an optional sign and currency symbol, the\n * digits with their thousands separators, the decimals, and a unit.\n */\nconst NUMBER = /(?<![\\p{L}\\p{N}_.])([+\\-−]?)([$€£¥]?)(\\d{1,3}(?:,\\d{3})+|\\d+)(?:\\.(\\d+))?(?:\\s?(%|percent\\b|k\\b|thousand\\b|m\\b|million\\b|seconds?\\b|secs?\\b|s\\b|minutes?\\b|mins?\\b|hours?\\b|hrs?\\b|h\\b))?/giu\n\n/** Minutes and seconds written together (`2m 04s`), read as one figure in seconds. */\nconst DURATION = /(?<![\\p{L}\\p{N}_.])(?:(\\d+)\\s?h(?:ours?|rs?)?\\s+)?(\\d+)\\s?m(?:in(?:utes?)?)?\\s+(\\d{1,2})\\s?s(?:ec(?:onds?)?)?\\b/giu\n\nconst RISING = /\\b(?:rose|rise[sn]?|rising|grew|grow(?:s|n|ing)?|increas(?:e|ed|es|ing)|up|higher|gain(?:ed|s)?|jump(?:ed|s)?|climb(?:ed|s)?|more)\\b/i\nconst FALLING = /\\b(?:fell|fall(?:s|en|ing)?|drop(?:ped|s)?|declin(?:e|ed|es|ing)|decreas(?:e|ed|es|ing)|down|lower|lost|shr[au]nk|less|fewer)\\b/i\n\ninterface WrittenNumber {\n /** The figure as written, unsigned, in the unit's base (a percent, seconds, a plain count). */\n value: number\n decimals: number\n negative: boolean\n unit: 'percent' | 'thousand' | 'million' | 'seconds' | 'minutes' | 'hours' | 'currency' | null\n /** Where in the text it starts, for the words before it. */\n at: number\n raw: string\n}\n\nfunction unitOf(symbol: string, unit: string | undefined): WrittenNumber['unit'] {\n const word = (unit ?? '').toLowerCase()\n if (word === '%' || word === 'percent') return 'percent'\n if (word === 'k' || word === 'thousand') return 'thousand'\n if (word === 'm' || word === 'million') return 'million'\n if (/^(?:seconds?|secs?|s)$/.test(word)) return 'seconds'\n if (/^(?:minutes?|mins?)$/.test(word)) return 'minutes'\n if (/^(?:hours?|hrs?|h)$/.test(word)) return 'hours'\n return symbol ? 'currency' : null\n}\n\n/** Every figure a sentence writes, durations written as minutes and seconds read as one. */\nexport function aiInsightNumbers(text: string): WrittenNumber[] {\n const found: WrittenNumber[] = []\n const covered: Array<[number, number]> = []\n for (const match of text.matchAll(DURATION)) {\n const hours = Number(match[1] ?? 0)\n const seconds = hours * 3_600 + Number(match[2]) * 60 + Number(match[3])\n const at = match.index ?? 0\n covered.push([at, at + match[0].length])\n found.push({ value: seconds, decimals: 0, negative: false, unit: 'seconds', at, raw: match[0] })\n }\n for (const match of text.matchAll(NUMBER)) {\n const at = match.index ?? 0\n if (covered.some(([start, end]) => at >= start && at < end)) continue\n const whole = match[3].replace(/,/g, '')\n const decimals = match[4] ?? ''\n found.push({\n value: Number(decimals ? `${whole}.${decimals}` : whole),\n decimals: decimals.length,\n negative: match[1] === '-' || match[1] === '−',\n unit: unitOf(match[2], match[5]),\n at,\n raw: match[0],\n })\n }\n return found.sort((a, b) => a.at - b.at)\n}\n\nconst round = (value: number, decimals: number) => {\n const scale = 10 ** decimals\n return Math.round(value * scale) / scale\n}\n\nconst truncate = (value: number, decimals: number) => {\n const scale = 10 ** decimals\n return Math.trunc(value * scale) / scale\n}\n\n/** Whether a written figure reads a cell's value, at the decimals written, rounded or cut. */\nfunction reads(written: WrittenNumber, cell: number, scale: number): boolean {\n const base = Math.abs(cell) / scale\n const value = Math.abs(written.value)\n return round(base, written.decimals) === value || truncate(base, written.decimals) === value\n}\n\n/** The scales a unit may read a column's cells at: a percent is not a count, and seconds are not dollars. */\nfunction scalesFor(written: WrittenNumber, kind: AiInsightTable['columns'][number]['kind']): number[] {\n switch (written.unit) {\n case 'percent':\n return kind === 'percent' || kind === 'change' || kind === 'number' ? [1] : []\n case 'currency':\n return kind === 'money' ? [1] : []\n case 'thousand':\n return kind === 'count' || kind === 'number' || kind === 'money' ? [1_000] : []\n case 'million':\n return kind === 'count' || kind === 'number' || kind === 'money'\n ? [1_000_000]\n : kind === 'duration'\n ? [60]\n : []\n case 'seconds':\n return kind === 'duration' ? [1] : []\n case 'minutes':\n return kind === 'duration' ? [60] : []\n case 'hours':\n return kind === 'duration' ? [3_600] : []\n default:\n return kind === 'date' || kind === 'text' ? [] : kind === 'duration' ? [1, 60] : [1]\n }\n}\n\ninterface CitedCell {\n table: AiInsightTable\n kind: AiInsightTable['columns'][number]['kind']\n value: number\n}\n\n/** The numbers a citation vouches for beyond its cells: the window, its dates, and how many rows. */\nfunction framingNumbers(tables: readonly AiInsightTable[], cites: readonly AiInsightCitation[]): Set<number> {\n const numbers = new Set<number>()\n for (const table of tables) {\n if (table.period) {\n numbers.add(table.period.days)\n for (const day of [table.period.from, table.period.to]) {\n const [year, month, date] = day.split('-').map(Number)\n numbers.add(year).add(month).add(date)\n }\n }\n numbers.add(table.rows.length)\n }\n for (const cite of cites) numbers.add(cite.rows.length)\n numbers.add(cites.reduce((total, cite) => total + cite.rows.length, 0))\n return numbers\n}\n\n/** Whether a figure's digits are written inside a cited label: a year in a campaign's name, a path's number. */\nfunction inLabel(written: WrittenNumber, labels: readonly string[]): boolean {\n if (written.unit !== null || written.negative) return false\n const digits = written.raw.replace(/[^\\d.]/g, '')\n return labels.some((label) => new RegExp(`(?<![\\\\d.])${digits.replace('.', '\\\\.')}(?![\\\\d.])`).test(label))\n}\n\n/** The sign the words just before a figure give it, or `null` when they give none. */\nfunction directionBefore(text: string, at: number): 'rise' | 'fall' | null {\n const before = text.slice(Math.max(0, at - 40), at)\n const words = before.split(/\\s+/).slice(-4).join(' ')\n const rise = RISING.test(words)\n const fall = FALLING.test(words)\n if (rise === fall) return null\n return rise ? 'rise' : 'fall'\n}\n\n/**\n * The headline a person may read. One that runs long is only dropped: the\n * insight keeps its sentence, because length says nothing about whether it is\n * true.\n */\nfunction insightHeadline(insight: AiInsight): string {\n const headline = typeof insight?.headline === 'string' ? insight.headline.trim() : ''\n return headline.length <= AI_INSIGHT_HEADLINE_MAX_CHARS ? headline : ''\n}\n\ninterface CitedFigures {\n cells: CitedCell[]\n labels: string[]\n cited: AiInsightTable[]\n findings: string[]\n}\n\n/** The cells and labels a list of citations opens, and any citation that opens nothing. */\nfunction citedFigures(cites: readonly AiInsightCitation[], tables: readonly AiInsightTable[]): CitedFigures {\n const cells: CitedCell[] = []\n const labels: string[] = []\n const cited: AiInsightTable[] = []\n const findings: string[] = []\n for (const cite of cites) {\n const table = tables.find((entry) => entry.ref === cite?.table)\n if (!table) {\n findings.push(`insight-unknown-table:${String(cite?.table)}`)\n continue\n }\n cited.push(table)\n for (const index of (cite.rows ?? []).slice(0, AI_INSIGHT_MAX_CITED_ROWS)) {\n const row = Number.isInteger(index) ? table.rows[index] : undefined\n if (!row) {\n findings.push(`insight-unknown-row:${table.ref}:${String(index)}`)\n continue\n }\n for (const column of table.columns) {\n const value = row[column.key]\n if (typeof value === 'number' && Number.isFinite(value)) {\n cells.push({ table, kind: column.kind, value })\n } else if (typeof value === 'string') {\n labels.push(value)\n if (column.kind === 'date') {\n for (const part of value.split('-').map(Number)) {\n cells.push({ table, kind: 'count', value: part })\n }\n }\n }\n }\n }\n }\n return { cells, labels, cited, findings }\n}\n\n/** What a piece of writing says that the rows it cites do not: a figure they do not hold, or a direction they deny. */\nfunction numberFindings(text: string, cites: readonly AiInsightCitation[], figures: CitedFigures): string[] {\n const { cells, labels, cited } = figures\n const findings: string[] = []\n const framing = framingNumbers(cited, cites)\n for (const written of aiInsightNumbers(text)) {\n const matched = cells.filter((cell) =>\n scalesFor(written, cell.kind).some((scale) => reads(written, cell.value, scale)),\n )\n const framed =\n written.unit === null && written.decimals === 0 && !written.negative && framing.has(written.value)\n if (!matched.length && !framed && !inLabel(written, labels)) {\n findings.push(`insight-number-untraced:${written.raw.trim()}`)\n continue\n }\n // A rise or a fall is checked against the change it quotes, and only then:\n // \"down\" beside a count is not a claim about a sign.\n const changes = matched.filter((cell) => cell.kind === 'change' && cell.value !== 0)\n if (!changes.length || changes.length !== matched.length) continue\n const direction = directionBefore(text, written.at)\n if (!direction) continue\n const agrees = changes.some((cell) => (direction === 'rise' ? cell.value > 0 : cell.value < 0))\n if (!agrees) findings.push(`insight-direction:${written.raw.trim()}`)\n }\n return findings\n}\n\nconst insightCites = (insight: AiInsight): AiInsightCitation[] =>\n Array.isArray(insight.cites) ? insight.cites.slice(0, AI_INSIGHT_MAX_CITES) : []\n\n/** One insight's findings against the tables the job read; empty when it traces. */\nexport function checkAiInsight(insight: AiInsight, tables: readonly AiInsightTable[]): string[] {\n const sentences = typeof insight?.text === 'string' ? insight.text.trim() : ''\n if (!sentences) return ['insight-empty']\n const findings: string[] = []\n if (sentences.length > AI_INSIGHT_MAX_CHARS) findings.push('insight-too-long')\n // The headline is held to everything the sentence is: it is the part a\n // person reads first, and often the only part.\n const headline = insightHeadline(insight)\n const text = headline ? `${headline}. ${sentences}` : sentences\n if (MARKUP.test(text)) findings.push('insight-markup')\n if (hasPersonalDetails(text)) findings.push('insight-personal-details')\n\n const cites = insightCites(insight)\n if (!cites.length || cites.every((cite) => !Array.isArray(cite?.rows) || !cite.rows.length)) {\n return [...findings, 'insight-no-citation']\n }\n const figures = citedFigures(cites, tables)\n findings.push(...figures.findings)\n if (findings.some((finding) => finding.startsWith('insight-unknown-'))) return findings\n return [...findings, ...numberFindings(text, cites, figures)]\n}\n\n/**\n * A line beside the insights, held to everything an insight is, or `''` with\n * why. It is only dropped: a reason or a next step that cannot be kept says\n * nothing about whether the figures are true (AGL-4131).\n */\nfunction checkedLine(\n value: unknown,\n name: string,\n maxChars: number,\n cites: readonly AiInsightCitation[],\n tables: readonly AiInsightTable[],\n): { line: string; findings: string[] } {\n const line = typeof value === 'string' ? value.replace(/\\s+/g, ' ').trim() : ''\n if (!line) return { line: '', findings: [] }\n const refused = [\n ...(line.length > maxChars ? [`insight-${name}-too-long`] : []),\n ...(MARKUP.test(line) ? [`insight-${name}-markup`] : []),\n ...(hasPersonalDetails(line) ? [`insight-${name}-personal-details`] : []),\n ...numberFindings(line, cites, citedFigures(cites, tables)),\n ]\n return refused.length ? { line: '', findings: refused } : { line, findings: [] }\n}\n\n/**\n * Whether an insight cites a row a reason can rest on: a row of a table that\n * can hold a cause, and one that moved. A source or campaign whose change is 0\n * sent the same traffic as the week before, so it cannot explain a move; a\n * dated change has no change column and always can.\n */\nfunction citesACause(cites: readonly AiInsightCitation[], tables: readonly AiInsightTable[]): boolean {\n return cites.some((cite) => {\n const table = tables.find((candidate) => candidate.ref === cite.table)\n if (!table || !AI_INSIGHT_CAUSE_READERS.includes(table.reader)) return false\n return cite.rows.some((index) => {\n const row = table.rows[index]\n return Boolean(row) && row.change !== 0\n })\n })\n}\n\n/** A next step that promises what it would do is left out: nothing here can know. */\nconst PROMISE = /\\b(?:guarantee[sd]?|sure to|will (?:increase|boost|double|grow|raise|improve|bring|get you|rank))\\b/i\n\n/** The gap sentence a person may read: short, without figures and naming nobody; `null` otherwise. */\nexport function aiInsightGap(gap: unknown): string | null {\n if (typeof gap !== 'string') return null\n const text = gap.replace(/\\s+/g, ' ').trim()\n if (!text || text.length > AI_INSIGHT_GAP_MAX_CHARS || /\\d/.test(text) || MARKUP.test(text)) return null\n return hasPersonalDetails(text) ? null : text\n}\n\n/**\n * An answer held to the trace: the insights that trace kept in the order\n * written, the rest left out with why, and past `AI_INSIGHT_MAX_INSIGHTS`\n * nothing more is read.\n */\nexport function checkAiInsightAnswer(\n answer: Partial<AiInsightAnswer> | null | undefined,\n tables: readonly AiInsightTable[],\n): AiInsightCheck {\n const insights = Array.isArray(answer?.insights) ? answer.insights : []\n const kept: AiInsight[] = []\n const left: AiInsightVerdict[] = []\n const findings: string[] = []\n insights.forEach((insight, index) => {\n const own =\n index >= AI_INSIGHT_MAX_INSIGHTS ? ['insight-too-many'] : checkAiInsight(insight, tables)\n if (own.length) {\n left.push({ insight, findings: own })\n findings.push(...own)\n } else {\n const headline = insightHeadline(insight)\n const cites = insightCites(insight).map((cite) => ({\n table: cite.table,\n rows: cite.rows.slice(0, AI_INSIGHT_MAX_CITED_ROWS),\n }))\n const why = checkedLine(insight.why, 'why', AI_INSIGHT_WHY_MAX_CHARS, cites, tables)\n const reasoned = why.line && citesACause(cites, tables)\n if (why.line && !reasoned) findings.push('insight-why-no-cause')\n const next = checkedLine(insight.next, 'next', AI_INSIGHT_NEXT_MAX_CHARS, cites, tables)\n const promised = PROMISE.test(next.line)\n if (promised) findings.push('insight-next-promise')\n findings.push(...why.findings, ...next.findings)\n kept.push({\n ...(headline ? { headline } : {}),\n text: insight.text.trim(),\n ...(reasoned ? { why: why.line } : {}),\n ...(next.line && !promised ? { next: next.line } : {}),\n cites,\n })\n }\n })\n const gap = aiInsightGap(answer?.gap)\n if (answer?.gap && !gap) findings.push('insight-gap-unreadable')\n // Held to the rows the kept insights cite: it has no citations of its own,\n // and a figure in it should be one a reader can open just below it.\n const overview = checkedLine(\n answer?.overview,\n 'overview',\n AI_INSIGHT_OVERVIEW_MAX_CHARS,\n kept.flatMap((insight) => insight.cites),\n tables,\n )\n findings.push(...overview.findings)\n return { overview: overview.line || null, kept, left, gap, findings }\n}\n"],"names":["hasPersonalDetails","AI_INSIGHT_CAUSE_READERS","AI_INSIGHT_GAP_MAX_CHARS","AI_INSIGHT_HEADLINE_MAX_CHARS","AI_INSIGHT_MAX_CHARS","AI_INSIGHT_MAX_CITED_ROWS","AI_INSIGHT_MAX_CITES","AI_INSIGHT_MAX_INSIGHTS","AI_INSIGHT_NEXT_MAX_CHARS","AI_INSIGHT_OVERVIEW_MAX_CHARS","AI_INSIGHT_WHY_MAX_CHARS","MARKUP","NUMBER","DURATION","RISING","FALLING","unitOf","symbol","unit","word","toLowerCase","test","aiInsightNumbers","text","found","covered","match","matchAll","hours","Number","seconds","at","index","push","length","value","decimals","negative","raw","some","start","end","whole","replace","sort","a","b","round","scale","Math","truncate","trunc","reads","written","cell","base","abs","scalesFor","kind","framingNumbers","tables","cites","numbers","Set","table","period","add","days","day","from","to","year","month","date","split","map","rows","cite","reduce","total","inLabel","labels","digits","label","RegExp","directionBefore","before","slice","max","words","join","rise","fall","insightHeadline","insight","headline","trim","citedFigures","cells","cited","findings","find","entry","ref","String","row","isInteger","undefined","column","columns","key","isFinite","part","numberFindings","figures","framing","matched","filter","framed","has","changes","direction","agrees","insightCites","Array","isArray","checkAiInsight","sentences","every","finding","startsWith","checkedLine","name","maxChars","line","refused","citesACause","candidate","includes","reader","Boolean","change","PROMISE","aiInsightGap","gap","checkAiInsightAnswer","answer","insights","kept","left","forEach","own","why","reasoned","next","promised","overview","flatMap"],"mappings":";AAAA;;;;;;;;;;;;;;;C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CAPABILITIES, AI_PALETTE, AI_SURFACES, AI_SX_TOKENS } from "./a
|
|
|
21
21
|
import { linealRelationshipPermits } from "@aglyn/aglyn/app-utils/lineal-order";
|
|
22
22
|
import { NODE_MAP_MAX_BYTES, nodeMapBytes } from "@aglyn/aglyn/app-utils/measure-node-map";
|
|
23
23
|
import { parseMediaRef } from "@aglyn/aglyn/app-utils/media-ref";
|
|
24
|
+
import { ELEMENT_HIDDEN_CLASS } from "@aglyn/aglyn/app-utils/element-hidden-style";
|
|
24
25
|
import { SX_SCHEME_DARK_KEY } from "@aglyn/aglyn/app-utils/scheme-sx";
|
|
25
26
|
import { COMPONENT_PROP_NAME_PATTERN, REUSABLE_INSTANCE_COMPONENT_ID, REUSABLE_INSTANCE_PROP_VALUES_KEY } from "@aglyn/aglyn/app-utils/reusable-component-keys";
|
|
26
27
|
import { createIdUrlSafe } from "@aglyn/aglyn/foundation/constants/app";
|
|
@@ -777,9 +778,22 @@ function validate(input, surface, context) {
|
|
|
777
778
|
const boundByNodeId = new Map();
|
|
778
779
|
// A code-built Icon's drawing, from the library by the id it names (AGL-3660).
|
|
779
780
|
const iconByNodeId = new Map();
|
|
781
|
+
// A code-built element that starts hidden until an interaction shows it
|
|
782
|
+
// (AGL-4139): the Besigner's own setting, that one class and no other.
|
|
783
|
+
const startsHidden = new Set();
|
|
780
784
|
const forSanitizer = {};
|
|
781
|
-
for (const [id,
|
|
785
|
+
for (const [id, raw] of Object.entries(nodes)){
|
|
782
786
|
var _ref1;
|
|
787
|
+
let node = raw;
|
|
788
|
+
if (codeBuilt && isRecord(node) && isRecord(node.props) && node.props['className'] === ELEMENT_HIDDEN_CLASS) {
|
|
789
|
+
const _node_props = node.props, { className: _hidden } = _node_props, props = _object_without_properties_loose(_node_props, [
|
|
790
|
+
"className"
|
|
791
|
+
]);
|
|
792
|
+
startsHidden.add(id);
|
|
793
|
+
node = _extends({}, node, {
|
|
794
|
+
props
|
|
795
|
+
});
|
|
796
|
+
}
|
|
783
797
|
if (!isRecord(node) || !isRecord(node.props)) {
|
|
784
798
|
forSanitizer[id] = node;
|
|
785
799
|
continue;
|
|
@@ -915,6 +929,7 @@ function validate(input, surface, context) {
|
|
|
915
929
|
for (const key of Object.keys(raw.props)){
|
|
916
930
|
var _node_props;
|
|
917
931
|
if (iconByNodeId.has(id) && (key === 'iconId' || key === 'iconPath')) continue;
|
|
932
|
+
if (startsHidden.has(id) && key === 'className') continue;
|
|
918
933
|
if (key !== 'sx' && lifted[key] === undefined && kept[key] === undefined && ((_node_props = node.props) == null ? void 0 : _node_props[key]) === undefined && raw.props[key] !== undefined) {
|
|
919
934
|
repairs.push(`${id}.${key} was an unsafe handler, address or markup; dropped`);
|
|
920
935
|
}
|
|
@@ -1010,7 +1025,9 @@ function validate(input, surface, context) {
|
|
|
1010
1025
|
pluginId: entry.pluginId,
|
|
1011
1026
|
parentId,
|
|
1012
1027
|
nodes: children,
|
|
1013
|
-
props: _extends({}, propsResult.props, reference.kept, boundProps, iconByNodeId.get(id))
|
|
1028
|
+
props: _extends({}, propsResult.props, reference.kept, boundProps, iconByNodeId.get(id), startsHidden.has(id) ? {
|
|
1029
|
+
className: ELEMENT_HIDDEN_CLASS
|
|
1030
|
+
} : {})
|
|
1014
1031
|
}, sx ? {
|
|
1015
1032
|
sx
|
|
1016
1033
|
} : {}, hiddenByNodeId.has(id) ? {
|