@rsconcept/rstool 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,39 +1,39 @@
1
- # RS language and rstool — reference
2
-
3
- ## rstool contract
4
-
5
- - Package: `@rsconcept/rstool`
6
- - Contract version: `1.4.0` (`CONTRACT_VERSION`)
7
- - Core class: `RSToolAgent`
8
- - Public imports: `@rsconcept/rstool` and `@rsconcept/rstool/wrapper`
9
-
10
- ### Methods
11
-
12
- | Method | Purpose |
13
- | ----------------------------------------------------------- | ------------------------------------------------------------------ |
14
- | `createSession(initial?)` | New in-memory session → `{ sessionId, contractVersion }` |
15
- | `addOrUpdateConstituenta(sessionId, { draft })` | Merge draft; analyze in session context → `{ state, diagnostics }` |
16
- | `analyzeExpression(sessionId, { expression, cstType })` | Parse/typecheck snippet without persisting a constituent |
17
- | `getFormState(sessionId)` | Clone of full session state |
18
- | `listDiagnostics(sessionId, filters?)` | Accumulated diagnostics; optional `constituentId` filter |
19
- | `commitStep(sessionId, message?)` | Record revision checkpoint |
20
- | `exportSession(sessionId)` | JSON string `{ contractVersion, state, diagnostics }` |
21
- | `exportPortalSchema(sessionId)` | Portal schema import JSON string using versioned schema shape |
22
- | `exportPortalModel(sessionId)` | Portal model import JSON string using versioned model values shape |
23
- | `importSession(payload)` | New session from export |
24
- | `setConstituentaValue(sessionId, { target, type?, value })` | Set one base binding or structured value → `SessionModelState` |
25
- | `setConstituentaValues(sessionId, { items })` | Batch set values → `SessionModelState` |
26
- | `clearConstituentaValues(sessionId, { items })` | Clear values by constituent id → `SessionModelState` |
27
- | `getModelState(sessionId)` | Clone of session interpretation state |
28
- | `evaluateExpression(sessionId, { expression, cstType })` | Evaluate snippet in session context → `EvaluationResult` |
29
- | `evaluateConstituenta(sessionId, { constituentId })` | Evaluate stored definition → `EvaluationResult` |
30
- | `recalculateModel(sessionId)` | Recalculate all inferrable constituents → `{ items[] }` |
1
+ # RSLang и rstool — справочник
2
+
3
+ ## Контракт rstool
4
+
5
+ - Пакет: `@rsconcept/rstool`
6
+ - Версия контракта: `1.4.0` (`CONTRACT_VERSION`)
7
+ - Основной класс: `RSToolAgent`
8
+ - Публичные импорты: `@rsconcept/rstool` и `@rsconcept/rstool/wrapper`
9
+
10
+ ### Методы
11
+
12
+ | Метод | Назначение |
13
+ | ----------------------------------------------------------- | ----------------------------------------------------------------------------- |
14
+ | `createSession(initial?)` | Новая in-memory сессия → `{ sessionId, contractVersion }` |
15
+ | `addOrUpdateConstituenta(sessionId, { draft })` | Слияние черновика; анализ в контексте сессии → `{ state, diagnostics }` |
16
+ | `analyzeExpression(sessionId, { expression, cstType })` | Разбор/типизация фрагмента без сохранения конституенты |
17
+ | `getFormState(sessionId)` | Клон полного состояния сессии |
18
+ | `listDiagnostics(sessionId, filters?)` | Накопленные диагностики; опциональный фильтр `constituentId` |
19
+ | `commitStep(sessionId, message?)` | Зафиксировать контрольную точку ревизии |
20
+ | `exportSession(sessionId)` | JSON-строка `{ contractVersion, state, diagnostics }` |
21
+ | `exportPortalSchema(sessionId)` | JSON импорта схемы Portal |
22
+ | `exportPortalModel(sessionId)` | JSON импорта модели Portal |
23
+ | `importSession(payload)` | Новая сессия из экспорта |
24
+ | `setConstituentaValue(sessionId, { target, type?, value })` | Одна привязка базового понятия или структурное значение → `SessionModelState` |
25
+ | `setConstituentaValues(sessionId, { items })` | Пакетная установка значений → `SessionModelState` |
26
+ | `clearConstituentaValues(sessionId, { items })` | Очистка значений по id конституент → `SessionModelState` |
27
+ | `getModelState(sessionId)` | Клон состояния интерпретации сессии |
28
+ | `evaluateExpression(sessionId, { expression, cstType })` | Вычисление фрагмента в контексте сессии → `EvaluationResult` |
29
+ | `evaluateConstituenta(sessionId, { constituentId })` | Вычисление сохранённого определения → `EvaluationResult` |
30
+ | `recalculateModel(sessionId)` | Пересчёт всех выводимых конституент → `{ items[] }` |
31
31
 
32
32
  ### `ConstituentaDraft`
33
33
 
34
34
  ```ts
35
35
  {
36
- id: number; // stable id within session
36
+ id: number; // стабильный id внутри сессии
37
37
  alias: string;
38
38
  cstType: CstType;
39
39
  definitionFormal: string;
@@ -43,27 +43,27 @@
43
43
  }
44
44
  ```
45
45
 
46
- Omitted text fields default to `''` in stored state.
46
+ Пропущенные текстовые поля в сохранённом состоянии по умолчанию `''`.
47
47
 
48
- ### `SessionState` metadata
48
+ ### Метаданные `SessionState`
49
49
 
50
- Set on `createSession(initial?)` or via `importSession`:
50
+ Задаются в `createSession(initial?)` или через `importSession`:
51
51
 
52
52
  ```ts
53
53
  {
54
- alias: string; // library item alias
55
- title: string; // display title
56
- comment: string; // developer notes
54
+ alias: string; // alias объекта библиотеки
55
+ title: string; // отображаемое название
56
+ comment: string; // заметки разработчика
57
57
  }
58
58
  ```
59
59
 
60
- All default to `''` when omitted.
60
+ При опускании все поля по умолчанию `''`.
61
61
 
62
- ### Model and evaluation types
62
+ ### Типы модели и вычисления
63
63
 
64
64
  ```ts
65
- type RSToolValue = number | RSToolValue[]; // runtime value
66
- type BasicBinding = Record<number, string>; // base-set element labels
65
+ type RSToolValue = number | RSToolValue[]; // значение во время выполнения
66
+ type BasicBinding = Record<number, string>; // подписи элементов базового множества
67
67
 
68
68
  interface SessionModelState {
69
69
  items: { id: number; type: string; value: RSToolValue | BasicBinding }[];
@@ -79,19 +79,19 @@ interface EvaluationResult {
79
79
  }
80
80
  ```
81
81
 
82
- Base/constant bindings use `type: "basic"` and `value: { "0": "label", … }`. Structured values use normalized typification as `type` and nested arrays for sets/tuples.
82
+ Привязки `basic`/`constant` используют `type: "basic"` и `value: { "0": "label", … }`. Структурные значения нормализованная типизация в `type` и вложенные массивы для множеств/кортежей.
83
83
 
84
- ### Stdio protocol
84
+ ### Протокол stdio
85
85
 
86
- Process: `npx rstool-wrapper`
86
+ Процесс: `npx rstool-wrapper`
87
87
 
88
- 1. **Ready** (no request): `{"id":null,"ok":true,"result":{"ready":true,"wrapper":"rstool-stdio","contractVersion":"1.4.0"}}`
89
- 2. **Request**: `{"id":"<unique>","method":"<name>","params":{...}}`
90
- 3. **Response**: `{"id":"<same>","ok":true,"result":...}` or `{"id":"...","ok":false,"error":{"code":"...","message":"..."}}`
88
+ 1. **Ready** (без запроса): `{"id":null,"ok":true,"result":{"ready":true,"wrapper":"rstool-stdio","contractVersion":"1.4.0"}}`
89
+ 2. **Запрос**: `{"id":"<unique>","method":"<name>","params":{...}}`
90
+ 3. **Ответ**: `{"id":"<same>","ok":true,"result":...}` или `{"id":"...","ok":false,"error":{"code":"...","message":"..."}}`
91
91
 
92
- Extra methods: `ping`, `methods`.
92
+ Дополнительные методы: `ping`, `methods`.
93
93
 
94
- Example chain:
94
+ Пример цепочки:
95
95
 
96
96
  ```json
97
97
  {"id":"1","method":"createSession","params":{}}
@@ -108,9 +108,9 @@ Example chain:
108
108
  {"id":"9","method":"evaluateConstituenta","params":{"sessionId":"…","input":{"constituentId":3}}}
109
109
  ```
110
110
 
111
- `RSToolWrapperClient`: spawns `rstool-wrapper` by default and implements `waitUntilReady()`, `call(method, params)`, `close()`.
111
+ `RSToolWrapperClient`: по умолчанию запускает `rstool-wrapper`; методы `waitUntilReady()`, `call(method, params)`, `close()`.
112
112
 
113
- ### Analysis result
113
+ ### Результат анализа
114
114
 
115
115
  ```ts
116
116
  interface AnalysisResult {
@@ -121,79 +121,77 @@ interface AnalysisResult {
121
121
  }
122
122
  ```
123
123
 
124
- ## RS language
124
+ ## RSLang
125
125
 
126
- Intro (help): language is FOL-based; set vs logic expression split; parameterized templates for term/predicate functions.
126
+ Кратко: язык на базе логики первого порядка; разделение множественных и логических выражений; параметризованные шаблоны для функций и предикатов.
127
127
 
128
- - **Typification**: structure type of an expression; grades include elements (`Xi`, `Ci`), `Z`, tuples `(H1×…×Hn)`, sets `ℬ(H)`, logic `Logic`, parameterized `Hr 🠔 [H1,…,Hi]`. On `structure` (`S#`), `definitionFormal` **is** the typification. On `term` (`D#`), typification is **inferred from** the definition.
128
+ - **Типизация**: структурный тип выражения; ступени включают элементы (`Xi`, `Ci`), `Z`, кортежи `(H1×…×Hn)`, множества `ℬ(H)`, логику `Logic`, параметризованные `Hr 🠔 [H1,…,Hi]`. У `structure` (`S#`) поле `definitionFormal` **задаёт** типизацию. У `term` (`D#`) типизация **выводится** из определения.
129
129
 
130
- ## Grammar tokens
130
+ ## Токены грамматики
131
131
 
132
- From `rslang.grammar`:
132
+ Из `rslang.grammar`:
133
133
 
134
- | Category | Tokens / forms |
135
- | ---------------------- | ----------------------------------------------------- |
136
- | Globals | `X`, `C`, `S`, `D`, `A`, `T` + digits (`Global` rule) |
137
- | Functions / predicates | `F<n>`, `P<n>` |
138
- | Radicals | `R<n>` |
139
- | Locals | `_a-zα-ω` + optional digits |
140
- | Logic | `¬` `∀` `∃` `⇔` `⇒` `∨` `&` |
141
- | Sets | `ℬ` `∪` `\` `∆` `∩` `×` `∈` `∉` `⊆` `⊂` … |
142
- | Ops | `Pr`, `pr`, `Fi`, `card`, `bool`, `debool`, `red` |
143
- | Literals | digits, `Z`, `∅` |
134
+ | Категория | Токены / формы |
135
+ | ------------------- | ------------------------------------------------------- |
136
+ | Глобальные | `X`, `C`, `S`, `D`, `A`, `T` + цифры (правило `Global`) |
137
+ | Функции / предикаты | `F<n>`, `P<n>` |
138
+ | Радикалы | `R<n>` |
139
+ | Локальные | `_a-zα-ω` + опциональные цифры |
140
+ | Логика | `¬` `∀` `∃` `⇔` `⇒` `∨` `&` |
141
+ | Множества | `ℬ` `∪` `\` `∆` `∩` `×` `∈` `∉` `⊆` `⊂` … |
142
+ | Операции | `Pr`, `pr`, `Fi`, `card`, `bool`, `debool`, `red` |
143
+ | Литералы | цифры, `Z`, `∅` |
144
144
 
145
- Full grammar pointers and precedence notes: `docs/GRAMMAR-REF.md`.
145
+ Полная грамматика и приоритеты: `docs/GRAMMAR-REF.md`.
146
146
 
147
- ## Help topic map (companion docs)
147
+ ## Документация
148
148
 
149
- Standalone agents should consult the bundled distilled docs (`docs/*.md` inside `@rsconcept/rstool`):
149
+ | Тема | Документ |
150
+ | ---------------------------------------- | ------------------------------------------------------------ |
151
+ | Идентификаторы, литералы | `docs/SYNTAX.md` § «Имена и литералы» |
152
+ | Ступени, `Logic`, параметризованные типы | `docs/TYPIFICATION.md` § «Ступени» |
153
+ | Логические выражения | `docs/SYNTAX.md` § «Логические выражения (LE)» |
154
+ | Операторы над множествами | `docs/SYNTAX.md` § «Теоретико-множественные выражения (STE)» |
155
+ | Целочисленная арифметика | `docs/SYNTAX.md` § «Арифметика» |
156
+ | Дополнительные и производные типизации | `docs/TYPIFICATION.md` § «Дополнительные типизации» |
157
+ | Кванторы | `docs/SYNTAX.md` § «Кванторы» |
158
+ | Параметризованные функции, шаблоны | `docs/SYNTAX.md` § «Параметризованные выражения» |
159
+ | Модель корректности / валидация | `docs/SYNTAX.md` § «Корректность» |
160
+ | Семантические тесты определений | `docs/MODEL-TESTING.md` |
161
+ | Словарь предметной области | `docs/DOMAIN.md` |
162
+ | Поля конституент и порядок | `docs/CONSTITUENTA.md` |
163
+ | REST API Portal | `docs/PORTAL-API.md` |
164
+ | Токены грамматики / приоритеты | `docs/GRAMMAR-REF.md` |
150
165
 
151
- | Topic | Bundled doc |
152
- | ------------------------------------ | ------------------------------------------ |
153
- | Identifiers, literals | `docs/SYNTAX.md` § _Identifier rules_ |
154
- | Grades, `Logic`, parameterized types | `docs/TYPIFICATION.md` |
155
- | Logical expressions | `docs/SYNTAX.md` § _Logical expressions_ |
156
- | Set operators | `docs/SYNTAX.md` § _Set-theoretic_ |
157
- | Integer arithmetic | `docs/SYNTAX.md` § _Arithmetic_ |
158
- | Structural / typification reshaping | `docs/TYPIFICATION.md` § _Forming/derived_ |
159
- | Quantifiers | `docs/SYNTAX.md` § _Quantifiers_ |
160
- | Parameterized functions, templates | `docs/SYNTAX.md` § _Parameterised_ |
161
- | Correctness / validation mindset | `docs/SYNTAX.md` § _Correctness model_ |
162
- | Definition semantic tests | `docs/MODEL-TESTING.md` |
163
- | Domain vocabulary | `docs/DOMAIN.md` |
164
- | Constituent fields and ordering | `docs/CONSTITUENTA.md` |
165
- | Portal REST API | `docs/PORTAL-API.md` |
166
- | Grammar tokens / precedence | `docs/GRAMMAR-REF.md` |
166
+ Воркфлоу и чеклисты — `skills/rstool-helper/GUIDE.md`.
167
167
 
168
- ## Error codes
168
+ ## Коды ошибок
169
169
 
170
- rstool re-exports `RSErrorCode.definitionNotAllowed` (`0x8862`) for base/constant violations.
170
+ Категории и исправления по коду: `docs/DIAGNOSTICS.md`.
171
171
 
172
- Categories and per-code fix guidance: `docs/DIAGNOSTICS.md`.
172
+ Категории:
173
173
 
174
- Categories:
174
+ - `0x84xx` — синтаксис / разбор
175
+ - `0x28xx` — предупреждения локальных объявлений
176
+ - `0x88xx` — семантика / типы
177
+ - `0x886x` — уровень конституент (пустая производная, запрещённое определение)
178
+ - `0x81xx` — вычисление (runtime; из `evaluateExpression` / `evaluateConstituenta`)
175
179
 
176
- - `0x84xx` syntax / parse
177
- - `0x28xx` — local declaration warnings
178
- - `0x88xx` — semantic / type
179
- - `0x886x` — constituent-level (empty derived, definition not allowed)
180
- - `0x81xx` — evaluation (runtime; returned by `evaluateExpression` / `evaluateConstituenta`)
180
+ ## Форма экспорта сессии
181
181
 
182
- ## Exported session shape
182
+ `exportSession(sessionId)` возвращает JSON-строку `{ contractVersion, state, diagnostics }`.
183
183
 
184
- `exportSession(sessionId)` returns a JSON string with `{ contractVersion, state, diagnostics }`.
184
+ - `state.alias`, `state.title`, `state.comment` метаданные объекта библиотеки для экспорта в Portal (`comment` JSON `description`).
185
+ - `state.items[]` — каждая конституента с `id`, `alias`, `cstType`, `definitionFormal`, опциональными текстовыми полями и вложенным результатом анализа.
186
+ - `state.model.items[]` — присутствует, если заданы значения интерпретации.
187
+ - `diagnostics[]` — накопленные диагностики со смещениями и кодами.
185
188
 
186
- - `state.alias`, `state.title`, `state.comment` — library-item metadata for Portal export (`comment` → JSON `description`).
187
- - `state.items[]` contains each constituent with `id`, `alias`, `cstType`, `definitionFormal`, optional text fields, and nested analysis output.
188
- - `state.model.items[]` is present when interpretation values have been set.
189
- - `diagnostics[]` contains accumulated diagnostics with offsets and codes.
189
+ ## JSON импорта Portal
190
190
 
191
- ## Portal import JSON
191
+ Для **Load from JSON** на существующей схеме или модели Portal:
192
192
 
193
- For **Load from JSON** on an existing Portal schema or model:
193
+ - `exportPortalSchema(sessionId)` файл схемы
194
+ - `exportPortalModel(sessionId)` — файл модели
194
195
 
195
- - `exportPortalSchema(sessionId)` schema file
196
- - `exportPortalModel(sessionId)` model file
197
-
198
- - Schema `items[]`: versioned constituent fields (`cst_type`, `definition_formal`, `term_raw`, …).
199
- - Model `items[]`: `{ id, type, value }` per binding.
196
+ - Схема `items[]`: поля конституент (`cst_type`, `definition_formal`, `term_raw`, …).
197
+ - Модель `items[]`: `{ id, type, value }` на каждую привязку.
@@ -18,9 +18,9 @@ Then continue with the canonical files below.
18
18
 
19
19
  ## Canonical files (read before rstool work)
20
20
 
21
- - **Start here** — workflow: `node_modules/@rsconcept/rstool/skills/rstool-helper/GUIDE.md`
22
- - API, stdio, contract: `node_modules/@rsconcept/rstool/skills/rstool-helper/REFERENCE.md`
23
- - Examples, pitfalls: `node_modules/@rsconcept/rstool/skills/rstool-helper/EXAMPLES.md`
21
+ - **Start here** — воркфлоу и чеклисты: `node_modules/@rsconcept/rstool/skills/rstool-helper/GUIDE.md`
22
+ - API, stdio, контракт: `node_modules/@rsconcept/rstool/skills/rstool-helper/REFERENCE.md`
23
+ - Примеры, типичные ошибки: `node_modules/@rsconcept/rstool/skills/rstool-helper/EXAMPLES.md`
24
24
  - Language / domain docs: `node_modules/@rsconcept/rstool/docs/*.md`
25
25
  - Install procedure: `node_modules/@rsconcept/rstool/skills/INSTALL.md`
26
26