@things-factory/figure-service 10.1.263 → 10.1.266

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +13 -0
  2. package/dist-server/service/figure/figure-ai-scenarios.js +11 -3
  3. package/dist-server/service/figure/figure-ai-scenarios.js.map +1 -1
  4. package/dist-server/service/figure/figure-context.d.ts +10 -13
  5. package/dist-server/service/figure/figure-context.js +64 -4
  6. package/dist-server/service/figure/figure-context.js.map +1 -1
  7. package/dist-server/service/figure/figure-format.d.ts +2 -0
  8. package/dist-server/service/figure/figure-format.js +1 -1
  9. package/dist-server/service/figure/figure-format.js.map +1 -1
  10. package/dist-server/service/figure/figure-mutation.d.ts +2 -2
  11. package/dist-server/service/figure/figure-mutation.js +25 -4
  12. package/dist-server/service/figure/figure-mutation.js.map +1 -1
  13. package/dist-server/service/figure/figure-propose-steps.d.ts +5 -1
  14. package/dist-server/service/figure/figure-propose-steps.js +11 -7
  15. package/dist-server/service/figure/figure-propose-steps.js.map +1 -1
  16. package/dist-server/service/figure/figure-type.d.ts +6 -0
  17. package/dist-server/service/figure/figure-type.js +20 -1
  18. package/dist-server/service/figure/figure-type.js.map +1 -1
  19. package/dist-server/service/figure/figure-write.d.ts +31 -0
  20. package/dist-server/service/figure/figure-write.js +51 -0
  21. package/dist-server/service/figure/figure-write.js.map +1 -1
  22. package/dist-server/tsconfig.tsbuildinfo +1 -1
  23. package/package.json +8 -8
  24. package/server/service/figure/figure-ai-scenarios.test.ts +32 -0
  25. package/server/service/figure/figure-ai-scenarios.ts +9 -3
  26. package/server/service/figure/figure-catalog-seen-db.test.ts +153 -0
  27. package/server/service/figure/figure-category-db.test.ts +6 -6
  28. package/server/service/figure/figure-context.test.ts +116 -2
  29. package/server/service/figure/figure-context.ts +55 -3
  30. package/server/service/figure/figure-format.ts +3 -2
  31. package/server/service/figure/figure-mutation.ts +27 -6
  32. package/server/service/figure/figure-propose-steps.ts +19 -8
  33. package/server/service/figure/figure-public-db.test.ts +1 -1
  34. package/server/service/figure/figure-rename-db.test.ts +1 -1
  35. package/server/service/figure/figure-revert-db.test.ts +3 -0
  36. package/server/service/figure/figure-type.ts +13 -0
  37. package/server/service/figure/figure-write.ts +60 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@things-factory/figure-service",
3
- "version": "10.1.263",
3
+ "version": "10.1.266",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "@things-factory:registry": "https://registry.npmjs.org"
@@ -25,18 +25,18 @@
25
25
  "test:templates": "node --test scripts/templates.test.mts"
26
26
  },
27
27
  "dependencies": {
28
- "@hatiolab/figure-model": "^0.12.3",
28
+ "@hatiolab/figure-model": "^0.12.4",
29
29
  "@operato/typeorm-history": "^10.0.0",
30
- "@things-factory/ai-client-base": "^10.1.263",
31
- "@things-factory/attachment-base": "^10.1.263",
32
- "@things-factory/auth-base": "^10.1.263",
30
+ "@things-factory/ai-client-base": "^10.1.265",
31
+ "@things-factory/attachment-base": "^10.1.265",
32
+ "@things-factory/auth-base": "^10.1.265",
33
33
  "@things-factory/env": "^10.1.149",
34
- "@things-factory/setting-base": "^10.1.263",
35
- "@things-factory/shell": "^10.1.263",
34
+ "@things-factory/setting-base": "^10.1.265",
35
+ "@things-factory/shell": "^10.1.265",
36
36
  "graphql-scalars": "^1.22.4",
37
37
  "graphql-upload": "^15.0.2",
38
38
  "jszip": "^3.10.1",
39
39
  "koa-router": "^7.4.0"
40
40
  },
41
- "gitHead": "f1ee39eb316c58c7eefa4c35651228d1d1ea4bcf"
41
+ "gitHead": "7c28fbc4a3a031d804a16708143da1b0afd19200"
42
42
  }
@@ -62,6 +62,38 @@ describe('AI 모델링 시나리오', () => {
62
62
  expect(scenario.check(shallow.source, shallow.base)).toContainEqual(expect.stringMatching(/a 90° bend asked/))
63
63
  })
64
64
 
65
+ /*
66
+ * Outside review 2026-11-09: a bottom of 1 mm and of 40 mm passed a request for 15. Each answer below is the
67
+ * reference with one condition changed, so a check that skips a condition shows which one.
68
+ */
69
+ describe('open-tote: each condition asked is checked on its own', () => {
70
+ const scenario = FIGURE_AI_SCENARIOS.find(s => s.id === 'open-tote')!
71
+ const cavity = (change: Record<string, unknown>) => [{ kind: 'set-cavity', part: 'bin', cavity: { wall: 10, start: { closed: 15 }, end: 'open', ...change } }]
72
+ const misses = (answer: unknown[]) => {
73
+ const { base, source } = made(scenario, answer)
74
+ return scenario.check(source, base)
75
+ }
76
+
77
+ it.each([
78
+ ['a closed top', cavity({ end: { closed: 15 } }), /top is not open/],
79
+ ['an open bottom', cavity({ start: 'open' }), /bottom is open too/],
80
+ ['a 1 mm bottom', cavity({ start: { closed: 1 } }), /bottom is 1 mm, 15 asked/],
81
+ ['a 40 mm bottom', cavity({ start: { closed: 40 } }), /bottom is 40 mm, 15 asked/],
82
+ ['one wall of 20 mm', cavity({ wall: { 'x-': 10, 'x+': 20, 'z-': 10, 'z+': 10 } }), /walls .*20.*, 10 asked/],
83
+ ['the box made larger', [{ kind: 'set-section', part: 'bin', across: { x: 700 } }, ...cavity({})], /x size is 700, it was 600/]
84
+ ])('%s is refused, and only for that', (_, answer, said) => {
85
+ expect(misses(answer as unknown[])).toEqual([expect.stringMatching(said)])
86
+ })
87
+
88
+ it('the box taken away is refused', () => {
89
+ expect(misses([{ kind: 'remove-part', target: 'bin' }])).toEqual(['the box is gone'])
90
+ })
91
+
92
+ it('a 15 mm bottom within the kernel\'s tolerance passes', () => {
93
+ expect(misses(cavity({ start: { closed: 15.4 } }))).toEqual([])
94
+ })
95
+ })
96
+
65
97
  describe.each(FIGURE_AI_SCENARIOS.map(s => [s.id, s] as const))('%s', (_, scenario) => {
66
98
  it('its reference answer is taken by the kernel and the gate, and passes its check', () => {
67
99
  const { base, source } = made(scenario, scenario.reference)
@@ -599,14 +599,20 @@ export const FIGURE_AI_SCENARIOS: FigureAIScenario[] = [
599
599
  covers: ['set-cavity'],
600
600
  prompt: '이 상자를 위가 열린 통으로 만들어 줘. 벽 두께 10mm, 바닥 두께 15mm',
601
601
  base: boxDraft,
602
- check: after => {
602
+ /* Read from the shape the kernel evaluated, not the answer's numbers: other steps can reach the same box. */
603
+ check: (after, before) => {
603
604
  const bin = scenarioPartsOf(after).find(p => p.id === 'bin')
604
605
  if (!bin) return ['the box is gone']
605
- const c = bin.shape?.cavity
606
- if (!c) return ['no inside']
606
+ const was = scenarioPartsOf(before!).find(p => p.id === 'bin')!
607
607
  const misses: string[] = []
608
+ for (const axis of ['x', 'y', 'z'] as const)
609
+ if (!near(bin.extent[axis], was.extent[axis])) misses.push(`the box's ${axis} size is ${bin.extent[axis]}, it was ${was.extent[axis]}`)
610
+ const c = bin.shape?.cavity
611
+ if (!c) return [...misses, 'no inside']
608
612
  if (c.end !== 'open') misses.push('its top is not open')
613
+ /* An end is 'open' or { closed: <thickness left there> }. */
609
614
  if (c.start === 'open') misses.push('its bottom is open too')
615
+ else if (!near(Number(c.start?.closed), 15)) misses.push(`its bottom is ${c.start?.closed} mm, 15 asked`)
610
616
  if (!Object.values(c.wall).every(w => near(w as number, 10))) misses.push(`walls ${Object.values(c.wall).join(', ')}, 10 asked`)
611
617
  return misses
612
618
  },
@@ -0,0 +1,153 @@
1
+ /**
2
+ * The catalogue fields -- type, category, tags -- live on the row, not in the source, so the source's compare-and-swap
3
+ * does not hold them. An update of them that says what the editor saw goes on only while the row still holds that
4
+ * (outside review 2026-11-09, :3300: two tabs set the category, the later one wrote over the first without a word).
5
+ */
6
+ import type { DataSource } from 'typeorm'
7
+
8
+ const { DataSource: TypeOrmDataSource } = require('typeorm')
9
+ const shell = require('@things-factory/shell')
10
+ const authBase = require('@things-factory/auth-base')
11
+ const settingBase = require('@things-factory/setting-base')
12
+ const { createFigureAsset, addFigureBox, serializeFigureAsset, parseFigureAsset } = require('@hatiolab/figure-model')
13
+
14
+ let dataSource: DataSource | null = null
15
+ let Figure: any
16
+ let FigureMutation: any
17
+ let write: any
18
+
19
+ function loadCompiled(modulePath: string): any {
20
+ const { existsSync } = require('fs')
21
+ const { join } = require('path')
22
+ const resolved = join(__dirname, '..', '..', '..', 'dist-server', `${modulePath}.js`)
23
+ if (!existsSync(resolved))
24
+ throw new Error(`figure-service 산출물이 없다: ${resolved}\n먼저 빌드할 것:\n yarn workspace @things-factory/figure-service build:server`)
25
+ return require(resolved)
26
+ }
27
+
28
+ beforeAll(async () => {
29
+ Figure = loadCompiled('service/figure/figure').Figure
30
+ const FigureHistory = loadCompiled('service/figure/figure-history').FigureHistory
31
+ const FigureNamespace = loadCompiled('service/figure/figure-namespace-entity').FigureNamespace
32
+ const Subscriber = loadCompiled('service/figure/event-subscriber').FigureHistoryEntitySubscriber
33
+ ;({ FigureMutation } = loadCompiled('service/figure/figure-mutation'))
34
+ write = loadCompiled('service/figure/figure-write')
35
+ dataSource = new TypeOrmDataSource({
36
+ type: 'sqlite',
37
+ database: ':memory:',
38
+ synchronize: true,
39
+ dropSchema: true,
40
+ namingStrategy: new shell.NamingStrategy(),
41
+ entities: [...shell.entities, ...authBase.entities, ...settingBase.entities, Figure, FigureHistory, FigureNamespace],
42
+ subscribers: [Subscriber],
43
+ logging: false
44
+ })
45
+ await dataSource.initialize()
46
+ shell.addDataSource('default', dataSource)
47
+ shell.addDataSource('tx', dataSource)
48
+ })
49
+
50
+ afterAll(async () => {
51
+ await dataSource?.destroy()
52
+ dataSource = null
53
+ })
54
+
55
+ const source = (name: string) =>
56
+ serializeFigureAsset(addFigureBox(createFigureAsset(name), { id: 'body', size: { x: 100, y: 100, z: 100 }, position: { x: 0, y: 50, z: 0 } }))
57
+ let seq = 0
58
+ async function figureIn() {
59
+ const name = `seen-${++seq}`
60
+ const domain = await dataSource!.getRepository(shell.Domain).save({ name, subdomain: name })
61
+ const ctx = { state: { domain, user: undefined, tx: dataSource!.manager } }
62
+ const figure = await new FigureMutation().saveFigure(source('Bin'), ctx, undefined, undefined, require('crypto').randomUUID(), undefined, `bin-${seq}`)
63
+ return { ctx, id: figure.id as string }
64
+ }
65
+ const update = (ctx: any, id: string, patch: object, seen?: object) => new FigureMutation().updateFigure(id, patch, ctx, seen)
66
+ const row = (id: string) => dataSource!.getRepository(Figure).findOneOrFail({ where: { id } })
67
+
68
+ describe('a catalogue field changed by another editor first', () => {
69
+ it('two editors saw no category: the first is written, the second refused with what the row holds now', async () => {
70
+ const { ctx, id } = await figureIn()
71
+ await update(ctx, id, { category: '검증-B' }, { category: null })
72
+ await expect(update(ctx, id, { category: '검증-A' }, { category: null })).rejects.toMatchObject({
73
+ extensions: { code: 'FIGURE_CATALOG_CONFLICT', fields: [{ field: 'category', now: '검증-B' }] }
74
+ })
75
+ expect((await row(id)).category).toBe('검증-B')
76
+ })
77
+
78
+ it('seen as the row holds it, it is written; an empty category is no category either way', async () => {
79
+ const { ctx, id } = await figureIn()
80
+ await update(ctx, id, { category: '' }, { category: null })
81
+ await update(ctx, id, { category: 'lines' }, { category: null })
82
+ await update(ctx, id, { category: 'cells' }, { category: 'lines' })
83
+ expect((await row(id)).category).toBe('cells')
84
+ })
85
+
86
+ it('tags are compared as a list: an empty list is none, another list is a conflict', async () => {
87
+ const { ctx, id } = await figureIn()
88
+ await update(ctx, id, { tags: ['a'] }, { tags: [] })
89
+ await expect(update(ctx, id, { tags: ['b'] }, { tags: null })).rejects.toMatchObject({
90
+ extensions: { code: 'FIGURE_CATALOG_CONFLICT', fields: [{ field: 'tags', now: ['a'] }] }
91
+ })
92
+ await update(ctx, id, { tags: ['a', 'b'] }, { tags: ['a'] })
93
+ expect((await row(id)).tags).toEqual(['a', 'b'])
94
+ })
95
+
96
+ it('refused, nothing of the update is written -- the source sent with it neither', async () => {
97
+ const { ctx, id } = await figureIn()
98
+ await update(ctx, id, { category: 'first' }, { category: null })
99
+ const before = await row(id)
100
+ const renamed = serializeFigureAsset({ ...parseFigureAsset(before.source), name: 'Renamed' })
101
+ await expect(update(ctx, id, { category: 'second', source: renamed }, { category: null })).rejects.toMatchObject({ extensions: { code: 'FIGURE_CATALOG_CONFLICT' } })
102
+ expect((await row(id)).source).toBe(before.source)
103
+ expect((await row(id)).category).toBe('first')
104
+ })
105
+
106
+ it('a change between the check and the write finds nothing to write: the same check is in the UPDATE', async () => {
107
+ const { id } = await figureIn()
108
+ const repository = dataSource!.getRepository(Figure)
109
+ await repository.update({ id }, { category: 'meanwhile', tags: ['x'] })
110
+ for (const seen of [{ category: null }, { category: 'before' }, { tags: null }, { tags: ['y'] }]) {
111
+ const result = await repository.update({ id, ...write.catalogCriteriaOf(seen) }, { description: 'not written' })
112
+ expect(result.affected).toBe(0)
113
+ }
114
+ for (const seen of [{ category: 'meanwhile' }, { tags: ['x'] }, { category: 'meanwhile', tags: ['x'] }]) {
115
+ const result = await repository.update({ id, ...write.catalogCriteriaOf(seen) }, { description: 'written' })
116
+ expect(result.affected).toBe(1)
117
+ }
118
+ })
119
+
120
+ it('a catalogue field changed without what was seen of it is refused: there is no unchecked way to write one', async () => {
121
+ const { ctx, id } = await figureIn()
122
+ await expect(update(ctx, id, { category: 'one' })).rejects.toMatchObject({ extensions: { code: 'FIGURE_CATALOG_SEEN_REQUIRED', fields: ['category'] } })
123
+ await expect(update(ctx, id, { category: 'one', tags: ['a'] }, { category: null })).rejects.toMatchObject({ extensions: { code: 'FIGURE_CATALOG_SEEN_REQUIRED', fields: ['tags'] } })
124
+ expect((await row(id)).category).toBeNull()
125
+ /* A patch that changes none of them needs none: a description, a picture. */
126
+ await update(ctx, id, { description: 'no catalogue field' })
127
+ expect((await row(id)).description).toBe('no catalogue field')
128
+ })
129
+
130
+ it('only the fields changed are compared: one changed elsewhere and not by this patch does not refuse it', async () => {
131
+ const { ctx, id } = await figureIn()
132
+ await update(ctx, id, { tags: ['elsewhere'] }, { tags: null })
133
+ await update(ctx, id, { category: 'mine' }, { category: null })
134
+ expect(await row(id)).toMatchObject({ category: 'mine', tags: ['elsewhere'] })
135
+ })
136
+
137
+ it('tag order is part of the value: the same tags in another order are a change, and a conflict', async () => {
138
+ const { ctx, id } = await figureIn()
139
+ await update(ctx, id, { tags: ['a', 'b'] }, { tags: null })
140
+ await expect(update(ctx, id, { tags: ['c'] }, { tags: ['b', 'a'] })).rejects.toMatchObject({ extensions: { code: 'FIGURE_CATALOG_CONFLICT' } })
141
+ })
142
+
143
+ it('after a conflict, a save expecting what the row held then is refused again if it changed once more', async () => {
144
+ const { ctx, id } = await figureIn()
145
+ await update(ctx, id, { category: 'B' }, { category: null })
146
+ const refused = await update(ctx, id, { category: 'A' }, { category: null }).catch((e: any) => e)
147
+ const now = refused.extensions.fields[0].now
148
+ expect(now).toBe('B')
149
+ await update(ctx, id, { category: 'C' }, { category: 'B' })
150
+ await expect(update(ctx, id, { category: 'A' }, { category: now })).rejects.toMatchObject({ extensions: { code: 'FIGURE_CATALOG_CONFLICT', fields: [{ field: 'category', now: 'C' }] } })
151
+ expect((await row(id)).category).toBe('C')
152
+ })
153
+ })
@@ -77,8 +77,8 @@ describe('categories', () => {
77
77
  const ctx = await context()
78
78
  expect(await new FigureQuery().figureCategories()).toBeNull()
79
79
  const figure = await draft(ctx, 'free')
80
- await new FigureMutation().updateFigure(figure.id, { category: 'conveyors' }, ctx)
81
- await new FigureMutation().updateFigure(figure.id, { category: 'lines' }, ctx)
80
+ await new FigureMutation().updateFigure(figure.id, { category: 'conveyors' }, ctx, { category: null })
81
+ await new FigureMutation().updateFigure(figure.id, { category: 'lines' }, ctx, { category: 'conveyors' })
82
82
  await expect(new FigureMutation().releaseFigure(figure.id, 'one', ctx)).resolves.toMatchObject({ version: 1 })
83
83
  })
84
84
 
@@ -88,10 +88,10 @@ describe('categories', () => {
88
88
  const ctx = await context()
89
89
  const figure = await draft(ctx, 'mixer')
90
90
  await expect(new FigureMutation().releaseFigure(figure.id, 'one', ctx)).rejects.toMatchObject({ code: 'figure-category-missing' })
91
- await expect(new FigureMutation().updateFigure(figure.id, { category: 'conveyors' }, ctx)).rejects.toMatchObject({ code: 'figure-category-unknown' })
92
- await new FigureMutation().updateFigure(figure.id, { category: 'EQUIPMENT' }, ctx)
93
- await expect(new FigureMutation().updateFigure(figure.id, { category: 'CARRIER' }, ctx)).rejects.toMatchObject({ code: 'figure-category-fixed' })
94
- await expect(new FigureMutation().updateFigure(figure.id, { category: 'EQUIPMENT', description: 'same category again' }, ctx)).resolves.toBeTruthy()
91
+ await expect(new FigureMutation().updateFigure(figure.id, { category: 'conveyors' }, ctx, { category: null })).rejects.toMatchObject({ code: 'figure-category-unknown' })
92
+ await new FigureMutation().updateFigure(figure.id, { category: 'EQUIPMENT' }, ctx, { category: null })
93
+ await expect(new FigureMutation().updateFigure(figure.id, { category: 'CARRIER' }, ctx, { category: 'EQUIPMENT' })).rejects.toMatchObject({ code: 'figure-category-fixed' })
94
+ await expect(new FigureMutation().updateFigure(figure.id, { category: 'EQUIPMENT', description: 'same category again' }, ctx, { category: 'EQUIPMENT' })).resolves.toBeTruthy()
95
95
  await expect(new FigureMutation().releaseFigure(figure.id, 'one', ctx)).resolves.toMatchObject({ version: 1 })
96
96
  })
97
97
 
@@ -6,12 +6,12 @@
6
6
  * here are made by the kernel's own commands, as a person makes them in the modeller: a rack of shelves, each fastened on
7
7
  * the one below, grown until it crosses the budget.
8
8
  */
9
- import { FIGURE_PROPOSAL_KINDS, applyFigureProposal, createFigureAsset, serializeFigureAsset } from '@hatiolab/figure-model'
9
+ import { FIGURE_PROPOSAL_KINDS, applyFigureProposal, createFigureAsset, figurePipesOf, serializeFigureAsset } from '@hatiolab/figure-model'
10
10
  import type { FigureAsset } from '@hatiolab/figure-model'
11
11
  import type { AIClient } from '@things-factory/ai-client-base'
12
12
 
13
13
  import { FIGURE_CONTEXT_BUDGET, figureViewOf, unreadPartEdits, unreadSectionEdits } from './figure-context'
14
- import { ProposeFigureFailure, judgeFigureAnswer, proposeFigureSteps } from './figure-propose-steps'
14
+ import { ProposeFigureFailure, judgeFigureAnswer, proposeFigureSteps, taskPromptFigure } from './figure-propose-steps'
15
15
  import { parseSource } from './figure-format'
16
16
 
17
17
  const shelf = (i: number) => [
@@ -286,3 +286,117 @@ describe('the step writer is shown the same view', () => {
286
286
  expect(client.sent).toHaveLength(0)
287
287
  })
288
288
  })
289
+
290
+ /*
291
+ * Outside review 2026-11-09: the view of a large figure was measured, then every pipe and palette token of the draft was
292
+ * appended to the prompt beside it -- an outline of 2,335 characters went out as 129,994. What the writer is shown of
293
+ * the draft is the view and only the view: its pipes and tokens are chosen inside the same budget.
294
+ */
295
+ describe('pipes and palette tokens are inside the view’s budget', () => {
296
+ /* Not fastened: a pipe fastened to the plane carries its seat's graph, and one of 11 pieces is past the kernel's 1 MiB. */
297
+ const pipePart = (id: string, path: unknown[]) => [{ kind: 'add-part', part: { id, kind: 'pipe', dimensions: { radius: 40, wall: 4 }, path } }]
298
+ const ELBOW = [{ line: 500 }, { bend: { radius: 120, angle: 90, toward: 90 } }, { line: 400 }]
299
+ /* 31 pieces: the most a sweep takes is 32. */
300
+ const LONG = Array.from({ length: 31 }, (_, i) => (i % 2 ? { bend: { radius: 120, angle: 30, toward: (i * 45) % 360 } } : { line: 200 + i }))
301
+ const chars = (value: unknown) => JSON.stringify(value).length
302
+ /** The prompt's own words around the view: the request, the instructions, the line names. */
303
+ const PROMPT_WORDS = 2_000
304
+
305
+ let tokens: FigureAsset
306
+ let pipes: FigureAsset
307
+ let padded: FigureAsset
308
+ beforeAll(() => {
309
+ /* One elbow and 4,000 palette tokens, the reproduction's figure. */
310
+ tokens = applyFigureProposal(createFigureAsset('Elbow'), pipePart('pipe', ELBOW) as never)
311
+ for (let i = 0; i < 4_000; i++) (tokens.palette as Record<string, string>)[`palette.audit-extra-token-${i}`] = '#123456'
312
+ tokens.appearance.find(a => a.target === 'pipe')!.material = { token: 'palette.audit-extra-token-3999' } as never
313
+
314
+ /* Pipes, one with a long path, until the figure is twice the budget: all its parts cannot be read at once. */
315
+ let many = applyFigureProposal(createFigureAsset('Pipes'), pipePart('long', LONG) as never)
316
+ for (let i = 0; size(many) <= 2 * FIGURE_CONTEXT_BUDGET; i++) many = applyFigureProposal(many, pipePart(`pipe-${i}`, ELBOW) as never)
317
+ pipes = many
318
+
319
+ /* A single elbow padded to just under the budget: whole by its source, past it with its pipe's reading. */
320
+ const pad = (n: number) =>
321
+ applyFigureProposal(applyFigureProposal(createFigureAsset('Padded'), pipePart('pipe', ELBOW) as never), [
322
+ { kind: 'add-part', part: { id: 'stand', kind: 'box', dimensions: { width: 200, height: 200, depth: 200 } } },
323
+ { kind: 'add-binding', id: 'seat', label: 'x'.repeat(n), role: 'seat', part: 'stand', face: 'top', accepts: ['box'], capacity: 1 }
324
+ ] as never)
325
+ const probe = pad(1_000)
326
+ padded = pad(1_000 + FIGURE_CONTEXT_BUDGET - 10 - chars(probe))
327
+ })
328
+
329
+ it('the figures are what they say: the kernel takes them, each past or at the edge of the budget', () => {
330
+ expect(chars(tokens)).toBeGreaterThan(FIGURE_CONTEXT_BUDGET)
331
+ expect(chars(pipes)).toBeGreaterThan(FIGURE_CONTEXT_BUDGET)
332
+ expect(chars(padded)).toBe(FIGURE_CONTEXT_BUDGET - 10)
333
+ expect(figurePipesOf(pipes).long.path).toHaveLength(31)
334
+ })
335
+
336
+ it('a large palette, nothing read: the view is within the budget and the prompt adds nothing of the draft to it', () => {
337
+ const view = figureViewOf(tokens)
338
+ expect(view.whole).toBe(false)
339
+ expect(view.shown).toEqual([])
340
+ expect(view.pipes).toBeUndefined()
341
+ expect(chars(view)).toBeLessThanOrEqual(FIGURE_CONTEXT_BUDGET)
342
+ expect(view.palette!.more).toBeGreaterThan(0)
343
+ expect(view.palette!.tokens.length + view.palette!.more!).toBe(4_000 + Object.keys(createFigureAsset('x').palette).length)
344
+
345
+ const prompt = taskPromptFigure({ client: undefined as never, prompt: 'change nothing', base: tokens }, view)
346
+ expect(prompt.length).toBeLessThanOrEqual(FIGURE_CONTEXT_BUDGET + PROMPT_WORDS)
347
+ expect(prompt).not.toContain('"radius":40,"wall":4,"path"')
348
+ expect(prompt).toMatch(/and \d+ more, in \/palette\./)
349
+ })
350
+
351
+ it('the selected pipe is shown with its set-pipe reading and its token first, and only it may be changed', () => {
352
+ const view = figureViewOf(tokens, { parts: ['pipe'] })
353
+ expect(view.shown).toEqual(['pipe'])
354
+ expect(view.pipes).toEqual({ pipe: figurePipesOf(tokens).pipe })
355
+ expect(view.palette!.tokens[0]).toBe('palette.audit-extra-token-3999')
356
+ expect(chars(view)).toBeLessThanOrEqual(FIGURE_CONTEXT_BUDGET)
357
+ expect(unreadPartEdits(tokens, [{ kind: 'set-pipe', part: 'pipe', path: ELBOW } as never], view)).toEqual([])
358
+ })
359
+
360
+ it('many pipes: only the pipes shown are read, a long path whole; the others are not in the prompt and may not change', () => {
361
+ const view = figureViewOf(pipes, { parts: ['long'] })
362
+ expect(view.shown).toEqual(['long'])
363
+ expect(Object.keys(view.pipes!)).toEqual(['long'])
364
+ expect(view.pipes!.long).toEqual(figurePipesOf(pipes).long)
365
+ expect(chars(view)).toBeLessThanOrEqual(FIGURE_CONTEXT_BUDGET)
366
+
367
+ const prompt = taskPromptFigure({ client: undefined as never, prompt: 'extend', base: pipes }, view)
368
+ expect(prompt.length).toBeLessThanOrEqual(FIGURE_CONTEXT_BUDGET + PROMPT_WORDS)
369
+ expect(prompt).toContain(JSON.stringify({ long: figurePipesOf(pipes).long }))
370
+ expect(prompt).not.toContain(JSON.stringify(figurePipesOf(pipes)['pipe-0']))
371
+ expect(unreadPartEdits(pipes, [{ kind: 'set-pipe', part: 'pipe-0', path: ELBOW } as never], view)).toEqual([expect.stringMatching(/UNREAD_PART.*"pipe-0"/)])
372
+ })
373
+
374
+ it('pipes asked for that do not fit are said in notRead, not shown, and their readings are not in the view', () => {
375
+ const all = partsOf(pipes)
376
+ const view = figureViewOf(pipes, { parts: all })
377
+ /* The reasons are themselves held to the budget: as many as fit are said, and one is enough to stop the proposal. */
378
+ expect(view.notRead!.length).toBeGreaterThan(0)
379
+ for (const one of view.notRead!) expect(view.shown).not.toContain((one as { part: string }).part)
380
+ expect(Object.keys(view.pipes ?? {})).toEqual(view.shown)
381
+ expect(chars(view)).toBeLessThanOrEqual(FIGURE_CONTEXT_BUDGET)
382
+ })
383
+
384
+ it('a source within the budget whose readings would cross it is shown in part, not whole with them appended', () => {
385
+ const view = figureViewOf(padded)
386
+ expect(view.whole).toBe(false)
387
+ expect(chars(view)).toBeLessThanOrEqual(FIGURE_CONTEXT_BUDGET)
388
+ const prompt = taskPromptFigure({ client: undefined as never, prompt: 'x', base: padded }, view)
389
+ expect(prompt.length).toBeLessThanOrEqual(FIGURE_CONTEXT_BUDGET + PROMPT_WORDS)
390
+ })
391
+
392
+ it('a whole figure is shown with every pipe and token, all of it within the budget', () => {
393
+ const elbow = applyFigureProposal(createFigureAsset('Elbow'), pipePart('pipe', ELBOW) as never)
394
+ const view = figureViewOf(elbow)
395
+ expect(view.whole).toBe(true)
396
+ expect(view.pipes).toEqual(figurePipesOf(elbow))
397
+ expect(view.palette!.tokens).toEqual(Object.keys(elbow.palette))
398
+ const prompt = taskPromptFigure({ client: undefined as never, prompt: 'x', base: elbow }, view)
399
+ expect(prompt).toContain(serializeFigureAsset(elbow))
400
+ expect(prompt).toContain(JSON.stringify(figurePipesOf(elbow)))
401
+ })
402
+ })
@@ -8,9 +8,15 @@
8
8
  * Pointer with the entries inside it, and read by pointer. The full source stays on the server: a proposal is applied
9
9
  * and judged on it, on the version the request was made on.
10
10
  *
11
+ * Beside the source or the outline the view carries what the writer works from that the source does not say plainly: each
12
+ * pipe as set-pipe takes it and the palette's token names. They are chosen inside the same budget -- a pipe with the part
13
+ * shown, the tokens of the parts shown first -- so nothing is added to the view after it was measured (outside review
14
+ * 2026-11-09: an outline of 2,335 characters went out as a prompt of 129,994, every pipe and token appended to it).
15
+ *
11
16
  * A proposal on a figure shown in part changes only what it was shown: no part not read in full, and nothing inside a
12
17
  * section left out and not read. Read is what the server put before the writer, never what a model says it read.
13
18
  */
19
+ import { figurePipesOf } from '@hatiolab/figure-model'
14
20
  import type { FigureAsset, FigureProposalStep } from '@hatiolab/figure-model'
15
21
 
16
22
  /** The most of a figure, serialized, the model is shown in one read. Not a validity limit: that is the kernel's. */
@@ -82,6 +88,13 @@ export interface FigureView {
82
88
  shown?: string[]
83
89
  /** The sections read, by pointer. */
84
90
  sections?: Record<string, unknown>
91
+ /** Each pipe and duct of the parts in the view, as set-pipe takes it: every one when whole, the shown parts' in part. */
92
+ pipes?: Record<string, unknown>
93
+ /**
94
+ * The palette's token names, when the view does not already hold the palette: the shown parts' first, as many as fit,
95
+ * with how many more there are in /palette.
96
+ */
97
+ palette?: { tokens: string[]; more?: number }
85
98
  /** What was asked for and not shown, with why and what to read instead. */
86
99
  notRead?: ({ part: string; reason: string } | { section: string; reason: string })[]
87
100
  }
@@ -245,6 +258,15 @@ export function figureOutlineOf(asset: FigureAsset, chars = length(asset)): Figu
245
258
  return outline as FigureOutline
246
259
  }
247
260
 
261
+ /**
262
+ * Every pipe and duct of a figure as set-pipe takes it, from one evaluation that every part shown takes its own from.
263
+ * A figure with no swept shape is not evaluated for it.
264
+ */
265
+ function pipesOf(asset: FigureAsset): Record<string, unknown> {
266
+ const swept = ((asset.document.model as Dynamic).nodes as Dynamic[]).some(n => typeof n?.op === 'string' && n.op.startsWith('sweep@'))
267
+ return swept ? figurePipesOf(asset) : {}
268
+ }
269
+
248
270
  /* ── The view ────────────────────────────────────────────────────────────────────────── */
249
271
 
250
272
  /**
@@ -253,10 +275,14 @@ export function figureOutlineOf(asset: FigureAsset, chars = length(asset)): Figu
253
275
  */
254
276
  export function figureViewOf(asset: FigureAsset, request: FigureReadRequest = {}): FigureView {
255
277
  const chars = length(asset)
256
- if (chars <= FIGURE_CONTEXT_BUDGET) return { whole: true, source: asset }
278
+ const pipes = pipesOf(asset)
279
+ if (chars <= FIGURE_CONTEXT_BUDGET) {
280
+ const whole: FigureView = { whole: true, source: asset, ...(Object.keys(pipes).length ? { pipes } : {}), palette: { tokens: Object.keys(asset.palette ?? {}) } }
281
+ if (length(whole) <= FIGURE_CONTEXT_BUDGET) return whole
282
+ }
257
283
 
258
284
  const outline = figureOutlineOf(asset, chars)
259
- const view: FigureView = { whole: false, outline, parts: {}, shown: [], sections: {}, notRead: [] }
285
+ const view: FigureView = { whole: false, outline, parts: {}, shown: [], sections: {}, pipes: {}, notRead: [] }
260
286
  const room = () => FIGURE_CONTEXT_BUDGET - length(view)
261
287
  const refuse = (one: { part: string; reason: string } | { section: string; reason: string }) => {
262
288
  if (length(one) + 1 <= room()) view.notRead!.push(one)
@@ -268,11 +294,15 @@ export function figureViewOf(asset: FigureAsset, request: FigureReadRequest = {}
268
294
  refuse({ part, reason: `${part} is not a part of this figure; the outline lists its parts` })
269
295
  continue
270
296
  }
271
- const cost = length(one) + length(part) + length(part) + 3
297
+ /* A pipe is shown with its set-pipe reading or not at all: the reading is how its path is written back. */
298
+ const pipe = pipes[part]
299
+ const cost = length(one) + length(part) + length(part) + 3 + (pipe ? length(pipe) + length(part) + 2 : 0)
272
300
  view.parts![part] = one
273
301
  view.shown!.push(part)
302
+ if (pipe) view.pipes![part] = pipe
274
303
  if (room() >= 0) continue
275
304
  delete view.parts![part]
305
+ delete view.pipes![part]
276
306
  view.shown!.pop()
277
307
  if (cost <= FIGURE_CONTEXT_BUDGET - length(outline)) {
278
308
  refuse({ part, reason: `${part} (${cost} characters) does not fit beside what is already read; read it in another call with fewer parts or sections` })
@@ -308,7 +338,29 @@ export function figureViewOf(asset: FigureAsset, request: FigureReadRequest = {}
308
338
  })
309
339
  }
310
340
 
341
+ /*
342
+ The palette's token names, where the outline left /palette out: the shown parts' tokens first, then the rest, while
343
+ they fit; the rest are counted, and /palette is read by pointer like any section left out.
344
+ */
311
345
  if (!view.notRead!.length) delete view.notRead
346
+ if (!Object.keys(view.pipes!).length) delete view.pipes
347
+ if ((outline.omitted ?? []).some(o => o.section === '/palette')) {
348
+ const used = view.shown!.map(part => (view.parts![part]!.appearance as Dynamic)?.material?.token).filter((t): t is string => typeof t === 'string')
349
+ const all = Object.keys(asset.palette ?? {})
350
+ const ordered = [...new Set([...used.filter(t => all.includes(t)), ...all])]
351
+ const palette: { tokens: string[]; more?: number } = { tokens: [], more: ordered.length }
352
+ view.palette = palette
353
+ for (const token of ordered) {
354
+ palette.tokens.push(token)
355
+ palette.more = ordered.length - palette.tokens.length
356
+ if (room() < 0) {
357
+ palette.tokens.pop()
358
+ palette.more = ordered.length - palette.tokens.length
359
+ break
360
+ }
361
+ }
362
+ if (!palette.more) delete palette.more
363
+ }
312
364
  return view
313
365
  }
314
366
 
@@ -17,7 +17,8 @@ export interface ParsedSource {
17
17
  /** The source to store, as the kernel serializes it. */
18
18
  source: string
19
19
  /** Computed from the source, never taken from the client -- a client's numbers could lie to the catalogue. */
20
- derived: { score: number; triangles: number; groups: number }
20
+ /** The catalogue's columns read from the source: its name, and the measures the card shows. */
21
+ derived: { name: string; score: number; triangles: number; groups: number }
21
22
  /** Findings that do not block the save; the caller returns them with the answer. */
22
23
  violations: FigureFinding[]
23
24
  }
@@ -134,7 +135,7 @@ export function parseSource(sourceJson: string): ParsedSource {
134
135
  const score = figureScoreOf(asset)
135
136
  return {
136
137
  source: serializeFigureAsset(asset),
137
- derived: { score: (score?.score ?? null) as unknown as number, triangles: cost.triangles, groups: cost.groups },
138
+ derived: { name: asset.name, score: (score?.score ?? null) as unknown as number, triangles: cost.triangles, groups: cost.groups },
138
139
  violations: []
139
140
  }
140
141
  }
@@ -7,7 +7,7 @@ import { aiClientFor } from '@things-factory/ai-client-base'
7
7
 
8
8
  import { Figure } from './figure.js'
9
9
  import { FigureHistory } from './figure-history.js'
10
- import { FigurePatch, FigureRevertResult, FigureSaveResult, NewFigure } from './figure-type.js'
10
+ import { FigureCatalogSeen, FigurePatch, FigureRevertResult, FigureSaveResult, NewFigure } from './figure-type.js'
11
11
  import { FigureReplacedDraft } from './figure-replaced-draft.js'
12
12
  import { revertKeepingDraft, undoRevert } from './figure-revert.js'
13
13
  import { recordProposals } from './figure-proposal.js'
@@ -18,7 +18,7 @@ import { assertReleasableNamespace, namespaceForNewFigure, namespaceOf } from '.
18
18
  import { assertFigureCategory, assertReleasableCategory } from './figure-categories.js'
19
19
  import { parseSource } from './figure-format.js'
20
20
  import { ProposeFigureFailure, proposalFailureForPerson, proposeFigureSteps } from './figure-propose-steps.js'
21
- import { prepareFigureWrite, compareAndSwapFigure, pictureOf } from './figure-write.js'
21
+ import { prepareFigureWrite, compareAndSwapFigure, pictureOf, assertCatalogSeen, catalogConflict, catalogConflictsOf, catalogCriteriaOf } from './figure-write.js'
22
22
  import { keepMesh, requireMeshFiles } from './figure-mesh-store.js'
23
23
  import { GlbRefusal, GLB_MAX_BYTES } from './figure-glb.js'
24
24
  import { FigureMeshUpload } from './figure-type.js'
@@ -235,12 +235,23 @@ export class FigureMutation {
235
235
  async updateFigure(
236
236
  @Arg('id') id: string,
237
237
  @Arg('patch') patch: FigurePatch,
238
- @Ctx() context: ResolverContext
238
+ @Ctx() context: ResolverContext,
239
+ @Arg('seen', type => FigureCatalogSeen, {
240
+ nullable: true,
241
+ description:
242
+ 'The type, category and tags as the editor saw them, null when empty. Required for each of them the patch changes (FIGURE_CATALOG_SEEN_REQUIRED); ' +
243
+ 'the update goes on only while the row still holds them (FIGURE_CATALOG_CONFLICT).'
244
+ })
245
+ seen?: FigureCatalogSeen
239
246
  ): Promise<FigureSaveResult> {
240
247
  const { domain, user, tx } = context.state
241
248
  const repository = tx.getRepository(Figure)
242
249
 
243
250
  const figure = await ownFigure(repository, domain, id)
251
+ assertCatalogSeen(patch, seen)
252
+ /* The catalogue fields are the row's, not the source's: checked here and again in the UPDATE (catalogCriteriaOf). */
253
+ const conflicts = seen ? catalogConflictsOf(figure, seen) : []
254
+ if (conflicts.length) throw catalogConflict(conflicts)
244
255
 
245
256
  /*
246
257
  **그림만 바꾸면 발행이 풀리지 않는다.** 미리보기에서 사람이 돌려 놓은 각도로 찍은 그림이 그렇게 온다.
@@ -257,7 +268,7 @@ export class FigureMutation {
257
268
 
258
269
  // 정본이 바뀌면 파생값도 다시 계산한다. 안 바뀌었으면 손대지 않는다 —
259
270
  // 이름만 고쳤는데 점수가 흔들리면 읽는 사람이 원인을 못 찾는다.
260
- let derived: { score: number; triangles: number; groups: number } | undefined
271
+ let derived: { name: string; score: number; triangles: number; groups: number } | undefined
261
272
  let violations = []
262
273
  let source = figure.source
263
274
 
@@ -316,8 +327,18 @@ export class FigureMutation {
316
327
  ...picture,
317
328
  updater: user
318
329
  }
319
- if ('source' in changes) await compareAndSwapFigure(criteria => repository.update(criteria, changes), id, domain.id, figure.source)
320
- else await repository.update({ id, domain: { id: domain.id } }, changes)
330
+ const unchanged = seen ? catalogCriteriaOf(seen) : {}
331
+ const written = async (criteria: object) => {
332
+ const result = await repository.update({ ...criteria, ...unchanged } as never, changes)
333
+ /* Nothing written: a catalogue field changed since the check above is said as one; the source as before. */
334
+ if (seen && result.affected !== 1) {
335
+ const now = catalogConflictsOf(await repository.findOneOrFail({ where: { id, domain: { id: domain.id } } }), seen)
336
+ if (now.length) throw catalogConflict(now)
337
+ }
338
+ return result
339
+ }
340
+ if ('source' in changes) await compareAndSwapFigure(written, id, domain.id, figure.source)
341
+ else await written({ id, domain: { id: domain.id } })
321
342
  const saved = await repository.findOneOrFail({ where: { id, domain: { id: domain.id } } })
322
343
 
323
344
  return { figure: saved, violations }