@vectoriox/iox-ui 5.110.0 → 5.112.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.
@@ -0,0 +1,178 @@
1
+ import { AssistIssue, AssistIssueCode, HandleMap, resolveHandle } from './brief';
2
+ import { AssistField, AssistFieldKind, assistFields, ContentTypeSchema } from './content-fields';
3
+ import { BOOLEAN_FALSE, BOOLEAN_TRUE, FieldEdit } from './fields-schema';
4
+ import { BriefValue, isPlainRecord, readFieldValue } from './field-values';
5
+ import { containsHtml, paragraphsToRichText } from './rich-text';
6
+ import { ContentRecord } from './summarize-item';
7
+
8
+ /**
9
+ * Family `fields`, applied (plan §3c rule 6): the SAME pure check runs on the server (on a copy, before the turn is
10
+ * shown) and in the client (the trial in the form). All or none — one refused edit refuses the turn, which is re-asked
11
+ * once with the issues, never repaired in code. Never mutates its input.
12
+ * - a handle maps back through the brief's map; an unknown one is refused (T1);
13
+ * - a never-written field, a wrong type, a choice outside the options, markup in a text: refused;
14
+ * - a multiLang field gets ONE locale key, the others kept (T5);
15
+ * - rich text is stored as escaped `<p>` paragraphs; the change carries the paragraphs (T6);
16
+ * - a field the owner edited since the last turn is KEPT unless the sentence names it (rule 9);
17
+ * - an edit that changes nothing is dropped.
18
+ */
19
+
20
+ export interface FieldEditContext {
21
+ readonly schema: ContentTypeSchema;
22
+ readonly handles: HandleMap;
23
+ /** The locale a multiLang field is written in. */
24
+ readonly locale: string;
25
+ /** Fields (keys or handles) the owner changed since the last AI turn. */
26
+ readonly ownerEdited?: ReadonlyArray<string>;
27
+ /** Fields (keys or handles) the sentence names. Default: read from `sentence` by `fieldsNamedIn`. */
28
+ readonly named?: ReadonlyArray<string>;
29
+ readonly sentence?: string;
30
+ }
31
+
32
+ export interface FieldChange {
33
+ readonly handle: string;
34
+ readonly key: string;
35
+ readonly label: string;
36
+ readonly kind: AssistFieldKind;
37
+ /** Readable: text, paragraphs, a number, yes/no, options, words. */
38
+ readonly before: BriefValue;
39
+ readonly after: BriefValue;
40
+ readonly locale?: string;
41
+ }
42
+
43
+ export interface FieldEditsOutcome {
44
+ readonly ok: boolean;
45
+ /** The record with every change applied (stored form) — a copy of the input when refused. */
46
+ readonly result: ContentRecord;
47
+ readonly changes: ReadonlyArray<FieldChange>;
48
+ /** Proposed, but the owner edited the field since and the sentence did not name it. */
49
+ readonly kept: ReadonlyArray<FieldChange>;
50
+ readonly issues: ReadonlyArray<AssistIssue>;
51
+ }
52
+
53
+ type Coerced = { ok: true; stored: unknown; readable: BriefValue } | { ok: false; code: AssistIssueCode; message: string };
54
+
55
+ const refuse = (code: AssistIssueCode, message: string): Coerced => ({ ok: false, code, message });
56
+ const wrongType = (what: string) => refuse(AssistIssueCode.WrongType, `expected ${what}`);
57
+ const fine = (stored: unknown, readable: BriefValue = stored as BriefValue): Coerced => ({ ok: true, stored, readable });
58
+
59
+ function coerceText(value: unknown): Coerced {
60
+ if (typeof value !== 'string' || !value.trim()) return wrongType('a non-empty text');
61
+ if (containsHtml(value)) return refuse(AssistIssueCode.HtmlNotAllowed, 'markup is not written by Assist');
62
+ return fine(value.trim());
63
+ }
64
+
65
+ function coerceWords(value: unknown): { words: string[] } | Coerced {
66
+ if (!Array.isArray(value) || value.some(v => typeof v !== 'string')) return wrongType('a list of texts');
67
+ const words = [...new Set((value as string[]).map(v => v.trim()).filter(Boolean))];
68
+ if (!words.length) return wrongType('at least one text');
69
+ if (words.some(containsHtml)) return refuse(AssistIssueCode.HtmlNotAllowed, 'markup is not written by Assist');
70
+ return { words };
71
+ }
72
+
73
+ function coerceNumber(value: unknown): Coerced {
74
+ const n = typeof value === 'number' ? value : typeof value === 'string' && value.trim() !== '' ? Number(value.trim()) : NaN;
75
+ return Number.isFinite(n) ? fine(n) : wrongType('a number');
76
+ }
77
+
78
+ function coerceBoolean(value: unknown): Coerced {
79
+ if (typeof value === 'boolean') return fine(value);
80
+ if (value === BOOLEAN_TRUE || value === BOOLEAN_FALSE) return fine(value === BOOLEAN_TRUE);
81
+ return wrongType('yes or no');
82
+ }
83
+
84
+ function coerceChoice(field: AssistField, value: unknown): Coerced {
85
+ if (typeof value !== 'string') return wrongType('one of the options');
86
+ return field.options?.includes(value) ? fine(value) : refuse(AssistIssueCode.NotAnOption, `"${value}" is not an option of ${field.label}`);
87
+ }
88
+
89
+ function coerceList(field: AssistField, value: unknown): Coerced {
90
+ const read = coerceWords(value);
91
+ if (!('words' in read)) return read;
92
+ if (field.kind === AssistFieldKind.Choices) {
93
+ const outside = read.words.filter(w => !field.options?.includes(w));
94
+ if (outside.length) return refuse(AssistIssueCode.NotAnOption, `${outside.map(w => `"${w}"`).join(', ')} not an option of ${field.label}`);
95
+ }
96
+ return fine(read.words);
97
+ }
98
+
99
+ function coerceRichText(value: unknown): Coerced {
100
+ const read = coerceWords(value);
101
+ if (!('words' in read)) return read;
102
+ return fine(paragraphsToRichText(read.words), read.words);
103
+ }
104
+
105
+ function coerce(field: AssistField, value: unknown): Coerced {
106
+ switch (field.kind) {
107
+ case AssistFieldKind.RichText: return coerceRichText(value);
108
+ case AssistFieldKind.Number: return coerceNumber(value);
109
+ case AssistFieldKind.Boolean: return coerceBoolean(value);
110
+ case AssistFieldKind.Choice: return coerceChoice(field, value);
111
+ case AssistFieldKind.Choices:
112
+ case AssistFieldKind.Tags: return coerceList(field, value);
113
+ default: return coerceText(value);
114
+ }
115
+ }
116
+
117
+ const NAME_MIN_CHARS = 3;
118
+
119
+ /** The fields a sentence names by label, key or handle (case-insensitive) — rule 9's "unless the sentence names it". */
120
+ export function fieldsNamedIn(sentence: string, fields: ReadonlyArray<AssistField>): string[] {
121
+ const s = sentence.toLowerCase();
122
+ if (!s.trim()) return [];
123
+ return fields.filter(f => [f.label, f.key, f.handle].some(n => n.length >= NAME_MIN_CHARS && s.includes(n.toLowerCase()))).map(f => f.key);
124
+ }
125
+
126
+ const names = (list: ReadonlyArray<string> | undefined, fields: ReadonlyArray<AssistField>): Set<string> =>
127
+ new Set((list ?? []).map(n => fields.find(f => f.key === n || f.handle === n)?.key ?? n));
128
+
129
+ interface Planned {
130
+ field: AssistField;
131
+ stored: unknown;
132
+ change: FieldChange;
133
+ }
134
+
135
+ function plan(field: AssistField, handle: string, values: ContentRecord, coerced: { stored: unknown; readable: BriefValue }, locale: string): Planned | null {
136
+ const raw = values[field.key];
137
+ const own = field.locales ? (isPlainRecord(raw) ? raw : {}) : null;
138
+ const before = readFieldValue(field.kind, own ? own[locale] : raw);
139
+ if (JSON.stringify(before) === JSON.stringify(coerced.readable)) return null;
140
+ const stored = own ? { ...own, [locale]: coerced.stored } : coerced.stored;
141
+ const change: FieldChange = {
142
+ handle, key: field.key, label: field.label, kind: field.kind, before, after: coerced.readable, ...(own ? { locale } : {}),
143
+ };
144
+ return { field, stored, change };
145
+ }
146
+
147
+ export function applyFieldEdits(values: ContentRecord, edits: ReadonlyArray<FieldEdit>, ctx: FieldEditContext): FieldEditsOutcome {
148
+ const fields = assistFields(ctx.schema);
149
+ const issues: AssistIssue[] = [];
150
+ const planned: Planned[] = [];
151
+ const seen = new Set<string>();
152
+ const issue = (code: AssistIssueCode, handle: string, message: string) => issues.push({ code, handle, message });
153
+
154
+ for (const edit of edits) {
155
+ const resolved = resolveHandle(ctx.handles, edit.handle);
156
+ if ('issue' in resolved) { issues.push(resolved.issue); continue; }
157
+ const field = fields.find(f => f.key === resolved.target.key);
158
+ if (!field) { issue(AssistIssueCode.UnknownHandle, edit.handle, `"${edit.handle}" is not a field of ${ctx.schema.name}`); continue; }
159
+ if (seen.has(field.key)) { issue(AssistIssueCode.Duplicate, edit.handle, `${field.label} is written twice`); continue; }
160
+ seen.add(field.key);
161
+ if (field.never) { issue(AssistIssueCode.NeverWrite, edit.handle, `${field.label} is never written by Assist (${field.never})`); continue; }
162
+ if (field.locales && !field.locales.includes(ctx.locale)) { issue(AssistIssueCode.WrongLocale, edit.handle, `${field.label} has no ${ctx.locale}`); continue; }
163
+ const coerced = coerce(field, edit.value);
164
+ if ('code' in coerced) { issue(coerced.code, edit.handle, `${field.label}: ${coerced.message}`); continue; }
165
+ const p = plan(field, edit.handle, values, coerced, ctx.locale);
166
+ if (p) planned.push(p);
167
+ }
168
+
169
+ if (issues.length) return { ok: false, result: { ...values }, changes: [], kept: [], issues };
170
+
171
+ const edited = names(ctx.ownerEdited, fields);
172
+ const named = names(ctx.named ?? fieldsNamedIn(ctx.sentence ?? '', fields), fields);
173
+ const isKept = (p: Planned) => edited.has(p.field.key) && !named.has(p.field.key);
174
+ const applied = planned.filter(p => !isKept(p));
175
+ const result: Record<string, unknown> = { ...values };
176
+ for (const p of applied) result[p.field.key] = p.stored;
177
+ return { ok: true, result, changes: applied.map(p => p.change), kept: planned.filter(isKept).map(p => p.change), issues: [] };
178
+ }
@@ -0,0 +1,42 @@
1
+ import { AssistFieldKind } from './content-fields';
2
+ import { richTextParagraphs } from './rich-text';
3
+
4
+ /** A field's value as the model reads it: text, paragraphs, a number, yes/no, options, words, or per locale. */
5
+ export type BriefValue = string | number | boolean | ReadonlyArray<string> | Readonly<Record<string, string | ReadonlyArray<string>>> | null;
6
+
7
+ const LIST_KINDS: ReadonlySet<AssistFieldKind> = new Set([AssistFieldKind.Choices, AssistFieldKind.Tags]);
8
+
9
+ export const isPlainRecord = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
10
+ const asStrings = (v: unknown): string[] => (Array.isArray(v) ? v.filter(x => x !== null && x !== undefined && x !== '').map(String) : []);
11
+
12
+ function readNumber(raw: unknown): number | null {
13
+ if (typeof raw === 'number') return Number.isFinite(raw) ? raw : null;
14
+ if (typeof raw !== 'string' || raw.trim() === '') return null;
15
+ const n = Number(raw);
16
+ return Number.isFinite(n) ? n : null;
17
+ }
18
+
19
+ /** One stored value (a plain field, or one locale of a multiLang field) in its kind's readable form. */
20
+ export function readFieldValue(kind: AssistFieldKind, raw: unknown): BriefValue {
21
+ if (raw === undefined || raw === null) return null;
22
+ if (kind === AssistFieldKind.RichText) return richTextParagraphs(raw);
23
+ if (LIST_KINDS.has(kind)) return asStrings(raw);
24
+ if (kind === AssistFieldKind.Number) return readNumber(raw);
25
+ if (kind === AssistFieldKind.Boolean) return !!raw;
26
+ return typeof raw === 'string' ? raw : String(raw);
27
+ }
28
+
29
+ export function isEmptyFieldValue(v: unknown): boolean {
30
+ if (v === null || v === undefined) return true;
31
+ if (typeof v === 'string') return v.trim() === '';
32
+ if (Array.isArray(v)) return v.length === 0;
33
+ if (isPlainRecord(v)) return Object.values(v).every(isEmptyFieldValue);
34
+ return false;
35
+ }
36
+
37
+ /** A multiLang value's locales, each read in the field's kind. */
38
+ export function readLocaleValues(kind: AssistFieldKind, locales: ReadonlyArray<string>, raw: unknown): Record<string, BriefValue> {
39
+ const values = isPlainRecord(raw) ? raw : {};
40
+ return Object.fromEntries(locales.map(l => [l, readFieldValue(kind, values[l])]));
41
+ }
42
+
@@ -0,0 +1,117 @@
1
+ import { jsonClosedObject, jsonListOf, jsonOneOf, JsonSchema, jsonText } from '@vectoriox/iox-ui/generation-core';
2
+
3
+ import { assertAssistBudget, MAX_ASSIST_PROPERTIES } from './budget';
4
+ import { AssistBriefError, AssistIssueCode } from './brief';
5
+ import { AssistField, AssistFieldKind, assistFields, ContentTypeSchema, isWritable } from './content-fields';
6
+
7
+ /**
8
+ * The strict output format of family `fields` for one content type (plan §3b): one property per WRITABLE field, keyed
9
+ * by its handle, every key required, every object closed. "Leave it as it is" is the kind's NONE value — `''` for a
10
+ * text, a number (written in digits), a yes/no or a choice, `[]` for paragraphs and lists — never `null`: the house
11
+ * budget allows 8 unions a request, so nullable fields would cap a part at 8 fields; the house wire (plan-edits) uses
12
+ * the same "every key required, each with its none". So Assist never EMPTIES a field — clearing one is the owner's.
13
+ * Rich text is a list of plain paragraphs (trap T6); a multiLang field is written in ONE locale (trap T5). A type with
14
+ * more writable fields than one request holds is split into parts, each ≤ 40 properties (trap T7 — never raised).
15
+ */
16
+
17
+ export enum FieldsAnswerKey {
18
+ Fields = 'fields',
19
+ Note = 'note',
20
+ }
21
+
22
+ /** The answer object's own keys, beside the fields. */
23
+ const PART_OWN_PROPERTIES = Object.keys(FieldsAnswerKey).length;
24
+
25
+ /** How many fields one request carries. */
26
+ export const FIELDS_PER_PART = MAX_ASSIST_PROPERTIES - PART_OWN_PROPERTIES;
27
+
28
+ export const NONE_TEXT = '';
29
+ export const BOOLEAN_TRUE = 'true';
30
+ export const BOOLEAN_FALSE = 'false';
31
+
32
+ export interface FieldsSchemaOptions {
33
+ /** The locale a multiLang field is written in. */
34
+ readonly locale: string;
35
+ /** Only these fields (keys or handles) — the focus. Default: every writable field. */
36
+ readonly fields?: ReadonlyArray<string>;
37
+ }
38
+
39
+ export interface FieldsSchemas {
40
+ /** One strict format per request. Empty when nothing is writable. */
41
+ readonly parts: JsonSchema[];
42
+ /** Per part, the handles it carries. */
43
+ readonly handles: string[][];
44
+ }
45
+
46
+ const LEAVE_TEXT = `'' leaves it as it is`;
47
+ const LEAVE_LIST = '[] leaves it as it is';
48
+
49
+ function kindSchema(field: AssistField): { schema: JsonSchema; says: string } {
50
+ const options = [...(field.options ?? [])];
51
+ switch (field.kind) {
52
+ case AssistFieldKind.RichText: return { schema: jsonListOf(jsonText()), says: `paragraphs of plain text, no markup; ${LEAVE_LIST}` };
53
+ case AssistFieldKind.Number: return { schema: jsonText(), says: `a number in digits; ${LEAVE_TEXT}` };
54
+ case AssistFieldKind.Boolean: return { schema: jsonOneOf([NONE_TEXT, BOOLEAN_TRUE, BOOLEAN_FALSE]), says: `yes or no; ${LEAVE_TEXT}` };
55
+ case AssistFieldKind.Choice: return { schema: jsonOneOf([NONE_TEXT, ...options]), says: `one of its options; ${LEAVE_TEXT}` };
56
+ case AssistFieldKind.Choices: return { schema: jsonListOf(jsonOneOf(options)), says: `some of its options; ${LEAVE_LIST}` };
57
+ case AssistFieldKind.Tags: return { schema: jsonListOf(jsonText()), says: `a list of short words; ${LEAVE_LIST}` };
58
+ case AssistFieldKind.Textarea: return { schema: jsonText(), says: `plain text, may run several sentences; ${LEAVE_TEXT}` };
59
+ default: return { schema: jsonText(), says: `one line of plain text; ${LEAVE_TEXT}` };
60
+ }
61
+ }
62
+
63
+ function fieldSchema(field: AssistField, locale: string): JsonSchema {
64
+ const { schema, says } = kindSchema(field);
65
+ const inLocale = field.locales ? ` Written in ${locale} only.` : '';
66
+ return { ...schema, description: `${field.label}${field.required ? ' (required)' : ''} — ${says}.${inLocale}` };
67
+ }
68
+
69
+ function chosen(all: ReadonlyArray<AssistField>, wanted: ReadonlyArray<string> | undefined): AssistField[] {
70
+ if (!wanted) return all.filter(isWritable);
71
+ return wanted.map(w => {
72
+ const f = all.find(x => x.key === w || x.handle === w);
73
+ if (!f) throw new AssistBriefError(AssistIssueCode.UnknownHandle, `"${w}" is not a field of this type`);
74
+ return f;
75
+ }).filter(isWritable);
76
+ }
77
+
78
+ /** Splits n fields into the fewest parts that fit, as even as they come. */
79
+ function split<T>(list: ReadonlyArray<T>, max: number): T[][] {
80
+ if (!list.length) return [];
81
+ const count = Math.ceil(list.length / max);
82
+ const size = Math.ceil(list.length / count);
83
+ return Array.from({ length: count }, (_, i) => list.slice(i * size, (i + 1) * size));
84
+ }
85
+
86
+ function partSchema(fields: ReadonlyArray<AssistField>, locale: string, part: number, of: number): JsonSchema {
87
+ const properties = Object.fromEntries(fields.map(f => [f.handle, fieldSchema(f, locale)]));
88
+ const which = of > 1 ? ` (part ${part + 1} of ${of})` : '';
89
+ return jsonClosedObject({
90
+ [FieldsAnswerKey.Fields]: jsonClosedObject(properties, fields.map(f => f.handle), `Per field${which}: its new value, or its leave value.`),
91
+ [FieldsAnswerKey.Note]: { ...jsonText(), description: 'One short line for the owner on what changed, or what needs them.' },
92
+ }, Object.values(FieldsAnswerKey));
93
+ }
94
+
95
+ export function fieldsJsonSchema(schema: ContentTypeSchema, options: FieldsSchemaOptions): FieldsSchemas {
96
+ const groups = split(chosen(assistFields(schema), options.fields), FIELDS_PER_PART);
97
+ const parts = groups.map((g, i) => partSchema(g, options.locale, i, groups.length));
98
+ parts.forEach((p, i) => assertAssistBudget(`fields ${schema.name} part ${i + 1}`, [p]));
99
+ return { parts, handles: groups.map(g => g.map(f => f.handle)) };
100
+ }
101
+
102
+ /** One field's answer as the model wrote it. */
103
+ export interface FieldEdit {
104
+ readonly handle: string;
105
+ readonly value: unknown;
106
+ }
107
+
108
+ const isLeave = (v: unknown) => v === null || v === undefined || v === NONE_TEXT || (Array.isArray(v) && v.length === 0);
109
+
110
+ /** The parts' answers → the edits they make (every leave value dropped). */
111
+ export function decodeFieldsAnswers(answers: ReadonlyArray<unknown>): FieldEdit[] {
112
+ return answers.flatMap(answer => {
113
+ const fields = answer && typeof answer === 'object' ? (answer as Record<string, unknown>)[FieldsAnswerKey.Fields] : undefined;
114
+ if (!fields || typeof fields !== 'object' || Array.isArray(fields)) return [];
115
+ return Object.entries(fields as Record<string, unknown>).filter(([, v]) => !isLeave(v)).map(([handle, value]) => ({ handle, value }));
116
+ });
117
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * @vectoriox/iox-ui/assist-core — the shared, FRAMEWORK-FREE vocabulary of AI Assist (iox-ai-guidance
3
+ * `architecture/ai/ai-assist-plan.md` §3b): the surfaces and their specs, the brief and its handle map, the route
4
+ * request, and family `fields` for surface S2 (one content item) — its brief (`summarizeItem`), its strict output format
5
+ * (`fieldsJsonSchema`) and the ONE check that applies an answer (`applyFieldEdits`), run by iox-cms on a copy and by
6
+ * cms-client as the trial. Pure: no transport, no clock, no randomness.
7
+ * ⚠️ Not re-exported from the main entry. Consumers wire the usual trio — ng-package raw-ts assets, jest
8
+ * moduleNameMapper, tsconfig paths — or `nest start` dies with ERR_REQUIRE_ESM. It imports generation-core (the strict
9
+ * schema builders and budget), so a consumer maps both.
10
+ * TODO(after the 2026-11-19 demo): extract the fact gate `factIssues` out of generation-core's `planWordIssues` into
11
+ * this entry (plan §3b, R-H2) — `planWordIssues` becomes its caller; deferred because it edits generation-core.
12
+ */
13
+ export * from './surfaces';
14
+ export * from './budget';
15
+ export * from './brief';
16
+ export * from './content-fields';
17
+ export * from './rich-text';
18
+ export * from './field-values';
19
+ export * from './summarize-item';
20
+ export * from './fields-schema';
21
+ export * from './route-schema';
22
+ export * from './field-edits';
23
+ export * from './assist-turn';
24
+ export * from './assist-locale';
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Rich text crosses the model boundary as PLAIN PARAGRAPHS in both directions (trap T6): the brief reads the stored
3
+ * value (the item editor's Quill writes HTML) as paragraphs, and an answer's paragraphs become HTML only here, every
4
+ * character escaped — the model never writes markup that reaches a page.
5
+ */
6
+
7
+ const BLOCK_END = /<\/(p|div|h[1-6]|li|blockquote|pre)>|<br\s*\/?>/gi;
8
+ const TAG = /<[^>]*>/g;
9
+ const HTML_TAG = /<\/?[a-z][a-z0-9-]*(\s[^<>]*)?\/?>/i;
10
+
11
+ const ENTITIES: Readonly<Record<string, string>> = { '&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&#39;': "'", '&nbsp;': ' ' };
12
+ const ESCAPES: Readonly<Record<string, string>> = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
13
+
14
+ const decode = (text: string) => text.replace(/&(amp|lt|gt|quot|#39|nbsp);/g, e => ENTITIES[e] ?? e);
15
+ const escape = (text: string) => text.replace(/[&<>"']/g, c => ESCAPES[c]);
16
+
17
+ /** A stored rich-text value (HTML, or plain text) as its non-empty paragraphs. */
18
+ export function richTextParagraphs(value: unknown): string[] {
19
+ if (typeof value !== 'string') return [];
20
+ return decode(value.replace(BLOCK_END, '\n').replace(TAG, ''))
21
+ .split(/\n+/)
22
+ .map(p => p.replace(/\s+/g, ' ').trim())
23
+ .filter(Boolean);
24
+ }
25
+
26
+ /** Paragraphs as the editor's HTML: one `<p>` each, escaped. */
27
+ export function paragraphsToRichText(paragraphs: ReadonlyArray<string>): string {
28
+ return paragraphs.map(p => `<p>${escape(p.trim())}</p>`).join('');
29
+ }
30
+
31
+ /** True when a text written by the model carries markup — refused, never stripped. */
32
+ export const containsHtml = (text: string): boolean => HTML_TAG.test(text);
@@ -0,0 +1,49 @@
1
+ import { jsonAnyOf, jsonClosedObject, jsonListOf, jsonOneOf, JsonSchema, jsonText } from '@vectoriox/iox-ui/generation-core';
2
+
3
+ import { assertAssistBudget, MAX_ROUTE_PROPERTIES } from './budget';
4
+ import { AssistIssue, AssistIssueCode } from './brief';
5
+ import { AssistSurface, EditFamily, SURFACES } from './surfaces';
6
+
7
+ /**
8
+ * The route request (plan §3c rule 5): the first, small, fast question of every turn — which of THIS surface's
9
+ * families the sentence needs, or `cannot` with one line for the owner. Its family enum is the surface's, so the model
10
+ * cannot route a content-item sentence to the builder's Style.
11
+ */
12
+
13
+ export enum RouteAnswerKey {
14
+ Families = 'families',
15
+ Cannot = 'cannot',
16
+ Reply = 'reply',
17
+ }
18
+
19
+ export function routeJsonSchema(surface: AssistSurface): JsonSchema {
20
+ const schema = jsonClosedObject({
21
+ [RouteAnswerKey.Families]: { ...jsonListOf(jsonOneOf(SURFACES[surface].families)), description: 'The kinds of change the sentence asks for, in the order to make them. [] when it cannot be done here.' },
22
+ [RouteAnswerKey.Cannot]: { ...jsonAnyOf([jsonText(), { type: 'null' }]), description: 'Why it cannot be done here, in one line in the sentence\'s language — or null.' },
23
+ [RouteAnswerKey.Reply]: { ...jsonText(), description: 'One short line to the owner, in the sentence\'s language.' },
24
+ }, Object.values(RouteAnswerKey));
25
+ assertAssistBudget(`route ${surface}`, [schema], MAX_ROUTE_PROPERTIES);
26
+ return schema;
27
+ }
28
+
29
+ export interface AssistRoute {
30
+ readonly ok: boolean;
31
+ readonly families: ReadonlyArray<EditFamily>;
32
+ readonly cannot: string | null;
33
+ readonly reply: string;
34
+ readonly issues: ReadonlyArray<AssistIssue>;
35
+ }
36
+
37
+ const text = (v: unknown): string => (typeof v === 'string' ? v.trim() : '');
38
+
39
+ /** A route answer, checked against its surface: a family the surface does not have is refused, repeats dropped. */
40
+ export function readRoute(surface: AssistSurface, answer: unknown): AssistRoute {
41
+ const a = (answer && typeof answer === 'object' ? answer : {}) as Record<string, unknown>;
42
+ const allowed = new Set<string>(SURFACES[surface].families);
43
+ const named = Array.isArray(a[RouteAnswerKey.Families]) ? (a[RouteAnswerKey.Families] as unknown[]).map(String) : [];
44
+ const issues: AssistIssue[] = named.filter(f => !allowed.has(f))
45
+ .map(f => ({ code: AssistIssueCode.UnknownFamily, message: `"${f}" is not a family of ${surface}` }));
46
+ const families = [...new Set(named.filter(f => allowed.has(f)))] as EditFamily[];
47
+ const cannot = text(a[RouteAnswerKey.Cannot]) || null;
48
+ return { ok: !issues.length, families: cannot ? [] : families, cannot, reply: text(a[RouteAnswerKey.Reply]), issues };
49
+ }
@@ -0,0 +1,219 @@
1
+ import { AROUND_ITEMS_MAX, AROUND_TEXT_CHARS, MEMORY_TURNS } from './budget';
2
+ import { AssistBriefError, AssistIssueCode, Brief, FIELD_HANDLE_PREFIX, HandleMap, HandleTarget, NeverWrite, SIBLING_HANDLE_PREFIX } from './brief';
3
+ import { AssistField, AssistFieldKind, assistFields, ContentTypeSchema, isWritable, NeverWriteReason, titleField } from './content-fields';
4
+ import { BriefValue, isEmptyFieldValue, readFieldValue, readLocaleValues } from './field-values';
5
+ import { AssistScope, AssistSurface, SURFACES } from './surfaces';
6
+
7
+ /**
8
+ * The brief of surface S2 — one content item (plan §3c, §4 S2). Focus = the item (every field as a handle `f.<key>`,
9
+ * its kind, label, full value, which locales a multiLang field has filled) or ONE field when the owner opened the
10
+ * field's sparkle; around = the rest of the item (when the focus is a field) and up to five sibling items of the type,
11
+ * each value clipped to 160 characters — examples of the studio's voice, never something to copy.
12
+ */
13
+
14
+ export type ContentRecord = Readonly<Record<string, unknown>>;
15
+
16
+ export interface ItemBriefField {
17
+ readonly handle: string;
18
+ readonly label: string;
19
+ readonly kind: AssistFieldKind;
20
+ readonly required: boolean;
21
+ /** In the write locale for a multiLang field. */
22
+ readonly empty: boolean;
23
+ /** Absent on a never-written field: the model only learns whether it is filled. */
24
+ readonly value?: BriefValue;
25
+ readonly options?: ReadonlyArray<string>;
26
+ readonly locales?: { readonly filled: ReadonlyArray<string>; readonly empty: ReadonlyArray<string> };
27
+ readonly never?: NeverWriteReason;
28
+ }
29
+
30
+ export interface ItemFocus {
31
+ readonly scope: AssistScope;
32
+ readonly type: { readonly name: string; readonly label: string };
33
+ /** The item's name as the list shows it ('' for a new item). */
34
+ readonly title: string;
35
+ /** The `@title` field's handle, when the type has one. */
36
+ readonly titleHandle: string | null;
37
+ readonly fields: ReadonlyArray<ItemBriefField>;
38
+ }
39
+
40
+ export interface ItemSummary {
41
+ readonly handle: string;
42
+ readonly title: string;
43
+ /** handle → value, ≤ 160 characters. */
44
+ readonly fields: Readonly<Record<string, string>>;
45
+ }
46
+
47
+ export interface ItemAround {
48
+ /** The item's other fields, summarised — only when the focus is one field. */
49
+ readonly item: Readonly<Record<string, string>> | null;
50
+ readonly siblings: ReadonlyArray<ItemSummary>;
51
+ }
52
+
53
+ export type ItemBrief = Brief<ItemFocus, ItemAround>;
54
+
55
+ export interface ItemBriefContext {
56
+ /** The locale the turn writes in. */
57
+ readonly locale: string;
58
+ /** One field's key or handle: the per-field sparkle. */
59
+ readonly focusField?: string;
60
+ /** Other items of the type (the item itself is skipped); the first five are sent. */
61
+ readonly siblings?: ReadonlyArray<ContentRecord>;
62
+ readonly owner?: string | null;
63
+ readonly memory?: ReadonlyArray<string>;
64
+ }
65
+
66
+ export interface SummarizedItem {
67
+ readonly brief: ItemBrief;
68
+ readonly handles: HandleMap;
69
+ }
70
+
71
+ const ID_KEY = '_id';
72
+ const ELLIPSIS = '…';
73
+ const LIST_JOIN = ', ';
74
+ const PARAGRAPH_JOIN = '\n\n';
75
+
76
+ const TEXT_KINDS: ReadonlySet<AssistFieldKind> = new Set([AssistFieldKind.Text, AssistFieldKind.Textarea, AssistFieldKind.RichText]);
77
+
78
+ export const clipText = (text: string, max: number = AROUND_TEXT_CHARS): string =>
79
+ text.length <= max ? text : `${text.slice(0, max - ELLIPSIS.length).trimEnd()}${ELLIPSIS}`;
80
+
81
+ function briefField(field: AssistField, raw: unknown, locale: string): ItemBriefField {
82
+ const base = { handle: field.handle, label: field.label, kind: field.kind, required: field.required };
83
+ if (field.never) return { ...base, empty: isEmptyFieldValue(raw), never: field.never };
84
+ const options = field.options ? { options: field.options } : {};
85
+ if (field.locales) {
86
+ const values = readLocaleValues(field.kind, field.locales, raw);
87
+ const filled = field.locales.filter(l => !isEmptyFieldValue(values[l]));
88
+ return {
89
+ ...base, ...options,
90
+ empty: isEmptyFieldValue(values[locale]),
91
+ value: values as Record<string, string | ReadonlyArray<string>>,
92
+ locales: { filled, empty: field.locales.filter(l => !filled.includes(l)) },
93
+ };
94
+ }
95
+ const value = readFieldValue(field.kind, raw);
96
+ return { ...base, ...options, empty: isEmptyFieldValue(value), value };
97
+ }
98
+
99
+ const localeOrFirst = (values: Record<string, BriefValue>, locale: string): BriefValue =>
100
+ !isEmptyFieldValue(values[locale]) ? values[locale] : Object.values(values).find(v => !isEmptyFieldValue(v)) ?? null;
101
+
102
+ /** A value as one clipped line: the write locale first (else the first filled one), paragraphs and lists joined. */
103
+ function summaryText(field: AssistField, raw: unknown, locale: string): string {
104
+ const value = field.locales ? localeOrFirst(readLocaleValues(field.kind, field.locales, raw), locale) : readFieldValue(field.kind, raw);
105
+ if (value === null) return '';
106
+ const text = Array.isArray(value) ? value.join(field.kind === AssistFieldKind.RichText ? PARAGRAPH_JOIN : LIST_JOIN) : String(value);
107
+ return clipText(text.replace(/\s+/g, ' ').trim());
108
+ }
109
+
110
+ function summaries(fields: ReadonlyArray<AssistField>, record: ContentRecord, locale: string): Record<string, string> {
111
+ return Object.fromEntries(fields
112
+ .map(f => [f.handle, summaryText(f, record[f.key], locale)] as const)
113
+ .filter(([, text]) => text !== ''));
114
+ }
115
+
116
+ function findFocusField(fields: ReadonlyArray<AssistField>, focus: string): AssistField {
117
+ const found = fields.find(f => f.key === focus || f.handle === focus || f.handle === `${FIELD_HANDLE_PREFIX}${focus}`);
118
+ if (!found) throw new AssistBriefError(AssistIssueCode.UnknownHandle, `"${focus}" is not a field of this type`);
119
+ return found;
120
+ }
121
+
122
+ const neverList = (fields: ReadonlyArray<AssistField>): NeverWrite[] =>
123
+ fields.filter(f => f.never).map(f => ({ handle: f.handle, label: f.label, reason: f.never as string }));
124
+
125
+ function siblingsOf(record: ContentRecord, siblings: ReadonlyArray<ContentRecord>): ContentRecord[] {
126
+ const own = record[ID_KEY];
127
+ return siblings.filter(s => own === undefined || s[ID_KEY] !== own).slice(0, AROUND_ITEMS_MAX);
128
+ }
129
+
130
+ /** S2's brief and its handle map: `f.<key>` per field, `s<n>` per sibling (its id stays in the map, never sent). */
131
+ export function summarizeItem(schema: ContentTypeSchema, item: ContentRecord, ctx: ItemBriefContext): SummarizedItem {
132
+ const fields = assistFields(schema);
133
+ const focused = ctx.focusField ? findFocusField(fields, ctx.focusField) : null;
134
+ const title = titleField(schema, fields);
135
+ const voiceFields = fields.filter(f => isWritable(f) && TEXT_KINDS.has(f.kind));
136
+ const siblings = siblingsOf(item, ctx.siblings ?? []);
137
+ const siblingHandle = (i: number) => `${SIBLING_HANDLE_PREFIX}${i + 1}`;
138
+ const surface = SURFACES[AssistSurface.ContentItem];
139
+ const scope = focused ? AssistScope.Field : AssistScope.Item;
140
+
141
+ const handles: Record<string, HandleTarget> = Object.fromEntries([
142
+ ...fields.map(f => [f.handle, { key: f.key, path: [f.key] }] as const),
143
+ ...siblings.map((s, i) => [siblingHandle(i), { key: siblingHandle(i), path: [], ...(s[ID_KEY] !== undefined ? { id: String(s[ID_KEY]) } : {}) }] as const),
144
+ ]);
145
+
146
+ const brief: ItemBrief = {
147
+ surface: AssistSurface.ContentItem,
148
+ focus: {
149
+ scope,
150
+ type: { name: schema.name, label: schema.metaData?.label || schema.name },
151
+ title: title ? summaryText(title, item[title.key], ctx.locale) : '',
152
+ titleHandle: title?.handle ?? null,
153
+ fields: (focused ? [focused] : fields).map(f => briefField(f, item[f.key], ctx.locale)),
154
+ },
155
+ around: {
156
+ item: focused ? summaries(fields.filter(f => f !== focused && isWritable(f)), item, ctx.locale) : null,
157
+ siblings: siblings.map((s, i) => ({
158
+ handle: siblingHandle(i),
159
+ title: title ? summaryText(title, s[title.key], ctx.locale) : '',
160
+ fields: summaries(voiceFields, s, ctx.locale),
161
+ })),
162
+ },
163
+ owner: ctx.owner ?? null,
164
+ rules: {
165
+ families: surface.families,
166
+ locale: ctx.locale,
167
+ never: neverList(fields),
168
+ scope,
169
+ widensTo: surface.scopes.slice(surface.scopes.indexOf(scope) + 1),
170
+ },
171
+ memory: (ctx.memory ?? []).slice(-MEMORY_TURNS),
172
+ };
173
+ return { brief, handles };
174
+ }
175
+
176
+ export enum ItemSuggestionKind {
177
+ FillEmpty = 'fillEmpty',
178
+ Translate = 'translate',
179
+ Shorten = 'shorten',
180
+ WriteSeo = 'writeSeo',
181
+ }
182
+
183
+ /** A quick action the box offers, built from the brief (never canned text — the client words it). */
184
+ export interface ItemSuggestion {
185
+ readonly kind: ItemSuggestionKind;
186
+ readonly handles: ReadonlyArray<string>;
187
+ /** Translate: the locale to fill. */
188
+ readonly locale?: string;
189
+ }
190
+
191
+ /** A text this long is worth a "Shorten". */
192
+ export const SHORTEN_FROM_CHARS = 280;
193
+ const SEO_WORDS: ReadonlyArray<string> = ['seo', 'meta'];
194
+
195
+ const textLength = (v: BriefValue | undefined): number =>
196
+ typeof v === 'string' ? v.length : Array.isArray(v) ? v.join(' ').length : 0;
197
+
198
+ function translations(writable: ReadonlyArray<ItemBriefField>): ItemSuggestion[] {
199
+ const byLocale = new Map<string, string[]>();
200
+ for (const f of writable) {
201
+ if (!f.locales || !f.locales.filled.length) continue;
202
+ for (const l of f.locales.empty) byLocale.set(l, [...(byLocale.get(l) ?? []), f.handle]);
203
+ }
204
+ return [...byLocale].map(([locale, handles]) => ({ kind: ItemSuggestionKind.Translate, locale, handles }));
205
+ }
206
+
207
+ /** S2's quick actions: Fill empty fields, Translate to <locale>, Shorten, Write SEO — each only when it applies. */
208
+ export function itemSuggestions(brief: ItemBrief): ItemSuggestion[] {
209
+ const writable = brief.focus.fields.filter(f => !f.never);
210
+ const empty = writable.filter(f => f.empty).map(f => f.handle);
211
+ const long = writable.filter(f => TEXT_KINDS.has(f.kind) && !f.locales && textLength(f.value) >= SHORTEN_FROM_CHARS).map(f => f.handle);
212
+ const seo = writable.filter(f => SEO_WORDS.some(w => f.handle.slice(FIELD_HANDLE_PREFIX.length).toLowerCase().startsWith(w))).map(f => f.handle);
213
+ return [
214
+ ...(empty.length ? [{ kind: ItemSuggestionKind.FillEmpty, handles: empty }] : []),
215
+ ...translations(writable),
216
+ ...(long.length ? [{ kind: ItemSuggestionKind.Shorten, handles: long }] : []),
217
+ ...(seo.length ? [{ kind: ItemSuggestionKind.WriteSeo, handles: seo }] : []),
218
+ ];
219
+ }