@rsconcept/rstool 0.2.1 → 0.4.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.
Files changed (50) hide show
  1. package/README.md +3 -1
  2. package/dist/index-uhkmwruf.d.ts +46 -0
  3. package/dist/index.d.ts +5 -4
  4. package/dist/index.js +2 -2
  5. package/dist/mappers/model-adapter.d.ts +1 -1
  6. package/dist/mappers/schema-adapter.d.ts +1 -1
  7. package/dist/models/index.d.ts +5 -4
  8. package/dist/models/index.js +2 -2
  9. package/dist/models/rstool-agent.d.ts +1 -1
  10. package/dist/models/rstool-agent.js +1 -92
  11. package/dist/models/session.d.ts +1 -1
  12. package/dist/models/tool-contract.d.ts +1 -1
  13. package/dist/models/tool-contract.js +1 -1
  14. package/dist/models/tool-contract.js.map +1 -1
  15. package/dist/rstool-agent-BZi5jO1y.js +158 -0
  16. package/dist/rstool-agent-BZi5jO1y.js.map +1 -0
  17. package/dist/{rstool-agent-DkeH5Qml.d.ts → rstool-agent-pRaPnZay.d.ts} +6 -4
  18. package/dist/session/session-store.d.ts +2 -1
  19. package/dist/session/session-store.js +3 -0
  20. package/dist/session/session-store.js.map +1 -1
  21. package/dist/{session-BHGCCLfQ.d.ts → session-BPgsE80c.d.ts} +12 -1
  22. package/dist/{tool-contract-CsGqg_0P.d.ts → tool-contract-n1ghUOrK.d.ts} +5 -3
  23. package/dist/wrapper/stdio-wrapper.js +13 -1
  24. package/dist/wrapper/stdio-wrapper.js.map +1 -1
  25. package/docs/CONCEPTUAL-SCHEMA.md +50 -140
  26. package/docs/CONSTITUENTA.md +37 -62
  27. package/docs/DIAGNOSTICS.md +85 -130
  28. package/docs/DOMAIN.md +68 -91
  29. package/docs/GRAMMAR-REF.md +35 -86
  30. package/docs/MODEL-TESTING.md +57 -0
  31. package/docs/PORTAL-API.md +22 -36
  32. package/docs/README.md +14 -13
  33. package/docs/SYNTAX.md +49 -104
  34. package/docs/TYPIFICATION.md +41 -60
  35. package/package.json +1 -1
  36. package/skills/README.md +6 -8
  37. package/skills/rstool-helper/EXAMPLES.md +91 -105
  38. package/skills/rstool-helper/GUIDE.md +67 -114
  39. package/skills/rstool-helper/REFERENCE.md +43 -11
  40. package/skills/rstool-helper/SKILL.md +5 -8
  41. package/src/index.ts +6 -0
  42. package/src/models/index.ts +8 -0
  43. package/src/models/portal-json.ts +45 -0
  44. package/src/models/rstool-agent.test.ts +98 -0
  45. package/src/models/rstool-agent.ts +72 -4
  46. package/src/models/session.ts +11 -0
  47. package/src/models/tool-contract.ts +3 -1
  48. package/src/session/session-store.ts +3 -0
  49. package/src/wrapper/stdio-wrapper.ts +14 -0
  50. package/dist/models/rstool-agent.js.map +0 -1
@@ -1,130 +1,85 @@
1
- # Diagnostics reference
2
-
3
- Use this when an `analyzeExpression` / `addOrUpdateConstituenta` call returns errors in `result.diagnostics`.
4
-
5
- ## How to read a diagnostic
6
-
7
- Each `DiagnosticRecord` carries:
8
-
9
- - `code` — numeric `RSErrorCode` (see table). The high nibble identifies the class (`0x82xx` lexer, `0x84xx` parser, `0x88xx` semantic, `0x81xx` runtime, `0x28xx` warnings).
10
- - `params` — substitution arguments for the message (identifier names, sets, etc.).
11
- - `from`, `to` — character positions in the _expression text_ that should be patched. Always edit `definitionFormal` by range.
12
- - `constituentId` present in session diagnostics from `listDiagnostics`.
13
-
14
- Resolve `code` from **`@rsconcept/domain`** (installed: `node_modules/@rsconcept/domain/src/rslang/error.ts`):
15
-
16
- - **`RSErrorCode`** — reverse-lookup the numeric value to its symbol name (`missingParenthesis`, `globalNotTyped`, …). The identifier is the canonical error kind; inline comments on each member document the hex id.
17
- - **`getRSErrorPrefix(code)`**short label with class + hex (`P8406`, `S8803`, …).
18
- - **`params`**substitution arguments from the reporter (see `*.test.ts` cases in `domain/src/rslang/` for examples per code).
19
- - **Tables below** typical causes and agent fixes when patching `definitionFormal`.
20
-
21
- ## Class table
22
-
23
- | Mask | Class | Behaviour |
24
- | --------------- | -------------------- | ------------------------------------------------------------------------------ |
25
- | `0x8400` family | Parser | Lexical / syntactic problems; expression cannot be analysed further |
26
- | `0x8800` family | Semantic | Definition-level issues (types, scopes, structure) |
27
- | `0x8100` family | Runtime / evaluation | Raised during `evaluateExpression` / `evaluateConstituenta` |
28
- | `0x2800` family | Warning | Not critical; expression still valid |
29
- | `0x88Cx` | Schema-level | Rules enforced by the schema layer (`cstEmptyDerived`, `definitionNotAllowed`) |
30
-
31
- `isCritical(code)` returns `false` only for `localDoubleDeclare` and `localNotUsed`.
32
-
33
- ## High-priority codes
34
-
35
- ### Parser
36
-
37
- | Code | Symbol | Typical cause | Agent fix |
38
- | -------- | ---------------------- | ------------------------------------ | ------------------------------- |
39
- | `0x8400` | `unknownSyntax` | Stray token / typo | Re-tokenise around `from`–`to` |
40
- | `0x8406` | `missingParenthesis` | Unmatched `(` `)` | Insert matching paren near `to` |
41
- | `0x8407` | `missingCurlyBrace` | Unmatched `{` `}` | Insert matching brace |
42
- | `0x8408` | `missingSquareBracket` | Unmatched `[` `]` | Insert matching bracket |
43
- | `0x8409` | `bracketMismatch` | Mixed bracket types | Replace one bracket to match |
44
- | `0x840A` | `doubleParenthesis` | `(( ... ))` redundancy | Remove one pair |
45
- | `0x840B` | `missingOpenBracket` | Closing bracket without opener | Insert opening bracket earlier |
46
- | `0x8415` | `expectedLocal` | Quantifier or filter expects a local | Provide a lowercase variable |
47
- | `0x8416` | `expectedType` | Missing typification annotation | Add explicit grade |
48
-
49
- ### Semanticlocals and scopes
50
-
51
- | Code | Symbol | Typical cause | Agent fix |
52
- | -------- | -------------------- | -------------------------------- | ------------------------------- |
53
- | `0x8801` | `localUndeclared` | Variable used before declaration | Bind via quantifier / parameter |
54
- | `0x8802` | `localShadowing` | Local redeclared in inner scope | Rename inner variable |
55
- | `0x8815` | `localOutOfScope` | Local escapes its binder | Move usage inside the binder |
56
- | `0x2801` | `localDoubleDeclare` | Same local declared twice | Warning; rename |
57
- | `0x2802` | `localNotUsed` | Declared local never referenced | Warning; remove or use |
58
-
59
- ### Semantic — types
60
-
61
- | Code | Symbol | Typical cause | Agent fix |
62
- | -------- | ------------------------------- | ------------------------------------------------------ | --------------------------------------------------- |
63
- | `0x8803` | `typesNotEqual` | Operands have different typifications | Convert / project to matching grade |
64
- | `0x8804` | `globalNotTyped` | Referenced global has no typification | Ensure dependency is upserted and typechecked first |
65
- | `0x8805` | `invalidDecart` | Cartesian product on non-set operand | Wrap operand in `ℬ(...)` if appropriate |
66
- | `0x8806` | `invalidBoolean` | `ℬ(...)` applied to a non-set | Use a set-grade operand |
67
- | `0x8807` | `invalidTypeOperation` | Operator not defined for these types | Re-check the typification table |
68
- | `0x8808` | `invalidCard` | `card(...)` on a non-set | Use a set operand |
69
- | `0x8809` | `invalidDebool` | `debool(...)` on non-singleton | Ensure exactly one element first |
70
- | `0x880B` | `globalFuncWithoutArgs` | Calling a function without `[]` args | Provide arguments |
71
- | `0x8810` | `invalidReduce` | `red(...)` on something not `ℬ(ℬ(...))` | Wrap in extra `ℬ` or change source |
72
- | `0x8811` | `invalidProjectionTuple` | `pr_i((a,b))` with out-of-range index | Use valid index |
73
- | `0x8812` | `invalidProjectionSet` | `Pr_i(S)` on non-tuple set | Use a tuple-set source |
74
- | `0x8813` | `invalidEnumeration` | `{a, b}` with incompatible element types | Match element typifications |
75
- | `0x8814` | `invalidCortegeDeclare` | Tuple declaration with mismatched arity | Match declaration to use |
76
- | `0x8816` | `invalidElementPredicate` | S` typification mismatch | Match `ξ`'s grade to elements of `S` |
77
- | `0x8817` | `invalidEmptySetUsage` | `∅` in a position that needs a concrete element | Provide explicit typified operand |
78
- | `0x8818` | `invalidArgsArity` | Wrong number of arguments to function | Match function declaration |
79
- | `0x8819` | `invalidArgumentType` | Argument typification mismatch | Adjust caller or function signature |
80
- | `0x881C` | `globalStructure` | Wrong structural shape of referenced global | Re-check `structure` constituent shape |
81
- | `0x8821` | `radicalUsage` | Radical used outside parameter domain | Move usage into parameter declarations |
82
- | `0x8822` | `invalidFilterArgumentType` | `Fi[D](S)` parameter does not match index typification | Match `D` to projected grade |
83
- | `0x8823` | `invalidFilterArity` | Filter parameter count ≠ multi-index length | Align lengths |
84
- | `0x8824` | `arithmeticNotSupported` | Arithmetic operator outside integer context | Use integer expressions |
85
- | `0x8825` | `typesNotCompatible` | Generic type incompatibility | Re-examine surrounding context |
86
- | `0x8826` | `orderingNotSupported` | `<`, `≤` etc. used outside integer | Ensure operands are integers |
87
- | `0x8827` | `expectedLogic` | Definition where `Logic` is required | Wrap in logical expression or change `cstType` |
88
- | `0x8828` | `expectedSetexpr` | Definition where STE required | Convert from logic to set expression |
89
- | `0x8829` | `invalidArgumentCortegeDeclare` | Tuple parameter declaration mismatch | Match tuple arity in declaration |
90
-
91
- ### Schema / cstType validation
92
-
93
- | Code | Symbol | Trigger | Fix |
94
- | -------- | ---------------------- | ------------------------------------------------------ | ------------------------------------------------------ |
95
- | `0x8861` | `cstEmptyDerived` | Derived constituent with empty `definitionFormal` | Provide a definition |
96
- | `0x8862` | `definitionNotAllowed` | `basic`/`constant` with non-empty formal | Clear the formal |
97
- | `0x8840` | `globalNoValue` | Reference to global without a model value | Set value via `setConstituentaValue` before evaluating |
98
- | `0x8841` | `invalidPropertyUsage` | Property-only constituent used where value is required | Use a different operand |
99
-
100
- ### Runtime (evaluation)
101
-
102
- | Code | Symbol | Cause |
103
- | -------- | ------------------------- | ---------------------------------------- |
104
- | `0x8100` | `calcUnknownError` | Unspecified evaluation failure |
105
- | `0x8101` | `setOverflow` | Intermediate set too large |
106
- | `0x8102` | `booleanBaseLimit` | `ℬ(X)` overflow at runtime |
107
- | `0x8103` | `calcGlobalMissing` | Referenced global has no current value |
108
- | `0x8104` | `iterationsLimit` | Iterative computation exceeded limit |
109
- | `0x8105` | `calcInvalidDebool` | `debool` on multi-element set at runtime |
110
- | `0x8106` | `iterateInfinity` | Iteration over an infinite set |
111
- | `0x8107` | `calculationNotSupported` | Construct cannot be evaluated |
112
-
113
- ## Common agent mistakes
114
-
115
- - **Setting a value on a derived constituent**: derived `term`, `axiom`, `statement` are inferrable. Use `evaluateConstituenta` / `recalculateModel`. Setting them throws `Constituent <alias> is inferrable and cannot be set directly`.
116
- - **Forgetting empty formal on `basic` / `constant`**: results in `definitionNotAllowed`. Pass `definitionFormal: ''`.
117
- - **Out-of-order dependencies**: referencing `D2` before upserting it raises `localUndeclared` or `globalNotTyped`. Always topologically sort.
118
- - **Wrong cstType for the role**: `axiom`/`statement` whose definition is not `Logic` raises `expectedLogic`. A `term` whose body is logical raises `expectedSetexpr`.
119
- - **Negative literals**: `-5` does not parse. Use `0 - 5`.
120
- - **Radicals in result expressions**: `[α∈R1] (α, R1)` raises `radicalUsage`. Use radicals only in parameter domains.
121
- - **Evaluating before bindings are set**: `evaluateExpression` referencing `X1` without a `setConstituentaValue(..., target: <X1.id>)` raises `calcGlobalMissing` (`0x8103`).
122
-
123
- ## Diagnostics loop
124
-
125
- 1. Run `analyzeExpression` on a scratch.
126
- 2. If `analysis.success === false`, iterate `analysis.diagnostics`.
127
- 3. For each diagnostic: read `code`, `from`, `to`, and `params`. Look up `code` in `RSErrorCode` (`error.ts`) and use `getRSErrorPrefix` if you need a display id.
128
- 4. Patch `definitionFormal` based on the range — never blindly retry without changing the input.
129
- 5. Re-send. Repeat until success.
130
- 6. Only then call `addOrUpdateConstituenta` to commit the constituent into the session.
1
+ # Диагностика
2
+
3
+ Читай, когда `analyzeExpression` или `addOrUpdateConstituenta` вернули `diagnostics`.
4
+
5
+ ## `DiagnosticRecord`
6
+
7
+ - `code` — числовой `RSErrorCode`.
8
+ - `params` — аргументы сообщения.
9
+ - `from`, `to` диапазон в `definitionFormal`.
10
+ - `constituentId` — есть в диагностике сессии из `listDiagnostics`.
11
+
12
+ Источник истины: `@rsconcept/domain/src/rslang/error.ts`. Для короткого вида UI/логов используй `getRSErrorPrefix(code)`.
13
+
14
+ ## Классы кодов
15
+
16
+ - `0x8400` parser: синтаксис и скобки.
17
+ - `0x8800`semantic: типизации, области видимости, структура.
18
+ - `0x8100`runtime/evaluation: вычисление модели.
19
+ - `0x2800`warning: обычно не блокирует выражение.
20
+ - `0x88Cx` — правила схемы и `cstType`.
21
+
22
+ ## Частые parser-коды
23
+
24
+ - `0x8400 unknownSyntax` неопределенная синтаксическая ошибка.
25
+ - `0x8406 missingParenthesis` не закрыты `(` `)`.
26
+ - `0x8407 missingCurlyBrace` не закрыты `{` `}`.
27
+ - `0x8408 missingSquareBracket` не закрыты `[` `]`.
28
+ - `0x8409 bracketMismatch` смешаны типы скобок.
29
+ - `0x840A doubleParenthesis` лишняя пара скобок.
30
+ - `0x840B missingOpenBracket` — закрывающая скобка без открывающей.
31
+ - `0x8415 expectedLocal` нужна локальная переменная.
32
+ - `0x8416 expectedType` — нужна явная ступень.
33
+
34
+ ## Локальные переменные
35
+
36
+ - `0x8801 localUndeclared` — свяжи переменную квантором или параметром.
37
+ - `0x8802 localShadowing` переименуй внутреннюю переменную.
38
+ - `0x8815 localOutOfScope` перенеси использование внутрь области видимости.
39
+ - `0x2801 localDoubleDeclare` warning; объявление задублировано.
40
+ - `0x2802 localNotUsed` warning; переменная не используется.
41
+
42
+ ## Типизации и структура
43
+
44
+ - `0x8803 typesNotEqual` / `0x8825 typesNotCompatible` операнды несовместимы.
45
+ - `0x8804 globalNotTyped` сначала добавь и проанализируй поставщика.
46
+ - `0x8805 invalidDecart`, `0x8806 invalidBoolean`, `0x8810 invalidReduce` неверная ступень для операции.
47
+ - `0x8808 invalidCard` `card(...)` не над множеством.
48
+ - `0x8809 invalidDebool` — нет гарантии синглетона.
49
+ - `0x880B globalFuncWithoutArgs` функция вызвана без `[]`.
50
+ - `0x8811 invalidProjectionTuple`, `0x8812 invalidProjectionSet` — неверная проекция.
51
+ - `0x8813 invalidEnumeration` элементы перечисления разных ступеней.
52
+ - `0x8816 invalidElementPredicate` S` с несовместимыми ступенями.
53
+ - `0x8818 invalidArgsArity`, `0x8819 invalidArgumentType` неверный вызов функции.
54
+ - `0x8821 radicalUsage` радикал вне домена параметра.
55
+ - `0x8822 invalidFilterArgumentType`, `0x8823 invalidFilterArity` неверный `Fi`.
56
+ - `0x8824 arithmeticNotSupported`, `0x8826 orderingNotSupported` нужна ступень `Z`.
57
+ - `0x8827 expectedLogic` нужна логическая формула.
58
+ - `0x8828 expectedSetexpr` — нужно теоретико-множественное выражение, а не логика.
59
+
60
+ ## Схема и вычисление
61
+
62
+ - `0x8861 cstEmptyDerived` у выводимой конституенты пустая формула.
63
+ - `0x8862 definitionNotAllowed` у `basic`/`constant` непустая формула.
64
+ - `0x8840 globalNoValue` / `0x8103 calcGlobalMissing` нет значения в модели.
65
+ - `0x8841 invalidPropertyUsage` `Property` использован как вычислимое значение.
66
+ - `0x8101 setOverflow`, `0x8102 booleanBaseLimit`, `0x8104 iterationsLimit` выражение слишком дорого вычислять.
67
+ - `0x8105 calcInvalidDebool` `debool` получил не синглетон.
68
+ - `0x8106 iterateInfinity`, `0x8107 calculationNotSupported` конструкция не исполнима в конечной модели.
69
+
70
+ ## Типичные ошибки агентов
71
+
72
+ - Задавать значение `term`/`axiom`/`statement` напрямую.
73
+ - Писать формулу у `basic` или `constant`.
74
+ - Добавлять потребителя раньше поставщика.
75
+ - Давать логическое тело `term` или нелогическое тело `axiom`/`statement`.
76
+ - Использовать `R#` в теле результата.
77
+ - Вычислять производные понятия до привязки данных для базовых.
78
+
79
+ ## Цикл исправления
80
+
81
+ 1. Запусти `analyzeExpression`.
82
+ 2. Прочитай `code`, `from`, `to`, `params`.
83
+ 3. Исправь именно диапазон в `definitionFormal`.
84
+ 4. Не повторяй вызов без изменения ввода.
85
+ 5. После успеха вызывай `addOrUpdateConstituenta`.
package/docs/DOMAIN.md CHANGED
@@ -1,91 +1,68 @@
1
- # Domain reference
2
-
3
- Compact English distillation of the canonical Russian domain glossary (`CONTEXT.md`). Read this first if you are an agent unfamiliar with the Concept Portal vocabulary.
4
-
5
- ## Core concepts
6
-
7
- - **Subject domain**a sphere of human activity that requires coordination and communication.
8
- - **Conceptual schema (`КС`)** — a formal system of definitions for a subject domain, made of constituents.
9
- - **Conceptual model (`РСМодель`)** — a pairing of a conceptual schema with an interpretation in concrete data.
10
- - **Operations Synthesis Schema (`ОСС`)** — a graph of load and synthesis operations that drives schema construction and evolution.
11
- - **RS language (`родоструктурная экспликация`)** — the formal genus-structure language used to define concepts, relations and operations inside a schema.
12
- - **Typification** the computable structural type of a constituent's formal definition; the formal constraint on admissible interpretations.
13
- - **Term graph**a directed dependency graph over constituents; an edge means "constituent A appears in constituent B's definition".
14
-
15
- ## Constituents
16
-
17
- A **constituent** is the atomic building block of a conceptual schema. Each constituent may carry a term, a convention, a typification, a formal definition, a textual interpretation, and a comment. By role, a constituent is either undefined, derived, or a statement.
18
-
19
- Constituent aliases follow a strict prefix scheme:
20
-
21
- | Alias prefix | Role | Notes |
22
- | ------------ | ---------------------------------------- | ----------------------------------------------------------------------------------------------- |
23
- | `N#` | Nominoid | Free vocabulary item, no formal definition |
24
- | `X#` | Base set | Undefined concept, set of elements |
25
- | `C#` | Constant set | Undefined concept, set of elements, allows arithmetic predicates and operations |
26
- | `S#` | Structured concept (**genus structure**) | Undefined concept; `definitionFormal` gives **typification**; meaning via `convention` / axioms |
27
- | `D#` | Term | Derived concept; `definitionFormal` is the **definition**; value computed in a model |
28
- | `F#` | Term-function | Parameterised derived concept yielding an STE |
29
- | `P#` | Predicate-function | Parameterised derived concept yielding a logical expression |
30
- | `A#` | Axiom | Logical statement asserting requirements |
31
- | `T#` | Statement | Logical assertion about the model |
32
- | `R#` | Radical | Template placeholder for arbitrary typification |
33
-
34
- **Undefined concepts** (`X#`, `C#`, `S#`) are introduced by conventions (and optional axioms). For `S#`, the formal field states **typification** (the grade of elements), not a defining construction. **Derived concepts** (`D#`, `F#`, `P#`, `A#`, `T#`) carry a formal **definition** and must follow declaration order — every referenced constituent must already exist; their model values are obtained by evaluation.
35
-
36
- **Structure vs term:** `S#` with `ℬ(X1×X1)` declares “elements are pairs over `X1`”; the actual pairs come from interpretation. `D#` with `X1×X1` as the whole expression denotes the **full Cartesian product** (all pairs), which is a computed set use `S#` + projections when modeling a relation.
37
-
38
- A **crucial constituent** is marked as content-bearing for filtering / focus; it has no semantic effect on the formal calculus.
39
-
40
- ## Statuses
41
-
42
- Each constituent has one of the following correctness statuses:
43
-
44
- | Status | Meaning |
45
- | ------------ | ------------------------------------------------------------------ |
46
- | Unknown | Not yet validated |
47
- | OK | Validated as correct |
48
- | Error | Validation failed |
49
- | Property | Defines a non-computable set; only membership tests are admissible |
50
- | Incalculable | Cannot be evaluated directly (e.g. expected exponential blow-up) |
51
-
52
- ## RSModel evaluation states
53
-
54
- In a conceptual model each item has one of the following evaluation statuses:
55
-
56
- | Status | Meaning |
57
- | ------------------- | ----------------------------------------------- |
58
- | `NO_EVAL` (1) | Not evaluated (definition is not interpretable) |
59
- | `NOT_PROCESSED` (2) | Interpretation has not been computed yet |
60
- | `INVALID_DATA` (3) | Provided data is invalid |
61
- | `EVAL_FAIL` (4) | Evaluation raised an error |
62
- | `AXIOM_FALSE` (5) | Axiom evaluated to FALSE |
63
- | `EMPTY` (6) | Result is the empty set |
64
- | `HAS_DATA` (7) | Interpretation computed and non-empty |
65
-
66
- ## Synthesis and OSS
67
-
68
- - **Load operation** attaches an existing schema to the OSS graph.
69
- - **Synthesis operation** combines operand schemas via an **identification table** (pairs of constituents to be treated as equivalent) and produces a result schema with **inherited constituents**.
70
- - **Cross-cutting changes** propagate edits from a **source constituent** to its **inherited constituents** through the OSS. Inherited constituents are not edited directly.
71
- - **Diamond synthesis** uses operand schemas with shared ancestors.
72
- - **Concept block** is a nominal grouping of schemas inside the OSS.
73
-
74
- ## Relationships
75
-
76
- - A conceptual schema **contains** many constituents.
77
- - A conceptual model **interprets** exactly one schema at a given state.
78
- - An OSS **contains** load and synthesis operations.
79
- - A synthesis operation **consumes** one or more input schemas plus an identification table and **produces** a result schema with inherited constituents.
80
- - Cross-cutting changes **propagate** from a source constituent to its inherited descendants.
81
- - The term graph is **derived** from the formal definitions of constituents.
82
-
83
- ## Dependency vocabulary
84
-
85
- - **Consumers** — constituents that mention this one in their definitions.
86
- - **Suppliers** — constituents this one mentions in its definition.
87
- - **Dependents** — direct and transitive consumers.
88
- - **Influencers** — direct and transitive suppliers.
89
- - **Generating expression** — a definition referencing a single external constituent with no added content.
90
- - **Base concept (for generation)** — the constituent on which a generating expression is built.
91
- - **Generated concept** — a constituent produced from a generating expression.
1
+ # Доменная справка
2
+
3
+ Термины, используемые в Concept Portal.
4
+
5
+ ## Основные термины
6
+
7
+ - **Предметная область**область, для которой строится система определений.
8
+ - **Концептуальная схема (`КС`)** — система понятий, утверждений и связей между ними.
9
+ - **Концептуальная модель (`КМ`)** — КС плюс интерпретация ее понятий на конечных данных.
10
+ - **Операционная схема синтеза (`ОСС`)** — граф загрузок и синтезов КС.
11
+ - **Родоструктурная экспликация (`RSLang`)** — формальный язык для понятий, отношений, операций и утверждений.
12
+ - **Типизация / ступень** структура значений выражения: элемент, целое, кортеж, множество, `Logic`.
13
+ - **Граф термов**зависимости: конституента ссылается на другую в формальном определении.
14
+
15
+ ## Конституенты
16
+
17
+ **Конституента** часть КС. Главное для агента: `alias`, `cstType`, `definitionFormal`, `term`, `definitionText`, `convention`. `comment` комментарий и пояснения разработчика схемы, полезно для контекста.
18
+
19
+ - `N#` **номиноид**: словарная сущность. В родоструктурной экспликации не используется.
20
+ - `X#` — **базисное множество**: неопределяемое понятие, формула пустая.
21
+ - `C#` **константное множество**: неопределяемое множество для арифметики и порядка, формула пустая.
22
+ - `S#` **родовая структура**: неопределяемое структурное понятие; формула задает типизацию.
23
+ - `D#` **терм**: определяемое понятие; формула вычисляет значение.
24
+ - `F#` **терм-функция**: параметризованный терм.
25
+ - `P#` **предикат-функция**: параметризованное логическое выражение.
26
+ - `A#` **аксиома**: логическое требование к модели.
27
+ - `T#` **высказывание**: логическое утверждение о модели.
28
+ - `R#` **радикал**: шаблонная ступень в параметрах.
29
+
30
+ Правило: `X#`, `C#`, `S#` задаются конвенцией и интерпретацией; `D#`, `F#`, `P#`, `A#`, `T#` выводятся по формуле. Поставщики должны идти раньше потребителей.
31
+
32
+ Не путай `S#` и `D#`: `S1: ℬ(X1×X1)` интерпретируемое отношение из пар; `D1 := X1×X1` — декартово произведение.
33
+
34
+ ## Статусы выражений
35
+
36
+ - `Unknown` — не проверено.
37
+ - `OK` — корректно.
38
+ - `Error` ошибка в определении.
39
+ - `Property` — неразмерное: доступна только проверка принадлежности.
40
+ - `Incalculable` — невычислимо напрямую.
41
+
42
+ ## Статусы вычисления в модели
43
+
44
+ - `NO_EVAL` — нечего вычислять.
45
+ - `NOT_PROCESSED` вычисление не запускалось.
46
+ - `INVALID_DATA` неверная интерпретация.
47
+ - `EVAL_FAIL` ошибка вычисления.
48
+ - `AXIOM_FALSE` аксиома ложна.
49
+ - `EMPTY` результат пуст.
50
+ - `HAS_DATA` результат вычислен и непустой.
51
+
52
+ ## Зависимости
53
+
54
+ - **Поставщики** конституенты, на которые ссылается текущая.
55
+ - **Потребители** — конституенты, которые ссылаются на текущую.
56
+ - **Влияющие** — прямые и транзитивные поставщики.
57
+ - **Зависимые** прямые и транзитивные потребители.
58
+ - **Основание** конституента, из которой формально порождают новые термы.
59
+ - **Порожденная конституента** построена из основания без новой предметной договоренности.
60
+
61
+ ## ОСС и синтез
62
+
63
+ - **Загрузка** добавляет внешнюю или собственную КС в ОСС.
64
+ - **Синтез** строит новую КС из операций-аргументов через таблицу отождествлений.
65
+ - **Наследованные конституенты** пришли из исходных схем; их определения обычно read-only.
66
+ - **Сквозные изменения** идут от исходной конституенты к наследникам.
67
+ - **Ромбовидный синтез** использует КС с общими предками; чаще требует ручного отождествления дублей.
68
+ - **Концептуальный блок** группа схем внутри предметной области.
@@ -1,98 +1,47 @@
1
- # Grammar reference (pointers)
1
+ # Грамматика: короткая карта
2
2
 
3
- Below is a compact token map agents can use without opening the grammar. For full grammar see `@rsconcept/domain` package.
3
+ Этого обычно достаточно агенту. Полная грамматика живет в `@rsconcept/domain`.
4
4
 
5
- ## Token classes
5
+ ## Токены
6
6
 
7
- | Class | Tokens / examples |
8
- | --------------- | ---------------------------------------------------------- |
9
- | Whitespace | space, tab, newline |
10
- | Integer literal | `0`, `42` |
11
- | Empty set | `∅` |
12
- | Integer set | `Z` |
13
- | Globals | `X#`, `C#`, `S#`, `D#`, `F#`, `P#`, `A#`, `T#`, `N#`, `R#` |
14
- | Locals | `x`, `ξ`, `μ2`, `y1` |
15
- | Punctuation | `(`, `)`, `[`, `]`, `{`, `}`, `,`, `;` |
16
- | Comment | none — RSLang has no comments inside formal expressions |
7
+ - Литералы: `0`, `42`, `Z`, `∅`.
8
+ - Алиасы: `X#`, `C#`, `S#`, `D#`, `F#`, `P#`, `A#`, `T#`, `R#`.
9
+ - Локальные переменные: `x`, `ξ`, `μ2`, `y1`.
10
+ - Скобки и разделители: `()`, `[]`, `{}`, `,`, `;`.
11
+ - Комментариев в формальных выражениях нет.
17
12
 
18
- ## Set / structural operators
13
+ ## Операторы
19
14
 
20
- | Token | Symbol |
21
- | -------------------- | -------------------------- |
22
- | Union | `∪` |
23
- | Intersection | `∩` |
24
- | Difference | `\` |
25
- | Symmetric difference | `∆` |
26
- | Cartesian product | `×` |
27
- | Boolean | `ℬ` |
28
- | Sum set | `red` |
29
- | Singleton | `bool` |
30
- | Desingleton | `debool` |
31
- | Small projection | `pr1`, `pr1,3`, … |
32
- | Large projection | `Pr1`, `Pr2,4`, … |
33
- | Filter | `Fi1[D](S)`, `Fi1,2[D](S)` |
34
- | Cardinality | `card` |
15
+ - Множества: `∪`, `∩`, `\`, `∆`, `×`, `ℬ`.
16
+ - Структуры: `red`, `bool`, `debool`, `pr1`, `Pr1`, `Fi1[D](S)`, `card`.
17
+ - Предикаты: `∈`, `∉`, `⊆`, `⊂`, `⊄`, `=`, `≠`, `<`, `≤`, `>`, `≥`.
18
+ - Связки: `¬`, `&`, `∨`, `⇒`, `⇔`.
19
+ - Кванторы: `∀`, `∃`.
35
20
 
36
- ## Predicates
21
+ Мультииндексы парсятся как список натуральных чисел: `pr1,3`, `Pr2,4`, `Fi1,2[D](S)`.
37
22
 
38
- | Token | Symbol |
39
- | ---------------- | ------ |
40
- | Membership | `∈` |
41
- | Non-membership | `∉` |
42
- | Inclusion | `⊆` |
43
- | Strict inclusion | `⊂` |
44
- | Non-inclusion | `⊄` |
45
- | Equality | `=` |
46
- | Inequality | `≠` |
47
- | Less | `<` |
48
- | Less-or-equal | `≤` |
49
- | Greater | `>` |
50
- | Greater-or-equal | `≥` |
23
+ ## Декларации
51
24
 
52
- ## Logical connectives
25
+ - Терм-функция: `F# ::= [<params>] <body STE>`.
26
+ - Предикат-функция: `P# ::= [<params>] <body LE>`.
27
+ - Параметр: `α ∈ <STE>`.
28
+ - Вызов: `F#[<arg1>, <arg2>]`.
53
29
 
54
- | Token | Symbol |
55
- | ----------- | ------ |
56
- | Negation | `¬` |
57
- | Conjunction | `&` |
58
- | Disjunction | `∨` |
59
- | Implication | `⇒` |
60
- | Equivalence | `⇔` |
30
+ ## Приоритеты
61
31
 
62
- ## Quantifiers
32
+ 1. Вызовы функций, проекции, `ℬ`, `bool`, `debool`, `red`, `card`.
33
+ 2. `×`.
34
+ 3. `*`.
35
+ 4. `+`, `-`.
36
+ 5. `∪`, `∩`, `\`, `∆`.
37
+ 6. Предикаты: `∈`, `=`, `<`, ...
38
+ 7. `¬`.
39
+ 8. `&`.
40
+ 9. `∨`.
41
+ 10. `⇒`.
42
+ 11. `⇔`.
63
43
 
64
- | Token | Symbol |
65
- | ----------- | ------ |
66
- | Universal | `∀` |
67
- | Existential | `∃` |
44
+ ## Когда читать исходники
68
45
 
69
- ## Declarators
70
-
71
- | Token | Form |
72
- | --------------------- | ------------------------------------------------- |
73
- | Function declaration | `F# ::= [<params>] <body STE>` |
74
- | Predicate declaration | `P# ::= [<params>] <body LE>` |
75
- | Parameter declaration | `α ∈ <STE>` (commas separate; commas inside `[]`) |
76
- | Function call | `F#[<arg1>, <arg2>, …]` |
77
-
78
- ## Precedence (from highest to lowest)
79
-
80
- 1. Function calls, projections, boolean
81
- 2. Cartesian product `×`
82
- 3. Multiplicative `*`
83
- 4. Additive `+`, `-`
84
- 5. Set operators `∪`, `∩`, `\`, `∆`
85
- 6. Predicates (`∈`, `=`, `<`, …)
86
- 7. Negation `¬`
87
- 8. Conjunction `&`
88
- 9. Disjunction `∨`
89
- 10. Implication `⇒`
90
- 11. Equivalence `⇔`
91
-
92
- Multi-index tokens inside projections / filters are parsed as a comma-separated list of natural numbers.
93
-
94
- ## When to consult the full grammar
95
-
96
- - Grammar conflicts or surprising error positions — read `rslang.grammar` directly.
97
- - Adding new operators or precedence rules — must be done in the domain package, not in rstool.
98
- - Lezer terms / token IDs — see `@rsconcept/domain/src/rslang/parser/token.ts` and `parser.terms.ts`.
46
+ - Позиция ошибки неожиданная.
47
+ - Нужны Lezer terms/token IDs: `@rsconcept/domain/src/rslang/parser/token.ts`, `parser.terms.ts`.
@@ -0,0 +1,57 @@
1
+ # Тестирование определений через концептуальную модель
2
+
3
+ Концептуальная модель (`КМ`) полезна как маленький стенд для проверки семантики выражений. Если агент не уверен, что формула означает именно нужную операцию, не угадывай по виду выражения: создай минимальную схему, задай тестовые значения для неопределяемых конституент и вычисли результат.
4
+
5
+ ## Когда использовать
6
+
7
+ - Неочевидны `S#` против `D#`, проекции `Pr*` / `pr*`, фильтры `Fi*`, `red`, `bool`, `debool`.
8
+ - Формула синтаксически корректна, но есть сомнение в семантике результата.
9
+ - Нужно проверить, что аксиома действительно ловит ошибочные данные.
10
+ - Пользователь просит надежно изменить важное определение, а пример данных можно сделать маленьким.
11
+
12
+ Для простой проверки типизации сначала используй `analyzeExpression`. КМ нужна, когда вопрос зависит от интерпретации данных и вычисленного значения.
13
+
14
+ ## Минимальный цикл
15
+
16
+ 1. Создай отдельную `createSession` или изолированную копию текущей сессии.
17
+ 2. Добавь только нужные поставщики: `X#`, `C#`, `S#` и проверяемые `D#` / `F#` / `P#` / `A#`.
18
+ 3. Проверь формулы через `analyzeExpression` и `addOrUpdateConstituenta`.
19
+ 4. Задай значения базисов и структур через `setConstituentaValue` или `setConstituentaValues`.
20
+ 5. Вычисли проверяемую формулу через `evaluateExpression` или сохраненную конституенту через `evaluateConstituenta`.
21
+ 6. Сравни результат с ожидаемым значением; если есть несколько зависимых определений, запусти `recalculateModel`.
22
+
23
+ ## Что задавать руками
24
+
25
+ `basic`, `constant`, `structure` можно интерпретировать напрямую. `term`, `function`, `predicate`, `axiom`, `statement` должны вычисляться из формулы, поэтому их напрямую не задавай.
26
+
27
+ Пример формы данных:
28
+
29
+ ```ts
30
+ const TUPLE_ID = -111;
31
+
32
+ tool.setConstituentaValues(sessionId, {
33
+ items: [
34
+ { target: 1, value: { 0: 'ann', 1: 'bob', 2: 'cat' } },
35
+ { target: 2, value: [[TUPLE_ID, 0, 1], [TUPLE_ID, 0, 2]] }
36
+ ]
37
+ });
38
+ ```
39
+
40
+ Здесь `X1` получает подписи элементов, а `S1: ℬ(X1×X1)` получает множество пар по индексам элементов `X1`.
41
+
42
+ ## Скрипты-тесты
43
+
44
+ Если проверка влияет на поведение схемы или есть риск регрессии, вынеси ее в маленький скрипт или colocated `*.test.ts`:
45
+
46
+ 1. Собери минимальную сессию с нужными конституентами.
47
+ 2. Задай тестовые значения неопределяемых конституент.
48
+ 3. Вычисли целевые конституенты.
49
+ 4. Проверь `success`, `status`, `diagnostics.length` и само `value`.
50
+
51
+ Тест должен проверять смысл формулы, а не только отсутствие диагностик. Для аксиом отдельно проверяй положительный и отрицательный набор данных: корректная модель должна давать истинную аксиому, ошибочная — `AXIOM_FALSE` или диагностируемый сбой вычисления.
52
+
53
+ ## Ограничения
54
+
55
+ - Маленькая КМ проверяет семантику на выбранных данных, но не доказывает определение для всех моделей.
56
+ - Не подменяй предметное соглашение тестом: если смысл `S#` не ясен, уточни `convention` или спроси пользователя.
57
+ - Не добавляй искусственные конституенты в рабочую схему только ради теста. Держи scratch-сессию или тестовый скрипт отдельно.