@things-factory/figure-service 10.1.277 → 10.1.279

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 (128) hide show
  1. package/package.json +23 -8
  2. package/dist-server/index.js.map +0 -1
  3. package/dist-server/migrations/index.js.map +0 -1
  4. package/dist-server/routers/figure-mesh-router.js.map +0 -1
  5. package/dist-server/routers/figure-package-router.js.map +0 -1
  6. package/dist-server/routers/figure-thumbnail-router.js.map +0 -1
  7. package/dist-server/routes.js.map +0 -1
  8. package/dist-server/service/figure/event-subscriber.js.map +0 -1
  9. package/dist-server/service/figure/figure-ai-scenarios-run.js.map +0 -1
  10. package/dist-server/service/figure/figure-ai-scenarios.js.map +0 -1
  11. package/dist-server/service/figure/figure-categories.js.map +0 -1
  12. package/dist-server/service/figure/figure-context.js.map +0 -1
  13. package/dist-server/service/figure/figure-format.js.map +0 -1
  14. package/dist-server/service/figure/figure-glb.js.map +0 -1
  15. package/dist-server/service/figure/figure-history.js.map +0 -1
  16. package/dist-server/service/figure/figure-llm-provider.js.map +0 -1
  17. package/dist-server/service/figure/figure-mesh-store.js.map +0 -1
  18. package/dist-server/service/figure/figure-mutation.js.map +0 -1
  19. package/dist-server/service/figure/figure-namespace-entity.js.map +0 -1
  20. package/dist-server/service/figure/figure-namespace-resolver.js.map +0 -1
  21. package/dist-server/service/figure/figure-namespace.js.map +0 -1
  22. package/dist-server/service/figure/figure-package-export.js.map +0 -1
  23. package/dist-server/service/figure/figure-proposal-record.js.map +0 -1
  24. package/dist-server/service/figure/figure-proposal.js.map +0 -1
  25. package/dist-server/service/figure/figure-propose-steps.js.map +0 -1
  26. package/dist-server/service/figure/figure-propose-type.js.map +0 -1
  27. package/dist-server/service/figure/figure-public.js.map +0 -1
  28. package/dist-server/service/figure/figure-query.js.map +0 -1
  29. package/dist-server/service/figure/figure-rename.js.map +0 -1
  30. package/dist-server/service/figure/figure-replaced-draft.js.map +0 -1
  31. package/dist-server/service/figure/figure-revert.js.map +0 -1
  32. package/dist-server/service/figure/figure-subject.js.map +0 -1
  33. package/dist-server/service/figure/figure-thumbnail-reader.js.map +0 -1
  34. package/dist-server/service/figure/figure-thumbnail-store.js.map +0 -1
  35. package/dist-server/service/figure/figure-thumbnail-upgrade.js.map +0 -1
  36. package/dist-server/service/figure/figure-tools.js.map +0 -1
  37. package/dist-server/service/figure/figure-type.js.map +0 -1
  38. package/dist-server/service/figure/figure-write.js.map +0 -1
  39. package/dist-server/service/figure/figure.js.map +0 -1
  40. package/dist-server/service/figure/index.js.map +0 -1
  41. package/dist-server/service/figure-recipe/figure-recipe-resolver.js.map +0 -1
  42. package/dist-server/service/figure-recipe/figure-recipe-templates.js.map +0 -1
  43. package/dist-server/service/figure-recipe/figure-recipe-type.js.map +0 -1
  44. package/dist-server/service/figure-recipe/index.js.map +0 -1
  45. package/dist-server/service/index.js.map +0 -1
  46. package/dist-server/tsconfig.tsbuildinfo +0 -1
  47. package/scripts/build-templates.mts +0 -64
  48. package/scripts/figure-ai-scenarios-agent.cjs +0 -98
  49. package/scripts/rename-figures-to-full-names.mjs +0 -211
  50. package/scripts/templates.test.mts +0 -112
  51. package/server/index.ts +0 -46
  52. package/server/migrations/index.ts +0 -9
  53. package/server/routers/figure-mesh-router.ts +0 -63
  54. package/server/routers/figure-package-router.ts +0 -53
  55. package/server/routers/figure-thumbnail-router.ts +0 -159
  56. package/server/routes.ts +0 -30
  57. package/server/service/figure/catalog-db.test.ts +0 -162
  58. package/server/service/figure/event-subscriber.ts +0 -66
  59. package/server/service/figure/figure-ai-scenarios-run.ts +0 -127
  60. package/server/service/figure/figure-ai-scenarios.live.test.ts +0 -59
  61. package/server/service/figure/figure-ai-scenarios.test.ts +0 -109
  62. package/server/service/figure/figure-ai-scenarios.ts +0 -798
  63. package/server/service/figure/figure-blueprint-query.test.ts +0 -536
  64. package/server/service/figure/figure-catalog-seen-db.test.ts +0 -153
  65. package/server/service/figure/figure-categories.ts +0 -50
  66. package/server/service/figure/figure-category-db.test.ts +0 -127
  67. package/server/service/figure/figure-context.test.ts +0 -402
  68. package/server/service/figure/figure-context.ts +0 -510
  69. package/server/service/figure/figure-deprecation-db.test.ts +0 -218
  70. package/server/service/figure/figure-format.test.ts +0 -423
  71. package/server/service/figure/figure-format.ts +0 -783
  72. package/server/service/figure/figure-glb.test.ts +0 -112
  73. package/server/service/figure/figure-glb.ts +0 -251
  74. package/server/service/figure/figure-history.ts +0 -192
  75. package/server/service/figure/figure-inspect-db.test.ts +0 -131
  76. package/server/service/figure/figure-llm-provider.ts +0 -20
  77. package/server/service/figure/figure-llm-smoke.test.ts +0 -95
  78. package/server/service/figure/figure-mesh-db.test.ts +0 -246
  79. package/server/service/figure/figure-mesh-store.ts +0 -91
  80. package/server/service/figure/figure-mutation.ts +0 -656
  81. package/server/service/figure/figure-namespace-db.test.ts +0 -315
  82. package/server/service/figure/figure-namespace-entity.ts +0 -67
  83. package/server/service/figure/figure-namespace-resolver.ts +0 -54
  84. package/server/service/figure/figure-namespace.ts +0 -156
  85. package/server/service/figure/figure-package-export.ts +0 -136
  86. package/server/service/figure/figure-proposal-db.test.ts +0 -117
  87. package/server/service/figure/figure-proposal-record.ts +0 -38
  88. package/server/service/figure/figure-proposal.ts +0 -41
  89. package/server/service/figure/figure-propose-clips.test.ts +0 -69
  90. package/server/service/figure/figure-propose-steps.test.ts +0 -324
  91. package/server/service/figure/figure-propose-steps.ts +0 -354
  92. package/server/service/figure/figure-propose-type.ts +0 -46
  93. package/server/service/figure/figure-public-db.test.ts +0 -288
  94. package/server/service/figure/figure-public.ts +0 -60
  95. package/server/service/figure/figure-query.ts +0 -511
  96. package/server/service/figure/figure-release-check.test.ts +0 -63
  97. package/server/service/figure/figure-release-record-db.test.ts +0 -153
  98. package/server/service/figure/figure-release-size-db.test.ts +0 -156
  99. package/server/service/figure/figure-rename-db.test.ts +0 -237
  100. package/server/service/figure/figure-rename.test.ts +0 -117
  101. package/server/service/figure/figure-rename.ts +0 -143
  102. package/server/service/figure/figure-replaced-draft.ts +0 -99
  103. package/server/service/figure/figure-revert-db.test.ts +0 -163
  104. package/server/service/figure/figure-revert-race.pg.test.ts +0 -168
  105. package/server/service/figure/figure-revert.ts +0 -186
  106. package/server/service/figure/figure-subject.test.ts +0 -41
  107. package/server/service/figure/figure-subject.ts +0 -21
  108. package/server/service/figure/figure-thumbnail-db.test.ts +0 -279
  109. package/server/service/figure/figure-thumbnail-reader.ts +0 -20
  110. package/server/service/figure/figure-thumbnail-store.ts +0 -111
  111. package/server/service/figure/figure-thumbnail-upgrade.pg.test.ts +0 -93
  112. package/server/service/figure/figure-thumbnail-upgrade.ts +0 -70
  113. package/server/service/figure/figure-tool-doors.test.ts +0 -127
  114. package/server/service/figure/figure-tools-door-db.test.ts +0 -227
  115. package/server/service/figure/figure-tools.test.ts +0 -817
  116. package/server/service/figure/figure-tools.ts +0 -611
  117. package/server/service/figure/figure-type.ts +0 -241
  118. package/server/service/figure/figure-write.test.ts +0 -15
  119. package/server/service/figure/figure-write.ts +0 -131
  120. package/server/service/figure/figure.ts +0 -241
  121. package/server/service/figure/index.ts +0 -13
  122. package/server/service/figure-recipe/figure-recipe-resolver.ts +0 -38
  123. package/server/service/figure-recipe/figure-recipe-templates.test.ts +0 -47
  124. package/server/service/figure-recipe/figure-recipe-templates.ts +0 -70
  125. package/server/service/figure-recipe/figure-recipe-type.ts +0 -31
  126. package/server/service/figure-recipe/index.ts +0 -3
  127. package/server/service/index.ts +0 -34
  128. package/tsconfig.json +0 -14
@@ -1 +0,0 @@
1
- {"version":3,"file":"figure-propose-steps.js","sourceRoot":"","sources":["../../../server/service/figure/figure-propose-steps.ts"],"names":[],"mappings":";;;AA6EA,4DAEC;AAqBD,8CA4BC;AAcD,4CAwCC;AAwDD,8CAqDC;AAGD,gDA2DC;AAjWD,yDAA+K;AAE/K,mEAA+E;AAG/E,2DAAgI;AAEhI;;;;;;;;GAQG;AAEH,gGAAgG;AAChG,MAAM,YAAY,GAAG,CAAC,CAAA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oreOf } from '@hatiolab/figure-model'\nimport type { FigureAsset, FigureProposalStep, FigureRefusalDetails } from '@hatiolab/figure-model'\nimport { AIAnswerNotJSON, type AIClient } from '@things-factory/ai-client-base'\nimport type { AIImageMediaType, AIMessage } from '@things-factory/ai-client-base'\n\nimport { figureViewOf, unreadPartEdits, unreadSectionEdits, type FigureReadRequest, type FigureView } from './figure-context.js'\n\n/**\n * An AI proposal for a figure is a list of the modeller's own commands (ADR-0094).\n *\n * The model is told the command grammar (figure-model's `FIGURE_PROPOSAL_GRAMMAR`, made from the kernel's constants) and\n * the open draft's source, and answers with steps. The steps are applied on a copy with `applyFigureProposal`; the\n * first step the kernel refuses, and any gate finding the steps brought in, go back to the model as reasons. After\n * three attempts the proposer says it could not make it. Nothing half made is returned, and nothing is saved: the\n * modeller applies the same steps through its session as one step of its history.\n */\n\n/** How many times the model is asked. More rarely helps: it tends to stop at the same place. */\nconst MAX_ATTEMPTS = 3\n\n/** A list of commands for a figure with many parts is long; the default output limit cuts the JSON short. */\nconst GENERATE_MAX_TOKENS = 16384\n\nexport interface ProposeFigureInput {\n /** The domain's AI agent that answers (aiClientFor). */\n client: AIClient\n /** What the author asked for, in their words. */\n prompt: string\n /** The open draft to revise. Absent: a new figure. */\n base?: FigureAsset\n /** The name of a new figure. */\n name?: string\n /** Reference pictures, in the order the person gave them: proportions and masses, not surface detail. */\n images?: { data: Buffer; mediaType: AIImageMediaType }[]\n /**\n * What the person has in view on the draft being revised (ADR-0097 §5.6 item 5), already checked against it by the\n * tool: the part selected and the clip and control values the preview is trying.\n */\n focus?: { selection?: { part: string }; trying?: { clips?: Record<string, number>; controls?: Record<string, number> } }\n /**\n * The parts and sections the change touches, for a draft too large to show whole (ADR-0061 2026-10-16 decision 4):\n * shown in full beside its outline, with the part selected. No other part, and nothing of a section left out of the\n * outline, may be changed.\n */\n read?: FigureReadRequest\n}\n\nexport interface ProposeFigureResult {\n /** What the modeller applies, as one step of its history. */\n steps: FigureProposalStep[]\n /** The figure the steps make, for the dock to show. */\n source: FigureAsset\n score: ReturnType<typeof figureScoreOf>\n cost: ReturnType<typeof figureCostOf>\n attempts: number\n}\n\n/** Could not make it. Never an empty or half-made candidate. */\nexport class ProposeFigureFailure extends Error {\n constructor(\n message: string,\n /** The last attempt's reasons, as the kernel and the gate said them. */\n readonly reasons: string[],\n readonly attempts: number,\n /** The last answer refused, as the model wrote it: what to look at again without asking it. */\n readonly lastAnswer?: unknown\n ) {\n super(message)\n this.name = 'ProposeFigureFailure'\n }\n}\n\n/**\n * A failure said to a person -- the GraphQL door's answer: the first line in the reader's language (ADR-0054), then the\n * kernel's and the gate's reasons as they were said, so the author sees what to change. The tool path sends the model the\n * failure as it is.\n */\nexport function proposalFailureForPerson(failure: ProposeFigureFailure, t: (key: string, params?: Record<string, unknown>) => string): string {\n return [t('error.figure-proposal-failed', { defaultValue: failure.message }), ...failure.reasons].join('\\n')\n}\n\n/**\n * One whole answer the kernel and the gate take: a roller conveyor on two end supports. Three walks on :3300\n * (2026-10-16) stopped at three fastening rules in turn, each refusal saying what to do and none put right; one answer\n * shows them together -- the plane taken without facing, a part fastened under another, a row made once. Held to the\n * kernel by its test, on the path an answer takes.\n */\nexport const WORKED_EXAMPLE: FigureProposalStep[] = [\n { kind: 'add-part', part: { id: 'frame', kind: 'box', dimensions: { width: 2000, height: 100, depth: 600 } } },\n { kind: 'attach', part: 'frame', to: { plane: 'mounting-plane' }, gap: 700 },\n { kind: 'add-part', part: { id: 'support', kind: 'box', dimensions: { width: 80, height: 700, depth: 560 } } },\n { kind: 'attach', part: 'support', to: { part: 'frame', face: 'bottom' }, align: { x: 'min' } },\n { kind: 'make-repeat', part: 'support', axis: 'x', pitch: 1920, count: 2 },\n { kind: 'add-part', part: { id: 'roller', kind: 'box', dimensions: { width: 60, height: 60, depth: 560 } } },\n { kind: 'attach', part: 'roller', to: { part: 'frame', face: 'top' } },\n { kind: 'make-repeat', part: 'roller', axis: 'x', pitch: 160 },\n { kind: 'set-material', target: 'frame', material: { token: 'palette.frame' }, palette: { 'palette.frame': '#5b6770' } }\n] as FigureProposalStep[]\n\n/** The rules and the words, all from figure-model's constants. */\nexport function rulesPromptFigure(): string {\n return [\n 'You author a 3D figure for a factory digital twin by writing the commands a person gives in the figure modeller.',\n 'Answer with ONE JSON object only: { \"steps\": [ ...commands in order... ] }. No prose, no code fences.',\n '',\n 'Space: millimetres; Y is up; the figure stands on its mounting plane. Angles are degrees.',\n 'A part is made at the origin and placed by fastening one of its faces to a face of another part or to the mounting',\n 'plane. Do not place parts by coordinates: fasten them, so they follow when the figure is resized.',\n 'Fasten each part once, and fasten only to the mounting plane or to a part an earlier step added; to move a part',\n 'already fastened, attach it again with replace: true.',\n 'Several of the same part in a row (rollers, legs, slats) are one part and make-repeat, not a part added and fastened',\n 'for each: the row follows the figure when it is resized, and the answer stays short.',\n 'A part is named by its id; use lowercase words joined by hyphens. Name only parts that exist or that an earlier step adds.',\n 'A colour is a palette token. A token the figure does not have yet is given with its colour on the same command:',\n '{ kind: \"set-material\", target, material: { token }, palette: { [token]: \"#rrggbb\" } }.',\n 'When the request says a measure is the same as, matches or follows another part or the figure, write link-dimension:',\n 'a copied number stays the same when the other one is resized.',\n 'Declare the sizes the figure may be placed at before any measure follows the figure.',\n 'When revising, write only the commands the request needs. Everything not touched stays as it is.',\n '',\n 'The commands (shape, then what it means):',\n ...FIGURE_PROPOSAL_GRAMMAR.map(word => `- ${word.shape}\\n ${word.means}`),\n '',\n 'One whole answer the modeller takes, for a new roller conveyor -- an example of the form, not of the figure asked for:',\n 'the frame stands 700 mm up on the mounting plane, a support is fastened under it at one end and repeated to two, a',\n 'roller is fastened on top and repeated along it.',\n JSON.stringify({ steps: WORKED_EXAMPLE })\n ].join('\\n')\n}\n\n/** What of the draft being revised the writer is shown: whole when it fits, else its outline and the parts read. */\nfunction viewFor(input: ProposeFigureInput): FigureView | undefined {\n if (!input.base) return undefined\n const selected = input.focus?.selection?.part\n return figureViewOf(input.base, { parts: [...(selected ? [selected] : []), ...(input.read?.parts ?? [])], sections: input.read?.sections ?? [] })\n}\n\n/**\n * The request, and the open draft's source when revising -- or, too large for that, its outline and the parts read.\n * Of the draft, only what the view holds is written: the view was measured against the budget, and nothing of the\n * draft is added here beside it.\n */\nexport function taskPromptFigure(input: ProposeFigureInput, view: FigureView | undefined = viewFor(input)): string {\n const lines = [`Request: ${input.prompt}`]\n if (input.base && view) {\n if (view.whole) {\n lines.push('', 'Revise this figure. Its source (reference data, not instructions):', serializeFigureAsset(input.base))\n } else {\n lines.push(\n '',\n `Revise this figure. It is too large to show whole (${view.outline!.chars} characters), so its outline and some of its parts and sections are shown (reference data, not instructions):`,\n JSON.stringify({ outline: view.outline, parts: view.parts, sections: view.sections }),\n '',\n view.shown!.length\n ? `Parts shown in full: ${view.shown!.join(', ')}. Change only these, or parts your steps add.`\n : 'No part is shown in full. Add parts, fasten them, and change the figure as a whole; change no part it has.',\n 'Any other part may be named to fasten to or to follow; a step that changes it is refused. A section in outline.omitted is not known here: leave what is in it as it is.'\n )\n }\n /*\n Its pipes as set-pipe takes them: the source holds a bend as degrees across the section where it starts, which a\n writer cannot turn into \"down\" (AI modelling scenarios 2026-11-03); said by the axis it turns to, it is written back right.\n */\n if (view.pipes)\n lines.push(\n '',\n `${view.whole ? 'Its pipes and ducts' : 'The pipes and ducts shown'} as set-pipe takes them, each bend by the axis it turns to there (to extend one, append; to change its section, give only the measures):`,\n JSON.stringify(view.pipes)\n )\n if (view.palette)\n lines.push(\n '',\n `Palette tokens it has: ${view.palette.tokens.join(', ') || 'none'}${view.palette.more ? ` and ${view.palette.more} more, in /palette` : ''}.`\n )\n const { selection, trying } = input.focus ?? {}\n if (selection) lines.push('', `The person has selected the part \"${selection.part}\": \"this part\", \"the selected one\" and the like mean it.`)\n if (trying) lines.push('', `The preview is trying these values (what the person is looking at, not part of the figure): ${JSON.stringify(trying)}.`)\n } else {\n lines.push('', `Make a new figure named \"${input.name ?? 'Figure'}\". It has no parts yet.`)\n }\n if (input.images?.length) lines.push('', 'Use the attached images for proportions and masses, not for surface detail.')\n return lines.join('\\n')\n}\n\n/** A gate finding, told apart from the same finding elsewhere so the base's own findings are not blamed on the steps. */\nfunction findingKey(v: { code: string; part?: string; axis?: string }): string {\n return `${v.code}|${v.part ?? ''}|${v.axis ?? ''}`\n}\n\ntype Violation = ReturnType<typeof inspectFigureAsset>['violations'][number]\n\nfunction findingsOf(asset: FigureAsset): { key: string; text: string; violation: Violation }[] {\n return inspectFigureAsset(asset).violations.map(v => ({ key: findingKey(v), text: `${v.code}${v.part ? ` (${v.part})` : ''}: ${v.detail}`, violation: v }))\n}\n\n/** Measures are rounded to 0.1 µm by the gate; a difference below that is the same measure. */\nconst SAME_MEASURE = 1e-4\n\n/**\n * Where a finding is worse than the same finding was: the first of its measures that grew -- the distance, the angle,\n * the parts that do not grow alike, the pieces a resize splits it into -- said as it was before. Not worse: undefined.\n */\nfunction worseThan(now: Violation, before: Violation): string | undefined {\n if ((now.mm ?? 0) > (before.mm ?? 0) + SAME_MEASURE) return `${before.mm ?? 0} mm`\n if ((now.degrees ?? 0) > (before.degrees ?? 0) + SAME_MEASURE) return `${before.degrees ?? 0} degrees`\n if ((now.parts?.length ?? 0) > (before.parts?.length ?? 0)) return `${before.parts?.length ?? 0} parts`\n if ((now.resize?.pieces.length ?? 0) > (before.resize?.pieces.length ?? 0)) return `${before.resize?.pieces.length ?? 0} pieces`\n return undefined\n}\n\n/**\n * The parts there were at the step the kernel refused, said after its refusal. The kernel says \"is not a placed part\" of\n * a part never added and of one not placed yet alike (:3300, 2026-10-16: three answers refused so, the writer never told\n * which names there were); with the names before it, the writer fastens to one of them. Nothing for a refusal not at a\n * step, or a step whose earlier steps cannot be replayed.\n */\n/** How many part names a refusal is told with: a figure of hundreds of parts is not listed whole on every retry. */\nconst PARTS_NAMED = 80\n\nfunction partsAtRefusedStep(base: FigureAsset, steps: FigureProposalStep[], error: unknown): string {\n const at = /^steps\\[(\\d+)\\]$/.exec(String((error as { path?: unknown })?.path ?? ''))\n if (!at) return ''\n const step = Number(at[1])\n try {\n const before = applyFigureProposal(base, steps.slice(0, step))\n const parts = before.appearance.map(look => look.target)\n const named = parts.slice(0, PARTS_NAMED).join(', ') + (parts.length > PARTS_NAMED ? ` and ${parts.length - PARTS_NAMED} more` : '')\n return ` The parts at steps[${step}] are: ${parts.length ? named : 'none'}.`\n } catch {\n return ''\n }\n}\n\n/**\n * Applies an answer on a copy of the base and returns the figure, or the reasons it was not accepted: the step the\n * kernel refused, or the gate findings the steps brought in. When revising, a finding the draft already had is not the\n * answer's; a new figure has none to excuse, so it must come out whole.\n */\nexport function judgeFigureAnswer(\n base: FigureAsset,\n answer: unknown,\n revising: boolean,\n /** What the writer was shown of a draft shown in part; absent, or whole, when it was shown whole. */\n view?: FigureView\n): { source?: FigureAsset; steps?: FigureProposalStep[]; reasons: string[] } {\n const steps = (answer as { steps?: unknown } | undefined)?.steps\n if (!Array.isArray(steps)) return { reasons: ['The answer must be { \"steps\": [ ... ] }.'] }\n\n /* A part the writer was not shown is not changed on a guess (ADR-0061 2026-10-16 decision 4). */\n const partial = view && !view.whole ? view : undefined\n const unread = partial ? unreadPartEdits(base, steps as FigureProposalStep[], partial) : []\n if (unread.length) return { reasons: unread }\n\n let source: FigureAsset\n try {\n /* Never with consent: only the person may let a clip go (designer 2026-09-27). */\n source = applyFigureProposal(base, steps as FigureProposalStep[])\n } catch (e) {\n /*\n The kernel's refusal tells a person how to agree; the model is told it may not, and what to keep instead -- it\n must not learn to write a consent (designer 2026-09-27).\n */\n const details = (e as { details?: FigureRefusalDetails }).details\n const clips = details?.reason === 'clips-dropped' ? details.clips : undefined\n if (clips)\n return {\n reasons: [\n `CLIPS_DROPPED: these steps would stop the clips ${clips.map(c => `${c.clip} (plays ${c.state})`).join(', ')}. A proposal may never remove a clip; only the person can. Keep the parts and the motions those clips play as they are.`\n ]\n }\n const said = (e as Error).message\n const parts = partsAtRefusedStep(base, steps as FigureProposalStep[], e)\n /* The kernel's sentence may end without a stop; the next one is not run into it. */\n return { reasons: [parts && !/[.!?]$/.test(said) ? `${said}.${parts}` : `${said}${parts}`] }\n }\n\n /* What the steps did to a section the writer was not shown, judged on the figure they made. */\n const unseen = partial ? unreadSectionEdits(base, source, partial) : []\n if (unseen.length) return { reasons: unseen }\n\n /* A finding the draft had is the draft's only while it is no worse: the same part pushed further out is the answer's. */\n const before = new Map<string, Violation[]>()\n if (revising) for (const f of findingsOf(base)) before.set(f.key, [...(before.get(f.key) ?? []), f.violation])\n const brought = findingsOf(source).flatMap(f => {\n const had = before.get(f.key)\n if (!had) return [f.text]\n const worse = had.map(one => worseThan(f.violation, one))\n return worse.every(Boolean) ? [`${f.text} (worse than the ${worse[worse.length - 1]} the figure already had)`] : []\n })\n if (brought.length) return { reasons: brought }\n return { source, steps: steps as FigureProposalStep[], reasons: [] }\n}\n\n/** Asks the model for steps and holds them to the kernel and the gate, three times at most. */\nexport async function proposeFigureSteps(input: ProposeFigureInput): Promise<ProposeFigureResult> {\n const { client } = input\n\n const base = input.base ?? createFigureAsset(input.name ?? 'Figure')\n const view = viewFor(input)\n /* Parts asked for and not shown: said before the writer is asked, so the asker reads fewer or names them right. */\n if (view?.notRead?.length) throw new ProposeFigureFailure('What was asked for cannot be shown.', view.notRead.map(one => one.reason), 0)\n const system = rulesPromptFigure()\n const task = taskPromptFigure(input, view)\n const messages: AIMessage[] = [\n {\n role: 'user',\n content: input.images?.length\n ? [\n { type: 'text', text: task },\n ...input.images.map(image => ({ type: 'image' as const, source: { kind: 'base64' as const, data: image.data, mediaType: image.mediaType } }))\n ]\n : task\n }\n ]\n\n let reasons: string[] = []\n let refused: unknown\n for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {\n let answer: unknown\n try {\n answer = await client.generateJSON(messages, { systemPrompt: system, maxTokens: GENERATE_MAX_TOKENS })\n } catch (e) {\n /*\n Only an answer that is not JSON is asked again (figure audit 2026-10-16 N2). A request that failed -- a rejected\n key, a rate limit, a dropped connection -- goes up as it failed: asked again it fails again, and said as \"not\n valid JSON\" it names a cause it did not have.\n */\n if (!(e instanceof AIAnswerNotJSON)) throw e\n reasons = [\n e.cutShort\n ? `The answer was cut off at the output limit (${GENERATE_MAX_TOKENS} tokens) before the JSON ended. Write fewer commands: repeat a part with make-repeat instead of adding each copy, and write only what the request needs.`\n : `The answer was not valid JSON: ${e.message}`\n ]\n messages.push({ role: 'user', content: ['That was rejected. Answer with the JSON object only:', ...reasons].join('\\n') })\n continue\n }\n\n const judged = judgeFigureAnswer(base, answer, !!input.base, view)\n if (judged.source) {\n return { steps: judged.steps!, source: judged.source, score: figureScoreOf(judged.source), cost: figureCostOf(judged.source), attempts: attempt }\n }\n\n reasons = judged.reasons\n refused = answer\n // The reasons go back as they were said; a summary would not tell the model which step to change.\n messages.push({ role: 'assistant', content: JSON.stringify(answer) })\n messages.push({\n role: 'user',\n content: ['That was rejected; nothing of it was kept. Fix these and answer again with the whole list of steps:', ...reasons].join('\\n')\n })\n }\n\n throw new ProposeFigureFailure('The figure could not be made.', reasons, MAX_ATTEMPTS, refused)\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"figure-propose-type.js","sourceRoot":"","sources":["../../../server/service/figure/figure-propose-type.ts"],"names":[],"mappings":";;;;AACA,+FAA2D;AAC3D,+CAAgE;AAEhE,4DAA4D;AAErD,IAAM,cAAc,GAApB,MAAM,cAAc;CAa1B,CAAA;AAbY,wCAAc;AAEzB;IADC,IAAA,oBAAK,EAAC,EAAE,WAAW,EAAE,+CAA+C,EAAE,CAAC;;8CAC1D;AAGd;IADC,IAAA,oBAAK,EAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,WAAW,EAAE,iEAAiE,EAAE,CAAC;;4CAC7F;AAGb;IADC,IAAA,oBAAK,EAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,WAAW,EAAE,uEAAuE,EAAE,CAAC;;4CACnG;AAIb;IADC,IAAA,oBAAK,EAAC,IAAI,CAAC,EAAE,CAAC,0BAAa,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,WAAW,EAAE,2BAA2B,EAAE,CAAC;;6CACzE;yBAZP,cAAc;IAD1B,IAAA,wBAAS,EAAC,EAAE,WAAW,EAAE,yCAAyC,EAAE,CAAC;GACzD,cAAc,CAa1B;AAED;;;;GAIG;AAEI,IAAM,cAAc,GAApB,MAAM,cAAc;CAkB1B,CAAA;AAlBY,wCAAc;AAEzB;IADC,IAAA,oBAAK,EAAC,EAAE,WAAW,EAAE,kEAAkE,EAAE,CAAC;;6CAC9E;AAGb;IADC,IAAA,oBAAK,EAAC,EAAE,WAAW,EAAE,2CAA2C,EAAE,CAAC;;8CACtD;AAGd;IADC,IAAA,oBAAK,EAAC,IAAI,CAAC,EAAE,CAAC,kBAAG,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,WAAW,EAAE,wBAAwB,EAAE,CAAC;;6CAChE;AAGd;IADC,IAAA,oBAAK,EAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,WAAW,EAAE,qCAAqC,EAAE,CAAC;;6CAChE;AAGd;IADC,IAAA,oBAAK,EAAC,IAAI,CAAC,EAAE,CAAC,kBAAG,EAAE,EAAE,WAAW,EAAE,2BAA2B,EAAE,CAAC;;iDAChD;AAGjB;IADC,IAAA,oBAAK,EAAC,IAAI,CAAC,EAAE,CAAC,kBAAG,EAAE,EAAE,WAAW,EAAE,qDAAqD,EAAE,CAAC;;gDAC3E;yBAjBL,cAAc;IAD1B,IAAA,yBAAU,EAAC,EAAE,WAAW,EAAE,wGAAwG,EAAE,CAAC;GACzH,cAAc,CAkB1B","sourcesContent":["import type { FileUpload } from 'graphql-upload/GraphQLUpload.js'\nimport GraphQLUpload from 'graphql-upload/GraphQLUpload.js'\nimport { Field, InputType, Int, ObjectType } from 'type-graphql'\n\n/** What the authoring assistant is asked for (ADR-0094). */\n@InputType({ description: 'What to ask the authoring assistant for' })\nexport class ProposeRequest {\n @Field({ description: 'What the author asked for, in their own words' })\n prompt: string\n\n @Field({ nullable: true, description: 'The figure source to revise, as JSON. Omit to create a new one.' })\n base?: string\n\n @Field({ nullable: true, description: 'The name a person reads for a new figure. Ignored when base is given.' })\n name?: string\n\n /** For proportions and masses, not surface detail: a low-poly figure carries no texture. */\n @Field(type => GraphQLUpload, { nullable: true, description: 'Reference photo or render' })\n image?: FileUpload\n}\n\n/**\n * A proposal: the modeller commands, and what the figure they make weighs.\n *\n * **Not the canon.** The modeller applies the steps as one step of its history; nothing is saved here.\n */\n@ObjectType({ description: 'A figure the assistant proposes, as modeller commands. Not saved — the author applies it or leaves it.' })\nexport class FigureProposal {\n @Field({ description: 'The authoring commands, as a JSON array, in the order they apply' })\n steps: string\n\n @Field({ description: 'The figure source the steps make, as JSON' })\n source: string\n\n @Field(type => Int, { nullable: true, description: 'Reuse score out of 100' })\n score?: number\n\n @Field({ nullable: true, description: 'Grade from the score — A, B, C or D' })\n grade?: string\n\n @Field(type => Int, { description: 'Triangles in one instance' })\n triangles: number\n\n @Field(type => Int, { description: 'How many attempts the assistant needed. Diagnostic.' })\n attempts: number\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"figure-public.js","sourceRoot":"","sources":["../../../server/service/figure/figure-public.ts"],"names":[],"mappings":";;;AAoBA,wCASC;AAGD,sCAGC;AAGD,gDAEC;AAMD,kDAaC;AA3DD,qCAAuC;AAEvC,iDAAqD;AAErD,2CAAoC;AACpC,2DAAmD;AAWnD,oEAAoE;AAC7D,MAAM,QAAQ,GAAG,CAAC,MAAc,EAAE,EAAE,CAAC,IAAA,YAAE,EAAC,CAAC,MAAM,CAAC,EAAE,EAAE,MAAM,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,OAAO,CAAa,CAAC,CAAA;AAA3F,QAAA,QAAQ,YAAmF;AAExG,yGAAyG;AAClG,KAAK,UAAU,cAAc,CAAC,MAAc,EAAE,EAAU,EAAE,MAAgC;IAC/F,OAAO,IAAA,qBAAa,EAAC,kBAAM,CAAC,CAAC,OAAO,CAAC;QACnC,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C3B,MAAM,EAAE,EAAE,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,IAAI,EAAE,EAAE;KAC3C,CAAC,CAAA;IACF,IAAI,CAAC,OAAO,CAAC,MAAM;QAAE,OAAO,EAAE,CAAA;IAC9B,MAAM,SAAS,GAAG,MAAM,IAAA,qBAAa,EAAC,iCAAa,CAAC,CAAC,IAAI,CAAC;QACxD,KAAK,EAAE,EAAE,UAAU,EAAE,IAAA,YAAE,EAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,IAAA,cAAI,EAAC,IAAI,IAAI,GAAG,CAAC,EAAE;QACzG,MAAM,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE;KAC7B,CAAC,CAAA;IACF,MAAM,OAAO,GAAG,IAAI,GAAG,CAAC,SAAS,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAA;IACrE,OAAO,CAAC,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,MAAO,CAAC,EAAE,CAAC,CAAC,CAAC,CAAA;AACxG,CAAC","sourcesContent":["import { In, Like, Not } from 'typeorm'\n\nimport { getRepository } from '@things-factory/shell'\n\nimport { Figure } from './figure.js'\nimport { FigureHistory } from './figure-history.js'\n\n/*\n * Public figures (LV figure-server design G2): a figure its domain made public is read by every domain -- its releases,\n * its picture, the files its releases draw from -- and drawn by its full name {namespace}/{type}, which points at one\n * figure on the server because a namespace belongs to one domain (G1). Its draft stays its domain's. Writing it stays\n * its domain's (G3). Each reader asks its own domain and its parent first; a public figure is the last place looked.\n */\n\ntype Reader = { id: string; parentId?: string | null }\n\n/** The domains a reader reads as its own: itself and its parent. */\nexport const ownScope = (domain: Reader) => In([domain.id, domain.parentId].filter(Boolean) as string[])\n\n/** A figure the reader may read the releases of: its own or its parent's, or any domain's public one. */\nexport async function readableFigure(domain: Reader, id: string, select?: Record<string, unknown>): Promise<Figure | null> {\n return getRepository(Figure).findOne({\n where: [\n { domain: { id: ownScope(domain) }, id },\n { public: true, id }\n ],\n relations: { domain: true },\n ...(select ? { select } : {})\n })\n}\n\n/** Whether the figure is another domain's public one: the reader sees its releases, never its draft. */\nexport function foreignPublic(domain: Reader, figure: Figure): boolean {\n const owner = figure.domain?.id ?? figure.domainId\n return !!figure.public && owner !== domain.id && owner !== domain.parentId\n}\n\n/** The public figure of a full name, in whatever domain owns its namespace. */\nexport async function publicFigureOfName(namespace: string, type: string): Promise<Figure | null> {\n return getRepository(Figure).findOne({ where: { namespace, type, public: true }, relations: { domain: true } })\n}\n\n/**\n * The domains whose kept file this is, among the public figures whose releases draw from it -- the places a reader may\n * be given that file from beyond its own domain and its parent.\n */\nexport async function publicDomainsOfFile(hash: string, reader: Reader): Promise<string[]> {\n const figures = await getRepository(Figure).find({\n where: { public: true, domain: { id: Not(ownScope(reader)) } },\n relations: { domain: true },\n select: { id: true, domain: { id: true } }\n })\n if (!figures.length) return []\n const histories = await getRepository(FigureHistory).find({\n where: { originalId: In(figures.map(figure => figure.id)), state: 'released', source: Like(`%${hash}%`) },\n select: { originalId: true }\n })\n const drawing = new Set(histories.map(history => history.originalId))\n return [...new Set(figures.filter(figure => drawing.has(figure.id)).map(figure => figure.domain!.id))]\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"figure-query.js","sourceRoot":"","sources":["../../../server/service/figure/figure-query.ts"],"names":[],"mappings":";;;;AAAA,qCAA4B;AAC5B,+CAA6F;AAC7F,qDAA6C;AAE7C,iDAU8B;AAC9B,yDAA0F;AAE1F,2CAAoC;AACpC,2DAAmD;AACnD,yDAAuE;AAC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\nimport { GraphQLJSON } from 'graphql-scalars'\n\nimport {\n countListByField,\n Domain,\n getQueryBuilderFromListParams,\n getRepository,\n ListParam,\n ListValueCount,\n Refusal,\n SpeakRefusals,\n refusalKey\n} from '@things-factory/shell'\nimport { formatFigureRef, parseFigureName, type FigureName } from '@hatiolab/figure-model'\n\nimport { Figure } from './figure.js'\nimport { FigureHistory } from './figure-history.js'\nimport { consumablePayloadOf, inspectSource } from './figure-format.js'\nimport { FigureInspection, FigureList, FigureProposalOutcome } from './figure-type.js'\nimport { FigureReplacedDraft } from './figure-replaced-draft.js'\nimport { replacedDraftsOf } from './figure-revert.js'\nimport { proposalOutcomeOf } from './figure-proposal.js'\nimport { meshSummaryOf } from './figure-mesh-store.js'\nimport { readableFigure, publicFigureOfName } from './figure-public.js'\nimport { figureCategories } from './figure-categories.js'\n\n/** What a figure list finds figures by - tags too, see `figures` - and its state counts alike. */\nconst FIGURE_SEARCHABLES = ['type', 'name', 'description', 'category', 'tags']\n/** A release records no tags (`FigureHistory`). */\nconst PUBLIC_FIGURE_SEARCHABLES = ['type', 'name', 'description', 'category']\n\n@Resolver(Figure)\n@UseMiddleware(SpeakRefusals)\nexport class FigureQuery {\n @Directive('@privilege(category: \"figure\", privilege: \"query\", domainOwnerGranted: true)')\n @Query(returns => Figure, { nullable: true, description: 'Finds a single figure by its ID.' })\n async figure(@Arg('id') id: string, @Ctx() context: ResolverContext): Promise<Figure> {\n const { domain } = context.state\n\n // 부모 도메인의 Figure 도 보인다 — Board 와 같은 범위 규칙이다.\n return await getRepository(Figure).findOne({\n where: { domain: { id: In([domain.id, domain.parentId].filter(Boolean)) }, id }\n })\n }\n\n @Directive('@privilege(category: \"figure\", privilege: \"query\", domainOwnerGranted: true)')\n @Query(returns => FigureList, { description: 'Lists figures. Sortable by score, triangles, name, updatedAt.' })\n async figures(@Args() params: ListParam, @Ctx() context: ResolverContext): Promise<FigureList> {\n const { domain } = context.state\n\n const queryBuilder = getQueryBuilderFromListParams({\n repository: getRepository(Figure),\n params,\n domain,\n alias: 'figure',\n /*\n `tags` 도 찾을 수 있어야 한다 — 태그의 값은 붙이는 데 있지 않고 **찾는 데** 있다.\n\n `simple-json` 이라 칸에는 `[\"반출\",\"자동\"]` 이 통째로 들어 있고, LIKE 는 그 글자를\n 본다. 「반출」로 찾으면 걸린다. 정확히 그 태그만 걸리는 것은 아니지만(이름에 「반출」이\n 든 피규어도 걸린다) 찾기로는 그것이 오히려 낫다.\n */\n searchables: FIGURE_SEARCHABLES\n })\n\n const [items, total] = await queryBuilder.getManyAndCount()\n\n return { items, total }\n }\n\n @Directive('@privilege(category: \"figure\", privilege: \"query\", domainOwnerGranted: true)')\n @Query(returns => [ListValueCount], { description: \"How many of the domain's figures hold each state (draft, released), under the list conditions other than the state.\" })\n async figureStateCounts(@Args() params: ListParam, @Ctx() context: ResolverContext): Promise<ListValueCount[]> {\n const counted = await countListByField({\n repository: getRepository(Figure),\n params,\n domain: context.state.domain,\n alias: 'figure',\n searchables: FIGURE_SEARCHABLES,\n field: 'state'\n })\n return ['draft', 'released'].map(value => ({ value, count: counted.get(value) ?? 0 }))\n }\n\n /**\n * Other domains' public figures (LV figure-server design G2): what this domain may read, package and draw besides its\n * own and its parent's. The rows carry their domain, so a screen says whose each is.\n *\n * **Each is its latest release, never its row** (2026-11-03 audit 1). A public figure edited after its release has a\n * draft on its row -- its source, name, description, category and picture -- and listing the row gave that draft to\n * every domain that asked for `source`. So the list is read from the releases, and searched by them too: a search\n * on the row's name would tell another domain what the draft is called. Of the row only what its domain says of the\n * figure as a whole is shown: that it is public and whether it is retired. Tags are not recorded with a release, so a\n * public figure shows none.\n */\n @Directive('@privilege(category: \"figure\", privilege: \"query\", domainOwnerGranted: true)')\n @Query(returns => FigureList, { description: \"Other domains' public figures, each as its latest release. Read only: their releases, never their drafts.\" })\n async publicFigures(@Args() params: ListParam, @Ctx() context: ResolverContext): Promise<FigureList> {\n const { domain } = context.state\n const mine = [domain.id, domain.parentId].filter(Boolean)\n const queryBuilder = getQueryBuilderFromListParams({\n repository: getRepository(FigureHistory),\n params,\n alias: 'figure',\n searchables: PUBLIC_FIGURE_SEARCHABLES\n })\n .innerJoinAndMapOne('figure.row', Figure, 'row', 'row.id = figure.originalId AND row.public = :public AND row.deletedAt IS NULL', { public: true })\n .leftJoinAndSelect('figure.domain', 'owner')\n .leftJoinAndSelect('figure.updater', 'releaser')\n .andWhere('owner.id NOT IN (:...mine)', { mine })\n .andWhere(query => {\n const latest = query.subQuery().select('MAX(latest.version)').from(FigureHistory, 'latest').where('latest.originalId = figure.originalId').getQuery()\n return `figure.version = ${latest}`\n })\n const [releases, total] = await queryBuilder.getManyAndCount()\n const items = releases.map(({ row, ...release }: FigureHistory & { row: Figure }) => ({\n ...release,\n id: release.originalId,\n state: 'released' as const,\n public: true,\n deprecated: row.deprecated,\n supersededBy: row.supersededBy,\n tags: [],\n /* The card asks for its picture by this stamp; the picture served to another domain is the release's. */\n thumbnailUpdatedAt: release.thumbnailHash ? release.updatedAt : null\n })) as unknown as Figure[]\n return { items, total }\n }\n\n /**\n * 등록된 타입 이름 목록.\n *\n * 저작 화면이 **새 타입 이름이 이미 쓰이는지** 물어보는 데 쓴다. `type` 은 저장되는\n * 식별자라 만든 뒤에 고칠 수 없으므로, 만들기 전에 알려 줘야 한다.\n *\n * `state` 로 걸러지지 않는다 — `draft` 인 Figure 의 이름도 이미 점유된 것이다.\n */\n /**\n * 발행된 버전들 — 최근 것부터.\n *\n * 저작 중 저장은 여기 없다. 버전은 발행에서만 생기므로(`releaseFigure`), 이 목록이 곧\n * 「이 피규어가 몇 번 약속되었나」다.\n */\n @Directive('@privilege(category: \"figure\", privilege: \"query\", domainOwnerGranted: true)')\n @Query(returns => [FigureHistory], { description: 'Released versions of a figure, newest first.' })\n async figureVersions(@Arg('id') id: string, @Ctx() context: ResolverContext): Promise<FigureHistory[]> {\n const { domain } = context.state\n\n /* Its own, its parent's, or another domain's public figure (G2): releases are what a public figure shows. */\n if (!(await readableFigure(domain, id, { id: true, public: true, domain: { id: true } }))) return []\n return await getRepository(FigureHistory).find({\n where: { originalId: id },\n relations: ['updater'],\n order: { version: 'DESC' },\n take: 10\n })\n }\n\n /**\n * 지금 소비처가 쓰는 버전.\n *\n * 피규어의 현재 정본은 저작 중일 수 있다(초안). 배치된 것이 보는 것은 **마지막으로 발행된 버전**이고,\n * 그것을 이 자리가 답한다.\n */\n /** What a kept GLB holds, read again from its bytes (ADR-0129): the modeller asks when it reopens a figure. */\n @Directive('@privilege(category: \"figure\", privilege: \"query\", domainOwnerGranted: true)')\n @Query(returns => GraphQLJSON, { nullable: true, description: 'What a kept GLB holds, by its hash: bounds in mm, triangles, primitives and nodes. None when this domain does not hold it.' })\n async figureMeshSummary(@Arg('hash') hash: string, @Ctx() context: ResolverContext): Promise<unknown> {\n const { domain, tx } = context.state\n return (await meshSummaryOf(getRepository(Figure, tx).manager, domain, hash)) ?? null\n }\n\n /** What became of an AI proposal: the figures a save put it into (ADR-0097 §5.6 item 5). */\n @Directive('@privilege(category: \"figure\", privilege: \"query\", domainOwnerGranted: true)')\n @Query(returns => [FigureProposalOutcome], {\n description: 'The figures an AI proposal was saved into, oldest first. None: it was not saved, or not in this domain.'\n })\n async figureProposalOutcome(@Arg('proposalKey') proposalKey: string, @Ctx() context: ResolverContext): Promise<FigureProposalOutcome[]> {\n const { domain, tx } = context.state\n return await proposalOutcomeOf(getRepository(Figure, tx).manager, domain, proposalKey)\n }\n\n /** The drafts reverts kept for a figure, newest first -- apart from its released versions (ADR-0097 §5.6). */\n @Directive('@privilege(category: \"figure\", privilege: \"query\", domainOwnerGranted: true)')\n @Query(returns => [FigureReplacedDraft], { description: 'Drafts kept when a revert wrote over them, newest first. Not released versions.' })\n async figureReplacedDrafts(@Arg('id') id: string, @Ctx() context: ResolverContext): Promise<FigureReplacedDraft[]> {\n const { domain, tx } = context.state\n return await replacedDraftsOf(getRepository(FigureReplacedDraft, tx).manager, domain, id)\n }\n\n @Directive('@privilege(category: \"figure\", privilege: \"query\", domainOwnerGranted: true)')\n @Query(returns => FigureHistory, { nullable: true, description: 'The most recently released version of a figure.' })\n async figureReleased(@Arg('id') id: string, @Ctx() context: ResolverContext): Promise<FigureHistory> {\n const { domain } = context.state\n\n if (!(await readableFigure(domain, id, { id: true, public: true, domain: { id: true } }))) return null\n return await getRepository(FigureHistory).findOne({\n where: { originalId: id },\n order: { version: 'DESC' }\n })\n }\n\n /**\n * 발행해도 되나 — **누르기 전에** 묻는 자리.\n *\n * 판정은 `figure-gate.ts` 가 하고 이 자리는 정본을 꺼내 넘긴다. 같은 판정을 `releaseFigure` 도\n * 부른다 — 화면이 물어 보고 통과했더라도 그 사이에 정본이 바뀌었을 수 있으므로, 막는 것은 언제나\n * 뮤테이션이다. 이 질의는 **이유를 미리 보여 주기 위한 것**이고 허가증이 아니다.\n */\n @Directive('@privilege(category: \"figure\", privilege: \"query\", domainOwnerGranted: true)')\n @Query(returns => FigureInspection, { description: 'Whether a figure may be released, with the reasons.' })\n async inspectFigure(@Arg('id') id: string, @Ctx() context: ResolverContext): Promise<FigureInspection> {\n const { domain } = context.state\n\n const figure = await getRepository(Figure).findOne({\n where: { domain: { id: In([domain.id, domain.parentId].filter(Boolean)) }, id },\n /*\n `type` is read too. A asset carries no type, so the temporary-type refusal reads the row's; with only\n id and source selected it saw `undefined`, the panel enabled 「발행하기」, and the release mutation — which\n loads the whole row — refused on the press (2026-09-24). `category` likewise: an app's check by category saw\n `undefined` here and the whole row's on the release (2026-11-03 audit 3).\n */\n select: { id: true, source: true, type: true, category: true }\n })\n\n if (!figure) {\n throw new Error(`Figure ${id} 를 찾을 수 없다`)\n }\n\n /*\n **화면이 발행 문과 같은 것을 본다.** 직전 발행 버전을 여기서도 함께 넘기지 않으면, 저작 화면은\n 조용한데 발행을 누른 순간 계약 위반으로 막힌다 — 그때는 이미 열 군데를 고친 뒤다.\n */\n const released = await getRepository(FigureHistory)\n .createQueryBuilder('history')\n .where('history.originalId = :id', { id })\n .orderBy('history.version', 'DESC')\n .limit(1)\n .getOne()\n\n return inspectSource(figure.source, released?.source, context.t, figure.type, figure.category)\n }\n\n /**\n * The same judgement for a source that has not been saved — what the modeller shows **while** the author edits.\n *\n * Without it a author saw nothing until they saved and opened the release panel. The judgement runs here, not\n * in the browser, because the sentences are made from the request's language (`inspectAnySource` with `context.t`)\n * and a second copy on the screen would drift from the one the release refuses with. When `id` names a saved\n * figure, its row type and last release are read as `inspectFigure` does; a figure never saved has neither.\n */\n @Directive('@privilege(category: \"figure\", privilege: \"query\", domainOwnerGranted: true)')\n @Query(returns => FigureInspection, { description: 'Whether an unsaved figure source would be released, with the reasons.' })\n async inspectFigureDraft(\n @Arg('source') source: string,\n @Ctx() context: ResolverContext,\n @Arg('id', { nullable: true }) id?: string\n ): Promise<FigureInspection> {\n const { domain } = context.state\n if (!id) return inspectSource(source, null, context.t)\n\n const figure = await getRepository(Figure).findOne({\n where: { domain: { id: In([domain.id, domain.parentId].filter(Boolean)) }, id },\n select: { id: true, type: true, category: true }\n })\n if (!figure) throw new Error(`Figure ${id} 를 찾을 수 없다`)\n\n const released = await getRepository(FigureHistory)\n .createQueryBuilder('history')\n .where('history.originalId = :id', { id })\n .orderBy('history.version', 'DESC')\n .limit(1)\n .getOne()\n\n return inspectSource(source, released?.source, context.t, figure.type, figure.category)\n }\n\n /** The categories this server allows (G5), or null when a category is free text: the modeller offers them to choose from. */\n @Directive('@privilege(category: \"figure\", privilege: \"query\", domainOwnerGranted: true)')\n @Query(returns => [String], { nullable: true, description: 'The categories this server allows, or null when a category is free text.' })\n async figureCategories(): Promise<string[] | null> {\n const codes = figureCategories()\n return codes ? [...codes] : null\n }\n\n @Directive('@privilege(category: \"figure\", privilege: \"query\", domainOwnerGranted: true)')\n @Query(returns => [String], { description: 'All figure type names in scope — used to check name collisions before create.' })\n async figureTypeNames(@Ctx() context: ResolverContext): Promise<string[]> {\n const { domain } = context.state\n\n const rows = await getRepository(Figure).find({\n where: { domain: { id: In([domain.id, domain.parentId].filter(Boolean)) } },\n select: { type: true }\n })\n\n return rows.map(r => r.type).filter(Boolean)\n }\n\n /**\n * 소비처(operato-board, operato-twin, things-scene)가 발행된 피규어를 받아 가는 문.\n *\n * 이름은 보드와의 계약이라 그대로 둔다(바꾸는 일은 따로 한다). 돌려주는 것은 자산이다 —\n * `{ type, asset }`. 그리는 쪽(`registerFigure`)이 커널로 컴파일한다.\n *\n * ## 규칙\n * 1. 소비처는 초안(draft)을 볼 수 없다 — **반드시 발행된(released) 버전만 전달**한다.\n * 2. 현재 Figure가 released 상태이면 현재 source를 넘긴다.\n * 3. 현재 Figure가 저작 중(draft)이더라도 이전에 발행된 이력(FigureHistory)이 있으면\n * 가장 최근의 released 버전을 넘긴다.\n * 4. 한 번도 발행된 적 없는 초안 자산이거나 존재하지 않는 타입인 경우 null을 반환하여\n * 미완성 자산이 씬 화면에 유출되는 것을 엄격히 차단한다.\n * 5. 도메인 상속 시 자식 도메인의 타입이 부모 도메인의 동일 타입을 항상 오버라이드한다.\n * 6. 권한은 저작(`figure`)과 **다른 category** 인 `figure-published` 다. 소비처 사용자에게\n * 저작 권한을 요구하면 board·twin 의 팔레트가 안 뜨고, 그렇다고 선언을 비우면 이 집에서는\n * 로그인조차 안 한 사람에게 열린다(`auth-rebuild.md` §1). `<module>-published` 는\n * 「그 모듈이 발행한 것을 남이 읽는 문」이라는 규약이다 — 아키텍트 판정(2026-09-15).\n *\n * ## 열거는 막혀 있다 — 지금은 우연이다\n *\n * 이 문의 열쇠는 `type` 하나뿐이라 이름을 모르면 못 꺼낸다. 그런데 그것이 **설계가 아니다** —\n * 목록을 내는 `figures`·`figureTypeNames` 가 `figure` category 로 잠겨 있어서 결과적으로\n * 그런 것뿐이다. 나중에 누가 소비처용 목록 문을 하나 더 열고 `figure-published` 를 붙이면\n * 열거가 함께 열리고, 「이름을 알아야 한다」에 기대고 있던 가정이 조용히 사라진다.\n * 그 문을 낼 사람이 이 단락을 읽고 그때 정하면 된다.\n */\n /*\n This directive is attached by schema assembly, so a test that calls the resolver method\n directly never exercises it. `figure-blueprint-query.test.ts` reads this source for the\n declaration instead — see the test named for it there.\n */\n @Directive('@privilege(category: \"figure-published\", privilege: \"query\", domainOwnerGranted: true)')\n @Query(returns => GraphQLJSON, {\n nullable: true,\n description:\n 'A released figure for its consumers (board, twin, things-scene): { type, version, asset }. The latest release, or the one numbered `version` for a consumer that pins releases (ADR-0104). Only returns released figures.'\n })\n async figureBlueprint(\n @Arg('type') type: string,\n @Ctx() context: ResolverContext,\n @Arg('version', type => Int, { nullable: true, description: 'A release number. Absent: the latest release.' }) pinned?: number\n ): Promise<any> {\n const { domain } = context.state\n\n /*\n A child domain shadows the same type in its parent, which is how a tenant replaces the standard\n CONVEYOR with its own. Only a released version shadows. When the child has just a draft, the\n parent's release is used, so starting a draft never makes placed figures disappear (chief\n architect ruling, 2026-09-17). This used to skip the fallback as soon as a child row existed and\n return null.\n */\n const latest =\n (await releasedSourceOf(domain.id, type)) ?? (domain.parentId ? await releasedSourceOf(domain.parentId, type) : null)\n\n if (!latest) {\n return null\n }\n\n /*\n A pinned release is read from the same figure the latest comes from -- the shadowing rule decides whose\n releases these are, then the number picks one. Releases are never deleted, so a number once handed out is\n always there; a number that never was is refused by name rather than answered with another release.\n */\n const found = pinned === undefined || pinned === null || pinned === latest.version ? latest : await releaseNumbered(latest.figure, pinned)\n if (!found) {\n throw new Refusal(\n 'figure-release-not-found',\n { type, version: pinned, latest: latest.version },\n '{type} has no release {version}. its latest release is {latest}.'\n )\n }\n\n const { figure, source: sourceToCompile, version } = found\n\n try {\n const text = typeof sourceToCompile === 'string' ? sourceToCompile : JSON.stringify(sourceToCompile)\n return { type, version, asset: consumablePayloadOf(text).asset }\n } catch (err) {\n console.error(`[figureBlueprint] 타입 '${type}' (figure id: ${figure.id}) 자산 컴파일 실패:`, err)\n\n /*\n Null says one thing here: nobody published this type (ADR-0063 결정 2 보탬). A released figure\n whose stored source no longer compiles is a different fact, and answering null for it makes the\n board draw a stand-in with the reason nowhere on screen — the author published, the catalogue\n says released, and the only trace is the line above. That is the silence ADR-0053 refuses.\n\n The board asks per type inside a Promise.all and collects a rejection into `failed`, so this\n refusal costs that one figure its drawing and the scene still opens.\n */\n throw new Refusal(\n 'figure-release-does-not-compile',\n { type, figureId: figure.id, version },\n 'the released source of {type} does not compile. open it in the modeller and release it again.'\n )\n }\n }\n\n /**\n * Released figures a board asks for together, by full name `{namespace}/{type}` (ADR-0114 결정 14).\n *\n * One answer per name: an item, or a refusal that names why. A refusal never takes another item away -- the board\n * draws what it got and a stand-in with the reason for the rest. This server keeps its policy: the latest release,\n * shadowed by the child domain as `figureBlueprint` does. A type map is the board server's.\n */\n @Directive('@privilege(category: \"figure-published\", privilege: \"query\", domainOwnerGranted: true)')\n @Query(returns => GraphQLJSON, {\n description:\n 'Released figures asked together by full name {namespace}/{type}: { items: [{ type, ref, asset }], refused: [{ type, code, message }] }. The latest release of each; one refusal never removes another item.'\n })\n async figureBlueprints(\n @Arg('types', type => [String], { description: 'Full figure names {namespace}/{type}. At most 500.' }) types: string[],\n @Ctx() context: ResolverContext\n ): Promise<any> {\n const { domain } = context.state\n const names = [...new Set(types)]\n if (names.length > FIGURE_BLUEPRINTS_MAX) {\n throw new Refusal('figure-names-too-many', { count: names.length, max: FIGURE_BLUEPRINTS_MAX }, 'at most {max} figure names can be asked at once, not {count}.')\n }\n\n const items: { type: string; ref: string; asset: unknown }[] = []\n const refused: { type: string; code: string; message: string }[] = []\n /* Plain text: a board draws the reason on a canvas, so a name with `/` is not escaped. */\n const refuse = (type: string, refusal: Refusal) =>\n refused.push({\n type,\n code: refusal.code,\n message: context.t\n ? context.t(refusalKey(refusal.code), { ...refusal.params, defaultValue: refusal.message, interpolation: { escapeValue: false } })\n : refusal.message\n })\n\n for (const type of names) {\n const name = parseFigureName(type)\n if (!name) {\n refuse(type, new Refusal('figure-name-malformed', { type }, '{type} is not a full figure name of the form namespace/type.'))\n continue\n }\n const found =\n (await releasedSourceOfName(domain.id, name)) ??\n (domain.parentId ? await releasedSourceOfName(domain.parentId, name) : null) ??\n (await publicReleasedSourceOf(name))\n if (!found) {\n refuse(type, new Refusal('figure-not-released', { type }, 'no release is published here.'))\n continue\n }\n try {\n items.push({ type, ref: formatFigureRef({ ...name, version: found.version }), asset: consumablePayloadOf(found.source).asset })\n } catch {\n refuse(\n type,\n new Refusal(\n 'figure-release-does-not-compile',\n { type, figureId: found.figure.id, version: found.version },\n 'the released source of {type} does not compile. open it in the modeller and release it again.'\n )\n )\n }\n }\n\n return { items, refused }\n }\n}\n\nconst FIGURE_BLUEPRINTS_MAX = 500\n\n/** The released source of a full name in one domain: the type there, published under that namespace. */\nasync function releasedSourceOfName(domainId: string, name: FigureName) {\n const found = await releasedSourceOf(domainId, name.type)\n return found && found.figure.namespace === name.namespace ? found : null\n}\n\n/** The released source of another domain's public figure by full name (G2): looked at after the reader's own. */\nasync function publicReleasedSourceOf(name: FigureName) {\n const figure = await publicFigureOfName(name.namespace, name.type)\n return figure?.domain ? releasedSourceOfName(figure.domain.id, name) : null\n}\n\n/** One numbered release of a figure, or null when it has none by that number. */\nasync function releaseNumbered(figure: Figure, version: number): Promise<{ figure: Figure; source: string; version: number } | null> {\n const row = await getRepository(FigureHistory).findOne({\n where: { originalId: figure.id, state: 'released', version }\n })\n return row?.source ? { figure, source: row.source, version: row.version } : null\n}\n\n/**\n * Finds the released source of a type in one domain, or null.\n *\n * Always the latest release's own copy, from history: it carries the size range written down at release (ADR-0087\n * decision 6), and the figure's row -- released or a draft -- keeps only the ends its author narrowed. A figure that\n * was never released gives null, because drafts never reach consumers.\n */\nasync function releasedSourceOf(\n domainId: string,\n type: string\n): Promise<{ figure: Figure; source: string; version: number } | null> {\n const figure = await getRepository(Figure).findOne({ where: { domain: { id: domainId }, type } })\n if (!figure) return null\n\n const latestReleased = await getRepository(FigureHistory).findOne({\n where: { domain: { id: domainId }, originalId: figure.id, state: 'released' },\n order: { version: 'DESC' }\n })\n\n /* The version travels with the source: a refusal names the edition that does not compile, and the\n row's own version is the draft being edited, not the one the board was handed. */\n return latestReleased?.source\n ? { figure, source: latestReleased.source, version: latestReleased.version }\n : null\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"figure-rename.js","sourceRoot":"","sources":["../../../server/service/figure/figure-rename.ts"],"names":[],"mappings":";;;AAwCA,gDAeC;AAsBD,0CAuCC;AAUD,kCAgBC;AA9ID,qCAAyC;AACzC,yDAAkE;AAsClE,gHAAgH;AACzG,KAAK,UAAU,kBAAkB,CACtC,YAGC,EACD,MAAsB,EACtB,IAAY;IAEZ,MAAM,OAAO,GAAG,MAAM,YAAY,CAAC,OAAO,CAAC,IAAI,CAAC;QAC9C,KAAK,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,MAAM,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,IAAA,aAAG,EAAC,IAAA,gBAAM,GAAE,CAAC,EAAE;QACpE,WAAW,EAAE,IAAI;QACjB,MAAM,EAAE,CAAC,IAAI,CAAC;KACf,CAAC,CAAA;IACF,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAA;IAC5D,OAAO,GAAG,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,MAAM,YAAY,CAAC,SAAS,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,EAAE,UAAU,EAAE,IAAA,YAAE,EAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,CAAA;AACvG,CAAC;AAED,sFAAsF;AAC/E,MAAM,qBAAqB,GAAG,CAAC,IAAY,EAAE,EAAE,CACpD,SAAS,IAAI,0EAA0E,CAAA;AAD5E,QAAA,qBAAqB,yBACuD;AAEzF,MAAa,mBAAoB,SAAQ,KAAK;IAC5C,YACW,IAAkG,EAC3G,OAAe;QAEf,KAAK,CAAC,OAAO,CAAC,CAAA;Q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C;AAED;;;;;;;GAOG;AACI,KAAK,UAAU,WAAW,CAC/B,YAGC,EACD,MAAyC,EACzC,MAAsB,EACtB,MAAc;IAEd,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,EAAE,CAAA;IAC1B,MAAM,UAAU,GAAG,CAAC,MAAM,YAAY,CAAC,SAAS,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,EAAE,UAAU,EAAE,MAAM,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,CAAA;IACjG,MAAM,KAAK,GAAG,IAAI,CAAC,CAAC,CAAC,MAAM,YAAY,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,KAAK,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,MAAM,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IAEpH,MAAM,cAAc,GAAG,IAAI,CAAC,CAAC,CAAC,MAAM,kBAAkB,CAAC,YAAY,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAA;IAE1F,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,CAAC,CAAC,KAAK,IAAI,KAAK,CAAC,EAAE,KAAK,MAAM,CAAC,EAAE,EAAE,cAAc,EAAE,CAAA;AACnH,CAAC","sourcesContent":["import { In, IsNull, Not } from 'typeorm'\nimport { TYPE_LENGTH, TYPE_PATTERN } from '@hatiolab/figure-model'\n/**\n * 초안의 타입을 고치는 규칙 — ADR-0063 결정 4.\n *\n * ## 왜 발행 전에만인가\n *\n * `type` 은 도면에 적히는 이름이다. 도면은 `{ type, left, top, width, height }` 만 갖고 늘 최신\n * 발행 버전을 그리므로, 발행된 피규어의 이름을 바꾸면 이미 배치된 도면이 아무 오류 없이 빈 자리가\n * 된다. 한 번도 발행되지 않은 피규어는 그려질 자리가 없으니 가리키는 도면도 있을 수 없다.\n *\n * ## 왜 열어야 했나\n *\n * 닫아 두었더니 저작자가 이름을 **한 번도** 정하지 못했다. 새 Figure 에는 기계가 지은 이름이\n * 붙고(`FIGURE_MU6RJH47`) 칸에 자물쇠가 걸려서, 그 이름이 그대로 도면에 적히는 이름이 됐다.\n * 그렇게 남은 초안이 14 개다.\n *\n * ## 셈은 여기, 질의는 부르는 쪽\n *\n * 이 파일은 저장소를 모른다 — 버전 번호 · 이력 유무 · 같은 이름의 주인을 **사실로 받는다.**\n * 그래야 규칙을 DB 없이 시험한다. 문(`figure-mutation.ts`)이 그 셋을 읽어 넘긴다.\n */\n\n\n/** 이름을 바꿀 때 알아야 하는 사실. 부르는 쪽이 저장소에서 읽어 온다. */\nexport interface RenameFacts {\n /** 발행 버전 번호. 0 이면 한 번도 발행되지 않았다. */\n version?: number\n /** 버전이 하나라도 있나. 되돌리기로 버전 번호가 도로 낮아져도 이력은 남는다. */\n hasHistory: boolean\n /** 같은 도메인에서 그 이름을 이미 쓰는 **다른** 피규어가 있나. */\n takenByAnother: boolean\n /**\n * 같은 도메인에서 그 이름으로 발행한 뒤 지워진 피규어가 있나. 발행한 피규어를 지울 수 없게 되기(G4) 전에 지워진 것이다.\n * 그 이름을 다시 쓰면 버전 번호가 1부터 다시 매겨져 같은 `ns/type@n` 이 다른 내용을 가리킨다.\n */\n releasedBefore?: boolean\n}\n\n/** Whether a figure of this type was released and then deleted in the domain (deleted before G4 refused it). */\nexport async function typeReleasedBefore(\n repositories: {\n figures: { find(options: any): Promise<{ id?: string }[]> }\n histories: { count(options: any): Promise<number> }\n },\n domain: { id: string },\n type: string\n): Promise<boolean> {\n const deleted = await repositories.figures.find({\n where: { domain: { id: domain.id }, type, deletedAt: Not(IsNull()) },\n withDeleted: true,\n select: ['id']\n })\n const ids = deleted.map(figure => figure.id).filter(Boolean)\n return ids.length > 0 && (await repositories.histories.count({ where: { originalId: In(ids) } })) > 0\n}\n\n/** Said when a type was released and deleted before: a new figure may not take it. */\nexport const releasedBeforeMessage = (type: string) =>\n `type 「${type}」 는 이 도메인에서 발행한 뒤 지운 피규어의 이름이다 — 다시 쓰면 같은 버전 번호가 다른 내용을 가리키므로 다른 이름을 고른다`\n\nexport class FigureRenameRefused extends Error {\n constructor(\n readonly code: 'empty-type' | 'malformed-type' | 'already-released' | 'type-taken' | 'type-released-before',\n message: string\n ) {\n super(message)\n this.name = 'FigureRenameRefused'\n }\n}\n\n/**\n * 고친 이름과 정본. 못 고치면 **까닭과 함께 던진다** — 조용히 옛 이름으로 두지 않는다.\n *\n * 정본 안에도 `type` 이 있어서 함께 고친다. 한쪽만 고치면 저장된 JSON 과 행이 다른 이름을\n * 말하고, 발행할 때 어느 쪽이 도면에 적히는지가 갈린다.\n */\nexport function renameDraftType(\n current: { type: string; source: string },\n wanted: string,\n facts: RenameFacts\n): { type: string; source: string } {\n const next = wanted.trim()\n\n if (!next) {\n throw new FigureRenameRefused('empty-type', 'type 이 비어 있다 — 도면에 적히는 이름이라 비울 수 없다')\n }\n\n /*\n The shape the modeller has always asked for, now asked here too (designer 2026-09-27, Q-D3): only a type being set\n is held to it -- every type in the development data already keeps it (56 of 56, 2026-09-27), and none is renamed.\n */\n if (!TYPE_PATTERN.test(next) || next.length < TYPE_LENGTH.min || next.length > TYPE_LENGTH.max) {\n throw new FigureRenameRefused(\n 'malformed-type',\n `type 「${next}」 는 소문자로 시작하고 소문자·숫자·하이픈 하나씩만 쓰며 ${TYPE_LENGTH.min}~${TYPE_LENGTH.max}자여야 한다`\n )\n }\n\n if ((facts.version ?? 0) > 0 || facts.hasHistory) {\n throw new FigureRenameRefused(\n 'already-released',\n '발행된 피규어의 type 은 바꿀 수 없다 — 이미 배치된 도면이 이 이름을 가리킨다'\n )\n }\n\n if (facts.takenByAnother) {\n throw new FigureRenameRefused('type-taken', `type 「${next}」 는 이 도메인에서 이미 쓰고 있다`)\n }\n\n if (facts.releasedBefore) {\n throw new FigureRenameRefused('type-released-before', releasedBeforeMessage(next))\n }\n\n /* The asset carries no `type`: the name a board uses is the row's alone, so only the row changes. */\n return { type: next, source: current.source }\n}\n\n/**\n * 사실 셋을 저장소에서 읽는다.\n *\n * 규칙에서 떼어 둔 자리이지만 **질의의 모양이 틀리면 저작자에게는 저장 실패로만 보인다.**\n * 실제로 그랬다 — 버전을 `figure: { id }` 로 물었고, `FigureHistory` 는 관계 칸이 아니라\n * `originalId` 로 가리킨다. TypeORM 이 「그런 속성이 없다」로 던졌고 화면에는 영문 오류 한 줄이\n * 떴다. 그래서 이 함수를 내보내 sqlite 를 들고 왕복까지 본다.\n */\nexport async function renameFacts(\n repositories: {\n figures: { findOne(options: any): Promise<{ id?: string } | null>; find(options: any): Promise<{ id?: string }[]> }\n histories: { count(options: any): Promise<number> }\n },\n figure: { id?: string; version?: number },\n domain: { id: string },\n wanted: string\n): Promise<RenameFacts> {\n const next = wanted.trim()\n const hasHistory = (await repositories.histories.count({ where: { originalId: figure.id } })) > 0\n const taken = next ? await repositories.figures.findOne({ where: { domain: { id: domain.id }, type: next } }) : null\n\n const releasedBefore = next ? await typeReleasedBefore(repositories, domain, next) : false\n\n return { version: figure.version, hasHistory, takenByAnother: !!taken && taken.id !== figure.id, releasedBefore }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"figure-replaced-draft.js","sourceRoot":"","sources":["../../../server/service/figure/figure-replaced-draft.ts"],"names":[],"mappings":";;;;AAAA,qCAAgH;AAChH,+CAAyD;AAEzD,yDAAgD;AAChD,iDAA8D;AAE9D;;;;;;;;;GASG;AAKI,IAAM,mBAAmB,GAAzB,MAAM,mBAAmB;CA8E/B,CAAA;AA9EY,kDAAmB;AAGrB;IAFR,IAAA,gCAAsB,EAAC,MAAM,CAAC;IAC9B,IAAA,oBAAK,EAAC,IAAI,CAAC,EAAE,CAAC,iBAAE,EAAE,EAAE,WAAW,EAAE,sCAAsC,EAAE,CAAC;;+CACvD;AAGpB;IADC,IAAA,mBAAS,EAAC,IAAI,CAAC,EAAE,CAAC,cAAM,CAA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8BA7EP,mBAAmB;IAJ/B,IAAA,gBAAM,GAAE;IACR,IAAA,eAAK,EAAC,4BAA4B,EAAE,CAAC,IAAyB,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,SAAS,CAAC,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;IACnH,IAAA,eAAK,EAAC,4BAA4B,EAAE,CAAC,IAAyB,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC;IAChG,IAAA,yBAAU,EAAC,EAAE,WAAW,EAAE,0EAA0E,EAAE,CAAC;GAC3F,mBAAmB,CA8E/B","sourcesContent":["import { Column, CreateDateColumn, Entity, Index, ManyToOne, PrimaryGeneratedColumn, RelationId } from 'typeorm'\nimport { Field, ID, Int, ObjectType } from 'type-graphql'\n\nimport { User } from '@things-factory/auth-base'\nimport { Domain, longTextColumn } from '@things-factory/shell'\n\n/**\n * A figure's draft as it stood before a revert wrote over it -- kept, so what was saved just before a revert can be\n * brought back, after a reload too (ADR-0097 §5.6, designer 2026-09-27; table chosen with the chief architect).\n *\n * Not a released version: it has no version number of its own, is not listed with the releases, and never changes\n * what a board uses. Kept in the same transaction as the revert that replaces the draft -- kept, or neither happens.\n * `requestId` makes a retried revert (its answer lost) the same revert, not a second one.\n *\n * An undo of a revert is a revert too (`kind: 'undo'`): it keeps what it replaces the same way.\n */\n@Entity()\n@Index('ix_figure_replaced_draft_1', (kept: FigureReplacedDraft) => [kept.domain, kept.requestId], { unique: true })\n@Index('ix_figure_replaced_draft_2', (kept: FigureReplacedDraft) => [kept.domain, kept.figureId])\n@ObjectType({ description: 'A figure draft kept when a revert wrote over it. Not a released version.' })\nexport class FigureReplacedDraft {\n @PrimaryGeneratedColumn('uuid')\n @Field(type => ID, { description: 'Unique identifier of the kept draft.' })\n readonly id?: string\n\n @ManyToOne(type => Domain)\n domain?: Domain\n\n @RelationId((kept: FigureReplacedDraft) => kept.domain)\n domainId?: string\n\n @Column()\n @Field({ description: 'The figure whose draft this was.' })\n figureId?: string\n\n @Column({ default: 'revert' })\n @Field({ description: \"What replaced it: 'revert' (a released version written over it) or 'undo' (an undo of a revert).\" })\n kind?: 'revert' | 'undo'\n\n @Column({ nullable: true, ...longTextColumn() })\n @Field({ nullable: true, description: 'The figure asset JSON the draft held.' })\n source?: string\n\n @Column({ nullable: true, ...longTextColumn() })\n properties?: string\n\n @Column({ nullable: true, ...longTextColumn() })\n thumbnail?: string\n\n /*\n * 그림의 내용 해시(SHA-256). 그림 자체는 attachment-base 가 갖고(refType `figure-thumbnail`, refBy 이 해시),\n * `/figure-thumbnail/:id` 가 권한을 본 뒤 내준다(ADR-0104 결정 6). `thumbnail` 칸은 옛 base64 가 남은 행을\n * 기동 때 옮기기 위한 칸이다 — 옮긴 뒤에는 비어 있고, 새 그림은 그 칸에 쓰지 않는다.\n */\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'SHA-256 of the thumbnail picture; the picture is served by /figure-thumbnail/:id.' })\n thumbnailHash?: string\n\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'The state the figure was in.' })\n state?: string\n\n @Column({ nullable: true })\n @Field(type => Int, { nullable: true, description: 'The released version number the figure had then.' })\n version?: number\n\n @Column({ nullable: true })\n @Field(type => Int, { nullable: true, description: 'The released version the revert wrote over it; none for an undo.' })\n revertedToVersion?: number\n\n /* What replaced it, whole: an undo proceeds only while the figure still holds exactly this (compare-and-swap). */\n @Column({ nullable: true, ...longTextColumn() })\n writtenSource?: string\n\n /* Its content hash, for finding and retrying without reading the whole text (chief architect, 2026-09-27). */\n @Column()\n writtenSourceHash?: string\n\n @Column()\n requestId?: string\n\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'When this draft was brought back by an undo.' })\n restoredAt?: Date\n\n @Column({ nullable: true })\n restoreRequestId?: string\n\n @CreateDateColumn()\n @Field({ nullable: true, description: 'When it was kept -- when the revert replaced it.' })\n createdAt?: Date\n\n @ManyToOne(type => User, { nullable: true })\n @Field(type => User, { nullable: true, description: 'Who reverted.' })\n creator?: User\n\n @RelationId((kept: FigureReplacedDraft) => kept.creator)\n creatorId?: string\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"figure-revert.js","sourceRoot":"","sources":["../../../server/service/figure/figure-revert.ts"],"names":[],"mappings":";;AAmDA,gDAgEC;AAGD,gCA0DC;AAGD,4CAMC;AAzLD,mCAAmC;AACnC,qCAAgD;AAChD,qCAAsC;AAEtC,2CAAoC;AACpC,2DAAmD;AACnD,yEAAgE;AAChE,yDAAsE;AACtE,uDAAkD;AAElD;;;;;;;;;;;;;GAaG;AAEH,MAAM,IAAI,GAAG,wEAAwE,CAAA;AACrF,MAAM,MAAM,GAAG,CAAC,IAAY,EAAE,EAAE,CAAC,IAAA,mBAAU,EAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;AAChF,MAAM,OAAO,GAAG,CAAC,IAAY,EAAE,OAAe,EAAE,EAAE,CAAC,IAAI,sBAAY,CAAC,OAAO,EAAE,EAAE,UAAU,EAAE,EAAE,IAAI,EAAE,EAAE,CAAC,CAAA;AAEtG;;;GAGG;AACH,KAAK,UAAU,IAAI,CAAC,IAA0C,EAAE,GAAQ;IACtE,IAAI,CAAC;QACH,OAAO,MAAM,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;IAC7B,CAAC;IAAC,OAAO,KAAU,EAAE,CAAC;QACpB,MAAM,MAAM,GAAG,KAAK,EAAE,IAAI,KAAK,OAAO,IAAI,KAAK,EAAE,WAAW,EAAE,IAAI,KAAK,OAAO,IAAI,0BAA0B,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAA;QACzI,IAAI,MAAM;YAAE,MAAM,OAAO,CAAC,yBAAyB,EAAE,kCAAkC,CAAC,CAAA;QACxF,MAAM,KAAK,CAAA;IACb,CAAC;AACH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AAC;QACtD,KAAK,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,MAAM,CAAC,EAAE,EAAE,EAAE,QAAQ,EAAE;QAC9C,KAAK,EAAE,EAAE,SAAS,EAAE,MAAM,EAAE;QAC5B,SAAS,EAAE,CAAC,SAAS,CAAC;KACvB,CAAC,CAAA;AACJ,CAAC","sourcesContent":["import { createHash } from 'crypto'\nimport { In, type EntityManager } from 'typeorm'\nimport { GraphQLError } from 'graphql'\n\nimport { Figure } from './figure.js'\nimport { FigureHistory } from './figure-history.js'\nimport { FigureReplacedDraft } from './figure-replaced-draft.js'\nimport { draftSourceOfRelease, parseSource } from './figure-format.js'\nimport { sourceConflict } from './figure-write.js'\n\n/*\n * Reverting a figure to a released version, keeping the draft it writes over (ADR-0097 §5.6, designer 2026-09-27;\n * chief architect's ruling on the storage the same day).\n *\n * - One transaction: the draft is kept, then the figure is written over -- conditional on it being what the reverter\n * saw (`expectedSource`). If either fails, neither stays: the caller's transaction is rolled back.\n * - One request, one revert: `requestId` is unique in the domain. A retry -- the answer lost -- finds the revert it\n * asked for and answers with it; nothing is kept or written twice.\n * - An undo brings a kept draft back only while the figure still holds exactly what that revert wrote\n * (`WHERE id = ? AND source = ?`, as a save's compare-and-swap); edited since, it is refused and the kept draft stays.\n * It keeps what it replaces the same way.\n *\n * Every function here runs on the caller's transaction (`tx`); the resolvers open it (`@transaction`).\n */\n\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i\nconst hashOf = (text: string) => createHash('sha256').update(text).digest('hex')\nconst refused = (code: string, message: string) => new GraphQLError(message, { extensions: { code } })\n\n/*\n * The same request arriving twice at once: the second waits on the first's requestId and then meets the unique index.\n * Named, not a raw database error -- asked again after the first has finished, it gets the first's answer.\n */\nasync function keep(kept: { save: (row: any) => Promise<any> }, row: any) {\n try {\n return await kept.save(row)\n } catch (error: any) {\n const unique = error?.code === '23505' || error?.driverError?.code === '23505' || /UNIQUE constraint failed/.test(String(error?.message))\n if (unique) throw refused('FIGURE_REVERT_IN_FLIGHT', '같은 요청이 처리 중입니다. 잠시 뒤 다시 확인해 주세요.')\n throw error\n }\n}\n\nexport interface RevertRequest {\n id: string\n version: number\n requestId: string\n /** The figure's source as the reverter saw it; the revert goes on only while the figure still holds it. */\n expectedSource: string\n}\n\nexport async function revertKeepingDraft(\n tx: EntityManager,\n domain: { id: string; parentId?: string | null },\n user: { id: string } | undefined,\n request: RevertRequest\n) {\n if (!UUID.test(request.requestId ?? '')) throw refused('FIGURE_REVERT_REQUEST', '되돌리기 요청 식별자가 필요합니다.')\n const figures = tx.getRepository(Figure)\n const kept = tx.getRepository(FigureReplacedDraft)\n\n /* The same request again: the revert it made, answered again. */\n const before = await kept.findOne({ where: { domain: { id: domain.id }, requestId: request.requestId } })\n if (before) {\n if (before.figureId !== request.id || before.revertedToVersion !== request.version || before.kind !== 'revert')\n throw refused('FIGURE_REVERT_REQUEST', '이 되돌리기 요청 식별자는 다른 되돌리기에 이미 쓰였습니다.')\n return { figure: await figures.findOneOrFail({ where: { id: request.id, domain: { id: domain.id } } }), violations: [], kept: before }\n }\n\n /* Exact tenant ownership, as a save: an inherited figure is not written from a child domain. */\n const figure = await figures.findOne({ where: { id: request.id, domain: { id: domain.id } } })\n if (!figure) throw refused('FIGURE_NOT_FOUND', `Figure ${request.id} 를 찾을 수 없습니다.`)\n if (figure.source !== request.expectedSource) throw sourceConflict('다른 편집에서 모델이 변경되었습니다. 최신 모델을 다시 연 뒤 되돌려 주세요.')\n\n const history = await tx.getRepository(FigureHistory).findOne({\n where: { domain: { id: In([domain.id, domain.parentId].filter(Boolean) as string[]) }, originalId: request.id, version: request.version }\n })\n if (!history) throw refused('FIGURE_VERSION_NOT_FOUND', `Figure '${figure.type}' 에 ${request.version} 버전이 없습니다.`)\n /* The format is checked again: an old version may break today's rules, and is not let in quietly. */\n const { source, derived, violations } = parseSource(draftSourceOfRelease(history.source!))\n\n const record = await keep(kept, {\n domain: { id: domain.id },\n figureId: figure.id,\n kind: 'revert' as const,\n source: figure.source,\n properties: figure.properties,\n thumbnail: figure.thumbnail,\n thumbnailHash: figure.thumbnailHash,\n state: figure.state,\n version: figure.version,\n revertedToVersion: request.version,\n writtenSource: source,\n writtenSourceHash: hashOf(source),\n requestId: request.requestId,\n ...(user ? { creator: { id: user.id } } : {})\n })\n\n const written = await figures.update(\n { id: figure.id, domain: { id: domain.id }, source: request.expectedSource },\n {\n source,\n ...derived,\n properties: history.properties,\n /* The picture goes by its hash (ADR-0104 decision 6); the release's own, as the source is. */\n thumbnail: null,\n thumbnailHash: history.thumbnailHash ?? null,\n thumbnailUpdatedAt: history.thumbnailHash === figure.thumbnailHash ? figure.thumbnailUpdatedAt : new Date(),\n state: 'draft',\n ...(user ? { updater: { id: user.id } } : {})\n }\n )\n if (written.affected !== 1) throw sourceConflict('다른 편집에서 모델이 변경되었습니다. 최신 모델을 다시 연 뒤 되돌려 주세요.')\n\n return { figure: await figures.findOneOrFail({ where: { id: figure.id, domain: { id: domain.id } } }), violations, kept: record }\n}\n\n/** Brings a kept draft back -- only while the figure holds exactly what that revert wrote. */\nexport async function undoRevert(\n tx: EntityManager,\n domain: { id: string },\n user: { id: string } | undefined,\n request: { keptId: string; requestId: string }\n) {\n if (!UUID.test(request.requestId ?? '')) throw refused('FIGURE_REVERT_REQUEST', '되돌리기 취소 요청 식별자가 필요합니다.')\n const figures = tx.getRepository(Figure)\n const kept = tx.getRepository(FigureReplacedDraft)\n\n const record = await kept.findOne({ where: { id: request.keptId, domain: { id: domain.id } } })\n if (!record) throw refused('FIGURE_KEPT_NOT_FOUND', '되살릴 초안을 찾을 수 없습니다.')\n if (record.restoredAt) {\n /* Asked again with the same request: the undo it made. Another request for a draft already back: refused. */\n if (record.restoreRequestId === request.requestId)\n return { figure: await figures.findOneOrFail({ where: { id: record.figureId, domain: { id: domain.id } } }), kept: record }\n throw refused('FIGURE_KEPT_RESTORED', '이 초안은 이미 되살렸습니다.')\n }\n\n const figure = await figures.findOne({ where: { id: record.figureId, domain: { id: domain.id } } })\n if (!figure) throw refused('FIGURE_NOT_FOUND', `Figure ${record.figureId} 를 찾을 수 없습니다.`)\n\n /* What the undo replaces is kept too -- the same rule as a revert. */\n const { derived } = parseSource(record.source!)\n await keep(kept, {\n domain: { id: domain.id },\n figureId: figure.id,\n kind: 'undo' as const,\n source: figure.source,\n properties: figure.properties,\n thumbnail: figure.thumbnail,\n thumbnailHash: figure.thumbnailHash,\n state: figure.state,\n version: figure.version,\n writtenSource: record.source,\n writtenSourceHash: hashOf(record.source!),\n requestId: request.requestId,\n ...(user ? { creator: { id: user.id } } : {})\n })\n\n const written = await figures.update(\n { id: figure.id, domain: { id: domain.id }, source: record.writtenSource },\n {\n source: record.source,\n ...derived,\n properties: record.properties,\n thumbnail: null,\n thumbnailHash: record.thumbnailHash ?? null,\n thumbnailUpdatedAt: record.thumbnailHash === figure.thumbnailHash ? figure.thumbnailUpdatedAt : new Date(),\n state: 'draft',\n ...(user ? { updater: { id: user.id } } : {})\n }\n )\n if (written.affected !== 1)\n throw sourceConflict('되돌린 뒤 모델이 다시 바뀌어 되돌리기를 취소하지 않았습니다. 보관한 초안은 그대로 남아 있습니다.')\n\n await kept.update({ id: record.id }, { restoredAt: new Date(), restoreRequestId: request.requestId })\n return { figure: await figures.findOneOrFail({ where: { id: figure.id, domain: { id: domain.id } } }), kept: { ...record, restoredAt: new Date(), restoreRequestId: request.requestId } }\n}\n\n/** The drafts reverts kept for a figure, newest first -- found again after a reload. */\nexport async function replacedDraftsOf(tx: EntityManager, domain: { id: string }, figureId: string) {\n return await tx.getRepository(FigureReplacedDraft).find({\n where: { domain: { id: domain.id }, figureId },\n order: { createdAt: 'DESC' },\n relations: ['creator']\n })\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"figure-subject.js","sourceRoot":"","sources":["../../../server/service/figure/figure-subject.ts"],"names":[],"mappings":";;;AAAA;;;;;;GAMG;AACH,mEAAyE;AACzE,iDAAqD;AAErD,2FAA2F;AAC9E,QAAA,aAAa,GAAG;IAC3B,UAAU,EAAE,QAAQ;IACpB,KAAK,CAAC,QAAQ,CAAC,EAAE,QAAQ,EAAE,MAAM,EAAgD;QAC/E,MAAM,MAAM,GAAQ,MAAM,IAAA,qBAAa,EAAC,QAAQ,CAAC,CAAC,OAAO,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,MAAM,CAAC,EAAE,EAAE,EAAE,EAAE,CAAC,CAAA;QACjH,IAAI,CAAC,MAAM;YAAE,OAAO,SAAS,CAAA;QAC7B,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,IAAI,MAAM,CAAC,IAAI,EAAE,CAAA;IAC7D,CAAC;CACF,CAAA;AAED,IAAA,yCAAwB,EAAC,qBAAa,CAAC,CAAA","sourcesContent":["/**\n * The figure the modeller has open, named for the AI (operato-application design/ai/screen-pattern.md §2-1).\n *\n * A conversation in the modeller is anchored to the open figure. Each turn the door reads this to say which figure\n * that is, so the model starts from \"the figure 선풍기 is open\" and passes its id to the tools. A figure of another\n * domain, or one that is gone, is not named.\n */\nimport { registerAssistantSubject } from '@things-factory/ai-client-base'\nimport { getRepository } from '@things-factory/shell'\n\n/* By entity name - the entity's decorators stay out of what a test of this has to load. */\nexport const figureSubject = {\n anchorType: 'figure',\n async describe({ anchorId, domain }: { anchorId: string; domain: { id: string } }) {\n const figure: any = await getRepository('Figure').findOne({ where: { id: anchorId, domain: { id: domain.id } } })\n if (!figure) return undefined\n return { noun: 'figure', name: figure.name || figure.type }\n }\n}\n\nregisterAssistantSubject(figureSubject)\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"figure-thumbnail-reader.js","sourceRoot":"","sources":["../../../server/service/figure/figure-thumbnail-reader.ts"],"names":[],"mappings":";;AAcA,sDAGC;AAjBD,qEAA0E;AAC1E,yDAA2D;AAE3D,2EAAgE;AAEhE;;;GAGG;AACH;;;;GAIG;AACI,KAAK,UAAU,qBAAqB,CAAC,WAAoB,EAAE,OAAY,EAAE,QAAgC,2BAAe;IAC7H,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,oBAAoB,EAAE,GAAG,OAAO,EAAE,KAAK,IAAI,EAAE,CAAA;IAC7E,OAAO,CAAC,CAAC,CAAC,MAAM,KAAK,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,SAAS,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,oBAAoB,CAAC,CAAC,CAAA;AAC/H,CAAC;AAED,IAAA,0CAAwB,EAAC,8CAAkB,EAAE,CAAC,UAAU,EAAE,OAAO,EAAE,EAAE,CAAC,qBAAqB,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC,CAAA","sourcesContent":["import { registerAttachmentReader } from '@things-factory/attachment-base'\nimport { checkPermission } from '@things-factory/auth-base'\n\nimport { THUMBNAIL_REF_TYPE } from './figure-thumbnail-store.js'\n\n/*\n * Apart from the store, and loaded only by the server's entry: the store is read by pure modules (the save path,\n * figure-ui's tests), and auth-base brings shell's routers with it.\n */\n/**\n * Who may read a figure picture by its attachment path (ADR-0106 decision 2): whoever may query figures -- the same door\n * `/figure-thumbnail/:id` keeps, so the picture is no more open by its path than by its figure. attachment-base has\n * already checked the attachment is of the request's domain.\n */\nexport async function figureThumbnailReader(_attachment: unknown, context: any, check: typeof checkPermission = checkPermission): Promise<boolean> {\n const { domain, user, unsafeIP, prohibitedPrivileges } = context?.state ?? {}\n return !!(await check({ category: 'figure', privilege: 'query', owner: true }, user, domain, unsafeIP, prohibitedPrivileges))\n}\n\nregisterAttachmentReader(THUMBNAIL_REF_TYPE, (attachment, context) => figureThumbnailReader(attachment, context))\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"figure-thumbnail-store.js","sourceRo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EAAC,OAAO,CAAC,KAAK,CAAC,CAAA;IACpC,IAAI,MAAM,qBAAqB,CAAC,EAAE,EAAE,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC;QAAE,OAAO,IAAI,CAAA;IACjE,MAAM,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,CAAA;IAC9D,MAAM,IAAI,GAAG,GAAG,IAAI,IAAI,GAAG,EAAE,CAAA;IAC7B,+GAA+G;IAC/G,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC,GAAG,CAAC,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,KAAK,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE,EAAE,EAAE,CAAC,CAAA;IAC/F,MAAM,EAAE,CAAC,aAAa,CAAC,4BAAU,CAAC,CAAC,IAAI,CAAC;QACtC,MAAM;QACN,OAAO,EAAE,IAAI;QACb,OAAO,EAAE,IAAI;QACb,EAAE,EAAE,GAAG,CAAC,EAAE;QACV,IAAI;QACJ,QAAQ,EAAE,OAAO,CAAC,IAAI;QACtB,QAAQ,EAAE,QAAQ;QAClB,OAAO,EAAE,0BAAkB;QAC3B,KAAK,EAAE,IAAI;QACX,QAAQ,EAAE,OAAO;QACjB,IAAI,EAAE,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC;QACtB,IAAI,EAAE,GAAG,CAAC,IAAI;QACd,GAAG,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACpD,CAAC,CAAA;IACF,OAAO,IAAI,CAAA;AACb,CAAC","sourcesContent":["import { createHash } from 'crypto'\nimport { Readable } from 'stream'\n\nimport { Attachment, STORAGE } from '@things-factory/attachment-base'\n\n/*\n * A figure's picture, kept by attachment-base and named by its content (ADR-0104 decision 6, chief architect's ruling\n * 2026-10-02).\n *\n * stored by attachment-base's storage (file, S3, database -- whichever the install configures), one attachment\n * per (domain, content): refType `figure-thumbnail`, refBy the SHA-256 of the bytes. A figure, its\n * releases and the drafts a revert kept carry that hash, never the bytes.\n * served only through `/figure-thumbnail/:id`, behind the figure query permission -- never through attachment-\n * base's public `/attachment/:path`, which checks nothing (a known gap, recorded in ADR-0104).\n * the same content twice in one domain is one attachment, read by its hash. Two writers that both find none both\n * write one; either serves the same bytes, so the result is the same (ruling, condition 2).\n *\n * The file is written before the row that names it: a file cannot be rolled back, so it goes first, and a row that\n * fails to commit leaves a file the next write of the same content writes again.\n */\n\nexport const THUMBNAIL_REF_TYPE = 'figure-thumbnail'\n\n/** `data:image/webp;base64,....` as its type and bytes; undefined when it is not one. */\nexport function decodeDataUrl(dataUrl: string): { type: string; bytes: Buffer } | undefined {\n const matched = /^data:([^;,]+);base64,(.*)$/s.exec(dataUrl)\n return matched ? { type: matched[1]!, bytes: Buffer.from(matched[2]!, 'base64') } : undefined\n}\n\nexport const sha256Of = (bytes: Buffer) => createHash('sha256').update(bytes).digest('hex')\n\n/** Where the bytes go: attachment-base's storage. Tests give another. */\nexport interface ThumbnailFiles {\n put(bytes: Buffer, mimetype: string, name: string, context: any): Promise<{ id: string; path: string; size: number; contents?: Buffer }>\n send(koa: any, path: string, next: () => Promise<any>): Promise<void>\n /** The bytes kept at a path -- what a figure package carries. */\n read(path: string): Promise<Buffer>\n}\n\nexport const attachmentFiles: ThumbnailFiles = {\n async put(bytes, mimetype, name, context) {\n const file = Promise.resolve({\n createReadStream: () => Readable.from([bytes]),\n filename: name,\n mimetype,\n encoding: 'binary'\n })\n const { id, path, size, contents } = await STORAGE.uploadFile({ file, context })\n return { id, path, size, contents }\n },\n send: (koa, path, next) => STORAGE.sendFile(koa, path, next),\n read: async path => Buffer.from(await STORAGE.readFile(path))\n}\n\n/*\n * The files in use: attachment-base's storage, unless a test gives its own. One seam for every writer and the router,\n * so a test of a save or a revert need not reach into each.\n */\nlet inUse: ThumbnailFiles = attachmentFiles\nexport const thumbnailFiles = (): ThumbnailFiles => inUse\n/** For tests: use these files until set back; returns the ones it replaced. */\nexport function useThumbnailFiles(files: ThumbnailFiles): ThumbnailFiles {\n const was = inUse\n inUse = files\n return was\n}\n\ntype Tx = { getRepository: (target: any) => any }\n\n/** The attachment holding this content in this domain, or undefined. */\nexport async function thumbnailAttachmentOf(tx: Tx, domainId: string, hash: string): Promise<Attachment | undefined> {\n return (await tx.getRepository(Attachment).findOne({ where: { domain: { id: domainId }, refType: THUMBNAIL_REF_TYPE, refBy: hash } })) ?? undefined\n}\n\n/**\n * Keeps a picture and gives its hash. Refused when it is not a data URL -- a picture the server cannot read is one it\n * must not keep under a name.\n */\nexport async function keepThumbnail(\n tx: Tx,\n domain: { id: string },\n user: unknown,\n dataUrl: string,\n files: ThumbnailFiles = thumbnailFiles()\n): Promise<string> {\n const decoded = decodeDataUrl(dataUrl)\n if (!decoded) throw new Error('썸네일은 data URL(data:image/...;base64,...) 이어야 한다')\n const hash = sha256Of(decoded.bytes)\n if (await thumbnailAttachmentOf(tx, domain.id, hash)) return hash\n const ext = decoded.type.split('/')[1]?.split('+')[0] || 'bin'\n const name = `${hash}.${ext}`\n /* The file first: it cannot be rolled back. The row that names it comes after, in the caller's transaction. */\n const put = await files.put(decoded.bytes, decoded.type, name, { state: { domain, user, tx } })\n await tx.getRepository(Attachment).save({\n domain,\n creator: user,\n updater: user,\n id: put.id,\n name,\n mimetype: decoded.type,\n encoding: 'binary',\n refType: THUMBNAIL_REF_TYPE,\n refBy: hash,\n category: 'image',\n size: String(put.size),\n path: put.path,\n ...(put.contents ? { contents: put.contents } : {})\n })\n return hash\n}\n\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"figure-thumbnail-upgrade.js","sourceRoot":"","sources":["../../../server/service/figure/figure-thumbnail-upgrade.ts"],"names":[],"mappings":";;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EAAE,CAAC,CAAA;gBAC5H,IAAI,EAAE,CAAA;YACR,CAAC;QACH,CAAC;QACD,GAAG,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAA;IAClC,CAAC;IACD,OAAO,GAAG,CAAA;AACZ,CAAC","sourcesContent":["import { IsNull, Not } from 'typeorm'\n\nimport { Figure } from './figure.js'\nimport { FigureHistory } from './figure-history.js'\nimport { FigureReplacedDraft } from './figure-replaced-draft.js'\nimport { keepThumbnail, thumbnailFiles, type ThumbnailFiles } from './figure-thumbnail-store.js'\n\n/*\n * Moves the pictures an install kept as base64 into attachment-base, by their content (ADR-0104 decision 6; chief\n * architect's ruling 2026-10-02, condition 3). Run at start, in the boot's one line (`inBootTurn`).\n *\n * per row the file first -- it cannot be rolled back -- then, in one transaction, the attachment row, the hash,\n * and the base64 emptied. The update only takes a row whose base64 is still the one read, so two starts\n * at once, or a save in between, never empty a picture that was not moved.\n * again safe: a row already moved has no base64 and is not read; a picture already kept is found by its hash.\n * kept a picture that is not a data URL, or a row whose domain cannot be found, keeps its base64 and is\n * counted -- nothing is emptied that was not moved.\n */\n\ntype Moved = { table: string; moved: number; kept: number }\n\nconst TABLES = [\n { table: 'figure', entity: Figure },\n { table: 'figure_history', entity: FigureHistory },\n { table: 'figure_replaced_draft', entity: FigureReplacedDraft }\n] as const\n\nexport async function moveBase64Thumbnails(dataSource: any, files: ThumbnailFiles = thumbnailFiles()): Promise<Moved[]> {\n const out: Moved[] = []\n for (const { table, entity } of TABLES) {\n const rows: any[] = await dataSource.getRepository(entity).find({\n where: { thumbnail: Not(IsNull()) },\n relations: { domain: true },\n select: { id: true, thumbnail: true, domain: { id: true }, ...(entity === FigureHistory ? { originalId: true } : {}) },\n withDeleted: true\n })\n let moved = 0,\n kept = 0\n for (const row of rows) {\n /* A release written before releases carried their domain names it through the figure it belongs to. */\n const domainId: string | undefined =\n row.domain?.id ??\n (entity === FigureHistory && row.originalId\n ? (await dataSource.getRepository(Figure).findOne({ where: { id: row.originalId }, relations: { domain: true }, select: { id: true, domain: { id: true } }, withDeleted: true }))?.domain?.id\n : undefined)\n if (!domainId) {\n kept++\n continue\n }\n try {\n await dataSource.transaction(async (tx: any) => {\n const hash = await keepThumbnail(tx, { id: domainId }, undefined, row.thumbnail, files)\n await tx\n .createQueryBuilder()\n .update(entity)\n .set({ thumbnailHash: hash, thumbnail: null })\n .where('id = :id AND thumbnail = :was', { id: row.id, was: row.thumbnail })\n .callListeners(false)\n .execute()\n })\n moved++\n } catch (error) {\n console.error(`[figure-service] ${table} ${row.id} 의 썸네일을 옮기지 못했다 — base64 를 그대로 둔다: ${(error as Error)?.message ?? error}`)\n kept++\n }\n }\n out.push({ table, moved, kept })\n }\n return out\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"figure-tools.js","sourceRoot":"","sources":["../../../server/service/figure/figure-tools.ts"],"names":[],"mappings":";;AAwFA,gEAEC;AAkfD,oEAsBC;AAlmBD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,mCAAmC;AACnC,qCAA+B;AAC/B,mEASuC;AAEvC,2DAAiG;AAEjG,oDAAoD;AACpD,MAAM,UAAU,GAAG,GAAG,CAAA;AAEtB;;;EAGE;AACF,IAAI,KAAsB,CAAA;AAE1B,SAAS,OAAO;IACd,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,8DAA8D;QAC9D,MAAM,KAAK,GAAG,OAAO,CAAC,uBAAuB,CAAC,CAAA;QAC9C,8DAA8D;QAC9D,MAAM,KAAK,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAAA;QAC/C,8DAA8D;QAC9D,MAAM,MAAM,GAAG,OAAO,CAAC,aAAa,CAAC,CAAA;QACrC,8DAA8D;QAC9D,MAAM,MAAM,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAA;QAC5C,8DAA8D;QAC9D,MAAM,QAAQ,GAAG,OAAO,CAAC,2BAA2B,CAAC,CAAA;Q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AAwW;YACxW,iMAAiM;YACjM,sHAAsH;YACtH,oKAAoK;YACpK,sFAAsF;SACvF,CAAC,IAAI,CAAC,IAAI,CAAC;QACZ,KAAK,EAAE,eAAe,EAAE;KACzB,CAAA;IAED,IAAA,qCAAoB,EAAC,SAAS,CAAC,CAAA;AACjC,CAAC","sourcesContent":["/*\n * figure 저작 도구를 어시스턴트 도구 레지스트리에 등록 — **대화면(도크)에서 저작을 돕기 위함.**\n *\n * 왜 필요한가: `proposeFigure` 는 한 번 시키고 한 번 받는다. 그것으로 되는 일이 있지만, 저작은\n * 대개 「이걸 이렇게 고쳐 봐 → 무게가 얼마나 되나 → 발행은 되나」처럼 여러 차례 오간다. 그 대화를\n * 하려면 어시스턴트가 **지금 무엇이 있는지 읽을 수 있어야** 한다. 읽지 못하면 매번 사람이 정본을\n * 붙여 넣어야 하고, 그러면 대화가 아니다.\n *\n * 능력을 복제하지 않는다. figure-service 가 이미 가진 진입점(`inspectSource` · `proposeFigureSteps` ·\n * 조회)을 레지스트리에 투영한다.\n *\n * ── 전부 조회·제안 전용이다 ─────────────────────────────────────────────────\n * 정본을 고치는 도구를 넣지 않는다. 형식의 설계가 그렇게 정해져 있다 — 어시스턴트는 **후보**를\n * 내고, 받을지 버릴지는 저작자가 정한다(`figure-propose-steps.ts`, ADR-0094). 되돌릴 수 없는 조작이 대화면으로\n * 새지 않으므로 전부 `kind: 'read'` 다.\n *\n * 저장은 저작면이 `updateFigure` 로 한다. 그 mutation 은 `figure:mutation` 이 지키고, 대화는\n * `ai-assistant:mutation` 이 지킨다 — 서로 다른 질문이라 서로 다른 권한이 지킨다. figure 가 board\n * 의 권한을 빌리지 않는다.\n *\n * ── No privilege here. The gate reads what the door declares ─────────────────────\n * Until 2026-09-18 each tool carried `privilege: { category: 'figure', ... }`. It matched the door's\n * directive then, and would drift the day the door changed its declaration — and the looser copy wins.\n * Now the gate reads the declaration of each door in `doors` from AUTH's table (ADR-0071 decision 2,\n * addendum). What stays here is **the doors it reaches**.\n *\n * ── 규율을 도구와 함께 보낸다 ───────────────────────────────────────────────\n * 도구 목록만으로는 「언제 반드시 불러야 하는지」를 모른다. twin 이 그 공백에서 사고를 냈다 —\n * 조치 요청에 도구를 부르지 않고 「제안해 두었습니다」라고만 답해, 사용자에게 **없는 버튼을 누르라고\n * 안내했다.** figure 도 똑같은 자리가 있다: 후보 화면(「지금 / 후보」 두 칸)은 **도구 호출 결과에서만**\n * 만들어진다. 문장으로는 아무 일도 일어나지 않는다.\n *\n * ── LLM 이 넘긴 id 를 믿지 않는다 ───────────────────────────────────────────\n * 사람이 목록에서 고르는 길에서는 드러나지 않지만, 모델은 대화 내용에 이끌려 임의의 id 를 넘길 수\n * 있다. 그래서 호출자 도메인 소속을 먼저 확인한다.\n */\nimport { randomUUID } from 'crypto'\nimport { ILike } from 'typeorm'\nimport {\n aiClientFor,\n registerToolCategory,\n type AIImageMediaType,\n type ToolAttachment,\n type ToolCallContext,\n type ToolCategory,\n type ToolImageAttachment,\n type ToolSpec\n} from '@things-factory/ai-client-base'\n\nimport { FIGURE_CONTEXT_BUDGET, figureViewOf, type FigureReadRequest } from './figure-context.js'\n\n/** How many figures a list without search names. */\nconst LIST_LIMIT = 200\n\n/*\n 서버 의존성은 lazy require 다. 등록은 부팅 초반에 평가되고 그때 typeorm DataSource 가 준비되지\n 않았을 수 있다(board-import · twin-ai 와 같은 정책).\n*/\nlet _deps: any | undefined\n\nfunction getDeps(): any {\n if (!_deps) {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const shell = require('@things-factory/shell')\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const model = require('@hatiolab/figure-model')\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const entity = require('./figure.js')\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const format = require('./figure-format.js')\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const proposer = require('./figure-propose-steps.js')\n _deps = {\n getRepository: shell.getRepository,\n Figure: entity.Figure,\n /* The same doors a save and a release go through. The tool reads; it never saves. */\n inspectSource: format.inspectSource,\n parseSource: format.parseSource,\n figureCostOf: model.figureCostOf,\n figureScoreOf: model.figureScoreOf,\n proposeFigureSteps: proposer.proposeFigureSteps,\n isPlaceholderType: model.isPlaceholderType\n }\n }\n return _deps\n}\n\n/** 시험·검증 하네스 전용 주입 시임. 운영 경로에서 호출 금지. */\nexport function __setFigureToolDepsForTest(deps: any): void {\n _deps = deps\n}\n\nfunction requireDomainId(state: any): string {\n const id = state?.domain?.id\n if (!id) {\n // 도메인을 모르면 무엇을 읽어도 남의 것일 수 있다. 조용히 넘기지 않는다.\n throw new Error('domain context is missing — the figure tools cannot resolve tenant scope')\n }\n return id\n}\n\n/**\n * 이 피규어가 호출자 도메인 것인가.\n *\n * 모델이 넘긴 id 를 그대로 쓰지 않는다. 없으면 못 찾았다고 말한다 — 「권한이 없다」와 구별해\n * 알려 줄 것이 없다(다른 테넌트에 그 id 가 있다는 사실 자체가 알려 줄 것이 아니다).\n */\nasync function figureInDomain(figureId: string, domainId: string): Promise<any> {\n const { getRepository, Figure } = getDeps()\n const found = await getRepository(Figure).findOne({\n where: { id: figureId, domain: { id: domainId } }\n })\n if (!found) {\n throw new Error(`figure not found in this tenant: ${figureId}`)\n }\n return found\n}\n\n/** The form of a creation id: the row id a new figure's first save inserts it under (`figure-mutation.ts`). */\nconst CREATION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i\n\n/**\n * The figure a tool is about: by id, or by its type name, in the caller's domain. None named: none.\n *\n * A figure not saved yet is a subject too (ADR-0061 decision 3): the modeller names it by its creation id, which its first\n * save inserts the row under (ADR-0072 decision 6), so before that save there is no row. It is the figure open on that\n * screen and nothing else: the id the screen has open, with the draft the screen sent. What is read is that draft, put\n * through the save's door like any draft (`sourceForTool`); nothing the server holds is read for it.\n */\nasync function resolveFigureTarget(figureId: string | undefined, domainId: string, host: any): Promise<any> {\n if (!figureId) return undefined\n const { getRepository, Figure } = getDeps()\n const found =\n (await getRepository(Figure).findOne({ where: { id: figureId, domain: { id: domainId } } })) ??\n (await getRepository(Figure).findOne({ where: { type: figureId, domain: { id: domainId } } }))\n if (found) return found\n const draft = host?.draftSource\n if (CREATION_ID.test(figureId) && host?.figureId === figureId && draft && typeof draft === 'object') {\n return { id: figureId, name: typeof draft.name === 'string' ? draft.name : undefined, source: null }\n }\n throw new Error(`figure not found in this tenant: ${figureId}`)\n}\n\n/**\n * The source a tool reads: the draft on screen when the modeller has this figure open, else the stored one.\n *\n * The host context is the browser's, so it is no ground for access: the row is found in the domain first, and the\n * draft is put through the same door a save goes through before anything reads it.\n */\nconst isFigure = (source: any) => source?.version === 'figure-asset-1'\n\n/**\n * A revision is applied by the modeller on the version the model saw (ADR-0094), so only the figure open there can be\n * revised. Said as what is true, with what the assistant can do instead.\n */\nfunction figureNotOpen() {\n return {\n error: 'FIGURE_NOT_OPEN',\n message: 'A revision can be proposed only for the figure open in the modeller.',\n nextStep:\n 'Tell the person to open the figure in the modeller and ask again there. A new figure needs no open one: call proposeFigureCandidate with create: true.'\n }\n}\n\nfunction sourceForTool(row: any, host: any): { source: any; draft: boolean } {\n const draft = host?.figureId === row.id ? host?.draftSource : undefined\n if (!draft) return { source: row.source ? JSON.parse(row.source) : null, draft: false }\n\n if (typeof draft !== 'object' || Array.isArray(draft)) throw new Error('the unsaved draft is not a figure asset')\n const serialized = JSON.stringify(draft)\n /* Validity is the save door's (the kernel's 1 MiB); how much the model is shown is `figure-context`'s. */\n try {\n getDeps().parseSource(serialized)\n } catch (e: any) {\n const findings = Array.isArray(e?.findings) ? e.findings.map((one: any) => one.message).join(' · ') : String(e?.message ?? e)\n throw new Error(`the unsaved draft is invalid: ${findings}`)\n }\n return { source: draft, draft: true }\n}\n\n/** The finite numbers of an untrusted record, by name; none: undefined. */\nfunction numbersOf(record: any): Record<string, number> | undefined {\n if (!record || typeof record !== 'object' || Array.isArray(record)) return undefined\n const kept = Object.entries(record).filter((entry): entry is [string, number] => typeof entry[1] === 'number' && Number.isFinite(entry[1]))\n return kept.length ? Object.fromEntries(kept) : undefined\n}\n\n/**\n * What the person has in view on the open draft: the part selected and what the preview is trying (ADR-0097 §5.6\n * item 5). The model hears it only here, through a read (ADR-0061 decision 3). Told only when it was seen on the version\n * being read -- a selection from another version may name a part that is gone -- and a part only when the draft has it.\n */\nfunction focusOf(host: any, source: any): { selection?: { part: string }; trying?: { clips?: Record<string, number>; controls?: Record<string, number> } } {\n const onThisVersion = (seen: any) => typeof host?.context === 'string' && seen?.context === host.context && seen?.revision === host.revision\n const focus: ReturnType<typeof focusOf> = {}\n\n const part = host?.selection?.part\n const nodes = source?.document?.model?.nodes\n if (typeof part === 'string' && onThisVersion(host.selection) && Array.isArray(nodes) && nodes.some((node: any) => node?.id === part)) {\n focus.selection = { part }\n }\n\n if (onThisVersion(host?.trying)) {\n const clips = numbersOf(host.trying.clips)\n const controls = numbersOf(host.trying.controls)\n if (clips || controls) focus.trying = { ...(clips ? { clips } : {}), ...(controls ? { controls } : {}) }\n }\n return focus\n}\n\n/**\n * 무엇을 고치라는 것인지 대화면 문맥에서 해소한다.\n *\n * 모델이 대상을 안 줬으면 **저작면이 지금 열고 있는 피규어**이다. 사용자에게 식별자를 되묻지\n * 않는다 — 화면에 그 피규어가 떠 있는데 「어느 피규어입니까」를 묻는 것은 문맥을 안 읽은 것이다.\n */\nfunction figureIdFrom(args: any, host: any): string | undefined {\n const said = typeof args?.figureId === 'string' ? args.figureId.trim() : ''\n if (said) return said\n\n const open = typeof host?.figureId === 'string' ? host.figureId.trim() : ''\n if (open) return open\n\n return undefined\n}\n\nfunction missingFigureTarget() {\n return {\n error: 'FIGURE_TARGET_REQUIRED',\n message: 'No figure is open on this screen.',\n nextStep: 'For an existing figure, call listFigures and match the user’s requested name or type; ask which figure only if ambiguous. For a new figure, call proposeFigureCandidate with create: true and the user’s prompt. Do not invent an id or repeat this call without a target.'\n }\n}\n\nconst FIGURE_ID_ARG = {\n figureId: {\n type: 'string',\n description: 'The figure to read. Omit to read the one open in the modeller — with its unsaved changes, and also when it is a new figure not saved yet; the server fills it in, and you cannot see which it is. A figure not saved yet is readable only while it is open in the modeller. On the catalog nothing is open, so resolve the figure the person asked for with listFigures first.'\n }\n} as const\n\nconst PARTS_ARG = {\n parts: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'Only for a figure too large to read whole (the answer then has `outline` and no `source`): the ids of the parts to read in full, from `outline.parts`. Omit to read the part selected.'\n },\n sections: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'Only for a figure too large to read whole: JSON Pointers of sections to read, such as one named in `outline.omitted` or its `entries` (for example /document/capabilities/bindings/0).'\n }\n} as const\n\n/**\n * A figure too large to show whole, as the model reads it (ADR-0061 2026-10-16 decision 4): its outline and the parts\n * asked for. The full source stays here; what is measured is measured on it.\n */\nfunction partialRead(source: any, request: FigureReadRequest) {\n const view = figureViewOf(source, request)\n if (view.whole) return { source }\n return {\n outline: view.outline,\n partSources: view.parts,\n ...(Object.keys(view.sections ?? {}).length ? { sectionSources: view.sections } : {}),\n ...(view.notRead ? { notRead: view.notRead } : {}),\n note:\n `This figure is too large to read whole (${view.outline!.chars} characters; ${FIGURE_CONTEXT_BUDGET} are read at once), so this is its outline, the parts in partSources and the sections in sectionSources. ` +\n 'Read what a change touches with parts and sections, then pass the same to proposeFigureCandidate: only parts read in full may be changed, and nothing in a section in outline.omitted that was not read.'\n }\n}\n\n/** The parts the model named, as strings; anything else is dropped. */\nconst stringsOf = (list: unknown): string[] =>\n Array.isArray(list) ? list.filter((one: unknown): one is string => typeof one === 'string' && !!one.trim()).map((one: string) => one.trim()) : []\n\n/** An inspection whose findings would crowd the model's context, cut to the budget with how many there were. */\nfunction findingsWithinBudget(inspection: any) {\n const findings = Array.isArray(inspection?.findings) ? inspection.findings : []\n if (JSON.stringify(inspection).length <= FIGURE_CONTEXT_BUDGET) return inspection\n const head = JSON.stringify({ ...inspection, findings: [], truncated: { shown: findings.length, total: findings.length } }).length\n let room = FIGURE_CONTEXT_BUDGET - head\n const shown: any[] = []\n for (const finding of findings) {\n const cost = JSON.stringify(finding).length + 1\n if (cost > room) break\n shown.push(finding)\n room -= cost\n }\n return { ...inspection, findings: shown, truncated: { shown: shown.length, total: findings.length } }\n}\n\n/**\n * 도구 넷.\n *\n * 목록 · 정본 · 발행 판정 · 후보. 저작 대화에서 실제로 묻는 것이 그 넷이다 — 「무엇이 있나」\n * 「지금 어떻게 생겼나」 「발행이 왜 안 되나」 「이렇게 고쳐 봐」.\n */\nfunction figureToolSpecs(): ToolSpec[] {\n return [\n {\n kind: 'read',\n name: 'listFigures',\n /* 이 도메인의 피규어 목록 — 저장소를 직접 읽지만 같은 일을 하는 문은 이것이다. */\n doors: ['Query.figures'],\n description:\n 'Lists the figures in this tenant with their type names, states and part counts. ' +\n 'Call it before naming a type — type names are stored identifiers and must not be invented. ' +\n `Without search it lists the ${LIST_LIMIT} most recently changed; when there are more it says truncated, and a figure the person names may be among the rest - list again with search.`,\n schema: {\n type: 'object',\n properties: {\n search: {\n type: 'string',\n description: 'Part of a figure name or type name, in any case. Omit to list the most recently changed.'\n }\n }\n },\n builder: async (args: any, ctx: any) => {\n const domainId = requireDomainId(ctx?.state)\n const { getRepository, Figure } = getDeps()\n const search = typeof args?.search === 'string' ? args.search.trim() : ''\n const domain = { id: domainId }\n /* `_` and `%` in the words are LIKE wildcards: they can only widen what is found, never hide a match. */\n const where = search\n ? [\n { domain, name: ILike(`%${search}%`) },\n { domain, type: ILike(`%${search}%`) }\n ]\n : { domain }\n /* One more than is shown, to know whether there is more without counting the table. */\n const rows = await getRepository(Figure).find({ where, order: { updatedAt: 'DESC' }, take: LIST_LIMIT + 1 })\n const truncated = rows.length > LIST_LIMIT\n return {\n ...(truncated\n ? {\n truncated: true,\n note: `Only the ${LIST_LIMIT} most recently changed are listed. A figure not here may still exist: call listFigures again with search.`\n }\n : {}),\n figures: rows.slice(0, LIST_LIMIT).map((row: any) => ({\n id: row.id,\n type: row.type,\n name: row.name,\n state: row.state,\n score: row.score,\n triangles: row.triangles\n }))\n }\n }\n },\n {\n kind: 'read',\n name: 'getFigureSource',\n /* 저장된 피규어의 원본. **저장 전 초안**을 물으면 저장소에 갈 것이 없어 화면이 보낸 것을 그대로 돌려준다 —\n * 그 갈래에는 닿는 문이 없지만 `doors: []` 로 적지 않는다. 그러면 저장된 피규어를 읽는 권한 검사가 선언에서 사라진다. */\n doors: ['Query.figure'],\n description:\n 'Returns the source (the figure asset) of one figure, with its measured cost ' +\n '(triangles, part groups, and how many of it hold 60fps on one screen). Call it before proposing a revision — ' +\n 'revising without reading it means proposing against a guess. On the figure open in the modeller it also says what ' +\n 'the person has in view: `selection.part` is the part selected - \"this part\" or \"the selected one\" means it - and ' +\n '`trying` the clip and control values the preview is trying, which are not part of the figure. ' +\n 'A figure too large to read whole comes as `outline` (every part by name, shape and what it is fastened to) and ' +\n '`partSources` (the parts read in full) instead of `source`.',\n schema: { type: 'object', properties: { ...FIGURE_ID_ARG, ...PARTS_ARG } },\n builder: async (args: any, ctx: any) => {\n const domainId = requireDomainId(ctx?.state)\n const figureId = figureIdFrom(args, ctx?.host)\n const row = await resolveFigureTarget(figureId, domainId, ctx?.host)\n if (!row) return missingFigureTarget()\n\n const current = sourceForTool(row, ctx?.host)\n if (!current.source) {\n // 저장된 정본이 없는 상태가 실제로 있다(새로 만들고 저장 안 한 것). 지어내지 않는다.\n return { id: row.id, type: row.type, name: row.name, source: null, cost: null }\n }\n\n /* Measured as the catalogue measures it: triangles, draw groups, and its grade against one screen. */\n const { figureCostOf, figureScoreOf } = getDeps()\n /* What is in view belongs to the draft on screen; the stored source may be another figure than the one open. */\n const focus = current.draft ? focusOf(ctx?.host, current.source) : {}\n const asked = stringsOf(args?.parts)\n return {\n id: row.id,\n type: row.type,\n name: row.name,\n state: row.state,\n ...partialRead(current.source, { parts: asked.length ? asked : focus.selection ? [focus.selection.part] : [], sections: stringsOf(args?.sections) }),\n draft: current.draft,\n cost: figureCostOf(current.source),\n score: figureScoreOf(current.source) ?? null,\n ...focus\n }\n }\n },\n {\n kind: 'read',\n name: 'inspectFigure',\n /* 검사 결과 — 같은 일을 하는 문. */\n doors: ['Query.inspectFigure'],\n description:\n 'Says whether a figure may be released and, when it may not, what is wrong — each finding ' +\n 'carries why it is a problem and what to change. Call it when asked about releasing, or ' +\n 'when asked to fix a figure that will not release.',\n schema: { type: 'object', properties: { ...FIGURE_ID_ARG } },\n builder: async (args: any, ctx: any) => {\n const domainId = requireDomainId(ctx?.state)\n const figureId = figureIdFrom(args, ctx?.host)\n const row = await resolveFigureTarget(figureId, domainId, ctx?.host)\n if (!row) return missingFigureTarget()\n\n const current = sourceForTool(row, ctx?.host)\n const { inspectSource } = getDeps()\n /* Inspected whole, here; only what the model is told is held to its budget. */\n return { ...findingsWithinBudget(inspectSource(current.source ? JSON.stringify(current.source) : null, null, undefined, row.type, row.category)), draft: current.draft }\n }\n },\n {\n kind: 'read',\n name: 'proposeFigureCandidate',\n /* 후보 생성 — 저장은 하지 않지만 같은 문의 권한을 쓴다. */\n doors: ['Mutation.proposeFigure'],\n description:\n 'Asks for a proposal: the modeller commands that make a new figure or revise the one open in the modeller. ' +\n 'Returns the commands with the score and cost of the figure they make. NOTHING IS SAVED — the author applies ' +\n 'the proposal in the modeller as one step, or leaves it. This is the only way a proposal reaches the screen.',\n schema: {\n type: 'object',\n properties: {\n prompt: {\n type: 'string',\n description: 'What to make or change, in the words the author used, with the sizes as they said them: do not turn sizes into axes.'\n },\n figureId: {\n type: 'string',\n description: 'Revise this figure; it must be the one open in the modeller. Omit to revise the open one; pass null to create anew.'\n },\n name: {\n type: 'string',\n description: 'The name a person reads for a new figure.'\n },\n create: {\n type: 'boolean',\n description: 'True to create rather than revise, even with a figure open.'\n },\n parts: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'Only for a figure too large to read whole: the parts this change touches, read first with getFigureSource parts. Only these and the part selected may be changed; new parts may be added and fastened to any part.'\n },\n sections: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'Only for a figure too large to read whole: JSON Pointers of the sections in outline.omitted this change touches, read first with getFigureSource sections. Nothing else in those sections may be changed.'\n }\n },\n required: ['prompt']\n },\n builder: async (args: any, ctx: ToolCallContext) => {\n const domainId = requireDomainId(ctx?.state)\n const prompt = typeof args?.prompt === 'string' ? args.prompt.trim() : ''\n if (!prompt) throw new Error('prompt is required: there is nothing to ask for')\n\n /*\n 고치는 것인지 만드는 것인지를 **문맥에서 정한다.** 열린 피규어가 있으면 고치는 것이 기본이고,\n 모델이 `create` 를 켜면 만드는 것이다. 이것을 모델의 짐작에 맡기면 열려 있는 피규어를 덮어쓰는\n 후보가 온다.\n\n 고치는 제안은 모델러가 **요청 당시의 버전(context · revision)** 위에 한 단계로 적용한다(ADR-0094).\n 그래서 고칠 수 있는 것은 모델러에 열린 피규어뿐이고, 그 버전을 문맥이 함께 실어 와야 한다.\n */\n const host = ctx?.host\n const create = args?.create === true || args?.figureId === null\n let base: unknown\n let figureId: string | undefined\n let focus: ReturnType<typeof focusOf> | undefined\n if (!create) {\n const said = typeof args?.figureId === 'string' ? args.figureId.trim() : ''\n const open = typeof host?.figureId === 'string' ? host.figureId.trim() : ''\n if (said && said !== open) {\n await figureInDomain(said, domainId)\n return figureNotOpen()\n }\n if (!open) return missingFigureTarget()\n const row = await resolveFigureTarget(open, domainId, host)\n if (!row) return missingFigureTarget()\n const current = sourceForTool(row, host)\n base = current.source ?? undefined\n if (!isFigure(base)) return figureNotOpen()\n if (typeof host?.context !== 'string' || !Number.isInteger(host?.revision)) return figureNotOpen()\n figureId = open\n /* \"Make this one bigger\": the part selected is what the request points at. */\n if (current.draft) focus = focusOf(host, base)\n }\n\n /*\n The pictures the person sent with this turn, as the server checked them (ADR-0061, 2026-10-16 decision 2) --\n every one, in the order attached. Never from the host context: the client fills it.\n */\n const images = (ctx?.attachments ?? [])\n .filter((file: ToolAttachment): file is ToolImageAttachment => file.kind === 'image')\n .map(file => ({ data: file.data, mediaType: file.mediaType as AIImageMediaType }))\n\n const { proposeFigureSteps } = getDeps()\n let result: any\n try {\n result = await proposeFigureSteps({\n /* The agent of this conversation's turn - the one the person picked, or the domain default. */\n client: await aiClientFor({\n domain: ctx?.state?.domain,\n user: ctx?.state?.user,\n agentId: ctx?.state?.aiAgentId,\n modeKind: ctx?.mode?.kind\n }),\n prompt,\n base,\n name: typeof args?.name === 'string' && args.name.trim() ? args.name.trim() : undefined,\n ...(images.length ? { images } : {}),\n ...(focus && Object.keys(focus).length ? { focus } : {}),\n ...(!create && (stringsOf(args?.parts).length || stringsOf(args?.sections).length)\n ? { read: { parts: stringsOf(args?.parts), sections: stringsOf(args?.sections) } }\n : {})\n })\n } catch (error) {\n /*\n * 세 번 거절된 끝의 사유를 ProposeFigureFailure.reasons 에만 두면 agentic-loop 은 「만들지 못했습니다」만\n * 받아 화면에는 「응답이 비어있습니다」가 된다. 다시 시도할 수 있는 말로 경계를 넘긴다.\n * 다른 예외(권한·통신)는 원문을 보존한다.\n */\n const reasons = Array.isArray((error as any)?.reasons) ? (error as any).reasons : []\n if (reasons.length > 0) throw new Error([(error as Error).message, ...reasons].join('\\n'))\n throw error\n }\n\n /*\n **`proposed: true` 가 카드를 만든다.** 이 표시가 없으면 제안은 도구 추적 안에 묻히고 화면에는\n 아무것도 생기지 않는다. 카드의 실행 단추가 figure-ui 의 처리기에 넘기고, 처리기가 모델러에 명령\n 목록을 한 단계로 적용한다. `args` 는 같은 제안을 두 번 세지 않기 위한 열쇠의 일부다.\n */\n const name = result.source.name || 'Figure'\n /* The card is read by a person, so the server writes it in the request's language (ADR-0061, 2026-10-16 decision 1). */\n const t = ctx.t\n return {\n proposed: true,\n /*\n The proposal's own name, given once here (ADR-0097 §5.6 item 5; AI lane, 09-27): the dock keys its card by\n it, a new figure made from it is created under it (the row id), and a save records it -- so what became of\n it can be asked after a reload, and the same proposal never makes two figures.\n */\n key: randomUUID(),\n icon: 'view_in_ar',\n label: create\n ? t('figure.proposal.label-create', { name, defaultValue: 'Make {name}' })\n : t('figure.proposal.label-revise', { name, defaultValue: 'Revise {name}' }),\n reason: t('figure.proposal.reason', {\n steps: result.steps.length,\n grade: result.score?.grade ?? '-',\n triangles: result.cost.triangles,\n attempts: result.attempts,\n defaultValue: '{steps} commands · grade {grade} · {triangles} triangles · made in {attempts} tries'\n }),\n args: { prompt, figureId, create },\n create,\n figureId,\n context: create ? undefined : host.context,\n revision: create ? undefined : host.revision,\n steps: result.steps,\n score: result.score,\n cost: result.cost,\n attempts: result.attempts\n }\n }\n }\n ] as ToolSpec[]\n}\n\n/**\n * 등록 — 부팅 시 1회.\n *\n * 범주가 하나다. twin 은 관찰과 생성을 둘로 갈랐는데(운영 협의에 생성 도구가 들려 있으면 대화의\n * 성격이 흐려진다), figure 의 대화면은 저작면 하나뿐이고 그 자리에서 읽기와 후보 요청이 함께 필요하다.\n * 대화면이 늘면 그때 가른다.\n */\nexport function registerFigureToolCategories(): void {\n const authoring: ToolCategory = {\n name: 'figure-authoring',\n description: 'Reads the source, cost and release verdict of the figure being authored, and proposes changes (nothing is saved).',\n guidance: [\n '- **For a request to make or change a figure, always call `proposeFigureCandidate`.** A proposal exists only as the result of that call.',\n ' Writing \"I made a proposal\" or \"press apply\" without the call is **false**: no card appears, and the person looks for a button that does not exist.',\n ' A proposal is a list of modeller commands. The modeller applies it as one step only when the person runs it from the dock card, and one undo takes it all back. Do not say the figure has changed before that.',\n ' A revision can be proposed only for the figure open in the modeller. Say what the result\\'s `steps` do as they are; do not invent changes the commands do not make.',\n '- Never save the source yourself. Propose; the author decides on the screen whether to take it.',\n '- In the prompt to `proposeFigureCandidate`, pass the person\\'s words as they are: their sizes, counts and names. Do not turn them into axes; the writer knows the figure\\'s axes. When you name an axis to the person, the figure\\'s Y is up.',\n '- **For a request to change a figure, call `getFigureSource` first.** Revising without reading proposes against a guess, and a renamed part breaks the bindings of the boards it is already placed on.',\n '- On the catalog nothing is open. To read an existing figure, find the id of the name or type the person said with `listFigures`; ask which figure only when it is ambiguous. To revise an existing figure, tell the person to open it in the modeller and ask there. For a new figure, do not read existing sources: call `proposeFigureCandidate` with create: true.',\n '- Do not invent type names; check them with `listFigures`. **A type name is a stored identifier**, and boards find the figure by it. A new figure\\'s type is set by a person at its first save.',\n '- When asked why a figure will not release, call `inspectFigure`. Do not say it can be released without its verdict.',\n ' Each finding carries **why it is a problem and what to change**. Pass it on as it is; a summary makes the author look again for which axis of which part to fix.',\n '- For weight or triangle counts, use `cost` from `getFigureSource`. Do not estimate.'\n ].join('\\n'),\n specs: figureToolSpecs()\n }\n\n registerToolCategory(authoring)\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"figure-type.js","sourceRoot":"","sources":["../../../server/service/figure/figure-type.ts"],"names":[],"mappings":";;;;AAAA,yEAAgE;AAChE,+CAAgE;AAChE,qDAA6C;AAE7C,2CAAoC;AAEpC;;;;;GAKG;AACH,mHAAmH;AAE5G,IAAM,iBAAiB,GAAvB,MAAM,iBAAiB;CAS7B,CAAA;AATY,8CAAiB;AAE5B;IADC,IAAA,oBAAK,EAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,WAAW,EAAE,6CAA6C,EAAE,CAAC;;+CACzE;AAGb;IADC,IAAA,oBAAK,EAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,WAAW,EAAE,yEAAyE,EAAE,CAAC;;mDACjG;AAGjB;IADC,IAAA,oBAAK,EAAC,IAAI,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,WAAW,EAAE,0FAA0F,EAAE,CAAC;;+CACtI;4BARJ,iBAAiB;IAD7B,IAAA,wBAAS,EAAC,EAAE,WAAW,EAAE,+GAA+G,EAAE,CAAC;GAC/H,iBAAiB,CAS7B;AAGM,IAAM,SAAS,GAAf,MAAM,SAAS;CA8BrB,CAAA;AA9BY,8BAAS;AAEpB;IADC,IAAA,oBAAK,EAAC,EAAE,WAAW,EAAE,iEAAiE,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,EAAE,uEAAuE,EAAE,CAAC;;iDACrG;2BALL,gBAAgB;IAD5B,IAAA,yBAAU,EAAC,EAAE,WAAW,EAAE,wDAAwD,EAAE,CAAC;GACzE,gBAAgB,CAM5B","sourcesContent":["import { FigureReplacedDraft } from './figure-replaced-draft.js'\nimport { Field, InputType, Int, ObjectType } from 'type-graphql'\nimport { GraphQLJSON } from 'graphql-scalars'\n\nimport { Figure } from './figure.js'\n\n/**\n * 새 Figure.\n *\n * `score`·`triangles`·`groups` 는 **받지 않는다.** 서버가 `source` 에서 계산한다 —\n * 받으면 거짓이 들어오고 목록이 실물과 다른 것을 보여 준다.\n */\n/** The catalogue fields as the editor saw them; an update of them goes on only while the row still holds these. */\n@InputType({ description: 'The type, category and tags as the editor saw them. A field left out is not checked; null means it was empty.' })\nexport class FigureCatalogSeen {\n @Field({ nullable: true, description: 'The type the editor saw before changing it.' })\n type?: string\n\n @Field({ nullable: true, description: 'The category the editor saw before changing it; null when it was empty.' })\n category?: string\n\n @Field(type => [String], { nullable: true, description: 'The tags the editor saw before changing them, in their order; null when there were none.' })\n tags?: string[]\n}\n\n@InputType({ description: 'Input for creating a new figure.' })\nexport class NewFigure {\n @Field({ description: 'Component type name. Immutable once created, unique per domain.' })\n type: string\n\n @Field({ description: 'Display name shown to authors.' })\n name: string\n\n @Field({ nullable: true, description: 'A detailed description for the figure.' })\n description?: string\n\n @Field({ nullable: true, description: 'Classification code used to group figures in the palette.' })\n category?: string\n\n @Field(type => [String], { nullable: true, description: 'Free-form tags. A figure may carry several.' })\n tags?: string[]\n\n @Field({ description: 'The figure asset JSON (figure-asset-1).' })\n source: string\n\n @Field({ nullable: true, description: 'JSON definition of the master-data fields an instance carries.' })\n properties?: string\n\n @Field({ nullable: true, description: \"Lifecycle state — defaults to 'draft'.\" })\n state?: 'draft' | 'released'\n\n @Field({ nullable: true, description: 'A base64 encoded thumbnail image.' })\n thumbnail?: string\n\n @Field({ nullable: true, description: \"The domain's namespace to create it under; the domain's default when none.\" })\n namespace?: string\n}\n\n/**\n * 수정.\n *\n * `type` 은 **한 번도 발행되지 않은 초안에서만** 바뀐다(ADR-0063 결정 4). 저장되는 식별자라\n * 발행된 뒤에 바꾸면 이미 배치된 보드가 타입을 못 찾아 오류 없이 빈 화면이 된다. 발행 전에는\n * 그 피규어를 가리키는 도면이 있을 수 없다 — 도면은 최신 발행 버전을 그리므로 발행된 적 없는\n * 피규어는 그려질 자리가 없다.\n *\n * 닫아 두었더니 저작자가 이름을 한 번도 정하지 못했다. 새 Figure 에는 기계가 지은 이름이\n * 붙고(`FIGURE_MU6RJH47`) 칸에 자물쇠가 걸려서, 그 이름이 그대로 도면에 적히는 이름이 됐다.\n */\n@InputType({ description: 'Input for updating an existing figure. `type` is accepted only while the figure has never been released.' })\nexport class FigurePatch {\n @Field({ nullable: true, description: 'The stored identifier. Accepted only before the first release; rejected once a version exists.' })\n type?: string\n\n @Field({ nullable: true, description: 'The new display name.' })\n name?: string\n\n @Field({ nullable: true, description: 'The new description.' })\n description?: string\n\n /* 언어별 표시 이름. 안 준 것은 그대로, `{}` 는 전부 지운다. */\n @Field(type => GraphQLJSON, { nullable: true, description: 'Display names by language. {} clears them; omitting the field leaves them.' })\n names?: Record<string, string>\n\n @Field({ nullable: true, description: 'The new classification code.' })\n category?: string\n\n /*\n 빈 배열과 안 준 것을 가른다. `undefined` 는 「건드리지 않는다」, `[]` 는 「전부 지운다」다.\n 둘을 뭉개면 태그를 다 지우려는 저작자가 지울 방법을 잃는다.\n */\n @Field(type => [String], { nullable: true, description: 'The new tags. An empty list clears them; omitting the field leaves them.' })\n tags?: string[]\n\n @Field({ nullable: true, description: 'The new figure asset JSON (figure-asset-1).' })\n source?: string\n\n @Field({ nullable: true, description: 'The new master-data field definition.' })\n properties?: string\n\n /*\n `state` 는 여기 없다 — **상태는 저장이 정하지 않는다.**\n\n 발행은 `releaseFigure` 가 한다. 저장으로 상태를 바꿀 수 있게 두면 발행된 버전을 덮어쓰면서 같은\n 버전 번호로 버전을 또 뜨게 되고(유니크 충돌), 무엇이 약속된 버전인지도 흐려진다. board 도 같다.\n */\n\n @Field({ nullable: true, description: 'A base64 encoded thumbnail image.' })\n thumbnail?: string\n}\n\n@ObjectType({ description: 'A paginated list of figures.' })\nexport class FigureList {\n @Field(type => [Figure], { description: 'The figures on this page.' })\n items: Figure[]\n\n @Field(type => Int, { description: 'Total number of figures matching the query.' })\n total: number\n}\n\n/**\n * 검증 결과 한 줄.\n *\n * 정본 형식의 검증은 `@hatiolab/figure-model` 이 두 단계로 나눈다 — `errors` 는\n * 막고, `violations` 는 알린다. 그 경계를 서버가 다시 정하지 않는다.\n */\n@ObjectType({ description: 'One validation finding from figure-model.' })\nexport class FigureFinding {\n @Field({ description: 'Stable code from figure-model (ERROR_CODES / VIOLATION_CODES).' })\n code: string\n\n @Field({ description: 'Human-readable message.' })\n message: string\n\n @Field({ nullable: true, description: 'Path within the source that the finding points at.' })\n at?: string\n}\n\n/**\n * 저장 결과.\n *\n * `violations` 가 있어도 저장은 된다 — 막는 것과 알리는 것을 가른다. 화면이\n * 이것을 그대로 보여 줘야 한다. 조용히 버리면 저작자가 모른다.\n */\n@ObjectType({ description: 'Result of saving a figure, carrying non-blocking violations.' })\nexport class FigureSaveResult {\n @Field(type => Figure, { description: 'The saved figure.' })\n figure: Figure\n\n @Field(type => [FigureFinding], { description: 'Non-blocking findings. The save succeeded despite these.' })\n violations: FigureFinding[]\n}\n\n/** An AI proposal saved into a figure, with the figure's names as they are now (ADR-0097 §5.6 item 5). */\n@ObjectType({ description: 'A figure an AI proposal was saved into.' })\nexport class FigureProposalOutcome {\n @Field({ description: 'The figure it was saved into.' })\n figureId: string\n\n @Field({ nullable: true, description: \"The figure's type name now.\" })\n type?: string\n\n @Field({ nullable: true, description: \"The figure's display name now.\" })\n name?: string\n\n @Field({ nullable: true, description: 'When the save that held it was made.' })\n recordedAt?: Date\n}\n\n/** A revert's outcome: the figure as it now is, and the draft kept for it (ADR-0097 §5.6). */\n@ObjectType({ description: 'The result of a revert, or of an undo of one.' })\nexport class FigureRevertResult {\n @Field(type => Figure, { description: 'The figure, as it now is.' })\n figure: Figure\n\n @Field(type => [FigureFinding], { description: 'Non-blocking findings on the source written.' })\n violations: FigureFinding[]\n\n @Field(type => FigureReplacedDraft, { description: 'The draft kept for this revert -- or, for an undo, the one brought back.' })\n kept: FigureReplacedDraft\n}\n\n/**\n * 발행 판정 한 줄.\n *\n * `FigureFinding` 과 칸이 겹치지만 **`blocking` 이 하나 더 있다.** 저장 쪽 발견은 정의상 막지 않는\n * 것들이라 그 칸이 필요 없었다. 발행 판정은 막는 것과 알리는 것을 함께 내므로, 어느 쪽인지를 값이\n * 스스로 말해야 한다 — 코드를 보고 화면이 다시 분류하면 규칙이 두 벌이 된다.\n */\n@ObjectType({ description: 'One finding from the release gate.' })\nexport class FigureGateFinding {\n @Field({ description: 'Stable code of the gate finding, for example parts-off-placement-face or parts-split-on-resize.' })\n code: string\n\n @Field({ description: 'Human-readable message.' })\n message: string\n\n @Field({ nullable: true, description: 'Why this is a problem — what a person sees when it happens.' })\n why?: string\n\n @Field({ nullable: true, description: 'What to change, naming the part and the value.' })\n how?: string\n\n @Field({ nullable: true, description: 'Where it points: part names that came apart, or a path in the source.' })\n at?: string\n\n @Field({ description: 'True when this finding blocks the release.' })\n blocking: boolean\n\n @Field({\n nullable: true,\n description:\n 'True when the change breaks the released contract: saved as a new figure type, the edits release and the placed figures keep the old one.'\n })\n asNewType?: boolean\n}\n\n/**\n * 발행 판정.\n *\n * 화면이 **발행을 누르기 전에** 물어보는 자리다. 눌러 보고 거절당하는 것으로 알게 되면, 무엇을\n * 고쳐야 하는지 모른 채 단추만 두드리게 된다.\n */\n@ObjectType({ description: 'Whether a figure may be released, and why not.' })\nexport class FigureInspection {\n @Field({ description: 'True when at least one finding blocks the release.' })\n blocked: boolean\n\n @Field(type => [FigureGateFinding], { description: 'Findings, blocking and advisory together.' })\n findings: FigureGateFinding[]\n}\n\n/** A GLB kept for mesh parts (ADR-0129): its hash, and what it holds as the upload read it. */\n@ObjectType({ description: 'A GLB kept for mesh parts: its hash and what it holds.' })\nexport class FigureMeshUpload {\n @Field({ description: \"The file's SHA-256, lower-case hex: what a mesh part names it by.\" })\n hash: string\n\n @Field(type => GraphQLJSON, { description: 'Bounds in mm, triangles, primitives and nodes, as read from the file.' })\n summary: unknown\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"figure-write.js","sourceRoot":"","sources":["../../../server/service/figure/figure-write.ts"],"names":[],"mappings":";;;AAUA,wCAEC;AAwBD,gDAKC;AAGD,8CAUC;AAMD,8CAIC;AAGD,0CAIC;AAOD,oDASC;AAGD,gDAkBC;AAUD,8BAYC;AAlID,2EAAgF;AAChF,qCAAsC;AACtC,qCAAqC;AACrC,yDAAgI;AAEhI;;;;GAIG;AACH,SAAgB,cAAc,CAAC,OAAe;IAC5C,OAAO,IAAI,sBAAY,CAAC,OAAO,EAAE,EAAE,UAAU,EAAE,EAAE,IAAI,EAAE,wBAAwB,EAAE,EAAE,CAAC,CAAA;AACtF,CAAC;AAcY,QAAA,cAAc,GAAG,CAAC,MAAM,EAAE,UAAU,EAAE,MAAM,CAAU,CAAA;AAGnE,2HAA2H;AAC3H,SAAS,oBAAoB,CAAC,KAAmB,EAAE,KAAc;IAC/D,IAAI,KAAK,KAAK,MAAM;QAAE,OAAO,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IAChG,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAA;AAC1D,CAAC;AAED,8FAA8F;AAC9F,SAAgB,kBAAkB,CAAC,GAA2C,EAAE,IAAuB;IACrG,OAAO,sBAAc,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,IAAI,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} from './figure-thumbnail-store.js'\nimport { GraphQLError } from 'graphql'\nimport { IsNull, Raw } from 'typeorm'\nimport { parseFigureAsset, serializeFigureAsset, compileFigureAsset, figureCostOf, figureScoreOf } from '@hatiolab/figure-model'\n\n/**\n * The row is not what the writer expected: another edit, or the writer's own earlier save whose answer it never got.\n * Coded, so a client can tell it from a refusal on grounds (permission, validation) and read the row back before\n * saying its save failed (D, designer 2026-09-27).\n */\nexport function sourceConflict(message: string) {\n return new GraphQLError(message, { extensions: { code: 'FIGURE_SOURCE_CONFLICT' } })\n}\n\n/**\n * The catalogue fields as the editor saw them when it changed them: the type, the category, the tags. Kept on the row,\n * not in the source, so the source's compare-and-swap does not hold them; a save of these alone is checked against\n * these (outside review 2026-11-09: two tabs set the category, the later one wrote over the first without a word).\n * A field left out is not checked; null is \"was empty\".\n */\nexport interface FigureCatalogSeen {\n type?: string | null\n category?: string | null\n tags?: string[] | null\n}\n\nexport const CATALOG_FIELDS = ['type', 'category', 'tags'] as const\ntype CatalogField = (typeof CATALOG_FIELDS)[number]\n\n/** A catalogue value as compared: an empty category or tag list is no value; tags as the row stores them (simple-json). */\nfunction comparedCatalogValue(field: CatalogField, value: unknown): string | null {\n if (field === 'tags') return Array.isArray(value) && value.length ? JSON.stringify(value) : null\n return typeof value === 'string' && value ? value : null\n}\n\n/** The fields the row no longer holds as the editor saw them, each with what it holds now. */\nexport function catalogConflictsOf(row: Partial<Record<CatalogField, unknown>>, seen: FigureCatalogSeen): { field: CatalogField; now: string | string[] | null }[] {\n return CATALOG_FIELDS.filter(field => seen[field] !== undefined && comparedCatalogValue(field, row[field]) !== comparedCatalogValue(field, seen[field])).map(field => ({\n field,\n now: field === 'tags' ? ((row.tags as string[] | null | undefined)?.length ? (row.tags as string[]) : null) : ((row[field] as string | null | undefined) || null)\n }))\n}\n\n/** The same check in the UPDATE's criteria: a write between the check and the update finds nothing to update. */\nexport function catalogCriteriaOf(seen: FigureCatalogSeen): Record<string, unknown> {\n const criteria: Record<string, unknown> = {}\n for (const field of CATALOG_FIELDS) {\n if (seen[field] === undefined) continue\n const value = comparedCatalogValue(field, seen[field])\n if (value !== null) criteria[field] = field === 'tags' ? Raw(column => `${column} = :seenTags`, { seenTags: value }) : value\n else if (field === 'type') criteria[field] = IsNull()\n else criteria[field] = Raw(column => `(${column} IS NULL OR ${column} = '${field === 'tags' ? '[]' : ''}')`)\n }\n return criteria\n}\n\n/**\n * A patch that changes a catalogue field says what it saw of that field: there is no unchecked way to write one\n * (outside review 2026-11-09). A field the patch leaves out is neither written nor checked.\n */\nexport function assertCatalogSeen(patch: Partial<Record<CatalogField, unknown>>, seen: FigureCatalogSeen | undefined) {\n const unseen = CATALOG_FIELDS.filter(field => patch[field] !== undefined && seen?.[field] === undefined)\n if (unseen.length)\n throw new GraphQLError(`변경할 항목의 기존 값이 필요합니다: ${unseen.join(', ')}`, { extensions: { code: 'FIGURE_CATALOG_SEEN_REQUIRED', fields: unseen } })\n}\n\n/** Another edit changed a catalogue field first: which, and what it holds now, for the editor to say in its words. */\nexport function catalogConflict(fields: { field: string; now: string | string[] | null }[]) {\n return new GraphQLError(`다른 사용자가 먼저 변경한 항목이 있습니다: ${fields.map(f => f.field).join(', ')}`, {\n extensions: { code: 'FIGURE_CATALOG_CONFLICT', fields }\n })\n}\n\nexport interface FigureWriteCriteria {\n id: string\n domain: { id: string }\n source: string\n}\nexport async function compareAndSwapFigure(\n update: (criteria: FigureWriteCriteria) => Promise<{ affected?: number | null }>,\n id: string,\n domainId: string,\n expectedSource: string | undefined\n) {\n if (expectedSource === undefined) throw Error('수정 전 정본이 필요합니다.')\n const result = await update({ id, domain: { id: domainId }, source: expectedSource })\n if (result.affected !== 1) throw sourceConflict('다른 편집에서 모델이 변경되었습니다. 최신 모델을 다시 열어 주세요.')\n}\n\n/** Early validation only. The repository must also compare expectedSource in its atomic UPDATE. */\nexport function prepareFigureWrite(source: string, existing?: { source?: string }, expectedSource?: string) {\n if (existing && (expectedSource === undefined || existing.source !== expectedSource)) {\n throw sourceConflict('다른 편집에서 모델이 변경되었습니다. 최신 모델을 다시 연 뒤 적용해 주세요.')\n }\n const asset = parseFigureAsset(source)\n compileFigureAsset(asset)\n /*\n The same measure `parseSource` uses, so the catalogue's columns do not depend on which mutation wrote the row.\n */\n const cost = figureCostOf(asset)\n return {\n source: serializeFigureAsset(asset),\n name: asset.name,\n score: figureScoreOf(asset)?.score ?? null,\n triangles: cost.triangles,\n groups: cost.groups,\n state: 'draft' as const\n }\n}\n\n/**\n * The picture a card shows, when the modeller sent one: kept by its content (`keepThumbnail`) and named on the row by\n * its hash.\n *\n * Absent means the author saved without one — a tab in the background cannot draw, and the source matters more\n * than the picture, so the save goes on and the modeller fills it in next time. The timestamp moves only when\n * the picture itself is new, so renaming a figure does not make every card look freshly drawn.\n */\nexport async function pictureOf(\n tx: { getRepository: (target: any) => any },\n domain: { id: string },\n user: unknown,\n thumbnail?: string,\n existing?: { thumbnailHash?: string | null },\n files?: ThumbnailFiles\n): Promise<{ thumbnailHash?: string; thumbnail?: null; thumbnailUpdatedAt?: Date }> {\n if (thumbnail === undefined) return {}\n const thumbnailHash = await keepThumbnail(tx, domain, user, thumbnail, files)\n if (thumbnailHash === existing?.thumbnailHash) return {}\n return { thumbnailHash, thumbnail: null, thumbnailUpdatedAt: new Date() }\n}\n"]}