odant-work 1.0.29 → 1.0.30

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 (33) hide show
  1. package/#system/package-manifest.json +34 -28
  2. package/$server/$folder/$class/ai/agents/builder.md +34 -24
  3. package/$server/$folder/$class/ai/agents/org-architect.md +40 -0
  4. package/$server/$folder/$class/ai/agents/readme.md +3 -1
  5. package/$server/$folder/$class/ai/agents/schema-validator.md +35 -0
  6. package/$server/$folder/$class/ai/skills/accounting-design.md +21 -0
  7. package/$server/$folder/$class/ai/skills/data-modeling.md +25 -0
  8. package/$server/$folder/$class/ai/skills/readme.md +3 -0
  9. package/$server/$folder/$class/ai/skills/schema-migration.md +23 -0
  10. package/$server/$folder/$class/handlers/pages/form/objects/$handler/objects.js +2 -0
  11. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/util.js +4 -0
  12. package/$server/$folder/lib/consultant/consultant.js +1 -1
  13. package/$server/$folder/lib/tree/tree.js +2 -1
  14. package/MODELS/$ai/$folder/$class/$ai/class.js +17 -3
  15. package/MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/trainer.js +103 -6
  16. package/MODELS/$ai/$folder/$class/$provider/handlers/pages/form/trainer/$handler/trainer.js +37 -14
  17. package/oda/components/layouts/editor-form/editor-form.js +16 -3
  18. package/package.json +1 -1
  19. package/sources/data/progress.md +16 -0
  20. package/sources/data/schema.js +66 -2
  21. package/sources/host/auto-updater.js +1 -1
  22. package/sources/modules/agent/index.js +4 -3
  23. package/sources/modules/agent/tools/work/classes.js +1081 -0
  24. package/sources/modules/agent/tools/work.js +1 -0
  25. package/sources/modules/trainer/halogen.js +350 -32
  26. package/sources/modules/trainer/huggingface.js +80 -6
  27. package/sources/modules/trainer/index.js +139 -3
  28. package/sources/modules/trainer/local-engine.js +26 -29
  29. package/sources/modules/trainer/paths.js +119 -0
  30. package/sources/modules/trainer/providers.js +51 -36
  31. package/sources/modules/trainer/runner.js +72 -31
  32. package/sources/server/class/security.js +10 -3
  33. package/sources/server/class.js +6 -0
@@ -0,0 +1,1081 @@
1
+ /**
2
+ * Инструменты конструирования, анализа, переноса и удаления классов WORK:
3
+ * - update_class — декларативная правка метаданных/полей/проводок/LAYOUT через штатные слои ($class.save)
4
+ * - inspect_class_tree — 5-уровневый аудит поддерева (типы, 3-осевое наследование, связи, work.db, ROLES) + simulate
5
+ * - move_class — переименование/перенос класса с проверкой ALLOWED_CHILD_TYPES, ссылок и миграцией work.db
6
+ * - delete_class — безопасное удаление класса с блокировкой при наличии данных/зависимостей и dry_run
7
+ */
8
+ import fs from 'node:fs';
9
+ import fsp from 'node:fs/promises';
10
+ import path from 'node:path';
11
+ import { FS } from '../../../../server/index.js';
12
+ import { ALLOWED_CHILD_TYPES } from '../../../../server/class/scaffold.js';
13
+ import { safeNodeName } from '../../../../server/safe-node-name.js';
14
+ import { dataStore, resolveBasePath, markClassesDirty } from '../../../../data/api.js';
15
+ import { getClass, descendants, isLeaf, DATA_TYPES, STRUCTURE_TYPES, MODULE_TYPES } from '../../../../data/classes.js';
16
+ import { classSchema, checkSchema, analyticSlots, findAncestor, classBasePath, FAMILY } from '../../../../data/schema.js';
17
+ import { tx } from '../../../../data/db.js';
18
+ import { beforeWrite, recordWrite } from '../../undo.js';
19
+ import { isAccessDenied } from '../../util.js';
20
+ import {
21
+ absPath, assertContextCone, contextConeOf, mustItem, callAs,
22
+ } from './common.js';
23
+
24
+ const ROOT_PROTECTED_CLASSES = new Set([
25
+ '/', '/ORGANIZATIONS', '/MODULES', '/USERS', '/MODELS', '/SERVICES', '/NODES', '/DATA',
26
+ ]);
27
+
28
+ /** Проверка границ правки структуры: запрещено менять /$server, и из организации — общий /MODULES. */
29
+ function assertClassScope(targetPath, ctx, actionLabel) {
30
+ assertContextCone(targetPath, ctx);
31
+ const norm = '/' + String(targetPath || '').replace(/\\/g, '/').split('/').filter(Boolean).join('/');
32
+ if (norm === '/$server' || norm.startsWith('/$server/'))
33
+ throw new Error(`${actionLabel}: системные классы /$server изменяет разработчик, а не инструменты моделирования`);
34
+ const cone = contextConeOf(ctx);
35
+ if (cone && (norm === '/MODULES' || norm.startsWith('/MODULES/'))) {
36
+ throw new Error(
37
+ `${actionLabel}: из контекста организации «${cone[1]}» запрещено менять общий шаблон ${norm}. `
38
+ + `Вноси правки в локальный слой /ORGANIZATIONS/${cone[1]}/MODULES/... или предложи изменение общего модуля в плане для запуска на уровне /MODULES`
39
+ );
40
+ }
41
+ return norm;
42
+ }
43
+
44
+ function isGlobalModulePath(normPath) {
45
+ return normPath === '/MODULES' || normPath.startsWith('/MODULES/');
46
+ }
47
+
48
+ function targetClassPath(args, ctx) {
49
+ return absPath(args?.path, ctx);
50
+ }
51
+
52
+ /** Прочитать собственный class.js как объект с дескрипторами (методы и геттеры сохраняются). */
53
+ async function loadOwnClassObject(clsItem) {
54
+ const metaFolder = clsItem?.meta_folder;
55
+ const file = metaFolder?.dir ? path.join(metaFolder.dir, 'class.js') : '';
56
+ if (!file || !fs.existsSync(file))
57
+ return { file, exists: false, raw: '', obj: {} };
58
+ const raw = await fsp.readFile(file, 'utf-8');
59
+ // Защита: если в файле есть внешние import-ы или код до export default, $class.save затрёт их
60
+ const stripped = raw.replace(/^\uFEFF/, '').trim();
61
+ if (/^\s*import\s+/m.test(stripped) || !/^(?:\/\*[\s\S]*?\*\/\s*|\/\/[^\n]*\n\s*)*export\s+default\b/.test(stripped)) {
62
+ throw new Error(
63
+ `у класса ${clsItem.path} в class.js есть импорты или код вне export default — правку этого файла должен делать разработчик через edit`
64
+ );
65
+ }
66
+ const obj = await clsItem.constructor.importScript(raw, clsItem.path);
67
+ return { file, exists: true, raw, obj: obj && typeof obj === 'object' ? obj : {} };
68
+ }
69
+
70
+ /** Склонировать объект с сохранением методов/геттеров/сеттеров. */
71
+ function cloneWithDescriptors(src) {
72
+ if (!src || typeof src !== 'object')
73
+ return {};
74
+ return Object.defineProperties({}, Object.getOwnPropertyDescriptors(src));
75
+ }
76
+
77
+ function upsertById(existingList, incomingList, replaceAll = false) {
78
+ const base = replaceAll ? [] : (Array.isArray(existingList) ? structuredClone(existingList) : []);
79
+ for (const raw of Array.isArray(incomingList) ? incomingList : []) {
80
+ if (!raw || typeof raw !== 'object' || !raw.id)
81
+ continue;
82
+ const id = String(raw.id);
83
+ const idx = base.findIndex(x => x && String(x.id) === id);
84
+ if (raw.delete_own === true) {
85
+ if (idx >= 0)
86
+ base.splice(idx, 1);
87
+ continue;
88
+ }
89
+ const clean = structuredClone(raw);
90
+ delete clean.delete_own;
91
+ if (idx >= 0)
92
+ base[idx] = { ...base[idx], ...clean, id };
93
+ else
94
+ base.push({ ...clean, id });
95
+ }
96
+ return base;
97
+ }
98
+
99
+ function sanitizeFieldInput(f) {
100
+ if (!f || typeof f !== 'object')
101
+ return f;
102
+ const out = structuredClone(f);
103
+ if (Array.isArray(out.fields) && !Array.isArray(out.FIELDS)) {
104
+ out.FIELDS = out.fields.map(sanitizeFieldInput);
105
+ delete out.fields;
106
+ }
107
+ else if (Array.isArray(out.FIELDS)) {
108
+ out.FIELDS = out.FIELDS.map(sanitizeFieldInput);
109
+ }
110
+ return out;
111
+ }
112
+
113
+ /** Найти входящие ссылки из всех классов (включая $structure ROLES[].LINKS) на targetPath (или его поддерево). */
114
+ function findIncomingReferences(db, targetPath, includeSubtree = true) {
115
+ const prefix = targetPath === '/' ? '/' : targetPath + '/';
116
+ const matchesTarget = (ref) => {
117
+ if (!ref || typeof ref !== 'string')
118
+ return false;
119
+ const clean = ref.trim();
120
+ if (clean === targetPath)
121
+ return true;
122
+ return includeSubtree && clean.startsWith(prefix);
123
+ };
124
+ const isSelfOrChild = (clsPath) => clsPath === targetPath || (includeSubtree && clsPath.startsWith(prefix));
125
+ const all = db.prepare('SELECT cid, path, type, label, own FROM classes').all();
126
+ const refs = [];
127
+
128
+ const scanFields = (cls, list, where) => {
129
+ for (const f of Array.isArray(list) ? list : []) {
130
+ if (!f || typeof f !== 'object')
131
+ continue;
132
+ const target = f.target || f.catalog || (typeof f.type === 'string' && f.type.startsWith('/') ? f.type : '');
133
+ if (matchesTarget(target))
134
+ refs.push({ from: cls.path, kind: 'field_link', detail: `${where}${f.id} → ${target}` });
135
+ if (f.struct && matchesTarget(f.struct))
136
+ refs.push({ from: cls.path, kind: 'field_struct', detail: `${where}${f.id} → ${f.struct}` });
137
+ const sub = Array.isArray(f.FIELDS) ? f.FIELDS : (Array.isArray(f.fields) ? f.fields : null);
138
+ if (sub)
139
+ scanFields(cls, sub, `${where}${f.id}.`);
140
+ }
141
+ };
142
+
143
+ for (const row of all) {
144
+ if (isSelfOrChild(row.path))
145
+ continue;
146
+ let own = {};
147
+ try { own = JSON.parse(row.own || '{}'); } catch { own = {}; }
148
+ const meta = own.METADATA || {};
149
+
150
+ const typesList = own.types ?? own.TYPES ?? meta.types ?? meta.TYPES;
151
+ if (Array.isArray(typesList)) {
152
+ for (const t of typesList) {
153
+ if (matchesTarget(t))
154
+ refs.push({ from: row.path, kind: 'mixin_type', detail: `types: ${t}` });
155
+ }
156
+ }
157
+ const anc = own.ancestor ?? own.extends ?? meta.ancestor ?? meta.extends;
158
+ if (matchesTarget(anc))
159
+ refs.push({ from: row.path, kind: 'ancestor', detail: `ancestor: ${anc}` });
160
+
161
+ scanFields(row, meta.FIELDS, '');
162
+ scanFields(row, own.OVERLAY ?? meta.OVERLAY, 'overlay.');
163
+
164
+ if (own.SOURCE && typeof own.SOURCE === 'object') {
165
+ if (matchesTarget(own.SOURCE.registry))
166
+ refs.push({ from: row.path, kind: 'virtual_registry', detail: `SOURCE.registry → ${own.SOURCE.registry}` });
167
+ if (matchesTarget(own.SOURCE.account))
168
+ refs.push({ from: row.path, kind: 'virtual_account', detail: `SOURCE.account → ${own.SOURCE.account}` });
169
+ }
170
+ for (const rule of Array.isArray(meta.POSTINGS) ? meta.POSTINGS : []) {
171
+ if (matchesTarget(rule?.debit?.account))
172
+ refs.push({ from: row.path, kind: 'posting_debit', detail: `POSTINGS[${rule.id}].debit → ${rule.debit.account}` });
173
+ if (matchesTarget(rule?.credit?.account))
174
+ refs.push({ from: row.path, kind: 'posting_credit', detail: `POSTINGS[${rule.id}].credit → ${rule.credit.account}` });
175
+ }
176
+ const roles = own['#security']?.ROLES;
177
+ if (Array.isArray(roles)) {
178
+ for (const r of roles) {
179
+ for (const l of Array.isArray(r?.LINKS) ? r.LINKS : []) {
180
+ const lp = typeof l === 'string' ? l : l?.path;
181
+ if (matchesTarget(lp))
182
+ refs.push({ from: row.path, kind: 'role_link', detail: `ROLES[${r.id || r.label}].LINKS → ${lp}` });
183
+ }
184
+ }
185
+ }
186
+ }
187
+ return refs;
188
+ }
189
+
190
+ function dbCountsForSubtree(db, cids, targetPath) {
191
+ if (!cids.length)
192
+ return { objects: {}, totalObjects: 0, entries: 0, registeredEntries: 0, accountEntries: 0, unitObjects: 0 };
193
+ const ph = cids.map(() => '?').join(',');
194
+ const byStatus = {};
195
+ let totalObjects = 0;
196
+ for (const r of db.prepare(`SELECT status, count(*) n FROM objects WHERE cid IN (${ph}) GROUP BY status`).all(...cids)) {
197
+ byStatus[r.status] = Number(r.n) || 0;
198
+ if (r.status !== 'deleted')
199
+ totalObjects += Number(r.n) || 0;
200
+ }
201
+ const entRow = db.prepare(
202
+ `SELECT count(*) n FROM entries WHERE op_cid IN (${ph}) OR debit_cid IN (${ph}) OR credit_cid IN (${ph})`
203
+ ).get(...cids, ...cids, ...cids);
204
+ const accRow = db.prepare(
205
+ `SELECT count(*) n FROM account_entries WHERE account_cid IN (${ph}) OR corr_cid IN (${ph}) OR op_cid IN (${ph})`
206
+ ).get(...cids, ...cids, ...cids);
207
+ const regRow = db.prepare(
208
+ `SELECT count(*) n FROM objects WHERE cid IN (${ph}) AND status = 'registered'`
209
+ ).get(...cids);
210
+ const unitRow = db.prepare(
211
+ `SELECT count(*) n FROM objects WHERE unit = ? AND status <> 'deleted'`
212
+ ).get(targetPath);
213
+ return {
214
+ objects: byStatus,
215
+ totalObjects,
216
+ registeredOperations: Number(regRow?.n) || 0,
217
+ entries: Number(entRow?.n) || 0,
218
+ accountEntries: Number(accRow?.n) || 0,
219
+ unitObjects: Number(unitRow?.n) || 0,
220
+ };
221
+ }
222
+
223
+ /** Определить разрешённых детей для контейнера в файловом дереве (с учётом ALLOWED_CHILD_TYPES). */
224
+ async function allowedChildrenFor(item) {
225
+ if (typeof item?.allowed_child_types === 'function' || item?.allowed_child_types) {
226
+ try {
227
+ const list = await item.allowed_child_types;
228
+ if (Array.isArray(list) && list.length)
229
+ return list;
230
+ }
231
+ catch { /* fallback */ }
232
+ }
233
+ return ALLOWED_CHILD_TYPES[item?.type] || [];
234
+ }
235
+
236
+ /** Рекурсивно обойти файловое поддерево классов на заданную глубину. */
237
+ async function walkClassSubtree(rootItem, maxDepth = 8) {
238
+ const nodes = [];
239
+ const treeIssues = [];
240
+ const roleIssues = [];
241
+
242
+ async function visit(cls, depth, parentType) {
243
+ await cls.init;
244
+ const allowed = await allowedChildrenFor(cls);
245
+ if (cls.type === '$class' && cls !== globalThis.WORK)
246
+ treeIssues.push(`${cls.path}: использован абстрактный тип $class (запрещено правилами WORK)`);
247
+
248
+ // Проверка нескольких метапапок $ в одной папке
249
+ if (cls.real_dir && fs.existsSync(cls.real_dir)) {
250
+ const dirs = fs.readdirSync(cls.real_dir, { withFileTypes: true })
251
+ .filter(d => d.isDirectory() && d.name.startsWith('$')).map(d => d.name);
252
+ if (dirs.length > 1)
253
+ treeIssues.push(`${cls.path}: несколько метапапок (${dirs.join(', ')})`);
254
+ }
255
+
256
+ // Проверка #security.ROLES на $structure / $base
257
+ const sec = cls.DATA?.['#security'];
258
+ if (sec && Array.isArray(sec.ROLES)) {
259
+ const roleIds = new Set();
260
+ for (const r of sec.ROLES) {
261
+ const rid = String(r?.id || '').trim();
262
+ if (!rid)
263
+ roleIssues.push(`${cls.path}: рабочее место без id в #security.ROLES`);
264
+ else if (roleIds.has(rid))
265
+ roleIssues.push(`${cls.path}: дублирующийся id рабочего места «${rid}»`);
266
+ else
267
+ roleIds.add(rid);
268
+ for (const l of Array.isArray(r?.LINKS) ? r.LINKS : []) {
269
+ const lp = typeof l === 'string' ? l : l?.path;
270
+ if (!lp)
271
+ continue;
272
+ const target = await globalThis.WORK.get_item(lp).catch(() => null);
273
+ if (!target)
274
+ roleIssues.push(`${cls.path}: битая ссылка LINKS в рабочем месте «${rid || r?.label}» → ${lp}`);
275
+ }
276
+ }
277
+ if ((cls.type === '$structure' || cls.type === '$base') && (!Array.isArray(sec.BOSS) || !sec.BOSS.length)) {
278
+ // Проверяем наличие BOSS выше не обязательно ошибка, но полезно отметить, если у $base нет BOSS
279
+ if (cls.type === '$base')
280
+ roleIssues.push(`${cls.path}: у организации ($base) не назначен руководитель (BOSS)`);
281
+ }
282
+ }
283
+
284
+ const children = [];
285
+ if (depth < maxDepth) {
286
+ const kids = (await cls.items).filter(x => x instanceof FS.$class);
287
+ for (const kid of kids) {
288
+ if (allowed.length && !allowed.includes(kid.type))
289
+ treeIssues.push(`${kid.path}: тип ${kid.type} не входит в allowed_child_types родителя ${cls.path} (${cls.type}: ${allowed.join(', ')})`);
290
+ children.push(kid.path);
291
+ await visit(kid, depth + 1, cls.type);
292
+ }
293
+ }
294
+ nodes.push({
295
+ path: cls.path,
296
+ type: cls.type,
297
+ label: cls.DATA?.label || cls.label || cls.id,
298
+ icon: cls.DATA?.icon || '',
299
+ parentType: parentType || '',
300
+ childrenCount: children.length,
301
+ });
302
+ }
303
+
304
+ await visit(rootItem, 0, rootItem.$parent?.type || '');
305
+ return { nodes, treeIssues, roleIssues };
306
+ }
307
+
308
+ /** Проверка конфликтов 3-осевого наследования (Types → Ancestor → Parent → Self) для одного класса. */
309
+ function analyzeInheritanceConflicts(db, cls) {
310
+ const conflicts = [];
311
+ const fieldOrigins = [];
312
+ const schema = classSchema(db, cls.cid);
313
+ if (!schema)
314
+ return { schema: null, conflicts, fieldOrigins };
315
+
316
+ const layers = [];
317
+ const seenLayer = new Set();
318
+ const addLayer = (axis, c) => {
319
+ if (!c || seenLayer.has(c.cid + ':' + axis))
320
+ return;
321
+ seenLayer.add(c.cid + ':' + axis);
322
+ layers.push({ axis, cid: c.cid, path: c.path, own: c.own || {} });
323
+ };
324
+
325
+ for (const t of schema.types || []) {
326
+ const tc = getClass(db, t);
327
+ if (tc)
328
+ addLayer('Types', tc);
329
+ }
330
+ const anc = findAncestor(db, cls);
331
+ if (anc)
332
+ addLayer('Ancestor', anc);
333
+ // Parent chain (same family)
334
+ let cur = cls.parent ? getClass(db, cls.parent) : null;
335
+ const pChain = [];
336
+ while (cur && FAMILY[cur.type] === schema.family) {
337
+ pChain.unshift(cur);
338
+ cur = cur.parent ? getClass(db, cur.parent) : null;
339
+ }
340
+ for (const p of pChain)
341
+ addLayer('Parent', p);
342
+ addLayer('Self', cls);
343
+
344
+ const seenField = new Map(); // id -> { type, required, axis, path }
345
+ for (const l of layers) {
346
+ const list = Array.isArray(l.own?.METADATA?.FIELDS) ? l.own.METADATA.FIELDS : [];
347
+ for (const f of list) {
348
+ if (!f?.id)
349
+ continue;
350
+ const id = String(f.id);
351
+ if (f.removed) {
352
+ const prev = seenField.get(id);
353
+ if (prev?.required)
354
+ conflicts.push(`${cls.path}: слой ${l.axis} (${l.path}) удаляет обязательное поле «${id}», унаследованное от ${prev.path}`);
355
+ continue;
356
+ }
357
+ const t = f.type ? String(f.type).toLowerCase() : '';
358
+ const prev = seenField.get(id);
359
+ if (prev && t && prev.type && t !== prev.type) {
360
+ conflicts.push(
361
+ `${cls.path}: конфликт типа поля «${id}» между ${prev.axis} (${prev.path}: ${prev.type}) и ${l.axis} (${l.path}: ${t})`
362
+ );
363
+ }
364
+ if (prev && prev.required && f.required === false)
365
+ conflicts.push(`${cls.path}: слой ${l.axis} (${l.path}) снимает обязательность у поля «${id}» (была в ${prev.path})`);
366
+ seenField.set(id, {
367
+ type: t || prev?.type || '',
368
+ required: f.required !== undefined ? Boolean(f.required) : Boolean(prev?.required),
369
+ axis: l.axis,
370
+ path: l.path,
371
+ });
372
+ }
373
+ }
374
+ for (const f of schema.fields || []) {
375
+ const src = seenField.get(f.id);
376
+ fieldOrigins.push({
377
+ id: f.id,
378
+ label: f.label,
379
+ type: f.type,
380
+ required: Boolean(f.required),
381
+ originAxis: src?.axis || 'Self',
382
+ originPath: src?.path || cls.path,
383
+ });
384
+ }
385
+ return { schema, conflicts, fieldOrigins };
386
+ }
387
+
388
+ /** Переписать строковую ссылку в объекте/классе при переносе класса (внутри организации/контекста). */
389
+ function rewritePathPrefix(val, oldPath, newPath) {
390
+ if (typeof val !== 'string')
391
+ return val;
392
+ const s = val.trim();
393
+ if (s === oldPath)
394
+ return newPath;
395
+ if (s.startsWith(oldPath + '/'))
396
+ return newPath + s.slice(oldPath.length);
397
+ return val;
398
+ }
399
+
400
+ function rewriteClassOwnRefs(obj, oldPath, newPath) {
401
+ let changed = false;
402
+ const rw = (v) => {
403
+ const next = rewritePathPrefix(v, oldPath, newPath);
404
+ if (next !== v)
405
+ changed = true;
406
+ return next;
407
+ };
408
+ const meta = obj.METADATA;
409
+ if (meta && typeof meta === 'object') {
410
+ for (const key of ['types', 'TYPES']) {
411
+ if (Array.isArray(meta[key]))
412
+ meta[key] = meta[key].map(rw);
413
+ }
414
+ if (typeof meta.ancestor === 'string')
415
+ meta.ancestor = rw(meta.ancestor);
416
+ if (typeof meta.extends === 'string')
417
+ meta.extends = rw(meta.extends);
418
+ const rwFields = (list) => {
419
+ if (!Array.isArray(list))
420
+ return;
421
+ for (const f of list) {
422
+ if (!f || typeof f !== 'object')
423
+ continue;
424
+ for (const k of ['target', 'catalog', 'struct'])
425
+ if (typeof f[k] === 'string')
426
+ f[k] = rw(f[k]);
427
+ if (typeof f.type === 'string' && f.type.startsWith('/'))
428
+ f.type = rw(f.type);
429
+ rwFields(f.FIELDS);
430
+ rwFields(f.fields);
431
+ }
432
+ };
433
+ rwFields(meta.FIELDS);
434
+ rwFields(meta.OVERLAY);
435
+ if (Array.isArray(meta.POSTINGS)) {
436
+ for (const r of meta.POSTINGS) {
437
+ if (r?.debit?.account)
438
+ r.debit.account = rw(r.debit.account);
439
+ if (r?.credit?.account)
440
+ r.credit.account = rw(r.credit.account);
441
+ }
442
+ }
443
+ }
444
+ for (const key of ['types', 'TYPES']) {
445
+ if (Array.isArray(obj[key]))
446
+ obj[key] = obj[key].map(rw);
447
+ }
448
+ if (typeof obj.ancestor === 'string')
449
+ obj.ancestor = rw(obj.ancestor);
450
+ if (typeof obj.extends === 'string')
451
+ obj.extends = rw(obj.extends);
452
+ if (obj.SOURCE && typeof obj.SOURCE === 'object') {
453
+ if (typeof obj.SOURCE.registry === 'string')
454
+ obj.SOURCE.registry = rw(obj.SOURCE.registry);
455
+ if (typeof obj.SOURCE.account === 'string')
456
+ obj.SOURCE.account = rw(obj.SOURCE.account);
457
+ }
458
+ if (Array.isArray(obj['#security']?.ROLES)) {
459
+ for (const r of obj['#security'].ROLES) {
460
+ if (!Array.isArray(r?.LINKS))
461
+ continue;
462
+ r.LINKS = r.LINKS.map(l => {
463
+ if (typeof l === 'string')
464
+ return rw(l);
465
+ if (l && typeof l === 'object' && typeof l.path === 'string')
466
+ return { ...l, path: rw(l.path) };
467
+ return l;
468
+ });
469
+ }
470
+ }
471
+ return changed;
472
+ }
473
+
474
+ export const updateClass = {
475
+ name: 'update_class',
476
+ risk: 'write',
477
+ target: targetClassPath,
478
+ description: 'Декларативно обновить существующий класс WORK (label, icon, description, types-миксины, METADATA.FIELDS, STATIC, OVERLAY, POSTINGS, SOURCE, METADATA.LAYOUT, AUTO_REGISTER, NUMERATOR, allowed_child_types) через штатное слоеное сохранение ($class.save), не затирая JS-методы класса и унаследованные слои. После правки автоматически проверяет схему (db_schema).',
479
+ parameters: {
480
+ type: 'object',
481
+ properties: {
482
+ path: { type: 'string', description: 'WORK-путь изменяемого класса' },
483
+ label: { type: 'string', description: 'Новое отображаемое название' },
484
+ icon: { type: 'string', description: 'Иконка из наборов ODA (carbon:..., icons:..., lineawesome:...)' },
485
+ description: { type: 'string', description: 'Описание класса' },
486
+ types: { type: 'array', items: { type: 'string' }, description: 'Массив WORK-путей миксинов (1-я ось наследования Types)' },
487
+ allowed_child_types: { type: 'array', items: { type: 'string' }, description: 'Разрешённые дочерние $-типы (без $class)' },
488
+ auto_register: { type: 'boolean', description: 'Автопроведение операции при создании (AUTO_REGISTER)' },
489
+ numerator: { description: 'Настройки нумератора операции ({ field, reset, pad, prefix, scope }) или false' },
490
+ source: { type: 'object', description: 'Источник виртуального справочника $virtual ({ registry, account, slot, mode })' },
491
+ fields: {
492
+ type: 'array',
493
+ description: 'Поля объектов (METADATA.FIELDS): upsert по id. Для удаления унаследованного поля передай { id, removed: true }, для удаления собственного — { id, delete_own: true }',
494
+ },
495
+ replace_fields: { type: 'boolean', description: 'Полностью заменить собственный METADATA.FIELDS переданным массивом (по умолчанию false — слияние по id)' },
496
+ static: { type: 'array', description: 'Свойства класса (METADATA.STATIC): upsert по id' },
497
+ replace_static: { type: 'boolean', description: 'Заменить собственный METADATA.STATIC целиком' },
498
+ overlay: { type: 'array', description: 'Поля расширения виртуального справочника (METADATA.OVERLAY): upsert по id' },
499
+ replace_overlay: { type: 'boolean', description: 'Заменить собственный METADATA.OVERLAY целиком' },
500
+ postings: { type: 'array', description: 'Правила проводок операции (METADATA.POSTINGS): upsert по id' },
501
+ replace_postings: { type: 'boolean', description: 'Заменить собственный METADATA.POSTINGS целиком' },
502
+ layout: { description: 'Раскладка карточки (METADATA.LAYOUT): массив для ROOT или объект { ROOT: [...], <structId>: [...] }, либо false для сброса' },
503
+ },
504
+ required: ['path'],
505
+ },
506
+ async permission(args, ctx) {
507
+ const p = absPath(args?.path, ctx);
508
+ if (isGlobalModulePath(p))
509
+ return { verdict: 'ask', reason: 'изменение общего эталонного модуля ' + p + ' повлияет на все организации' };
510
+ return null;
511
+ },
512
+ async run(args, ctx) {
513
+ const p = assertClassScope(absPath(args.path, ctx), ctx, 'update_class');
514
+ const item = await mustItem(p, ctx);
515
+ if (Array.isArray(item) || !(item instanceof FS.$class))
516
+ throw new Error(`update_class: ${p} не является классом`);
517
+ await item.init;
518
+
519
+ const { file, exists, obj: ownObj } = await loadOwnClassObject(item);
520
+ const nextObj = cloneWithDescriptors(ownObj);
521
+ const changes = [];
522
+
523
+ if (typeof args.label === 'string' && args.label.trim()) {
524
+ nextObj.label = args.label.trim();
525
+ changes.push('label');
526
+ }
527
+ if (typeof args.icon === 'string') {
528
+ if (args.icon.trim())
529
+ nextObj.icon = args.icon.trim();
530
+ else
531
+ delete nextObj.icon;
532
+ changes.push('icon');
533
+ }
534
+ if (typeof args.description === 'string') {
535
+ nextObj.description = args.description;
536
+ changes.push('description');
537
+ }
538
+ if (Array.isArray(args.types)) {
539
+ const cleanTypes = [];
540
+ for (const rawT of args.types) {
541
+ const t = absPath(String(rawT || '').trim(), ctx);
542
+ if (!t || t === item.path)
543
+ continue;
544
+ const tItem = await WORK.get_item(t).catch(() => null);
545
+ if (!tItem || !(tItem instanceof FS.$class))
546
+ throw new Error(`update_class: миксин types «${t}» не найден или не является классом`);
547
+ if (!cleanTypes.includes(t))
548
+ cleanTypes.push(t);
549
+ }
550
+ nextObj.METADATA = nextObj.METADATA ? cloneWithDescriptors(nextObj.METADATA) : {};
551
+ nextObj.METADATA.types = cleanTypes;
552
+ delete nextObj.types;
553
+ changes.push(`types (${cleanTypes.length})`);
554
+ }
555
+ if (Array.isArray(args.allowed_child_types)) {
556
+ const cleanAllowed = args.allowed_child_types.map(x => String(x || '').trim()).filter(Boolean);
557
+ if (cleanAllowed.includes('$class'))
558
+ throw new Error('update_class: $class — абстрактный тип и не может быть в allowed_child_types');
559
+ nextObj.allowed_child_types = cleanAllowed;
560
+ changes.push('allowed_child_types');
561
+ }
562
+ if (typeof args.auto_register === 'boolean') {
563
+ nextObj.AUTO_REGISTER = args.auto_register;
564
+ changes.push('AUTO_REGISTER');
565
+ }
566
+ if (args.numerator === false || (args.numerator && typeof args.numerator === 'object')) {
567
+ nextObj.NUMERATOR = args.numerator === false ? false : structuredClone(args.numerator);
568
+ changes.push('NUMERATOR');
569
+ }
570
+ if (args.source && typeof args.source === 'object') {
571
+ nextObj.SOURCE = { ...(nextObj.SOURCE || {}), ...structuredClone(args.source) };
572
+ changes.push('SOURCE');
573
+ }
574
+
575
+ const ensureMeta = () => {
576
+ nextObj.METADATA = nextObj.METADATA ? cloneWithDescriptors(nextObj.METADATA) : {};
577
+ return nextObj.METADATA;
578
+ };
579
+
580
+ if (Array.isArray(args.fields)) {
581
+ const meta = ensureMeta();
582
+ const incoming = args.fields.map(sanitizeFieldInput);
583
+ meta.FIELDS = upsertById(meta.FIELDS, incoming, Boolean(args.replace_fields));
584
+ changes.push(`FIELDS (${meta.FIELDS.length})`);
585
+ }
586
+ if (Array.isArray(args.static)) {
587
+ const meta = ensureMeta();
588
+ const incoming = args.static.map(sanitizeFieldInput);
589
+ meta.STATIC = upsertById(meta.STATIC, incoming, Boolean(args.replace_static));
590
+ changes.push(`STATIC (${meta.STATIC.length})`);
591
+ }
592
+ if (Array.isArray(args.overlay)) {
593
+ const meta = ensureMeta();
594
+ const existing = Array.isArray(nextObj.OVERLAY) ? nextObj.OVERLAY : meta.OVERLAY;
595
+ meta.OVERLAY = upsertById(existing, args.overlay.map(sanitizeFieldInput), Boolean(args.replace_overlay));
596
+ delete nextObj.OVERLAY;
597
+ changes.push(`OVERLAY (${meta.OVERLAY.length})`);
598
+ }
599
+ if (Array.isArray(args.postings)) {
600
+ const meta = ensureMeta();
601
+ meta.POSTINGS = upsertById(meta.POSTINGS, args.postings, Boolean(args.replace_postings));
602
+ changes.push(`POSTINGS (${meta.POSTINGS.length})`);
603
+ }
604
+ if (args.layout !== undefined) {
605
+ const meta = ensureMeta();
606
+ if (args.layout === false || args.layout === null) {
607
+ delete meta.LAYOUT;
608
+ delete nextObj.LAYOUT;
609
+ changes.push('LAYOUT (сброшен)');
610
+ }
611
+ else if (Array.isArray(args.layout) || typeof args.layout === 'object') {
612
+ meta.LAYOUT = structuredClone(args.layout);
613
+ delete nextObj.LAYOUT;
614
+ changes.push('LAYOUT');
615
+ }
616
+ else {
617
+ throw new Error('update_class: layout должен быть массивом, объектом слоёв { ROOT: [...] } или false');
618
+ }
619
+ }
620
+
621
+ if (!changes.length)
622
+ return `класс ${item.path}: изменений не передано`;
623
+
624
+ const prevSnap = exists && file ? await beforeWrite(file) : { existed: false };
625
+ const post = item.constructor.toScript(nextObj);
626
+ await callAs(item, 'save', { post }, ctx);
627
+ markClassesDirty();
628
+ if (file) {
629
+ const metaClassJs = item.path + '/' + item.type + '/class.js';
630
+ recordWrite(ctx, metaClassJs, prevSnap, file);
631
+ }
632
+
633
+ // Автопроверка схемы для учётных/структурных классов
634
+ let schemaErrors = [];
635
+ if (DATA_TYPES.includes(item.type) || STRUCTURE_TYPES.includes(item.type) || MODULE_TYPES.includes(item.type)) {
636
+ try {
637
+ const db = await dataStore(resolveBasePath(item.path));
638
+ const cls = getClass(db, item.path);
639
+ if (cls)
640
+ schemaErrors = checkSchema(db, cls.cid);
641
+ }
642
+ catch { /* для внемодульных классов кэш может не строиться */ }
643
+ }
644
+
645
+ const out = [`обновлён класс ${item.path} (${item.type}): ${changes.join(', ')}`];
646
+ if (schemaErrors.length)
647
+ out.push('ОШИБКИ СХЕМЫ:\n' + schemaErrors.map(e => '- ' + e).join('\n'));
648
+ else if (DATA_TYPES.includes(item.type))
649
+ out.push('проверка схемы (db_schema): ошибок нет');
650
+ return out.join('\n');
651
+ },
652
+ };
653
+
654
+ export const inspectClassTree = {
655
+ name: 'inspect_class_tree',
656
+ readonly: true,
657
+ description: 'Глубокий 5-уровневый аудит класса и его поддерева: 1) дерево и allowed_child_types; 2) конфликты 3-осевого наследования (Types → Ancestor → Parent → Self) и происхождение полей; 3) ошибки схемы и проводок (checkSchema); 4) счётчики объектов/проводок в work.db и входящие ссылки от других классов; 5) #security.ROLES и LINKS. Поддерживает simulate для оценки последствий планируемых изменений.',
658
+ parameters: {
659
+ type: 'object',
660
+ properties: {
661
+ path: { type: 'string', description: 'WORK-путь класса (по умолчанию точка задачи)' },
662
+ depth: { type: 'integer', description: 'Глубина обхода дерева (по умолчанию 8, до 20)' },
663
+ simulate: {
664
+ type: 'object',
665
+ description: 'Оценка последствий планируемого изменения без записи: { remove_field?, rename_field?: { from, to }, change_type?: { field, to }, move_to?, delete?: true }',
666
+ },
667
+ },
668
+ required: ['path'],
669
+ },
670
+ async run(args, ctx) {
671
+ const p = absPath(args.path, ctx);
672
+ const item = await mustItem(p, ctx);
673
+ if (Array.isArray(item) || !(item instanceof FS.$class))
674
+ throw new Error(`inspect_class_tree: ${p} не является классом`);
675
+ await callAs(item, 'assertAccess', {}, ctx).catch(e => { if (isAccessDenied(e)) throw e; });
676
+ await item.init;
677
+
678
+ const maxDepth = Math.min(20, Math.max(1, Number(args.depth) || 8));
679
+ const { nodes, treeIssues, roleIssues } = await walkClassSubtree(item, maxDepth);
680
+
681
+ const basePath = resolveBasePath(item.path);
682
+ const db = await dataStore(basePath);
683
+ const cls = getClass(db, item.path);
684
+
685
+ let schemaReport = null;
686
+ let inheritance = { schema: null, conflicts: [], fieldOrigins: [] };
687
+ let schemaErrors = [];
688
+ let incomingRefs = [];
689
+ let dbImpact = { objects: {}, totalObjects: 0, entries: 0, accountEntries: 0, registeredOperations: 0, unitObjects: 0 };
690
+ let simulation = null;
691
+
692
+ if (cls) {
693
+ const subCids = descendants(db, cls.cid);
694
+ for (const c of subCids) {
695
+ const subCls = getClass(db, c);
696
+ if (!subCls)
697
+ continue;
698
+ schemaErrors.push(...checkSchema(db, c));
699
+ const inh = analyzeInheritanceConflicts(db, subCls);
700
+ inheritance.conflicts.push(...inh.conflicts);
701
+ if (c === cls.cid) {
702
+ inheritance.schema = inh.schema;
703
+ inheritance.fieldOrigins = inh.fieldOrigins;
704
+ }
705
+ }
706
+ // Проверка правила «данные только в листьях»
707
+ for (const c of subCids) {
708
+ const subCls = getClass(db, c);
709
+ if (subCls && DATA_TYPES.includes(subCls.type) && !isLeaf(db, c)) {
710
+ const ownCnt = db.prepare("SELECT count(*) n FROM objects WHERE cid = ? AND status <> 'deleted'").get(c)?.n || 0;
711
+ if (ownCnt > 0)
712
+ treeIssues.push(`${c}: не-лист содержит ${ownCnt} собственных объектов (данные допускаются только в листьях)`);
713
+ }
714
+ }
715
+
716
+ incomingRefs = findIncomingReferences(db, item.path, true);
717
+ dbImpact = dbCountsForSubtree(db, subCids, item.path);
718
+
719
+ if (inheritance.schema) {
720
+ schemaReport = {
721
+ cid: inheritance.schema.cid,
722
+ type: inheritance.schema.type,
723
+ family: inheritance.schema.family,
724
+ leaf: inheritance.schema.leaf,
725
+ ancestor: inheritance.schema.ancestor,
726
+ types: inheritance.schema.types,
727
+ hasLayout: Boolean(inheritance.schema.layout),
728
+ fields: inheritance.fieldOrigins,
729
+ postingsCount: inheritance.schema.postings?.length || 0,
730
+ };
731
+ }
732
+
733
+ // Моделирование последствий (simulate)
734
+ const sim = args.simulate && typeof args.simulate === 'object' ? args.simulate : null;
735
+ if (sim) {
736
+ simulation = { requested: sim, warnings: [], affectedObjects: 0, affectedRefs: [] };
737
+ const checkFieldValueCount = (fieldId) => {
738
+ const ph = subCids.map(() => '?').join(',');
739
+ const rows = db.prepare(`SELECT body FROM objects WHERE cid IN (${ph}) AND status <> 'deleted'`).all(...subCids);
740
+ let filled = 0;
741
+ for (const r of rows) {
742
+ try {
743
+ const b = JSON.parse(r.body || '{}');
744
+ if (b[fieldId] !== undefined && b[fieldId] !== null && b[fieldId] !== '')
745
+ filled++;
746
+ }
747
+ catch { /* ignore */ }
748
+ }
749
+ return filled;
750
+ };
751
+ if (sim.remove_field) {
752
+ const fid = String(sim.remove_field);
753
+ simulation.affectedObjects = checkFieldValueCount(fid);
754
+ if (simulation.affectedObjects > 0)
755
+ simulation.warnings.push(`удаление поля «${fid}» затронет ${simulation.affectedObjects} объектов с заполненным значением`);
756
+ for (const r of inheritance.schema?.postings || []) {
757
+ if (JSON.stringify(r).includes(fid))
758
+ simulation.warnings.push(`поле «${fid}» используется в правиле проводки «${r.id}»`);
759
+ }
760
+ }
761
+ if (sim.rename_field?.from) {
762
+ const from = String(sim.rename_field.from);
763
+ simulation.affectedObjects = checkFieldValueCount(from);
764
+ if (simulation.affectedObjects > 0)
765
+ simulation.warnings.push(`переименование «${from}» → «${sim.rename_field.to}» требует миграции ${simulation.affectedObjects} объектов в work.db`);
766
+ }
767
+ if (sim.change_type?.field) {
768
+ const fid = String(sim.change_type.field);
769
+ simulation.affectedObjects = checkFieldValueCount(fid);
770
+ if (simulation.affectedObjects > 0)
771
+ simulation.warnings.push(`смена типа поля «${fid}» → ${sim.change_type.to} затронет ${simulation.affectedObjects} непустых значений (возможна несовместимость формата)`);
772
+ }
773
+ if (sim.move_to || sim.delete) {
774
+ simulation.affectedObjects = dbImpact.totalObjects;
775
+ simulation.affectedRefs = incomingRefs;
776
+ if (dbImpact.registeredOperations > 0)
777
+ simulation.warnings.push(`в поддереве есть ${dbImpact.registeredOperations} проведённых операций и ${dbImpact.entries} записей проводок`);
778
+ if (incomingRefs.length > 0)
779
+ simulation.warnings.push(`на класс ссылаются ${incomingRefs.length} мест(а) в других классах/ролях`);
780
+ }
781
+ }
782
+ }
783
+
784
+ const result = {
785
+ path: item.path,
786
+ type: item.type,
787
+ allowedChildTypes: await allowedChildrenFor(item),
788
+ nodesCount: nodes.length,
789
+ nodes: nodes.slice(0, 80),
790
+ schema: schemaReport,
791
+ dbImpact,
792
+ incomingRefs,
793
+ issues: {
794
+ tree: treeIssues,
795
+ inheritance: inheritance.conflicts,
796
+ schema: [...new Set(schemaErrors)],
797
+ roles: roleIssues,
798
+ },
799
+ ...(simulation ? { simulation } : {}),
800
+ };
801
+ return JSON.stringify(result, null, 2);
802
+ },
803
+ };
804
+
805
+ export const moveClass = {
806
+ name: 'move_class',
807
+ risk: 'danger',
808
+ target: (args, ctx) => {
809
+ const src = absPath(args?.path, ctx);
810
+ const parent = args?.new_parent ? absPath(args.new_parent, ctx) : path.posix.dirname(src);
811
+ const id = safeNodeName(String(args?.new_id || path.posix.basename(src)).trim());
812
+ return [src, parent === '/' ? '/' + id : parent + '/' + id];
813
+ },
814
+ description: 'Переименовать или перенести класс WORK в нового родителя. Проверяет ALLOWED_CHILD_TYPES, зависимости (Link, Struct, POSTINGS, SOURCE, types, LINKS) и записи work.db; при dry_run:true возвращает план последствий без изменений, при выполнении обновляет дерево, входящие ссылки (update_refs) и привязки в work.db.',
815
+ parameters: {
816
+ type: 'object',
817
+ properties: {
818
+ path: { type: 'string', description: 'Текущий WORK-путь класса' },
819
+ new_parent: { type: 'string', description: 'Новый родительский класс (если не указан — остаётся прежний)' },
820
+ new_id: { type: 'string', description: 'Новое имя узла (если не указано — остаётся прежнее)' },
821
+ update_refs: { type: 'boolean', description: 'Обновлять входящие ссылки в классах того же контекста (по умолчанию true)' },
822
+ dry_run: { type: 'boolean', description: 'Только анализ и план последствий без переноса (по умолчанию false)' },
823
+ },
824
+ required: ['path'],
825
+ },
826
+ async permission(args, ctx) {
827
+ if (args?.dry_run === true)
828
+ return { verdict: 'allow' };
829
+ const p = absPath(args?.path, ctx);
830
+ if (isGlobalModulePath(p))
831
+ return { verdict: 'ask', reason: 'перенос/переименование общего модуля ' + p + ' затронет все организации' };
832
+ return null;
833
+ },
834
+ async run(args, ctx) {
835
+ const srcPath = assertClassScope(absPath(args.path, ctx), ctx, 'move_class');
836
+ if (ROOT_PROTECTED_CLASSES.has(srcPath))
837
+ throw new Error(`move_class: корневой домен ${srcPath} переносить/переименовывать запрещено`);
838
+
839
+ const srcItem = await mustItem(srcPath, ctx);
840
+ if (Array.isArray(srcItem) || !(srcItem instanceof FS.$class))
841
+ throw new Error(`move_class: ${srcPath} не является классом`);
842
+ await srcItem.init;
843
+
844
+ const oldParentPath = path.posix.dirname(srcPath) || '/';
845
+ const newParentPath = args.new_parent
846
+ ? assertClassScope(absPath(args.new_parent, ctx), ctx, 'move_class')
847
+ : oldParentPath;
848
+ const newId = safeNodeName(String(args.new_id || srcItem.id).trim());
849
+ if (!newId)
850
+ throw new Error('move_class: пустое новое имя класса');
851
+ const dstPath = (newParentPath === '/' ? '' : newParentPath) + '/' + newId;
852
+ if (dstPath === srcPath)
853
+ return `класс ${srcPath} уже находится по этому пути`;
854
+ if (dstPath.startsWith(srcPath + '/'))
855
+ throw new Error(`move_class: нельзя перенести класс ${srcPath} внутрь самого себя (${dstPath})`);
856
+
857
+ const newParent = await mustItem(newParentPath, ctx);
858
+ if (Array.isArray(newParent) || !(newParent instanceof FS.$class))
859
+ throw new Error(`move_class: новый родитель ${newParentPath} не является классом`);
860
+ await newParent.init;
861
+
862
+ const srcType = srcItem.type;
863
+ const allowed = await allowedChildrenFor(newParent);
864
+ if (allowed.length && !allowed.includes(srcType)) {
865
+ throw new Error(
866
+ `move_class: внутри ${newParentPath} (${newParent.type}) нельзя разместить тип ${srcType}; допустимы: ${allowed.join(', ')}`
867
+ );
868
+ }
869
+ const existingDst = await WORK.get_item(dstPath).catch(() => null);
870
+ if (existingDst)
871
+ throw new Error(`move_class: целевой путь ${dstPath} уже существует`);
872
+
873
+ // Доступ администратора на источник и приёмник
874
+ if (ctx?.role && ctx.role !== 'BOSS' && ctx.role !== 'ADMIN')
875
+ throw new Error(`Доступ запрещён: задача выполняется в роли ${ctx.role}, перенос класса требует BOSS`);
876
+ await srcItem.assertAccess({ session: ctx.session, role: 'BOSS' }, FS.$class.ACCESS_LEVEL.ADMIN);
877
+ await newParent.assertAccess({ session: ctx.session, role: 'BOSS' }, FS.$class.ACCESS_LEVEL.WRITE);
878
+
879
+ const srcBase = resolveBasePath(srcPath);
880
+ const dstBase = resolveBasePath(dstPath);
881
+ if (srcBase !== dstBase)
882
+ throw new Error(`move_class: нельзя переносить класс между разными организациями/базами (${srcBase || '/'} → ${dstBase || '/'})`);
883
+
884
+ const db = await dataStore(srcBase);
885
+ const cls = getClass(db, srcPath);
886
+ const subCids = cls ? descendants(db, cls.cid) : [];
887
+ const incomingRefs = findIncomingReferences(db, srcPath, true);
888
+ const dbImpact = dbCountsForSubtree(db, subCids, srcPath);
889
+
890
+ if (args.dry_run === true) {
891
+ return JSON.stringify({
892
+ dryRun: true,
893
+ from: srcPath,
894
+ to: dstPath,
895
+ type: srcType,
896
+ subClassesCount: subCids.length,
897
+ dbImpact,
898
+ incomingRefs,
899
+ updateRefs: args.update_refs !== false,
900
+ }, null, 2);
901
+ }
902
+
903
+ const srcDir = srcItem.real_dir;
904
+ const oldParentItem = srcItem.$parent;
905
+ const dstDir = path.join(newParent.real_dir, newId);
906
+ await fsp.mkdir(path.dirname(dstDir), { recursive: true });
907
+ try {
908
+ await fsp.rename(srcDir, dstDir);
909
+ }
910
+ catch (e) {
911
+ if (e?.code !== 'EXDEV')
912
+ throw e;
913
+ await fsp.cp(srcDir, dstDir, { recursive: true });
914
+ await fsp.rm(srcDir, { recursive: true, force: true });
915
+ }
916
+
917
+ // Обновить ссылки в других классах внутри допустимого контура
918
+ const updatedRefClasses = [];
919
+ if (args.update_refs !== false && incomingRefs.length) {
920
+ const refClassPaths = [...new Set(incomingRefs.map(r => r.from))];
921
+ for (const refPath of refClassPaths) {
922
+ if (srcBase && !refPath.startsWith(srcBase + '/') && refPath !== srcBase)
923
+ continue;
924
+ const refItem = await WORK.get_item(refPath).catch(() => null);
925
+ if (!refItem || !(refItem instanceof FS.$class))
926
+ continue;
927
+ try {
928
+ const { obj: refObj } = await loadOwnClassObject(refItem);
929
+ const nextRefObj = cloneWithDescriptors(refObj);
930
+ if (rewriteClassOwnRefs(nextRefObj, srcPath, dstPath)) {
931
+ const post = refItem.constructor.toScript(nextRefObj);
932
+ await callAs(refItem, 'save', { post }, ctx);
933
+ updatedRefClasses.push(refPath);
934
+ }
935
+ }
936
+ catch { /* пропускаем классы с нестандартным class.js */ }
937
+ }
938
+ }
939
+
940
+ // Перепривязать записи в work.db для всех перенесённых классов поддерева
941
+ if (db && subCids.length) {
942
+ const pairs = subCids.map(oldCid => [oldCid, rewritePathPrefix(oldCid, srcPath, dstPath)]);
943
+ tx(db, () => {
944
+ for (const [oldCid, newCid] of pairs) {
945
+ if (oldCid === newCid)
946
+ continue;
947
+ db.prepare('UPDATE objects SET cid = ? WHERE cid = ?').run(newCid, oldCid);
948
+ db.prepare('UPDATE objects SET unit = ? WHERE unit = ?').run(newCid, oldCid);
949
+ db.prepare('UPDATE refs SET ref_cid = ? WHERE ref_cid = ?').run(newCid, oldCid);
950
+ db.prepare('UPDATE entries SET op_cid = ? WHERE op_cid = ?').run(newCid, oldCid);
951
+ db.prepare('UPDATE entries SET debit_cid = ? WHERE debit_cid = ?').run(newCid, oldCid);
952
+ db.prepare('UPDATE entries SET credit_cid = ? WHERE credit_cid = ?').run(newCid, oldCid);
953
+ db.prepare('UPDATE entries SET unit = ? WHERE unit = ?').run(newCid, oldCid);
954
+ db.prepare('UPDATE entry_analytics SET ref_cid = ? WHERE ref_cid = ?').run(newCid, oldCid);
955
+ db.prepare('UPDATE account_entries SET account_cid = ? WHERE account_cid = ?').run(newCid, oldCid);
956
+ db.prepare('UPDATE account_entries SET corr_cid = ? WHERE corr_cid = ?').run(newCid, oldCid);
957
+ db.prepare('UPDATE account_entries SET op_cid = ? WHERE op_cid = ?').run(newCid, oldCid);
958
+ db.prepare('UPDATE account_entries SET unit = ? WHERE unit = ?').run(newCid, oldCid);
959
+ }
960
+ });
961
+ }
962
+
963
+ oldParentItem?.reset?.();
964
+ newParent.reset?.();
965
+ globalThis.WORK_RAG?.invalidate?.(srcDir);
966
+ globalThis.WORK_RAG?.invalidate?.(dstDir);
967
+ markClassesDirty();
968
+
969
+ const summary = [
970
+ `перенесён класс ${srcPath} → ${dstPath} (${srcType})`,
971
+ `перепривязано записей в work.db: объектов ${dbImpact.totalObjects}, проводок ${dbImpact.entries}`,
972
+ ];
973
+ if (updatedRefClasses.length)
974
+ summary.push(`обновлены ссылки в классах: ${updatedRefClasses.join(', ')}`);
975
+ return summary.join('\n');
976
+ },
977
+ };
978
+
979
+ export const deleteClass = {
980
+ name: 'delete_class',
981
+ risk: 'danger',
982
+ target: targetClassPath,
983
+ description: 'Безопасно удалить класс (или отключить модуль). Сначала проверяет потомков, объекты и проводки в work.db, а также входящие ссылки от других классов/ролей. По умолчанию блокирует удаление непустых или используемых классов; при dry_run:true возвращает полный отчёт последствий.',
984
+ parameters: {
985
+ type: 'object',
986
+ properties: {
987
+ path: { type: 'string', description: 'WORK-путь удаляемого класса' },
988
+ dry_run: { type: 'boolean', description: 'Только проверка последствий без удаления (по умолчанию false)' },
989
+ mode: { type: 'string', enum: ['delete', 'disable_module'], description: 'delete — удалить класс; disable_module — мягко отключить модуль $module (set_enabled: false)' },
990
+ force: { type: 'boolean', description: 'Игнорировать входящие ссылки из других классов/ролей (по умолчанию false)' },
991
+ allow_purge_data: { type: 'boolean', description: 'Разрешить удаление вместе с объектами/проводками в work.db (по умолчанию false — защита данных)' },
992
+ },
993
+ required: ['path'],
994
+ },
995
+ async permission(args) {
996
+ if (args?.dry_run === true)
997
+ return { verdict: 'allow' };
998
+ return null;
999
+ },
1000
+ async run(args, ctx) {
1001
+ const p = assertClassScope(absPath(args.path, ctx), ctx, 'delete_class');
1002
+ if (ROOT_PROTECTED_CLASSES.has(p))
1003
+ throw new Error(`delete_class: корневой домен ${p} удалять запрещено`);
1004
+
1005
+ const item = await mustItem(p, ctx);
1006
+ if (Array.isArray(item) || !(item instanceof FS.$class))
1007
+ throw new Error(`delete_class: ${p} не является классом`);
1008
+ await item.init;
1009
+
1010
+ const itemType = item.type;
1011
+ const itemRealDir = item.real_dir;
1012
+ const itemParent = item.$parent;
1013
+ const basePath = resolveBasePath(p);
1014
+ const db = await dataStore(basePath);
1015
+ const cls = getClass(db, p);
1016
+ const subCids = cls ? descendants(db, cls.cid) : [p];
1017
+ const incomingRefs = cls ? findIncomingReferences(db, p, true) : [];
1018
+ const dbImpact = cls ? dbCountsForSubtree(db, subCids, p) : { totalObjects: 0, entries: 0, accountEntries: 0, registeredOperations: 0, unitObjects: 0 };
1019
+
1020
+ if (args.dry_run === true) {
1021
+ return JSON.stringify({
1022
+ dryRun: true,
1023
+ path: p,
1024
+ type: itemType,
1025
+ subClasses: subCids,
1026
+ dbImpact,
1027
+ incomingRefs,
1028
+ canDeleteSafely: dbImpact.totalObjects === 0 && dbImpact.entries === 0 && dbImpact.unitObjects === 0 && incomingRefs.length === 0,
1029
+ }, null, 2);
1030
+ }
1031
+
1032
+ if (args.mode === 'disable_module') {
1033
+ if (itemType !== '$module')
1034
+ throw new Error(`delete_class: режим disable_module применим только к модулю ($module), а ${p} имеет тип ${itemType}`);
1035
+ await callAs(item, 'set_enabled', { enabled: false }, ctx);
1036
+ markClassesDirty();
1037
+ return `модуль ${p} мягко отключён (enabled: false); данные и структура сохранены`;
1038
+ }
1039
+
1040
+ if (!args.force && incomingRefs.length > 0) {
1041
+ throw new Error(
1042
+ `delete_class: удаление ${p} заблокировано — на класс есть ${incomingRefs.length} входящих ссылок:\n`
1043
+ + incomingRefs.slice(0, 10).map(r => `- ${r.from}: ${r.detail}`).join('\n')
1044
+ + '\nСначала перестрой/отвяжи ссылки или передай force: true'
1045
+ );
1046
+ }
1047
+
1048
+ if (!args.allow_purge_data && (dbImpact.totalObjects > 0 || dbImpact.entries > 0 || dbImpact.accountEntries > 0 || dbImpact.unitObjects > 0)) {
1049
+ throw new Error(
1050
+ `delete_class: удаление ${p} заблокировано защитой данных — в work.db найдено: объектов ${dbImpact.totalObjects}, проведённых операций ${dbImpact.registeredOperations}, проводок ${dbImpact.entries}, объектов подразделения ${dbImpact.unitObjects}. `
1051
+ + `Сначала перенеси данные или используй allow_purge_data: true после подтверждения`
1052
+ );
1053
+ }
1054
+
1055
+ if (ctx?.role && ctx.role !== 'BOSS' && ctx.role !== 'ADMIN')
1056
+ throw new Error(`Доступ запрещён: задача выполняется в роли ${ctx.role}, удаление класса требует BOSS`);
1057
+ await item.assertAccess({ session: ctx.session, role: 'BOSS' }, FS.$class.ACCESS_LEVEL.ADMIN);
1058
+
1059
+ if (db && subCids.length && args.allow_purge_data) {
1060
+ const ph = subCids.map(() => '?').join(',');
1061
+ tx(db, () => {
1062
+ db.prepare(`DELETE FROM entry_analytics WHERE entry_id IN (SELECT id FROM entries WHERE op_cid IN (${ph}) OR debit_cid IN (${ph}) OR credit_cid IN (${ph}))`).run(...subCids, ...subCids, ...subCids);
1063
+ db.prepare(`DELETE FROM account_entries WHERE account_cid IN (${ph}) OR corr_cid IN (${ph}) OR op_cid IN (${ph})`).run(...subCids, ...subCids, ...subCids);
1064
+ db.prepare(`DELETE FROM entries WHERE op_cid IN (${ph}) OR debit_cid IN (${ph}) OR credit_cid IN (${ph})`).run(...subCids, ...subCids, ...subCids);
1065
+ db.prepare(`DELETE FROM refs WHERE obj_id IN (SELECT id FROM objects WHERE cid IN (${ph}))`).run(...subCids);
1066
+ db.prepare(`DELETE FROM object_versions WHERE id IN (SELECT id FROM objects WHERE cid IN (${ph}))`).run(...subCids);
1067
+ db.prepare(`DELETE FROM objects WHERE cid IN (${ph})`).run(...subCids);
1068
+ });
1069
+ }
1070
+
1071
+ if (fs.existsSync(itemRealDir))
1072
+ await fsp.rm(itemRealDir, { recursive: true, force: true });
1073
+ globalThis.WORK_RAG?.invalidate?.(itemRealDir);
1074
+ itemParent?.reset?.();
1075
+ markClassesDirty();
1076
+
1077
+ return `удалён класс ${p} (${itemType}); удалено подклассов: ${subCids.length}`;
1078
+ },
1079
+ };
1080
+
1081
+ export const classTools = [updateClass, inspectClassTree, moveClass, deleteClass];