@vectoriox/iox-ui 5.124.0 → 5.125.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,482 @@
1
+ import { jsonListOf, jsonOneOf, JsonSchema, jsonText } from '@vectoriox/iox-ui/generation-core';
2
+
3
+ import { assistFactIssues, AssistWordContext } from './assist-facts';
4
+ import { AROUND_TEXT_CHARS, MEMORY_TURNS } from './budget';
5
+ import { AssistIssue, AssistIssueCode, Brief, HandleMap, HandleTarget, NeverWrite } from './brief';
6
+ import { AssistField, AssistFieldKind, assistFields, ContentPropertyDef, ContentTypeSchema, isWritable, NeverWriteReason, titleField } from './content-fields';
7
+ import { applyFieldEdits } from './field-edits';
8
+ import { BriefValue, isEmptyFieldValue, isPlainRecord } from './field-values';
9
+ import { decodeFieldsAnswers, FieldEdit, FieldsAnswerKey, fieldsJsonSchema, FieldsSchemas } from './fields-schema';
10
+ import { containsHtml } from './rich-text';
11
+ import { ContentRecord, ItemSummary, summarizeItem } from './summarize-item';
12
+ import { AssistScope, AssistSurface, SURFACES } from './surfaces';
13
+
14
+ /**
15
+ * Surface S3 — photos → content (ai-assist-plan §4 S3, A-D11, R-H7): the owner's photos, uploaded FIRST, become DRAFT
16
+ * items of one content type. One photo = one item unless the owner says they are one item (the first photo is then the
17
+ * main image, the rest the gallery). Each group is read by ONE vision request (`assistRead`, ≤ 6 photos — F8) whose
18
+ * strict format is the type's writable fields (`fieldsJsonSchema`) plus which values came from the owner's notes and an
19
+ * alt text per photo. Every value is then tagged by where it came from: SEEN in the photo, FROM YOU (the owner's notes),
20
+ * or NEEDS YOU (left empty: a fact the owner gives — a price, a place, a date, a phone — or a required field nothing
21
+ * showed). The photos go into the type's picture fields by code, never by the model. Nothing is written by a read: the
22
+ * owner reviews the drafts and creates them (a Run, with Undo).
23
+ */
24
+
25
+ export enum PhotoGrouping {
26
+ /** One item per photo. */
27
+ Each = 'each',
28
+ /** Every photo is ONE item: the first the main image, the rest its gallery. */
29
+ One = 'one',
30
+ }
31
+
32
+ /** The most photos one S3 turn takes (the board: "Up to 20 at a time"). */
33
+ export const MAX_ASSIST_PHOTOS = 20;
34
+
35
+ /** The most photos one vision request reads (F8 — the reading's own limit); a larger group's others go to its gallery unread. */
36
+ export const PHOTOS_PER_READ = 6;
37
+
38
+ /** A photo the owner uploaded for the turn: its storage key, its address and the file's name. */
39
+ export interface AssistPhoto {
40
+ readonly key: string;
41
+ readonly url: string;
42
+ readonly name: string;
43
+ }
44
+
45
+ /** One future item: its handle (`p1`), its photos, and how many of them its read looks at. */
46
+ export interface PhotoGroup {
47
+ readonly handle: string;
48
+ readonly photos: ReadonlyArray<AssistPhoto>;
49
+ readonly read: number;
50
+ }
51
+
52
+ export const PHOTO_GROUP_HANDLE_PREFIX = 'p';
53
+ export const photoGroupHandle = (index: number): string => `${PHOTO_GROUP_HANDLE_PREFIX}${index + 1}`;
54
+
55
+ /** The groups the photos make — one per photo, or one for all. */
56
+ export function groupPhotos(photos: ReadonlyArray<AssistPhoto>, grouping: PhotoGrouping): PhotoGroup[] {
57
+ if (!photos.length) return [];
58
+ const group = (list: ReadonlyArray<AssistPhoto>, i: number): PhotoGroup => ({
59
+ handle: photoGroupHandle(i), photos: [...list], read: Math.min(list.length, PHOTOS_PER_READ),
60
+ });
61
+ return grouping === PhotoGrouping.One ? [group(photos, 0)] : photos.map((p, i) => group([p], i));
62
+ }
63
+
64
+ /** How many vision requests a turn makes — what its estimate multiplies. */
65
+ export const photoReadCount = (photos: number, grouping: PhotoGrouping): number =>
66
+ photos <= 0 ? 0 : grouping === PhotoGrouping.One ? 1 : photos;
67
+
68
+ // ── the type's picture fields ────────────────────────────────────────────────────────────────
69
+
70
+ enum PictureControl {
71
+ Image = 'image',
72
+ Media = 'media',
73
+ Gallery = 'gallery',
74
+ }
75
+
76
+ const STRING = 'string';
77
+ const ARRAY = 'array';
78
+
79
+ const isPictureLeaf = (def: ContentPropertyDef | undefined): boolean => !!def && def.type === STRING
80
+ && (def.controller?.type === PictureControl.Media || def.controller?.type === PictureControl.Image);
81
+ const isPictureList = (def: ContentPropertyDef | undefined): boolean => !!def && def.type === ARRAY
82
+ && (def.controller?.type === PictureControl.Gallery || isPictureLeaf(def.items) || def.items?.controller?.type === PictureControl.Media);
83
+
84
+ /** Where a draft's photos go: the main picture (the type's image role, else its first picture field) and its gallery. */
85
+ export interface PhotoSlots {
86
+ readonly main: string | null;
87
+ readonly gallery: string | null;
88
+ }
89
+
90
+ export function photoSlots(schema: ContentTypeSchema): PhotoSlots {
91
+ const props = schema.schemaObject?.properties ?? {};
92
+ const role = schema.metaData?.previewImageField;
93
+ const keys = Object.keys(props);
94
+ const main = role && isPictureLeaf(props[role]) ? role : keys.find(k => isPictureLeaf(props[k])) ?? null;
95
+ const gallery = keys.find(k => isPictureList(props[k])) ?? null;
96
+ return { main, gallery };
97
+ }
98
+
99
+ /** A type the photos can become: it has a picture field to put them in. */
100
+ export const takesPhotos = (schema: ContentTypeSchema): boolean => {
101
+ const slots = photoSlots(schema);
102
+ return !!(slots.main || slots.gallery);
103
+ };
104
+
105
+ const nameWords = (text: string): string[] => text.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(w => w.length >= 3);
106
+ const singular = (w: string): string => (w.endsWith('ies') ? `${w.slice(0, -3)}y` : w.endsWith('s') ? w.slice(0, -1) : w);
107
+
108
+ /**
109
+ * "Make them into" — the type suggested for the photos: one the sentence names (its name or label, either number), else
110
+ * the first type that takes photos. Null when none does (the owner adds a picture field first).
111
+ */
112
+ export function suggestPhotoType(schemas: ReadonlyArray<ContentTypeSchema>, sentence = ''): string | null {
113
+ const candidates = schemas.filter(takesPhotos);
114
+ const said = new Set(nameWords(sentence).map(singular));
115
+ const named = candidates.find(s => [s.name, s.metaData?.label ?? ''].some(n => nameWords(n).some(w => said.has(singular(w)))));
116
+ return (named ?? candidates[0])?.name ?? null;
117
+ }
118
+
119
+ // ── the brief ────────────────────────────────────────────────────────────────────────────────
120
+
121
+ export interface PhotoBriefField {
122
+ readonly handle: string;
123
+ readonly label: string;
124
+ readonly kind: AssistFieldKind;
125
+ readonly required: boolean;
126
+ readonly options?: ReadonlyArray<string>;
127
+ /** A multiLang field: written in the brief's locale only. */
128
+ readonly multiLang?: boolean;
129
+ }
130
+
131
+ export interface PhotosFocus {
132
+ readonly scope: AssistScope;
133
+ readonly type: { readonly name: string; readonly label: string };
134
+ readonly grouping: PhotoGrouping;
135
+ /** The groups — on a read request, only the one being read. */
136
+ readonly groups: ReadonlyArray<{ readonly handle: string; readonly photos: number; readonly read: number }>;
137
+ /** What the model may write, per draft. */
138
+ readonly fields: ReadonlyArray<PhotoBriefField>;
139
+ readonly titleHandle: string | null;
140
+ /** The fields the photos are put in by code — named so the model knows they are filled. */
141
+ readonly pictures: { readonly main: string | null; readonly gallery: string | null };
142
+ }
143
+
144
+ export interface PhotosAround {
145
+ /** Items of the type already in the studio — examples of its voice, never something to copy. */
146
+ readonly siblings: ReadonlyArray<ItemSummary>;
147
+ }
148
+
149
+ export type PhotosBrief = Brief<PhotosFocus, PhotosAround>;
150
+
151
+ export interface PhotosBriefContext {
152
+ readonly locale: string;
153
+ readonly grouping: PhotoGrouping;
154
+ readonly photos: ReadonlyArray<AssistPhoto>;
155
+ readonly siblings?: ReadonlyArray<ContentRecord>;
156
+ readonly owner?: string | null;
157
+ readonly memory?: ReadonlyArray<string>;
158
+ }
159
+
160
+ export interface SummarizedPhotos {
161
+ readonly brief: PhotosBrief;
162
+ readonly handles: HandleMap;
163
+ readonly groups: ReadonlyArray<PhotoGroup>;
164
+ readonly slots: PhotoSlots;
165
+ }
166
+
167
+ const labelOf = (schema: ContentTypeSchema, key: string | null): string | null =>
168
+ key ? (schema.schemaObject.properties[key]?.label || key) : null;
169
+
170
+ /** S3's brief: the type's writable fields (`f.<key>`), the groups (`p<n>`), the picture fields, siblings as voice. */
171
+ export function summarizePhotos(schema: ContentTypeSchema, ctx: PhotosBriefContext): SummarizedPhotos {
172
+ const fields = assistFields(schema);
173
+ const slots = photoSlots(schema);
174
+ const groups = groupPhotos(ctx.photos, ctx.grouping);
175
+ const item = summarizeItem(schema, {}, { locale: ctx.locale, siblings: ctx.siblings ?? [] });
176
+ const picture = new Set([slots.main, slots.gallery].filter(Boolean));
177
+ const title = titleField(schema, fields);
178
+ const surface = SURFACES[AssistSurface.ContentFromPhotos];
179
+ const handles: Record<string, HandleTarget> = {
180
+ ...item.handles,
181
+ ...Object.fromEntries(groups.map(g => [g.handle, { key: g.handle, path: [] }])),
182
+ };
183
+ const never: NeverWrite[] = fields.filter(f => f.never && !picture.has(f.key)).map(f => ({ handle: f.handle, label: f.label, reason: f.never as string }));
184
+ const brief: PhotosBrief = {
185
+ surface: AssistSurface.ContentFromPhotos,
186
+ focus: {
187
+ scope: AssistScope.Photos,
188
+ type: { name: schema.name, label: schema.metaData?.label || schema.name },
189
+ grouping: ctx.grouping,
190
+ groups: groups.map(g => ({ handle: g.handle, photos: g.photos.length, read: g.read })),
191
+ fields: fields.filter(isWritable).map(f => ({
192
+ handle: f.handle, label: f.label, kind: f.kind, required: f.required,
193
+ ...(f.options ? { options: f.options } : {}), ...(f.locales ? { multiLang: true } : {}),
194
+ })),
195
+ titleHandle: title && isWritable(title) ? title.handle : null,
196
+ pictures: { main: labelOf(schema, slots.main), gallery: labelOf(schema, slots.gallery) },
197
+ },
198
+ around: { siblings: item.brief.around.siblings },
199
+ owner: ctx.owner ?? null,
200
+ rules: {
201
+ families: surface.families,
202
+ locale: ctx.locale,
203
+ never,
204
+ scope: AssistScope.Photos,
205
+ widensTo: surface.scopes.slice(surface.scopes.indexOf(AssistScope.Photos) + 1),
206
+ },
207
+ memory: (ctx.memory ?? []).slice(-MEMORY_TURNS),
208
+ };
209
+ return { brief, handles, groups, slots };
210
+ }
211
+
212
+ /** The brief ONE read is sent: the same brief, its focus narrowed to the group being read (`p<n>`). */
213
+ export function photoGroupBrief(brief: PhotosBrief, handle: string): PhotosBrief {
214
+ const groups = brief.focus.groups.filter(g => g.handle === handle);
215
+ return { ...brief, focus: { ...brief.focus, scope: AssistScope.Photo, groups } };
216
+ }
217
+
218
+ // ── the strict format of one read ────────────────────────────────────────────────────────────
219
+
220
+ export enum PhotoAnswerKey {
221
+ FromYou = 'fromYou',
222
+ Alt = 'alt',
223
+ }
224
+
225
+ /** One read's format: the type's writable fields (split as any fields request) + which came from the notes + the alt texts. */
226
+ export function photoDraftJsonSchema(schema: ContentTypeSchema, options: { readonly locale: string; readonly read: number }): FieldsSchemas {
227
+ const altSchema: JsonSchema = {
228
+ ...jsonListOf(jsonText()),
229
+ description: `Exactly ${options.read} alt text(s), one per photo in the order shown: what it shows for a person who cannot see it, in ${options.locale}. Never a claim about the business.`,
230
+ };
231
+ const fromYou = (handles: ReadonlyArray<string>): JsonSchema => ({
232
+ ...jsonListOf(jsonOneOf(handles)),
233
+ description: 'The fields whose value came from the owner\'s notes, not from the photos. [] when none did.',
234
+ });
235
+ const writable = assistFields(schema).filter(isWritable);
236
+ if (!writable.length) {
237
+ // Nothing to write but the alt texts: one part with no fields at all.
238
+ const answer = { [PhotoAnswerKey.Alt]: altSchema, [FieldsAnswerKey.Note]: { ...jsonText(), description: 'One short line for the owner.' } };
239
+ return {
240
+ parts: [{ type: 'object', properties: answer, required: Object.keys(answer), additionalProperties: false } as JsonSchema],
241
+ handles: [[]],
242
+ };
243
+ }
244
+ return fieldsJsonSchema(schema, {
245
+ locale: options.locale,
246
+ extra: {
247
+ keys: [PhotoAnswerKey.FromYou, PhotoAnswerKey.Alt],
248
+ build: (handles, part) => ({
249
+ [PhotoAnswerKey.FromYou]: fromYou(handles),
250
+ ...(part === 0 ? { [PhotoAnswerKey.Alt]: altSchema } : {}),
251
+ }),
252
+ },
253
+ });
254
+ }
255
+
256
+ /** One read's answer, its parts joined. */
257
+ export interface PhotoDraftAnswer {
258
+ readonly edits: ReadonlyArray<FieldEdit>;
259
+ readonly fromYou: ReadonlyArray<string>;
260
+ readonly alt: ReadonlyArray<string>;
261
+ readonly note: string;
262
+ }
263
+
264
+ const listOf = (v: unknown): string[] => (Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : []);
265
+
266
+ export function decodePhotoDraftAnswers(answers: ReadonlyArray<unknown>): PhotoDraftAnswer {
267
+ const objects = answers.filter(isPlainRecord);
268
+ const notes = objects.map(a => a[FieldsAnswerKey.Note]).filter((n): n is string => typeof n === 'string' && n.trim() !== '').map(n => n.trim());
269
+ return {
270
+ edits: decodeFieldsAnswers(answers),
271
+ fromYou: [...new Set(objects.flatMap(a => listOf(a[PhotoAnswerKey.FromYou])))],
272
+ alt: objects.flatMap(a => listOf(a[PhotoAnswerKey.Alt])).map(t => t.trim()),
273
+ note: notes.join(' '),
274
+ };
275
+ }
276
+
277
+ // ── the draft ────────────────────────────────────────────────────────────────────────────────
278
+
279
+ /** Where a draft's value came from — what the review card says beside it. */
280
+ export enum ValueSource {
281
+ /** Visible in the photo. */
282
+ Seen = 'seen',
283
+ /** The owner's own words — the notes, or a value typed at review. */
284
+ FromYou = 'fromYou',
285
+ /** Left empty: a fact the owner gives, or a required field nothing showed. */
286
+ NeedsYou = 'needsYou',
287
+ /** Left empty, and nothing asks for it (an optional field the photos did not answer). */
288
+ Empty = 'empty',
289
+ }
290
+
291
+ /** The facts an owner gives — a field of one of these is NEEDS YOU when empty (R-H7: never filled by the AI). */
292
+ const OWNER_FACTS: ReadonlySet<NeverWriteReason> = new Set([
293
+ NeverWriteReason.Money, NeverWriteReason.Stock, NeverWriteReason.ProductCode, NeverWriteReason.Contact,
294
+ NeverWriteReason.Date, NeverWriteReason.WebAddress,
295
+ ]);
296
+
297
+ export interface DraftValue {
298
+ readonly handle: string;
299
+ readonly key: string;
300
+ readonly label: string;
301
+ readonly kind: AssistFieldKind;
302
+ /** Readable, like a change's `after`; null when empty. */
303
+ readonly value: BriefValue;
304
+ readonly source: ValueSource;
305
+ readonly locale?: string;
306
+ readonly never?: NeverWriteReason;
307
+ }
308
+
309
+ export interface PhotoDraft {
310
+ /** The group's handle (`p1`) — what the owner picks at review. */
311
+ readonly group: string;
312
+ readonly photos: ReadonlyArray<AssistPhoto>;
313
+ /** An alt text per photo read (the rest of a large group's gallery has none). */
314
+ readonly alt: ReadonlyArray<string>;
315
+ /** The title field's value, '' when none. */
316
+ readonly title: string;
317
+ /** The item as it will be stored — the fields written and the photos in their fields; never `isPublished`, never `info`. */
318
+ readonly values: ContentRecord;
319
+ /** Every field of the type but the picture fields, in schema order, with its source. */
320
+ readonly fields: ReadonlyArray<DraftValue>;
321
+ /** The model's line for the owner. */
322
+ readonly note: string;
323
+ }
324
+
325
+ export interface PhotoDraftContext {
326
+ readonly schema: ContentTypeSchema;
327
+ readonly handles: HandleMap;
328
+ readonly locale: string;
329
+ readonly group: PhotoGroup;
330
+ /** The owner's notes (may be empty). */
331
+ readonly sentence?: string;
332
+ readonly words?: AssistWordContext;
333
+ }
334
+
335
+ export interface PhotoDraftOutcome {
336
+ readonly ok: boolean;
337
+ readonly draft: PhotoDraft | null;
338
+ readonly issues: ReadonlyArray<AssistIssue>;
339
+ }
340
+
341
+ const ALT_HANDLE = 'alt';
342
+
343
+ function altIssues(alt: ReadonlyArray<string>, read: number): AssistIssue[] {
344
+ const issue = (message: string): AssistIssue => ({ code: AssistIssueCode.WrongType, handle: ALT_HANDLE, message });
345
+ if (alt.length !== read) return [issue(`expected ${read} alt text(s), one per photo — got ${alt.length}`)];
346
+ return alt.flatMap((t, i) => (!t ? [issue(`photo ${i + 1} has no alt text`)]
347
+ : containsHtml(t) ? [{ code: AssistIssueCode.HtmlNotAllowed, handle: ALT_HANDLE, message: `photo ${i + 1}: markup is not written by Assist` }]
348
+ : t.length > AROUND_TEXT_CHARS ? [issue(`photo ${i + 1}: an alt text is at most ${AROUND_TEXT_CHARS} characters`)] : []));
349
+ }
350
+
351
+ const sourceOfEmpty = (field: AssistField): ValueSource =>
352
+ (field.never && OWNER_FACTS.has(field.never)) || (!field.never && field.required) ? ValueSource.NeedsYou : ValueSource.Empty;
353
+
354
+ /**
355
+ * One read's answer → its draft, by the SAME check every fields turn runs (`applyFieldEdits` on an empty item, the fact
356
+ * gate included) plus the alt texts and the owner's-notes claim. All or none: an issue refuses the draft (the read is
357
+ * re-asked once with the issues). The photos are placed by code: main = the first, gallery = the rest.
358
+ */
359
+ export function draftFromPhotos(answer: PhotoDraftAnswer, ctx: PhotoDraftContext): PhotoDraftOutcome {
360
+ const applied = applyFieldEdits({}, answer.edits, {
361
+ schema: ctx.schema, handles: ctx.handles, locale: ctx.locale, sentence: ctx.sentence ?? '', words: ctx.words, named: [],
362
+ });
363
+ const notes = (ctx.sentence ?? '').trim();
364
+ const fromYou = answer.fromYou.filter(h => applied.changes.some(c => c.handle === h));
365
+ const issues: AssistIssue[] = [
366
+ ...applied.issues,
367
+ ...altIssues(answer.alt, ctx.group.read),
368
+ ...assistFactIssues(answer.alt.map(text => ({ handle: ALT_HANDLE, text })), { words: ctx.words, sentence: notes, existing: [] }),
369
+ ...answer.fromYou.filter(h => !Object.prototype.hasOwnProperty.call(ctx.handles, h))
370
+ .map(h => ({ code: AssistIssueCode.UnknownHandle, handle: h, message: `"${h}" is not a field of this type` })),
371
+ ...(!notes && fromYou.length ? [{ code: AssistIssueCode.NotFromOwner, message: 'the owner gave no notes, so no value came from them' }] : []),
372
+ ];
373
+ if (issues.length) return { ok: false, draft: null, issues };
374
+
375
+ const slots = photoSlots(ctx.schema);
376
+ const urls = ctx.group.photos.map(p => p.url);
377
+ const values: Record<string, unknown> = { ...applied.result };
378
+ if (slots.main) values[slots.main] = urls[0];
379
+ const galleryUrls = slots.main ? urls.slice(1) : urls;
380
+ if (slots.gallery && galleryUrls.length) values[slots.gallery] = galleryUrls;
381
+
382
+ const picture = new Set([slots.main, slots.gallery]);
383
+ const changed = new Map(applied.changes.map(c => [c.key, c]));
384
+ const fields: DraftValue[] = assistFields(ctx.schema).filter(f => !picture.has(f.key)).map(f => {
385
+ const c = changed.get(f.key);
386
+ const base = { handle: f.handle, key: f.key, label: f.label, kind: f.kind, ...(f.never ? { never: f.never } : {}) };
387
+ if (!c) return { ...base, value: null, source: sourceOfEmpty(f) };
388
+ return { ...base, value: c.after, source: fromYou.includes(f.handle) ? ValueSource.FromYou : ValueSource.Seen, ...(c.locale ? { locale: c.locale } : {}) };
389
+ });
390
+ const title = titleField(ctx.schema);
391
+ const titleValue = title ? fields.find(f => f.key === title.key)?.value : null;
392
+ return {
393
+ ok: true,
394
+ issues: [],
395
+ draft: {
396
+ group: ctx.group.handle, photos: ctx.group.photos, alt: answer.alt, title: typeof titleValue === 'string' ? titleValue : '',
397
+ values, fields, note: answer.note,
398
+ },
399
+ };
400
+ }
401
+
402
+ // ── the owner's own values at review ("City for all") ────────────────────────────────────────
403
+
404
+ const TEXT_CONTROLS: ReadonlySet<string> = new Set(['text', 'textarea', 'tag', 'email']);
405
+ const MULTI_LANG = 'multiLang';
406
+ /** The longest value an owner types for every draft at once. */
407
+ export const OWNER_FILL_MAX_CHARS = 500;
408
+
409
+ const isTextLeaf = (def: ContentPropertyDef | undefined): boolean => !!def && def.type === STRING && TEXT_CONTROLS.has(def.controller?.type ?? '');
410
+
411
+ function isTextField(schema: ContentTypeSchema, key: string): boolean {
412
+ const def = schema.schemaObject.properties[key];
413
+ if (def?.controller?.type === MULTI_LANG) return Object.values(def.properties ?? {}).every(isTextLeaf) && !!Object.keys(def.properties ?? {}).length;
414
+ return isTextLeaf(def);
415
+ }
416
+
417
+ /** The fields the owner may type ONE value into for every draft at review: plain text, never a secret, relation or picture. */
418
+ export function ownerFillFields(schema: ContentTypeSchema): AssistField[] {
419
+ const refused = new Set([NeverWriteReason.Secret, NeverWriteReason.Relation, NeverWriteReason.Media, NeverWriteReason.Structure]);
420
+ return assistFields(schema).filter(f => !(f.never && refused.has(f.never)) && isTextField(schema, f.key));
421
+ }
422
+
423
+ /** What the server refuses in a review's fill: a field the owner may not fill so, a value that is not one short text. */
424
+ export function ownerFillIssues(schema: ContentTypeSchema, fill: unknown): AssistIssue[] {
425
+ if (fill === undefined) return [];
426
+ if (!isPlainRecord(fill)) return [{ code: AssistIssueCode.BadRequest, message: 'the fill is an object of field → text' }];
427
+ const allowed = new Set(ownerFillFields(schema).map(f => f.key));
428
+ return Object.entries(fill).flatMap(([key, value]): AssistIssue[] => {
429
+ if (!allowed.has(key)) return [{ code: AssistIssueCode.UnknownHandle, handle: key, message: `"${key}" cannot be filled for every draft` }];
430
+ if (typeof value !== 'string' || !value.trim()) return [{ code: AssistIssueCode.WrongType, handle: key, message: `${key}: a text` }];
431
+ if (value.length > OWNER_FILL_MAX_CHARS) return [{ code: AssistIssueCode.WrongType, handle: key, message: `${key}: at most ${OWNER_FILL_MAX_CHARS} characters` }];
432
+ if (containsHtml(value)) return [{ code: AssistIssueCode.HtmlNotAllowed, handle: key, message: `${key}: no markup` }];
433
+ return [];
434
+ });
435
+ }
436
+
437
+ /**
438
+ * The owner's "for all" values put into a draft — only where the draft holds nothing (a value the photos gave is never
439
+ * overwritten); a multiLang field gets the locale's key. The value is the owner's: FROM YOU. Unknown keys are ignored
440
+ * (the server refuses them first, `ownerFillIssues`).
441
+ */
442
+ export function withOwnerFill(draft: PhotoDraft, fill: Readonly<Record<string, string>>, ctx: { readonly schema: ContentTypeSchema; readonly locale: string }): PhotoDraft {
443
+ const allowed = new Set(ownerFillFields(ctx.schema).map(f => f.key));
444
+ const values: Record<string, unknown> = { ...draft.values };
445
+ const filled = new Map<string, string>();
446
+ for (const [key, raw] of Object.entries(fill)) {
447
+ const value = typeof raw === 'string' ? raw.trim() : '';
448
+ if (!allowed.has(key) || !value) continue;
449
+ const multi = ctx.schema.schemaObject.properties[key]?.controller?.type === MULTI_LANG;
450
+ const current = multi ? (isPlainRecord(values[key]) ? (values[key] as Record<string, unknown>)[ctx.locale] : undefined) : values[key];
451
+ if (!isEmptyFieldValue(current)) continue;
452
+ values[key] = multi ? { ...(isPlainRecord(values[key]) ? values[key] as Record<string, unknown> : {}), [ctx.locale]: value } : value;
453
+ filled.set(key, value);
454
+ }
455
+ if (!filled.size) return draft;
456
+ const fields = draft.fields.map(f => (filled.has(f.key)
457
+ ? { ...f, value: filled.get(f.key)!, source: ValueSource.FromYou, ...(ctx.schema.schemaObject.properties[f.key]?.controller?.type === MULTI_LANG ? { locale: ctx.locale } : {}) }
458
+ : f));
459
+ return { ...draft, values, fields };
460
+ }
461
+
462
+ // ── a draft once written ─────────────────────────────────────────────────────────────────────
463
+
464
+ /** `info.source` of an item a Run wrote (plan §3e) — what the list's "AI draft" pill and the Run's Undo read. */
465
+ export const AI_DRAFT_SOURCE = 'ai';
466
+
467
+ /** The stamp a Run writes into a draft's `info` — `draftKey` makes a resumed write find what it already wrote. */
468
+ export interface AiDraftStamp {
469
+ readonly source: typeof AI_DRAFT_SOURCE;
470
+ readonly assistTurn: string;
471
+ readonly draftKey: string;
472
+ }
473
+
474
+ export const aiDraftStamp = (turnId: string, group: string): AiDraftStamp =>
475
+ ({ source: AI_DRAFT_SOURCE, assistTurn: turnId, draftKey: `${turnId}:${group}` });
476
+
477
+ /** An item a Run wrote that is still unpublished — the list shows it as an "AI draft". */
478
+ export function isAiDraft(item: unknown): boolean {
479
+ if (!isPlainRecord(item)) return false;
480
+ const info = item['info'];
481
+ return isPlainRecord(info) && info['source'] === AI_DRAFT_SOURCE && item['isPublished'] !== true;
482
+ }
@@ -5,7 +5,9 @@
5
5
  * (`fieldsJsonSchema`) and the ONE check that applies an answer (`applyFieldEdits`), run by iox-cms on a copy and by
6
6
  * cms-client as the trial — and family `words` for surface S1 (the builder, this page): `summarizePage`, `wordsJsonSchema`,
7
7
  * `applyWordEdits`, `pageSuggestions` — and family `style` (`pageLooks`, `styleJsonSchema`, `applyStyleEdits`; both applied as
8
- * one turn by `applyPageEdits`). Every family's words pass ONE fact gate (`assistFactIssues` over generation-core's
8
+ * one turn by `applyPageEdits`) — and surface S3, photos → content (`summarizePhotos`, `photoDraftJsonSchema`, `draftFromPhotos`:
9
+ * one vision read per photo group becomes a draft whose every value says where it came from; `withOwnerFill` for the
10
+ * review's "for all" values; the Run's wire in `assist-turn.ts`). Every family's words pass ONE fact gate (`assistFactIssues` over generation-core's
9
11
  * `factIssues`, R-H2). Pure: no transport, no clock, no randomness.
10
12
  * ⚠️ Not re-exported from the main entry. Consumers wire the usual trio — ng-package raw-ts assets, jest
11
13
  * moduleNameMapper, tsconfig paths — or `nest start` dies with ERR_REQUIRE_ESM. It imports generation-core (the strict
@@ -22,6 +24,7 @@ export * from './fields-schema';
22
24
  export * from './route-schema';
23
25
  export * from './assist-facts';
24
26
  export * from './field-edits';
27
+ export * from './photo-drafts';
25
28
  export * from './page-words';
26
29
  export * from './page-style';
27
30
  export * from './page-sections';
@@ -76,6 +76,7 @@ export enum AssistPermission {
76
76
  ContentRead = 'content_read',
77
77
  ContentCreate = 'content_create',
78
78
  ContentUpdate = 'content_update',
79
+ ContentDelete = 'content_delete',
79
80
  PageRead = 'page_read',
80
81
  PageCreate = 'page_create',
81
82
  PageUpdate = 'page_update',
@@ -105,14 +106,23 @@ export interface SurfaceSpec {
105
106
  /** The content permissions name a type (`content_<type>_<action>`), as the iox-cms guard specialises them. */
106
107
  readonly perContentType: boolean;
107
108
  readonly readsPhotos: boolean;
109
+ /**
110
+ * A sentence is routed to families first (plan §3c rule 5). A surface whose SCREEN is the route (S3: the owner opened
111
+ * "New from photos" — the families are fixed) asks no route request, and its sentence is the owner's notes, which may be
112
+ * empty.
113
+ */
114
+ readonly routed: boolean;
115
+ /** A Run surface: what its "Undo this turn" needs beyond the surface (it removes what the run wrote). */
116
+ readonly undoPermissions?: ReadonlyArray<AssistPermission>;
108
117
  /** The focus ladder, narrowest first. */
109
118
  readonly scopes: ReadonlyArray<AssistScope>;
110
119
  readonly status: SurfaceStatus;
111
120
  }
112
121
 
113
- const spec = (s: Omit<SurfaceSpec, 'perContentType' | 'readsPhotos'> & Partial<Pick<SurfaceSpec, 'perContentType' | 'readsPhotos'>>): SurfaceSpec => ({
122
+ const spec = (s: Omit<SurfaceSpec, 'perContentType' | 'readsPhotos' | 'routed'> & Partial<Pick<SurfaceSpec, 'perContentType' | 'readsPhotos' | 'routed'>>): SurfaceSpec => ({
114
123
  perContentType: false,
115
124
  readsPhotos: false,
125
+ routed: true,
116
126
  ...s,
117
127
  });
118
128
 
@@ -140,16 +150,20 @@ export const SURFACES: Readonly<Record<AssistSurface, SurfaceSpec>> = {
140
150
  scopes: [AssistScope.Field, AssistScope.Item, AssistScope.Type],
141
151
  status: SurfaceStatus.Built,
142
152
  }),
153
+ // S3 (AI4): one vision read per photo group writes a draft's fields (the photos go into its picture fields by code);
154
+ // the owner's "Create N drafts" is a Run, and its Undo removes what it wrote and the photos this flow uploaded.
143
155
  [AssistSurface.ContentFromPhotos]: spec({
144
156
  surface: AssistSurface.ContentFromPhotos,
145
157
  families: [EditFamily.Fields, EditFamily.Media],
146
158
  commit: CommitKind.Run,
147
- steps: [AssistStep.AssistRoute, AssistStep.AssistRead, AssistStep.AssistEdit],
159
+ steps: [AssistStep.AssistRead],
148
160
  permissions: [AssistPermission.ContentCreate, AssistPermission.StorageAll],
161
+ undoPermissions: [AssistPermission.ContentDelete],
149
162
  perContentType: true,
150
163
  readsPhotos: true,
164
+ routed: false,
151
165
  scopes: [AssistScope.Photo, AssistScope.Photos, AssistScope.Type],
152
- status: SurfaceStatus.Planned,
166
+ status: SurfaceStatus.Built,
153
167
  }),
154
168
  [AssistSurface.ContentList]: spec({
155
169
  surface: AssistSurface.ContentList,
@@ -231,7 +245,17 @@ const ALL_SUFFIX = '_all';
231
245
  */
232
246
  export function surfacePermissions(surface: AssistSurface, contentType?: string, families: ReadonlyArray<EditFamily> = []): string[] {
233
247
  const s = SURFACES[surface];
234
- const all = [...s.permissions, ...families.flatMap(f => s.familyPermissions?.[f] ?? [])];
248
+ return specialised(surface, contentType, [...s.permissions, ...families.flatMap(f => s.familyPermissions?.[f] ?? [])]);
249
+ }
250
+
251
+ /** What a Run surface's Undo needs: the surface's own permissions and its `undoPermissions`, specialised the same way. */
252
+ export function surfaceUndoPermissions(surface: AssistSurface, contentType?: string): string[] {
253
+ const s = SURFACES[surface];
254
+ return specialised(surface, contentType, [...s.permissions, ...(s.undoPermissions ?? [])]);
255
+ }
256
+
257
+ function specialised(surface: AssistSurface, contentType: string | undefined, all: ReadonlyArray<AssistPermission>): string[] {
258
+ const s = SURFACES[surface];
235
259
  const named = all.map(p => {
236
260
  if (!s.perContentType || !contentType || !p.startsWith(CONTENT_PERMISSION_PREFIX) || p.endsWith(ALL_SUFFIX)) return p as string;
237
261
  return `${CONTENT_PERMISSION_PREFIX}${contentType}_${p.slice(CONTENT_PERMISSION_PREFIX.length)}`;
@@ -320,6 +320,9 @@ export enum AiFeature {
320
320
  SiteGeneration = 'aiSiteGeneration',
321
321
  /** AI Assist on every screen (ai-assist-plan A-D6): its own switch, the plan's shared credits. */
322
322
  Assist = 'aiAssist',
323
+ /** Award-level generation (award-ingredients-plan AW-D23): Pro and Studio — read into the generation's tier
324
+ * (`generationTierOf`), never a step's own switch. */
325
+ AwardSites = 'awardSites',
323
326
  }
324
327
 
325
328
  /** The feature a step belongs to — the gate refuses a step whose feature the plan does not include. */
@@ -26,7 +26,7 @@ import { recipeListBinds } from './recipe-fields';
26
26
  import { assertStyleSlots, ComposeError, createSerializedNode, SerializedBinding, SerializedNode, setStyleProps, walkSerialized } from './serialized-node';
27
27
  import { SitePlanSourceKind, ContentFieldControl, ContentFieldPlan,
28
28
  ContentRole, ContentTypePlan, DataSourcePlan, DEFAULT_SITE_LOCALE, FactKey, FACT_KEYS, GlobalSlot, isRtlLocale, PagePlan, PageSectionPlan, PlanDataSourceMode,
29
- PlanDataSourceType, RelativeOp, roleField, SiteLocale, SitePlan, SitePlanSource, SITE_FACT_LABELS, SiteBusiness,
29
+ PlanDataSourceType, RelativeOp, roleField, SiteLocale, SitePlan, SitePlanSource, SITE_FACT_LABELS, SiteBusiness, GenerationTier,
30
30
  } from './site-plan.model';
31
31
  import { assertValidSitePlan, nextSourceOf, routeParams } from './validate-site-plan';
32
32
  import { MenuSide, NavRole, NavShape, planNavShape } from './nav-shape';
@@ -130,6 +130,8 @@ export interface ComposeContext {
130
130
  photoAlt?: (photoId: string) => string;
131
131
  /** A photo's shape (the inventory's); a `box:<shape>` id names its own. */
132
132
  photoShape?: (photoId: string) => `${LayoutPhotoShape}` | undefined;
133
+ /** The tier the plan was made at (its generation's stored tier, AW-D23) — absent = Basic: at most two composed pages. */
134
+ tier?: `${GenerationTier}`;
133
135
  }
134
136
 
135
137
  /** Where a composed layout's photos are, as the server keeps them and the screens read them (M8 gate 2): id → address. */
@@ -140,10 +142,12 @@ export interface LayoutPhotoAddress {
140
142
  }
141
143
 
142
144
  /** The composer's context for a site whose layouts name photos: the year, and each photo's address, words and shape. */
143
- export function composeContextOf(year: number, photos?: Readonly<Record<string, LayoutPhotoAddress>>): ComposeContext {
144
- if (!photos) return { year };
145
+ export function composeContextOf(year: number, photos?: Readonly<Record<string, LayoutPhotoAddress>>, tier?: `${GenerationTier}`): ComposeContext {
146
+ const tiered = tier ? { tier } : {};
147
+ if (!photos) return { year, ...tiered };
145
148
  return {
146
149
  year,
150
+ ...tiered,
147
151
  photoSrc: id => photos[id]?.url ?? '',
148
152
  photoAlt: id => photos[id]?.alt ?? '',
149
153
  photoShape: id => photos[id]?.shape as `${LayoutPhotoShape}` | undefined,
@@ -1501,7 +1505,7 @@ function composeLayoutPage(
1501
1505
  * composer never repairs a plan. `context` carries what the composer may not read for itself (the year).
1502
1506
  */
1503
1507
  export function composeSite(plan: SitePlan, context: ComposeContext): ComposedSite {
1504
- assertValidSitePlan(plan);
1508
+ assertValidSitePlan(plan, context?.tier ? { tier: context.tier } : {});
1505
1509
  if (!Number.isInteger(context?.year)) throw new ComposeError('composeSite needs the year (ComposeContext.year) — the composer reads no clock');
1506
1510
  const placeholders: ComposedPlaceholder[] = [];
1507
1511
  const issues: ComposeIssue[] = [];