odant-work 1.0.101 → 1.0.102

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 (63) hide show
  1. package/$server/$folder/$class/$structure/$department/ai/config.js +9 -0
  2. package/$server/$folder/$class/$structure/$department/ai/system.md +11 -0
  3. package/$server/$folder/$class/$structure/$department/class.js +9 -0
  4. package/$server/$folder/$class/$structure/$project/ai/config.js +9 -0
  5. package/$server/$folder/$class/$structure/$project/ai/system.md +12 -0
  6. package/$server/$folder/$class/$structure/$project/class.js +4 -1
  7. package/$server/$folder/$class/$structure/$project/handlers/pages/site/$handler/class.js +1 -1
  8. package/$server/$folder/$class/$structure/$server/ai/config.js +9 -0
  9. package/$server/$folder/$class/$structure/$server/ai/system.md +10 -0
  10. package/$server/$folder/$class/$structure/$server/class.js +2 -0
  11. package/$server/$folder/$class/$structure/$user/ai/config.js +9 -0
  12. package/$server/$folder/$class/$structure/$user/ai/system.md +8 -0
  13. package/$server/$folder/$class/$structure/$user/class.js +2 -0
  14. package/$server/$folder/$class/$structure/ai/system.md +1 -1
  15. package/$server/$folder/$class/$structure/class.js +4 -2
  16. package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/class.js +67 -20
  17. package/$server/$folder/$class/$structure/handlers/pages/form/system/agent/$handler/class.js +132 -3
  18. package/$server/$folder/$class/$structure/handlers/pages/form/system/staff/$handler/class.js +2 -2
  19. package/$server/$folder/$class/$structure/handlers/pages/site/$handler/class.js +2 -1
  20. package/$server/$folder/$class/ai/system.md +2 -2
  21. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/class.js +7 -0
  22. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/dock.js +22 -31
  23. package/$server/$folder/handlers/pages/form/$handler/class.js +47 -5
  24. package/$server/$folder/lib/chat-item/chat-item.js +14 -2
  25. package/$server/$folder/lib/consultant/consultant.js +1 -1
  26. package/$server/$folder/lib/explorer/explorer.js +20 -11
  27. package/$server/$folder/lib/icon/icon.js +1 -1
  28. package/$server/$folder/lib/node/node.js +3 -3
  29. package/$server/$folder/lib/site-loc/site-loc.js +8 -3
  30. package/$server/$folder/lib/tree/tree.js +6 -6
  31. package/AGENTS.md +3 -3
  32. package/package.json +1 -1
  33. package/scripts/import-bis.mjs +5 -5
  34. package/scripts/import-delovaya.mjs +5 -5
  35. package/sources/client/class.js +1 -1
  36. package/sources/client.js +19 -6
  37. package/sources/data/api.js +1 -1
  38. package/sources/data/classes.js +2 -1
  39. package/sources/data/schema.js +2 -0
  40. package/sources/host/auth-methods.js +1 -1
  41. package/sources/modules/agent/index.js +22 -6
  42. package/sources/modules/agent/node-rules.js +353 -9
  43. package/sources/modules/agent/scheduler.js +7 -0
  44. package/sources/modules/agent/scope.js +8 -6
  45. package/sources/modules/agent/tools/work/access.js +1 -1
  46. package/sources/modules/agent/tools/work/classes.js +1 -1
  47. package/sources/modules/agent/triggers.js +1 -1
  48. package/sources/modules/agent/twin-bus.js +2 -1
  49. package/sources/modules/notify/index.js +5 -2
  50. package/sources/modules/trainer/local-engine.js +3 -1
  51. package/sources/server/access/gateway.js +4 -3
  52. package/sources/server/access/links.js +9 -6
  53. package/sources/server/chat-threads.js +1 -1
  54. package/sources/server/class/base-template.js +3 -2
  55. package/sources/server/class/feed.js +30 -0
  56. package/sources/server/class/scaffold.js +137 -0
  57. package/sources/server/class/search.js +2 -2
  58. package/sources/server/class/security.js +1 -1
  59. package/sources/server/class.js +5 -3
  60. package/sources/server/folder.js +10 -6
  61. package/sources/server/logs.js +14 -0
  62. package/sources/server/node.js +1 -1
  63. package/sources/work.js +7 -0
@@ -144,7 +144,7 @@ function getDbSummary(db) {
144
144
  countFor(clsPath, clsType = '') {
145
145
  const cls = getClass(db, clsPath);
146
146
  const type = cls?.type || clsType;
147
- if (!type || type === '$project' || type === '$project' || type === '$structure' || type === '$domain')
147
+ if (!type || cls?.own?.isStructure || type === '$project' || type === '$structure' || type === '$domain')
148
148
  return 0;
149
149
  const key = `${type}:${cls?.cid || clsPath}`;
150
150
  if (subtreeCounts.has(key))
@@ -14,12 +14,13 @@ import fsp from 'node:fs/promises';
14
14
  import path from 'node:path';
15
15
  import { pathToFileURL } from 'node:url';
16
16
  import { tx } from './db.js';
17
+ import { structureSubtypesSync } from '../server/class/scaffold.js';
17
18
 
18
19
  /** Типы прикладных классов данных. */
19
20
  export const DATA_TYPES = Object.freeze(['$catalog', '$virtual', '$struct', '$operation', '$account', '$register']);
20
21
 
21
22
  /** Типы классов орг-структуры (подразделения), проектов, доменов и модулей. */
22
- export const STRUCTURE_TYPES = Object.freeze(['$structure', '$project']);
23
+ export const STRUCTURE_TYPES = Object.freeze([...new Set(['$structure', '$project', ...structureSubtypesSync()])]);
23
24
  export const MODULE_TYPES = Object.freeze(['$module', '$provider', '$mcp']);
24
25
  export const DOMAIN_TYPES = Object.freeze(['$domain']);
25
26
 
@@ -20,6 +20,7 @@
20
20
  import { getClass, ancestors, descendants, isLeaf, classesGeneration } from './classes.js';
21
21
  import { compile, BUILTIN_FUNCTIONS } from './expr.js';
22
22
  import { formatFio } from './fio.js';
23
+ import { structureSubtypesSync } from '../server/class/scaffold.js';
23
24
 
24
25
  /** Семейство типа класса: схема наследуется внутри семейства. */
25
26
  export const FAMILY = Object.freeze({
@@ -27,6 +28,7 @@ export const FAMILY = Object.freeze({
27
28
  $struct: 'struct',
28
29
  $operation: 'operation',
29
30
  $account: 'account', $register: 'account',
31
+ ...Object.fromEntries(structureSubtypesSync().map(t => [t, 'structure'])),
30
32
  $structure: 'structure', $project: 'structure',
31
33
  $module: 'module',
32
34
  });
@@ -306,7 +306,7 @@ export const authMethods = {
306
306
 
307
307
  let post = CORE.$class.toScript(credentials);
308
308
 
309
- let res = await $user_item.save({ filename: 'class.js', post, session: { $user: WORK } });
309
+ let res = await $user_item.save({ filename: 'class.js', post, session: { $user: WORK }, ignore_save_logs: true });
310
310
  let u = await this.$users;
311
311
  (await u.children)?.forEach?.(ch => ch.children = undefined);
312
312
  u.children = undefined;
@@ -276,23 +276,39 @@ export async function llmWithFallback(primaryPath, fallbackPaths = []) {
276
276
  };
277
277
  return adapter;
278
278
  }
279
- /** Первая доступная чат-модель в /MODULES/Модели (активная приоритетно), когда дефолтная модель отсутствует. */
280
- async function findFirstAvailableChatModel() {
279
+ const CLASSIFIER_MODEL_RE = /(классификатор|classifier|rerank|0\.6b)/i;
280
+
281
+ /** Первая доступная чат-модель в /MODULES/Модели (приоритетно default:true и основная LLM, не классификатор). */
282
+ export async function findFirstAvailableChatModel() {
281
283
  const root = await WORK.get_item('/MODULES/Модели').catch(() => null);
282
284
  let firstAny = '';
285
+ let firstActive = '';
286
+ let firstPrimary = '';
283
287
  for (const provider of (await root?.items) || []) {
288
+ await provider?.init?.catch?.(() => {});
289
+ if (provider?.DATA?.enabled === false)
290
+ continue;
284
291
  for (const m of (await provider.items) || []) {
285
- await m.init;
292
+ await m.init?.catch?.(() => {});
293
+ if (m?.DATA?.enabled === false)
294
+ continue;
286
295
  const caps = Array.isArray(m.capabilities) ? m.capabilities : String(m.capabilities || '').split(/[\s,]+/);
287
296
  if (!caps.includes('chat') || typeof m.streamChat !== 'function')
288
297
  continue;
298
+ const active = (m.aiActive ?? m.DATA?.aiActive) !== false;
299
+ const name = String(m.id || m.DATA?.label || m.label || m.path || '');
300
+ const isPrimary = active && !CLASSIFIER_MODEL_RE.test(name);
289
301
  if (!firstAny)
290
302
  firstAny = m.path;
291
- if ((m.aiActive ?? m.DATA?.aiActive) !== false)
303
+ if (active && !firstActive)
304
+ firstActive = m.path;
305
+ if (active && m.DATA?.default === true)
292
306
  return m.path;
307
+ if (isPrimary && !firstPrimary)
308
+ firstPrimary = m.path;
293
309
  }
294
310
  }
295
- return firstAny;
311
+ return firstPrimary || firstActive || firstAny;
296
312
  }
297
313
  /** Найти активную локальную модель в /MODULES/Модели/Local по capabilities (или id). */
298
314
  async function findActiveLocalModel({ caps = [], ids = [], method = '' } = {}) {
@@ -661,7 +677,7 @@ async function placeBlock(place, session, location, contextPath) {
661
677
  const label = place.DATA?.label || place.label || place.id || place.path || 'WORK';
662
678
  const cone = contextConeOf(contextPath || place.path);
663
679
  const pt = place.type;
664
- if (pt === '$structure') {
680
+ if (place.DATA?.isDepartment || pt === '$structure') {
665
681
  const orgName = cone?.[1] || '';
666
682
  lines.push(`- Твоя идентичность (субъект): ты — цифровой двойник подразделения «${label}»${orgName ? ` (организация «${orgName}»)` : ''}, путь ${place.path}. Отвечай и действуй от первого лица этого подразделения.`);
667
683
  }
@@ -5,13 +5,24 @@
5
5
  import fs from 'node:fs';
6
6
  import fsp from 'node:fs/promises';
7
7
  import path from 'node:path';
8
- import { loadDocs, loadSystemLayers } from './resources.js';
8
+ import { loadDocs, loadSystemLayers, loadConfig } from './resources.js';
9
9
  import { parseFrontmatter } from './util.js';
10
10
  import { resetTriggerCache } from './triggers.js';
11
11
  import { createSchedule, listSchedules, toggleSchedule, cancelSchedule } from './scheduler.js';
12
12
  import { DEV_MODE } from '../../host/config.js';
13
13
  import { audit } from '../../server/access/audit.js';
14
14
  import { FS } from '../../server/index.js';
15
+ import { indexDb, registerSchema } from '../../host/index-db.js';
16
+
17
+ registerSchema(`
18
+ CREATE TABLE IF NOT EXISTS agent_audit_state(
19
+ node_path TEXT PRIMARY KEY,
20
+ last_run INTEGER NOT NULL DEFAULT 0,
21
+ last_status TEXT NOT NULL DEFAULT '',
22
+ last_task TEXT NOT NULL DEFAULT '',
23
+ last_summary TEXT NOT NULL DEFAULT ''
24
+ );
25
+ `);
15
26
 
16
27
  const ACCESS_DENIED = 'Доступ запрещён';
17
28
  const SAFE_RULE_NAME_RE = /^[A-Za-z0-9\u0400-\u04FF_-]{1,64}$/;
@@ -105,11 +116,21 @@ export async function listNodeRules(storage, params = {}) {
105
116
  }
106
117
  const nodePath = storage?.path || '/';
107
118
  const schedules = await listSchedules({ nodePath }).catch(() => []);
119
+ const auditCfg = await resolveAuditConfig(storage);
120
+ const auditState = await readAuditState(nodePath);
121
+ const availableModels = await listAvailableChatModelsForUi().catch(() => []);
108
122
  const proactivity = {
109
123
  autoReply: storage?.DATA?.proactivity?.autoReply !== false,
110
124
  quietDigest: storage?.DATA?.proactivity?.quietDigest !== false,
125
+ audit: {
126
+ ...auditCfg,
127
+ lastRun: auditState?.last_run || 0,
128
+ lastStatus: auditState?.last_status || '',
129
+ lastTask: auditState?.last_task || '',
130
+ lastSummary: auditState?.last_summary || '',
131
+ },
111
132
  };
112
- return { triggers, schedules, proactivity };
133
+ return { triggers, schedules, proactivity, availableModels };
113
134
  }
114
135
 
115
136
  export async function saveNodeRule(storage, params = {}) {
@@ -219,6 +240,7 @@ async function saveOwnClassFields(storage, params, patch) {
219
240
  if (storage.meta_folder?.save_file) {
220
241
  await storage.meta_folder.save_file({
221
242
  ...params,
243
+ ignore_save_logs: true,
222
244
  filename: 'class.js',
223
245
  post: 'export default ' + FS.$class.toScript(copy),
224
246
  });
@@ -246,6 +268,20 @@ export async function saveNodeProactivity(storage, params = {}) {
246
268
  ...(typeof post.autoReply === 'boolean' ? { autoReply: post.autoReply } : {}),
247
269
  ...(typeof post.quietDigest === 'boolean' ? { quietDigest: post.quietDigest } : {}),
248
270
  };
271
+ if (post.audit && typeof post.audit === 'object') {
272
+ const prevAudit = prev.audit && typeof prev.audit === 'object' ? prev.audit : {};
273
+ const a = post.audit;
274
+ const cleanTime = (v, fb) => /^\d{2}:\d{2}$/.test(String(v || '').trim()) ? String(v).trim() : fb;
275
+ next.audit = {
276
+ ...prevAudit,
277
+ ...(typeof a.enabled === 'boolean' ? { enabled: a.enabled } : {}),
278
+ ...(a.windowStart !== undefined ? { windowStart: cleanTime(a.windowStart, prevAudit.windowStart || '20:00') } : {}),
279
+ ...(a.windowEnd !== undefined ? { windowEnd: cleanTime(a.windowEnd, prevAudit.windowEnd || '07:00') } : {}),
280
+ ...(a.intervalHours !== undefined ? { intervalHours: Math.max(1, Math.min(168, Number(a.intervalHours) || 24)) } : {}),
281
+ ...(a.model !== undefined ? { model: String(a.model || '').trim() } : {}),
282
+ ...(a.tz !== undefined ? { tz: String(a.tz || '').trim() } : {}),
283
+ };
284
+ }
249
285
  await saveOwnClassFields(storage, params, { proactivity: next });
250
286
  await recordBossSettingTask(storage, params, {
251
287
  title: 'Изменено поведение агента узла',
@@ -334,7 +370,7 @@ export async function runQuietDigests({ now = Date.now(), nodes = null } = {}) {
334
370
  list.push(base);
335
371
  const sub = (await base.items) || [];
336
372
  for (const child of sub) {
337
- if (child && child.type === STRUCTURE_TYPE && child.id?.[0] !== '$')
373
+ if (child && (child.type === STRUCTURE_TYPE || child.DATA?.isDepartment) && child.id?.[0] !== '$')
338
374
  list.push(child);
339
375
  }
340
376
  }
@@ -374,6 +410,314 @@ export async function runQuietDigests({ now = Date.now(), nodes = null } = {}) {
374
410
  return sent;
375
411
  }
376
412
 
413
+ const DEFAULT_AUDIT_PROMPT = 'Проведи регулярный аудит узла в режиме чтения: проверь состояние, ошибки, регламент (readme.md) и возможные улучшения. Ничего не меняй — только диагностика и конкретные предложения для BOSS. Если новых проблем и предложений нет — ответь ровно `[OK]`.';
414
+
415
+ function parseClockMinutes(hhmm, fallback) {
416
+ const m = /^(\d{2}):(\d{2})$/.exec(String(hhmm || '').trim());
417
+ if (!m)
418
+ return fallback;
419
+ const h = Number(m[1]), min = Number(m[2]);
420
+ if (h < 0 || h > 23 || min < 0 || min > 59)
421
+ return fallback;
422
+ return h * 60 + min;
423
+ }
424
+
425
+ /** Проверить, попадает ли текущее время `now` в разрешённое внерабочее окно `[windowStart, windowEnd)`. */
426
+ export function isInsideAuditWindow(now = Date.now(), { windowStart = '20:00', windowEnd = '07:00', tz = '' } = {}) {
427
+ const startMin = parseClockMinutes(windowStart, 20 * 60);
428
+ const endMin = parseClockMinutes(windowEnd, 7 * 60);
429
+ if (startMin === endMin)
430
+ return true;
431
+ const effectiveTz = tz || process.env.TZ || Intl.DateTimeFormat().resolvedOptions().timeZone;
432
+ let curMin;
433
+ try {
434
+ const parts = new Intl.DateTimeFormat('en-GB', {
435
+ timeZone: effectiveTz,
436
+ hour: '2-digit',
437
+ minute: '2-digit',
438
+ hour12: false,
439
+ }).formatToParts(new Date(now));
440
+ const hh = Number(parts.find(p => p.type === 'hour')?.value ?? 0) % 24;
441
+ const mm = Number(parts.find(p => p.type === 'minute')?.value ?? 0);
442
+ curMin = hh * 60 + mm;
443
+ }
444
+ catch {
445
+ const dt = new Date(now);
446
+ curMin = dt.getHours() * 60 + dt.getMinutes();
447
+ }
448
+ if (startMin < endMin)
449
+ return curMin >= startMin && curMin < endMin;
450
+ return curMin >= startMin || curMin < endMin;
451
+ }
452
+
453
+ export async function resolveAuditConfig(storage) {
454
+ const cfg = storage ? await loadConfig(storage).catch(() => ({})) : {};
455
+ const layerAudit = cfg?.audit && typeof cfg.audit === 'object' ? cfg.audit : {};
456
+ const nodeAudit = storage?.DATA?.proactivity?.audit && typeof storage.DATA.proactivity.audit === 'object'
457
+ ? storage.DATA.proactivity.audit
458
+ : {};
459
+ const isPersonal = Boolean(storage?.DATA?.isUser);
460
+ return {
461
+ enabled: nodeAudit.enabled ?? layerAudit.enabled ?? !isPersonal,
462
+ windowStart: String(nodeAudit.windowStart || layerAudit.windowStart || '20:00'),
463
+ windowEnd: String(nodeAudit.windowEnd || layerAudit.windowEnd || '07:00'),
464
+ intervalHours: Math.max(1, Math.min(168, Number(nodeAudit.intervalHours ?? layerAudit.intervalHours) || 24)),
465
+ model: String(nodeAudit.model ?? layerAudit.model ?? '').trim(),
466
+ tz: String(nodeAudit.tz ?? layerAudit.tz ?? '').trim(),
467
+ prompt: String(nodeAudit.prompt || layerAudit.prompt || DEFAULT_AUDIT_PROMPT).trim(),
468
+ };
469
+ }
470
+
471
+ async function listAvailableChatModelsForUi() {
472
+ const WORK = globalThis.WORK;
473
+ if (!WORK)
474
+ return [];
475
+ const modelsPath = '/' + ['MODULES', 'Модели'].join('/');
476
+ const root = await WORK.get_item(modelsPath).catch(() => null);
477
+ if (!root)
478
+ return [];
479
+ const out = [];
480
+ for (const prov of (await root.items) || []) {
481
+ await prov?.init?.catch?.(() => {});
482
+ if (prov?.DATA?.enabled === false)
483
+ continue;
484
+ for (const m of (await prov.items) || []) {
485
+ await m?.init?.catch?.(() => {});
486
+ if (m?.DATA?.enabled === false)
487
+ continue;
488
+ const caps = Array.isArray(m.capabilities) ? m.capabilities : String(m.capabilities || '').split(/[\s,]+/);
489
+ if (!caps.includes('chat'))
490
+ continue;
491
+ out.push({
492
+ path: m.path,
493
+ label: (m.DATA?.label || m.label || m.id) + ' (' + (prov.DATA?.label || prov.id) + ')',
494
+ active: (m.aiActive ?? m.DATA?.aiActive) !== false,
495
+ });
496
+ }
497
+ }
498
+ return out;
499
+ }
500
+
501
+ async function readAuditState(nodePath) {
502
+ try {
503
+ const d = await indexDb();
504
+ return d?.prepare('SELECT node_path, last_run, last_status, last_task, last_summary FROM agent_audit_state WHERE node_path = ?').get(nodePath) || null;
505
+ }
506
+ catch {
507
+ return null;
508
+ }
509
+ }
510
+
511
+ async function writeAuditState(nodePath, { lastRun, lastStatus, lastTask, lastSummary }) {
512
+ try {
513
+ const d = await indexDb();
514
+ d?.prepare(`
515
+ INSERT INTO agent_audit_state(node_path, last_run, last_status, last_task, last_summary)
516
+ VALUES(?, ?, ?, ?, ?)
517
+ ON CONFLICT(node_path) DO UPDATE SET
518
+ last_run = excluded.last_run,
519
+ last_status = excluded.last_status,
520
+ last_task = excluded.last_task,
521
+ last_summary = excluded.last_summary
522
+ `).run(nodePath, Number(lastRun) || Date.now(), String(lastStatus || ''), String(lastTask || ''), String(lastSummary || '').slice(0, 600));
523
+ }
524
+ catch { /* ignore */ }
525
+ }
526
+
527
+ function isQuietAuditOk(text) {
528
+ const clean = String(text || '').trim();
529
+ if (!clean)
530
+ return true;
531
+ return /^\[?OK\]?[.!]?$/i.test(clean);
532
+ }
533
+
534
+ /**
535
+ * Выполнить автономный аудит для одного узла структуры в read-only режиме (mode: 'plan').
536
+ * При `[OK]` молчит в чате (фиксирует только фоновую `.task` и запись в `agent_audit_state`);
537
+ * при наличии проблем/идей отправляет сводку BOSS со ссылкой на `.task`.
538
+ */
539
+ export async function runNodeAutonomousAudit(nodeItem, { now = Date.now(), force = false, session = null, runner = null } = {}) {
540
+ if (!nodeItem)
541
+ return { skipped: true, reason: 'no_node' };
542
+ await nodeItem.init?.catch?.(() => {});
543
+ const nodePath = String(nodeItem.path || '/').replace(/\/+$/, '') || '/';
544
+ const cfg = await resolveAuditConfig(nodeItem);
545
+ if (!force && !cfg.enabled)
546
+ return { skipped: true, reason: 'disabled', nodePath };
547
+ if (!force && !isInsideAuditWindow(now, cfg))
548
+ return { skipped: true, reason: 'outside_window', nodePath };
549
+
550
+ const prevState = await readAuditState(nodePath);
551
+ const intervalMs = cfg.intervalHours * 3600_000;
552
+ if (!force && prevState?.last_run && (now - Number(prevState.last_run)) < intervalMs)
553
+ return { skipped: true, reason: 'cooldown', nodePath };
554
+
555
+ const WORK = globalThis.WORK;
556
+ let bossUid = session?.uid || '';
557
+ if (!bossUid) {
558
+ if (nodeItem.DATA?.isUser) {
559
+ bossUid = nodeItem.id || '';
560
+ }
561
+ else {
562
+ const ownBosses = await Promise.resolve(nodeItem.bosses).catch(() => []);
563
+ const allBosses = ownBosses?.length ? ownBosses : (await Promise.resolve(nodeItem.allBosses).catch(() => []));
564
+ bossUid = allBosses?.[0]?.id || allBosses?.at?.(-1)?.id || '';
565
+ if (!bossUid && WORK) {
566
+ const rootBosses = await Promise.resolve(WORK.bosses).catch(() => []);
567
+ bossUid = rootBosses?.[0]?.id || '';
568
+ }
569
+ }
570
+ }
571
+ if (!bossUid)
572
+ return { skipped: true, reason: 'no_boss', nodePath };
573
+
574
+ let effectiveSession = session;
575
+ if (!effectiveSession) {
576
+ let userItem = WORK ? await (await WORK.$users)?.get_item('//' + bossUid).catch(() => null) : null;
577
+ if (Array.isArray(userItem))
578
+ userItem = userItem[0];
579
+ if (!userItem)
580
+ return { skipped: true, reason: 'no_user', nodePath };
581
+ effectiveSession = {
582
+ uid: bossUid,
583
+ principal: Object.freeze({ kind: 'user', id: bossUid }),
584
+ scheduled: true,
585
+ auditOnly: true,
586
+ };
587
+ }
588
+
589
+ const label = nodeItem.DATA?.label || nodeItem.label || nodeItem.id || (nodePath === '/' ? 'WORK' : nodePath);
590
+ const stamp = new Date(now).toLocaleString('ru-RU', cfg.tz ? { timeZone: cfg.tz } : undefined);
591
+ const fullPrompt = `[Автономный аудит · «${label}» · ${stamp}]\n${cfg.prompt}`;
592
+
593
+ const exec = runner || (async o => (await import('./index.js')).runOnce(o));
594
+ let res;
595
+ try {
596
+ res = await exec({
597
+ place: nodeItem,
598
+ session: effectiveSession,
599
+ prompt: fullPrompt,
600
+ model: cfg.model || undefined,
601
+ mode: 'plan',
602
+ signal: AbortSignal.timeout(10 * 60_000),
603
+ });
604
+ }
605
+ catch (err) {
606
+ const msg = String(err?.message || err);
607
+ await writeAuditState(nodePath, { lastRun: now, lastStatus: 'error', lastTask: prevState?.last_task || '', lastSummary: msg });
608
+ return { ok: false, error: msg, nodePath };
609
+ }
610
+
611
+ const answer = String(res?.content || '').trim();
612
+ const okQuiet = isQuietAuditOk(answer) && res?.status !== 'error';
613
+ const title = `Автоаудит: ${label}`;
614
+ let taskPath = '';
615
+ if (typeof nodeItem.save_file === 'function') {
616
+ const taskBody = {
617
+ name: title,
618
+ title,
619
+ status: res?.status === 'error' ? 'error' : 'done',
620
+ source: 'autonomous-audit',
621
+ mode: 'plan',
622
+ model: cfg.model || '',
623
+ nodePath,
624
+ created: now,
625
+ updated: Date.now(),
626
+ items: Array.isArray(res?.items) && res.items.length
627
+ ? res.items
628
+ : [
629
+ { id: 'u_' + now, type: 'user', time: now, content: fullPrompt },
630
+ { id: 'a_' + now, type: 'assistant', time: Date.now(), content: answer || '[OK]' },
631
+ ],
632
+ };
633
+ const saved = await nodeItem.save_file({
634
+ session: { ...effectiveSession, trigger: 'autonomous-audit' },
635
+ filename: `${now}.${bossUid}.task`,
636
+ ignore_save_logs: true,
637
+ post: JSON.stringify(taskBody, null, 2),
638
+ }).catch(() => null);
639
+ taskPath = saved?.logFullPath || saved?.path || '';
640
+ }
641
+
642
+ const status = okQuiet ? 'ok' : (res?.status === 'error' ? 'error' : 'findings');
643
+ await writeAuditState(nodePath, {
644
+ lastRun: now,
645
+ lastStatus: status,
646
+ lastTask: taskPath,
647
+ lastSummary: okQuiet ? 'Проблем и новых предложений не обнаружено' : answer.slice(0, 500),
648
+ });
649
+
650
+ if (!okQuiet && answer) {
651
+ const CHAT = await import('../../server/chat-threads.js');
652
+ const linkLine = taskPath ? `\n\nЗадача аудита: ${taskPath}` : '';
653
+ await CHAT.sendMessage(nodeItem, {
654
+ uid: bossUid,
655
+ asTwin: true,
656
+ kind: 'text',
657
+ message: `🔍 Автономный аудит узла «${label}»:\n${answer}${linkLine}`,
658
+ meta: { source: 'autonomous-audit', taskPath, actedAsBoss: true },
659
+ }).catch(() => {});
660
+ }
661
+
662
+ return { ok: true, status, nodePath, taskPath, quiet: okQuiet, summary: answer };
663
+ }
664
+
665
+ /**
666
+ * Пройти по структурам (WORK, $project, $department, и $user с явно включённым аудитом)
667
+ * и запустить внерабочий автономный аудит (не более 2 узлов за один цикл тика, чтобы не перегружать локальную LLM).
668
+ */
669
+ export async function runAutonomousAudits({ now = Date.now(), nodes = null, force = false, runner = null } = {}) {
670
+ const WORK = globalThis.WORK;
671
+ if (!WORK && !Array.isArray(nodes))
672
+ return [];
673
+ const list = Array.isArray(nodes) ? [...nodes] : [WORK];
674
+ if (!Array.isArray(nodes) && WORK) {
675
+ const collectProjectTree = async (node, depth = 0) => {
676
+ if (!node || depth > 5)
677
+ return;
678
+ const sub = (await Promise.resolve(node.items).catch(() => [])) || [];
679
+ for (const ch of sub) {
680
+ if (!ch || ch.id?.[0] === '$')
681
+ continue;
682
+ await ch.init?.catch?.(() => {});
683
+ if (ch.DATA?.isProject || ch.DATA?.isDepartment) {
684
+ list.push(ch);
685
+ await collectProjectTree(ch, depth + 1);
686
+ }
687
+ }
688
+ };
689
+ for (const topItem of (await Promise.resolve(WORK.items).catch(() => [])) || []) {
690
+ if (!topItem || topItem.id?.[0] === '$')
691
+ continue;
692
+ await topItem.init?.catch?.(() => {});
693
+ if (topItem.DATA?.usersContainer === true) {
694
+ for (const u of (await Promise.resolve(topItem.items).catch(() => [])) || []) {
695
+ if (!u || u.id?.[0] === '$')
696
+ continue;
697
+ await u.init?.catch?.(() => {});
698
+ if (u.DATA?.proactivity?.audit?.enabled === true)
699
+ list.push(u);
700
+ }
701
+ }
702
+ else if (topItem.DATA?.archiveType) {
703
+ await collectProjectTree(topItem, 0);
704
+ }
705
+ }
706
+ }
707
+
708
+ const results = [];
709
+ let executed = 0;
710
+ for (const nodeItem of list) {
711
+ if (!force && executed >= 2)
712
+ break;
713
+ const r = await runNodeAutonomousAudit(nodeItem, { now, force, runner }).catch(e => ({ ok: false, error: e?.message || String(e) }));
714
+ results.push(r);
715
+ if (!r?.skipped)
716
+ executed++;
717
+ }
718
+ return results;
719
+ }
720
+
377
721
  /**
378
722
  * Фоновая проверка входящей почты (IMAP) для узлов, у которых настроен хотя бы один ящик с imap.host
379
723
  * и не отключён mailAutoRefresh.
@@ -393,7 +737,7 @@ export async function runMailAutoRefresh({ nodes = null } = {}) {
393
737
  if (item.type === '$project' || item.type === '$project') {
394
738
  const sub = (await item.items) || [];
395
739
  for (const child of sub) {
396
- if (child && child.type === '$structure' && child.id?.[0] !== '$')
740
+ if (child && (child.type === '$structure' || child.DATA?.isDepartment) && child.id?.[0] !== '$')
397
741
  list.push(child);
398
742
  }
399
743
  }
@@ -676,7 +1020,7 @@ export async function listNodeStructures(storage, params = {}) {
676
1020
  return;
677
1021
  await node.init?.catch?.(() => {});
678
1022
  const p = String(node.path || '').replace(/\/+$/, '') || '/';
679
- if (['$project', '$structure'].includes(node.type) && p !== selfPath && !seen.has(p)) {
1023
+ if ((['$project', '$structure'].includes(node.type) || node.DATA?.isDepartment) && p !== selfPath && !seen.has(p)) {
680
1024
  seen.add(p);
681
1025
  out.push({
682
1026
  path: p,
@@ -691,7 +1035,7 @@ export async function listNodeStructures(storage, params = {}) {
691
1035
  if (!ch || ch.id?.[0] === '$')
692
1036
  continue;
693
1037
  await ch.init?.catch?.(() => {});
694
- if (['$domain', '$project', '$structure'].includes(ch.type))
1038
+ if (['$domain', '$project', '$structure'].includes(ch.type) || ch.DATA?.isDepartment)
695
1039
  await visit(ch, depth + 1);
696
1040
  }
697
1041
  };
@@ -776,7 +1120,7 @@ export async function getNodeStaffContext(storage, params = {}) {
776
1120
  userMap.set(entry.id, entry);
777
1121
  out.push(entry);
778
1122
  }
779
- else if (['$domain', '$folder', '$group', '$structure'].includes(t)) {
1123
+ else if (['$domain', '$folder', '$group', '$structure'].includes(t) || u?.DATA?.isDepartment) {
780
1124
  const children = await walkUsers(u, depth + 1);
781
1125
  if (children.length) {
782
1126
  out.push({
@@ -845,7 +1189,7 @@ export async function getNodeStaffContext(storage, params = {}) {
845
1189
  await node.init?.catch?.(() => {});
846
1190
  if (!node.id || node.id[0] === '$')
847
1191
  return null;
848
- if (!['$project', '$structure'].includes(node.type))
1192
+ if (!['$project', '$structure'].includes(node.type) && !node.DATA?.isDepartment)
849
1193
  return null;
850
1194
  // Проверяем видимость для текущего пользователя (не показываем чужие скрытые организации)
851
1195
  if (typeof node.canSee === 'function') {
@@ -872,7 +1216,7 @@ export async function getNodeStaffContext(storage, params = {}) {
872
1216
  if (!ch || ch.id?.[0] === '$')
873
1217
  continue;
874
1218
  await ch.init?.catch?.(() => {});
875
- if (['$project', '$structure'].includes(ch.type)) {
1219
+ if (['$project', '$structure'].includes(ch.type) || ch.DATA?.isDepartment) {
876
1220
  const built = await visit(ch, depth + 1);
877
1221
  if (built)
878
1222
  entry.children.push(built);
@@ -461,6 +461,7 @@ export async function cancelSchedule({ uid, id }) {
461
461
 
462
462
  let lastQuietDigestAt = 0;
463
463
  let lastMailRefreshAt = 0;
464
+ let lastAutonomousAuditAt = 0;
464
465
 
465
466
  /** Выполнить наступившие запуски (вызывается таймером; тесты — напрямую). */
466
467
  export async function runDue(now = Date.now(), runner = defaultRunner) {
@@ -497,6 +498,12 @@ export async function runDue(now = Date.now(), runner = defaultRunner) {
497
498
  .then(m => m.runMailAutoRefresh?.({ now }))
498
499
  .catch(() => {});
499
500
  }
501
+ if (runner === defaultRunner && !process.env.WORK_TEST && now - lastAutonomousAuditAt >= 15 * 60_000) {
502
+ lastAutonomousAuditAt = now;
503
+ import('./node-rules.js')
504
+ .then(m => m.runAutonomousAudits?.({ now }))
505
+ .catch(() => {});
506
+ }
500
507
  return done;
501
508
  }
502
509
 
@@ -138,13 +138,15 @@ export async function resolveTargetPlace(targetPath) {
138
138
  let item = await globalThis.WORK?.get_item?.(candidate);
139
139
  if (Array.isArray(item))
140
140
  item = item[item.length - 1] || null;
141
- if (item && (item instanceof FS.$class || item.type) && STRUCT_TYPES.has(item.type)) {
141
+ if (item && (item instanceof FS.$class || item.type)) {
142
142
  await item.init?.catch?.(() => {});
143
- return {
144
- path: item.path || candidate,
145
- node: item,
146
- label: item.DATA?.label || item.label || item.id || candidate,
147
- };
143
+ if (STRUCT_TYPES.has(item.type) || item.DATA?.isStructure === true) {
144
+ return {
145
+ path: item.path || candidate,
146
+ node: item,
147
+ label: item.DATA?.label || item.label || item.id || candidate,
148
+ };
149
+ }
148
150
  }
149
151
  }
150
152
  catch { /* try parent */ }
@@ -101,7 +101,7 @@ export const assign = {
101
101
  const declared = await cls.declared_roles;
102
102
  const roleKey = String(args.role || '').trim().toUpperCase();
103
103
  const declaredRole = (!args.place && !args.label && !Array.isArray(args.links) && roleKey) ? declared[roleKey] : null;
104
- const isStruct = typeof cls._isStructure === 'function' ? await cls._isStructure() : (cls.type === '$structure' || cls.type === '$project');
104
+ const isStruct = typeof cls._isStructure === 'function' ? await cls._isStructure() : (cls.DATA?.isStructure || cls.type === '$structure' || cls.type === '$project');
105
105
 
106
106
  // Проверяем, относится ли вызов к рабочему месту (#security.ROLES) в подразделении ($structure / $project)
107
107
  const hasExistingPlace = (rolesList, targetKey) => {
@@ -283,7 +283,7 @@ async function walkClassSubtree(rootItem, maxDepth = 8) {
283
283
  roleIssues.push(`${cls.path}: битая ссылка LINKS в рабочем месте «${rid || r?.label}» → ${lp}`);
284
284
  }
285
285
  }
286
- if ((cls.type === '$structure' || cls.type === '$project') && (!Array.isArray(sec.BOSS) || !sec.BOSS.length)) {
286
+ if ((cls.DATA?.isDepartment || cls.DATA?.isProject || cls.type === '$structure' || cls.type === '$project') && (!Array.isArray(sec.BOSS) || !sec.BOSS.length)) {
287
287
  // Проверяем наличие BOSS выше не обязательно ошибка, но полезно отметить, если у $project нет BOSS
288
288
  if (cls.type === '$project')
289
289
  roleIssues.push(`${cls.path}: у организации ($project) не назначен руководитель (BOSS)`);
@@ -510,7 +510,7 @@ export async function onChatEvent({ storage, thread, message, params = {} } = {}
510
510
  const allowDefaultReply = n === 0
511
511
  && !message.taskPath
512
512
  && text.length > 0
513
- && STRUCT_TYPES.has(storage.type)
513
+ && (STRUCT_TYPES.has(storage.type) || storage.DATA?.isStructure === true)
514
514
  && storage.DATA?.proactivity?.autoReply !== false
515
515
  && !globalThis.__workDisableDefaultTwinReply
516
516
  && (Boolean(runner || globalThis.__workDefaultTwinRunner) || (!process.env.NODE_TEST_CONTEXT && process.env.NODE_ENV !== 'test'));
@@ -86,7 +86,8 @@ export async function askTwin({ fromPath = '/', targetPath, question, session, d
86
86
  if (!targetItem || !(targetItem instanceof FS.$class))
87
87
  throw new Error(`twin_ask: узел не найден (${target})`);
88
88
  await targetItem.init;
89
- if (!STRUCT_TYPES.has(targetItem.type))
89
+ await targetItem.init?.catch?.(() => {});
90
+ if (!STRUCT_TYPES.has(targetItem.type) && targetItem.DATA?.isStructure !== true)
90
91
  throw new Error(`twin_ask: адресат ${target} не является структурным Агентом (${targetItem.type})`);
91
92
 
92
93
  let hasHumanAccess = true;