rei-lang 0.5.0 → 0.5.2

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.
package/README.md CHANGED
@@ -1,451 +1,499 @@
1
- # Rei (0₀式) — D-FUMT Computational Language
2
-
3
- [![npm version](https://img.shields.io/npm/v/rei-lang)](https://www.npmjs.com/package/rei-lang)
4
- [![License: Apache 2.0](https://img.shields.io/badge/License-Apache_2.0-gold.svg)](./LICENSE)
5
- [![Tests](https://img.shields.io/badge/tests-721%2F721-brightgreen)]()
6
-
7
- **Rei** (0₀式 / れいしき) is a mathematical computation language based on **D-FUMT** (Dimensional Fujimoto Universal Mathematical Theory). Its center-periphery patterns as language primitives achieve an **average 74% code reduction** over equivalent implementations in general-purpose languages.
8
-
9
- **Author:** Nobuki Fujimoto
10
-
11
- ---
12
-
13
- ## What's New in v0.5
14
-
15
- v0.5 introduces a **self-organizing agent runtime** — entities perceive, decide, and act autonomously, coordinated by a conflict-resolving mediator.
16
-
17
- - **EventBus**Type-safe event-driven architecture with flow momentum tracking
18
- - **Entity Agent** — Six-attribute autonomous agents (perceive → decide → act cycle)
19
- - **Mediator**Concurrent execution engine with conflict detection and resolution strategies
20
-
21
- ---
22
-
23
- ## Install
24
-
25
- ```bash
26
- npm install rei-lang
27
- ```
28
-
29
- ## Quick Start
30
-
31
- ### As a Library
32
-
33
- ```typescript
34
- import { rei } from 'rei-lang';
35
-
36
- // Multi-dimensional number computation
37
- rei('let field = 𝕄{5; 1, 2, 3, 4}');
38
- const result = rei('field |> compute :weighted');
39
- console.log(result); // 7.5
40
-
41
- // Define functions with compress
42
- rei('compress energy(m) = m |> compute :weighted');
43
- rei('let e = energy(𝕄{0; 10, 20, 30})');
44
- console.log(rei('e')); // 20
45
-
46
- // Genesis axiom system
47
- rei('let g = genesis()');
48
- rei('g |> forward');
49
- rei('g |> forward');
50
- console.log(rei('g.state')); // "line"
51
-
52
- // Reset state between sessions
53
- rei.reset();
54
- ```
55
-
56
- ### Interactive REPL
57
-
58
- ```bash
59
- npx rei
60
- ```
61
-
62
- ```
63
- ╔══════════════════════════════════════════╗
64
- ║ Rei (0₀式) REPL v0.5.0 ║
65
- ║ D-FUMT Computational Language ║
66
- ╚══════════════════════════════════════════╝
67
-
68
- 零 > 𝕄{5; 1, 2, 3, 4} |> compute :weighted
69
- 7.5
70
-
71
- > compress karma(i, e, r) = i * e * r
72
- compress karma(i, e, r)
73
-
74
- > karma(0.8, 0.9, 0.7)
75
- 0.504
76
- ```
77
-
78
- ### Execute a File
79
-
80
- ```bash
81
- npx rei program.rei
82
- ```
83
-
84
- ---
85
-
86
- ## Language Features
87
-
88
- ### Multi-Dimensional Numbers (𝕄)
89
-
90
- The core data structure. A center value with peripheral neighbors, computed in 4 modes:
91
-
92
- ```rei
93
- let m = 𝕄{5; 1, 2, 3, 4}
94
-
95
- m |> compute :weighted // center + weighted avg of neighbors
96
- m |> compute :multiplicative // center × Π(1 + nᵢ)
97
- m |> compute :harmonic // center + n / Σ(1/|nᵢ|)
98
- m |> compute :exponential // center × avg(e^nᵢ)
99
- ```
100
-
101
- ### Extended Numbers (拡張数)
102
-
103
- Numbers with subscript-based dimensional extension:
104
-
105
- ```rei
106
- let a = 0ooo // 3rd-order extension of zero
107
- a >> :x >> :x // extend: order 3 → 5
108
- a << // reduce: order 3 → 2
109
- a |> valStar // numeric projection: 0.001
110
-
111
- πooo // π extended to 3rd order
112
- 0₀ // D-FUMT zero symbol
113
- ```
114
-
115
- ### Compress (関数定義)
116
-
117
- Functions are defined with `compress` — reflecting D-FUMT's compression philosophy:
118
-
119
- ```rei
120
- compress distance(x, y) = sqrt(x * x + y * y)
121
- compress field(c, r) = 𝕄{c; r, r, r, r}
122
-
123
- distance(3, 4) // 5
124
- field(10, 2) |> compute :weighted // 12
125
- ```
126
-
127
- ### Pipe Operator (|>)
128
-
129
- Center-to-periphery data flow:
130
-
131
- ```rei
132
- -25 |> abs |> sqrt // 5
133
- [3, 1, 2] |> sort |> reverse // [3, 2, 1]
134
- "hello" |> upper // "HELLO"
135
- 𝕄{0; 1, 2, 3} |> normalize // normalized neighbors
136
- ```
137
-
138
- ### Genesis Axiom System (生成公理系)
139
-
140
- Models computational emergence from void:
141
-
142
- ```rei
143
- let g = genesis() // void
144
- g |> forward // void dot
145
- g |> forward // dot line
146
- g |> forward // line surface
147
- g |> forward // surface → solid
148
- g |> forward // solid → omega (Ω)
149
- g.omega // 1
150
- ```
151
-
152
- ### Four-Valued Logic (四価0π)
153
-
154
- Beyond true/false based on D-FUMT Theory #21:
155
-
156
- ```rei
157
- // true
158
- ⊥ // false
159
- ⊤π // true-pi (π-rotated truth)
160
- ⊥π // false-pi
161
-
162
- ¬⊤ // ⊥
163
- ⊥ // ⊥
164
- ⊥ ∨ ⊤ // ⊤
165
- ```
166
-
167
- ---
168
-
169
- ## v0.5 Agent Runtime
170
-
171
- ### EventBus (イベントバス)
172
-
173
- Type-safe event system with flow momentum tracking. Events follow a `category:action` pattern (e.g., `entity:fuse`, `agent:act`, `space:diffuse`).
174
-
175
- ```typescript
176
- import { rei, ReiEventBus } from 'rei-lang';
177
-
178
- // Access via Evaluator
179
- const ev = rei.evaluator();
180
- const bus = ev.eventBus;
181
-
182
- // Subscribe to events
183
- bus.on('entity:fuse', (event) => {
184
- console.log('Fusion occurred:', event.data);
185
- });
186
-
187
- // Subscribe with filter
188
- bus.subscribe(
189
- (e) => e.category === 'agent',
190
- (e) => console.log(`Agent ${e.data.agentId}: ${e.action}`)
191
- );
192
- ```
193
-
194
- In Rei syntax with pipe commands:
195
-
196
- ```rei
197
- // Emit a custom event
198
- "mySource" |> emit("entity:transform", "data")
199
-
200
- // Subscribe to events
201
- "entity:*" |> subscribe
202
-
203
- // Check flow momentum state
204
- 0 |> flow_momentum // → { state: "expanding", rate: 12.5, ... }
205
- ```
206
-
207
- ### Entity Agent (自律エンティティ)
208
-
209
- Entities in Rei are autonomous agents with the six D-FUMT attributes (場・流れ・記憶・層・関係・意志), executing a perceive → decide → act lifecycle.
210
-
211
- ```rei
212
- // Spawn an agent from a value
213
- let a = 𝕄{10; 1, 2, 3} |> spawn
214
-
215
- // Agent lifecycle
216
- a |> perceive // observe environment → Perception
217
- a |> decide // choose action → Decision
218
- a |> act // execute decision → ActionResult
219
-
220
- // Agent introspection
221
- a |> agent_sigma // σ metadata: state, step, memory, bindings
222
- a |> 自律σ // 日本語版
223
-
224
- // Agent behaviors: reactive / proactive / cooperative / competitive / contemplative
225
- ```
226
-
227
- ```typescript
228
- // Programmatic API
229
- import { ReiAgent, AgentRegistry } from 'rei-lang';
230
-
231
- const registry = new AgentRegistry();
232
- const agent = registry.spawn(42, {
233
- behavior: 'cooperative',
234
- autonomyLevel: 0.8,
235
- });
236
-
237
- const perception = agent.perceive(registry);
238
- const decision = agent.decide(perception);
239
- const result = agent.act(registry, decision);
240
- ```
241
-
242
- ### Mediator (調停エンジン)
243
-
244
- The Mediator coordinates multiple agents running concurrently, detecting and resolving conflicts with configurable strategies.
245
-
246
- ```rei
247
- // Concurrent execution — all agents perceive → decide → resolve conflicts → act
248
- 0 |> mediate // 1 round of concurrent execution
249
- 0 |> mediate(5) // 5 rounds with convergence detection
250
- 0 |> mediate(10, 0.8) // max 10 rounds, convergence threshold 0.8
251
-
252
- // Strategies: priority / cooperative / sequential / cancel_both / mediator
253
- 0 |> mediate_strategy("cooperative") // 協調 — merge conflicting intentions
254
- 0 |> 調停戦略("協調") // 日本語版
255
-
256
- // Inter-agent messaging
257
- "agent_a" |> mediate_message("agent_b", "hello") // point-to-point
258
- "agent_a" |> mediate_broadcast("共有データ") // broadcast to all
259
-
260
- // Mediator σ statistics and convergence history
261
- 0 |> mediator_sigma // { totalRounds, conflicts, convergenceHistory, ... }
262
- 0 |> 調停σ // 日本語版
263
- ```
264
-
265
- Conflict types detected automatically: **target contention** (same target), **resource conflict** (shared resource), **mutual fuse** (A↔B fusion), **contradictory** (fuse vs separate).
266
-
267
- Resolution strategies:
268
-
269
- | Strategy | Japanese | Behavior |
270
- |----------|----------|----------|
271
- | `priority` | 優先 | Highest confidence × priority wins |
272
- | `cooperative` | 協調 | Merge intentions into compromise |
273
- | `sequential` | 順次 | Execute in priority order |
274
- | `cancel_both` | 両方取消 | Cancel conflicting actions |
275
- | `mediator` | 調停者 | Mediator's own judgment (中道) |
276
-
277
- ```typescript
278
- // Programmatic API
279
- import { ReiMediator, AgentRegistry } from 'rei-lang';
280
-
281
- const registry = new AgentRegistry();
282
- const mediator = new ReiMediator(registry);
283
-
284
- // Spawn agents
285
- registry.spawn(10, { behavior: 'cooperative' });
286
- registry.spawn(20, { behavior: 'competitive' });
287
-
288
- // Run concurrent rounds with convergence detection
289
- const result = mediator.run({
290
- maxRounds: 10,
291
- convergenceThreshold: 0.8,
292
- });
293
- console.log(result.converged, result.totalRounds);
294
- ```
295
-
296
- ---
297
-
298
- ## Six Attributes (六属性)
299
-
300
- Every entity in Rei carries six attributes from D-FUMT theory:
301
-
302
- | Attribute | Japanese | Role |
303
- |-----------|----------|------|
304
- | Field (場) | ば | Spatial context and neighbors |
305
- | Flow (流れ) | ながれ | Temporal momentum and EventBus connection |
306
- | Memory (記憶) | きおく | History of observations and actions |
307
- | Layer (層) | そう | Hierarchical depth and nesting |
308
- | Relation (関係) | かんけい | Bindings between entities |
309
- | Will (意志) | いし | Intention-driven computation strategy |
310
-
311
- ```rei
312
- // Relation binding
313
- let x = 42
314
- let y = 100
315
- x |> bind(y, "collaborator") // create a relation
316
-
317
- // Will-driven computation
318
- let m = 𝕄{5; 1, 2, 3}
319
- m |> intend("maximize") // set intention
320
- m |> will_compute // compute guided by will
321
- ```
322
-
323
- ---
324
-
325
- ## RCT Compression (Rei Compression Theory)
326
-
327
- D-FUMT Theory #67 generative compression outperforming gzip on structured data:
328
-
329
- ```rei
330
- // Core compression (Direction 1-2)
331
- let data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
332
- data |> compress // compact θ representation
333
- data |> compress |> decompress // → lossless round-trip
334
-
335
- // Semantic compression (Direction 3)
336
- "let x = 𝕄{5; 1, 2, 3}" |> semantic_compress // → θ parameters
337
- "let x = 𝕄{5; 1, 2, 3}" |> 意味圧縮 // 日本語版
338
- ```
339
-
340
- ---
341
-
342
- ## Benchmarks
343
-
344
- | Task | Conventional | Rei | Reduction |
345
- |------|-------------|-----|-----------|
346
- | Image kernel calculations | 32 lines | 8 lines | **4×** |
347
- | Multi-dimensional data aggregation | 45 lines | 12 lines | **3.7×** |
348
- | Graph structure transformation | 52 lines | 14 lines | **3.7×** |
349
- | **Average** | | | **74%** |
350
-
351
- ---
352
-
353
- ## API Reference
354
-
355
- ### `rei(code: string): ReiValue`
356
-
357
- Evaluate a string of Rei code. State persists across calls.
358
-
359
- ### `rei.reset(): void`
360
-
361
- Clear all variable and function bindings.
362
-
363
- ### `rei.evaluator(): Evaluator`
364
-
365
- Access the underlying Evaluator instance (for EventBus, AgentRegistry, etc.).
366
-
367
- ### Classes
368
-
369
- | Class | Description |
370
- |-------|-------------|
371
- | `Lexer` | Tokenizer |
372
- | `Parser` | Recursive descent parser |
373
- | `Evaluator` | AST evaluator with environment/scope chain |
374
- | `ReiEventBus` | Type-safe event system with flow momentum |
375
- | `ReiAgent` | Autonomous entity with six attributes |
376
- | `AgentRegistry` | Agent lifecycle management |
377
- | `ReiMediator` | Concurrent execution engine with conflict resolution |
378
-
379
- ### Types
380
-
381
- | Type | Shape |
382
- |------|-------|
383
- | `MultiDimNumber` | `{ center, neighbors, mode, weights? }` |
384
- | `ReiExtended` | `{ base, order, subscripts, valStar() }` |
385
- | `GenesisState` | `{ state, omega, history }` |
386
- | `ReiFunction` | `{ name, params, body, closure }` |
387
- | `Quad` | `{ value: 'top' \| 'bottom' \| 'topPi' \| 'bottomPi' }` |
388
- | `ReiEvent` | `{ type, category, action, timestamp, data, source?, depth }` |
389
- | `AgentSigma` | `{ state, kind, behavior, step, perception, decisions, memory }` |
390
- | `MediatorSigma` | `{ totalRounds, conflicts, convergenceHistory, agentCount }` |
391
-
392
- ---
393
-
394
- ## Bilingual Pipe Commands (日本語対応)
395
-
396
- All pipe commands have Japanese aliases:
397
-
398
- | English | 日本語 | Description |
399
- |---------|--------|-------------|
400
- | `spawn` | `生成` | Create agent from value |
401
- | `perceive` | `知覚` | Agent observes environment |
402
- | `decide` | `判断` | Agent chooses action |
403
- | `act` | `行動` | Agent executes decision |
404
- | `agent_sigma` | `自律σ` | Agent metadata |
405
- | `mediate` | `調停` | Concurrent round execution |
406
- | `mediate_run` | `調停実行` | Multi-round execution |
407
- | `mediator_sigma` | `調停σ` | Mediator statistics |
408
- | `mediate_strategy` | `調停戦略` | Set conflict strategy |
409
- | `mediate_message` | `調停通信` | Point-to-point message |
410
- | `mediate_broadcast` | `調停放送` | Broadcast to all agents |
411
- | `emit` | `発火` | Emit event |
412
- | `subscribe` | `購読` | Subscribe to events |
413
- | `bind` | `結合` | Create relation binding |
414
- | `intend` | `意図` | Set entity intention |
415
- | `compress` | `圧縮` | RCT compression |
416
- | `decompress` | `復元` | RCT decompression |
417
-
418
- ---
419
-
420
- ## BNF Specification
421
-
422
- The complete BNF v0.3 specification is available in [`spec/`](./spec/).
423
-
424
- ---
425
-
426
- ## Theoretical Foundation
427
-
428
- Rei is grounded in **D-FUMT** (Dimensional Fujimoto Universal Mathematical Theory), a framework of 66 interconnected theories spanning pure mathematics to philosophy and AI consciousness. The language's core innovation — **center-periphery patterns as language primitives** — derives from D-FUMT's multi-dimensional number system theory.
429
-
430
- See [`theory/`](./theory/) for the complete theoretical documentation.
431
-
432
- ---
433
-
434
- ## ☮️ Peace Use Clause / 平和利用条項
435
-
436
- Rei is licensed under Apache 2.0 with an additional Peace Use Clause.
437
- Rei Apache 2.0 ライセンスに加え、平和利用条項が適用されます。
438
-
439
- Rooted in the Buddhist concept of "Kū" (空, Emptiness) and D-FUMT's consciousness mathematics, Rei is designed exclusively for the peaceful advancement of humanity. This software may not be used for:
440
- 仏教の「空」の概念と D-FUMT の意識数学に基づき、Rei は人類の平和的発展のためにのみ設計されています。以下の目的での使用は禁止されています:
441
-
442
- 🚫 Weapons, military systems, or LAWS / 兵器・軍事システム・自律型致死兵器
443
- 🚫 Human rights violations / 人権侵害
444
- 🚫 Intentional environmental destruction / 意図的な環境破壊
445
-
446
- Education, research, humanitarian aid, and creative endeavors are encouraged.
447
- ✅ 教育・研究・人道支援・創造的活動での使用を推奨します。
448
-
449
- See [PEACE_USE_CLAUSE.md](./PEACE_USE_CLAUSE.md) for full details.
450
-
451
- Apache 2.0 © Nobuki Fujimoto
1
+ # Rei (0₀式) — D-FUMT Computational Language
2
+
3
+ [![npm version](https://img.shields.io/npm/v/rei-lang)](https://www.npmjs.com/package/rei-lang)
4
+ [![License: Apache 2.0](https://img.shields.io/badge/License-Apache_2.0-gold.svg)](./LICENSE)
5
+ [![Tests](https://img.shields.io/badge/tests-799%2F799-brightgreen)]()
6
+
7
+ **Rei** (0₀式 / れいしき) is a mathematical computation language based on **D-FUMT** (Dimensional Fujimoto Universal Mathematical Theory). Its center-periphery patterns as language primitives achieve an **average 74% code reduction** over equivalent implementations in general-purpose languages.
8
+
9
+ **Author:** Nobuki Fujimoto
10
+
11
+ ---
12
+
13
+ ## What's New in v0.5.2 — Phase 4b/4c (Puzzle & Game Deepening)
14
+
15
+ ### Phase 4b: パズル推論深化
16
+ - **Hidden Single 検出** — 制約グループ内で唯一の候補位置を自動確定
17
+ - **Pointing Pair 検出** Box-Line Reduction による高度候補消去
18
+ - **推論層追跡 (ReasoningTrace)** — 各確定/消去ステップの推論層を記録
19
+ - **難易度分析 (DifficultyAnalysis)** — easy/medium/hard/expert の自動判定(スコア0-100)
20
+ - 新パイプ: `agent_difficulty` / `自律難易度`, `agent_trace` / `自律追跡`
21
+
22
+ ### Phase 4c: ゲーム推論深化
23
+ - **行動パターン分化** — reactive(防御的)/ proactive(攻撃的)/ contemplative(MC評価)/ competitive(minimax)
24
+ - **戦術パターン知覚** — threat, opportunity, fork, block, center, corner の自動検出
25
+ - **対局分析 (MatchAnalysis)** — プレイヤー別の手数・戦術パターン集計・サマリー生成
26
+ - 新パイプ: `agent_analyze` / `自律分析`
27
+
28
+ ```rei
29
+ // Phase 4b: パズル難易度分析
30
+ 30 |> generate_sudoku(42) |> agent_difficulty
31
+ // { level: "easy", score: 12, layersUsed: ["layer1_elimination"], ... }
32
+
33
+ // Phase 4c: 対局分析(reactive vs minimax)
34
+ "tic_tac_toe" |> game |> agent_analyze("reactive", "minimax")
35
+ // → { winner: 2, players: [{behavior: "reactive", ...}, {behavior: "competitive", ...}] }
36
+ ```
37
+
38
+ ## What's New in v0.5.1 AgentSpace (Phase 4a)
39
+
40
+ **Puzzles and games are the same abstraction.** AgentSpace unifies puzzle-solving and game-playing on the v0.5 agent runtime:
41
+
42
+ - **Puzzles** = cooperative multi-agent systems (all cells work toward a common goal)
43
+ - **Games** = competitive multi-agent systems (players have opposing objectives)
44
+
45
+ The only difference is agent `behavior` and mediator `strategy`.
46
+
47
+ ```rei
48
+ // Puzzle: Agent-based solving
49
+ 30 |> generate_sudoku(42) |> agent_solve // 81 cooperative agents solve sudoku
50
+ 30 |> 数独生成(42) |> 自律解法 // Japanese syntax
51
+
52
+ // Game: Agent-based play
53
+ game("tictactoe") |> agent_play("competitive", "cooperative")
54
+ game("tictactoe") |> agent_match // Full match to completion
55
+
56
+ // Unified observation
57
+ sudoku(grid) |> as_agent_space |> 調停σ // Same σ for both
58
+ game("tictactoe") |> as_agent_space |> 調停σ
59
+ ```
60
+
61
+ ### v0.5 Agent Runtime
62
+
63
+ v0.5 introduced a **self-organizing agent runtime** — entities perceive, decide, and act autonomously, coordinated by a conflict-resolving mediator.
64
+
65
+ - **EventBus** — Type-safe event-driven architecture with flow momentum tracking
66
+ - **Entity Agent** — Six-attribute autonomous agents (perceive → decide → act cycle)
67
+ - **Mediator** — Concurrent execution engine with conflict detection and resolution strategies
68
+
69
+ ---
70
+
71
+ ## Install
72
+
73
+ ```bash
74
+ npm install rei-lang
75
+ ```
76
+
77
+ ## Quick Start
78
+
79
+ ### As a Library
80
+
81
+ ```typescript
82
+ import { rei } from 'rei-lang';
83
+
84
+ // Multi-dimensional number computation
85
+ rei('let field = 𝕄{5; 1, 2, 3, 4}');
86
+ const result = rei('field |> compute :weighted');
87
+ console.log(result); // 7.5
88
+
89
+ // Define functions with compress
90
+ rei('compress energy(m) = m |> compute :weighted');
91
+ rei('let e = energy(𝕄{0; 10, 20, 30})');
92
+ console.log(rei('e')); // 20
93
+
94
+ // Genesis axiom system
95
+ rei('let g = genesis()');
96
+ rei('g |> forward');
97
+ rei('g |> forward');
98
+ console.log(rei('g.state')); // "line"
99
+
100
+ // Reset state between sessions
101
+ rei.reset();
102
+ ```
103
+
104
+ ### Interactive REPL
105
+
106
+ ```bash
107
+ npx rei
108
+ ```
109
+
110
+ ```
111
+ ╔══════════════════════════════════════════╗
112
+ ║ Rei (0₀式) REPL v0.5.0 ║
113
+ ║ D-FUMT Computational Language ║
114
+ ╚══════════════════════════════════════════╝
115
+
116
+ 零 > 𝕄{5; 1, 2, 3, 4} |> compute :weighted
117
+ 7.5
118
+
119
+ 零 > compress karma(i, e, r) = i * e * r
120
+ compress karma(i, e, r)
121
+
122
+ 零 > karma(0.8, 0.9, 0.7)
123
+ 0.504
124
+ ```
125
+
126
+ ### Execute a File
127
+
128
+ ```bash
129
+ npx rei program.rei
130
+ ```
131
+
132
+ ---
133
+
134
+ ## Language Features
135
+
136
+ ### Multi-Dimensional Numbers (𝕄)
137
+
138
+ The core data structure. A center value with peripheral neighbors, computed in 4 modes:
139
+
140
+ ```rei
141
+ let m = 𝕄{5; 1, 2, 3, 4}
142
+
143
+ m |> compute :weighted // center + weighted avg of neighbors
144
+ m |> compute :multiplicative // center × Π(1 + nᵢ)
145
+ m |> compute :harmonic // center + n / Σ(1/|nᵢ|)
146
+ m |> compute :exponential // center × avg(e^nᵢ)
147
+ ```
148
+
149
+ ### Extended Numbers (拡張数)
150
+
151
+ Numbers with subscript-based dimensional extension:
152
+
153
+ ```rei
154
+ let a = 0ooo // 3rd-order extension of zero
155
+ a >> :x >> :x // extend: order 3 → 5
156
+ a << // reduce: order 3 → 2
157
+ a |> valStar // numeric projection: 0.001
158
+
159
+ πooo // π extended to 3rd order
160
+ 0₀ // D-FUMT zero symbol
161
+ ```
162
+
163
+ ### Compress (関数定義)
164
+
165
+ Functions are defined with `compress` — reflecting D-FUMT's compression philosophy:
166
+
167
+ ```rei
168
+ compress distance(x, y) = sqrt(x * x + y * y)
169
+ compress field(c, r) = 𝕄{c; r, r, r, r}
170
+
171
+ distance(3, 4) // 5
172
+ field(10, 2) |> compute :weighted // 12
173
+ ```
174
+
175
+ ### Pipe Operator (|>)
176
+
177
+ Center-to-periphery data flow:
178
+
179
+ ```rei
180
+ -25 |> abs |> sqrt // 5
181
+ [3, 1, 2] |> sort |> reverse // [3, 2, 1]
182
+ "hello" |> upper // "HELLO"
183
+ 𝕄{0; 1, 2, 3} |> normalize // normalized neighbors
184
+ ```
185
+
186
+ ### Genesis Axiom System (生成公理系)
187
+
188
+ Models computational emergence from void:
189
+
190
+ ```rei
191
+ let g = genesis() // void
192
+ g |> forward // void → dot
193
+ g |> forward // dot → line
194
+ g |> forward // line surface
195
+ g |> forward // surface → solid
196
+ g |> forward // solid → omega (Ω)
197
+ g.omega // 1
198
+ ```
199
+
200
+ ### Four-Valued Logic (四価0π)
201
+
202
+ Beyond true/false — based on D-FUMT Theory #21:
203
+
204
+ ```rei
205
+ ⊤ // true
206
+ ⊥ // false
207
+ ⊤π // true-pi (π-rotated truth)
208
+ ⊥π // false-pi
209
+
210
+ ¬⊤ // ⊥
211
+ ⊤ ∧ ⊥ // ⊥
212
+ ⊤ //
213
+ ```
214
+
215
+ ---
216
+
217
+ ## v0.5 Agent Runtime
218
+
219
+ ### EventBus (イベントバス)
220
+
221
+ Type-safe event system with flow momentum tracking. Events follow a `category:action` pattern (e.g., `entity:fuse`, `agent:act`, `space:diffuse`).
222
+
223
+ ```typescript
224
+ import { rei, ReiEventBus } from 'rei-lang';
225
+
226
+ // Access via Evaluator
227
+ const ev = rei.evaluator();
228
+ const bus = ev.eventBus;
229
+
230
+ // Subscribe to events
231
+ bus.on('entity:fuse', (event) => {
232
+ console.log('Fusion occurred:', event.data);
233
+ });
234
+
235
+ // Subscribe with filter
236
+ bus.subscribe(
237
+ (e) => e.category === 'agent',
238
+ (e) => console.log(`Agent ${e.data.agentId}: ${e.action}`)
239
+ );
240
+ ```
241
+
242
+ In Rei syntax with pipe commands:
243
+
244
+ ```rei
245
+ // Emit a custom event
246
+ "mySource" |> emit("entity:transform", "data")
247
+
248
+ // Subscribe to events
249
+ "entity:*" |> subscribe
250
+
251
+ // Check flow momentum state
252
+ 0 |> flow_momentum // { state: "expanding", rate: 12.5, ... }
253
+ ```
254
+
255
+ ### Entity Agent (自律エンティティ)
256
+
257
+ Entities in Rei are autonomous agents with the six D-FUMT attributes (場・流れ・記憶・層・関係・意志), executing a perceive → decide → act lifecycle.
258
+
259
+ ```rei
260
+ // Spawn an agent from a value
261
+ let a = 𝕄{10; 1, 2, 3} |> spawn
262
+
263
+ // Agent lifecycle
264
+ a |> perceive // observe environment → Perception
265
+ a |> decide // choose action Decision
266
+ a |> act // execute decision → ActionResult
267
+
268
+ // Agent introspection
269
+ a |> agent_sigma // σ metadata: state, step, memory, bindings
270
+ a |> 自律σ // 日本語版
271
+
272
+ // Agent behaviors: reactive / proactive / cooperative / competitive / contemplative
273
+ ```
274
+
275
+ ```typescript
276
+ // Programmatic API
277
+ import { ReiAgent, AgentRegistry } from 'rei-lang';
278
+
279
+ const registry = new AgentRegistry();
280
+ const agent = registry.spawn(42, {
281
+ behavior: 'cooperative',
282
+ autonomyLevel: 0.8,
283
+ });
284
+
285
+ const perception = agent.perceive(registry);
286
+ const decision = agent.decide(perception);
287
+ const result = agent.act(registry, decision);
288
+ ```
289
+
290
+ ### Mediator (調停エンジン)
291
+
292
+ The Mediator coordinates multiple agents running concurrently, detecting and resolving conflicts with configurable strategies.
293
+
294
+ ```rei
295
+ // Concurrent execution — all agents perceive → decide → resolve conflicts → act
296
+ 0 |> mediate // 1 round of concurrent execution
297
+ 0 |> mediate(5) // 5 rounds with convergence detection
298
+ 0 |> mediate(10, 0.8) // max 10 rounds, convergence threshold 0.8
299
+
300
+ // Strategies: priority / cooperative / sequential / cancel_both / mediator
301
+ 0 |> mediate_strategy("cooperative") // 協調 — merge conflicting intentions
302
+ 0 |> 調停戦略("協調") // 日本語版
303
+
304
+ // Inter-agent messaging
305
+ "agent_a" |> mediate_message("agent_b", "hello") // point-to-point
306
+ "agent_a" |> mediate_broadcast("共有データ") // broadcast to all
307
+
308
+ // Mediator σ statistics and convergence history
309
+ 0 |> mediator_sigma // { totalRounds, conflicts, convergenceHistory, ... }
310
+ 0 |> 調停σ // 日本語版
311
+ ```
312
+
313
+ Conflict types detected automatically: **target contention** (same target), **resource conflict** (shared resource), **mutual fuse** (A↔B fusion), **contradictory** (fuse vs separate).
314
+
315
+ Resolution strategies:
316
+
317
+ | Strategy | Japanese | Behavior |
318
+ |----------|----------|----------|
319
+ | `priority` | 優先 | Highest confidence × priority wins |
320
+ | `cooperative` | 協調 | Merge intentions into compromise |
321
+ | `sequential` | 順次 | Execute in priority order |
322
+ | `cancel_both` | 両方取消 | Cancel conflicting actions |
323
+ | `mediator` | 調停者 | Mediator's own judgment (中道) |
324
+
325
+ ```typescript
326
+ // Programmatic API
327
+ import { ReiMediator, AgentRegistry } from 'rei-lang';
328
+
329
+ const registry = new AgentRegistry();
330
+ const mediator = new ReiMediator(registry);
331
+
332
+ // Spawn agents
333
+ registry.spawn(10, { behavior: 'cooperative' });
334
+ registry.spawn(20, { behavior: 'competitive' });
335
+
336
+ // Run concurrent rounds with convergence detection
337
+ const result = mediator.run({
338
+ maxRounds: 10,
339
+ convergenceThreshold: 0.8,
340
+ });
341
+ console.log(result.converged, result.totalRounds);
342
+ ```
343
+
344
+ ---
345
+
346
+ ## Six Attributes (六属性)
347
+
348
+ Every entity in Rei carries six attributes from D-FUMT theory:
349
+
350
+ | Attribute | Japanese | Role |
351
+ |-----------|----------|------|
352
+ | Field (場) | ば | Spatial context and neighbors |
353
+ | Flow (流れ) | ながれ | Temporal momentum and EventBus connection |
354
+ | Memory (記憶) | きおく | History of observations and actions |
355
+ | Layer () | そう | Hierarchical depth and nesting |
356
+ | Relation (関係) | かんけい | Bindings between entities |
357
+ | Will (意志) | いし | Intention-driven computation strategy |
358
+
359
+ ```rei
360
+ // Relation binding
361
+ let x = 42
362
+ let y = 100
363
+ x |> bind(y, "collaborator") // create a relation
364
+
365
+ // Will-driven computation
366
+ let m = 𝕄{5; 1, 2, 3}
367
+ m |> intend("maximize") // set intention
368
+ m |> will_compute // compute guided by will
369
+ ```
370
+
371
+ ---
372
+
373
+ ## RCT Compression (Rei Compression Theory)
374
+
375
+ D-FUMT Theory #67 generative compression outperforming gzip on structured data:
376
+
377
+ ```rei
378
+ // Core compression (Direction 1-2)
379
+ let data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
380
+ data |> compress // → compact θ representation
381
+ data |> compress |> decompress // → lossless round-trip
382
+
383
+ // Semantic compression (Direction 3)
384
+ "let x = 𝕄{5; 1, 2, 3}" |> semantic_compress // → θ parameters
385
+ "let x = 𝕄{5; 1, 2, 3}" |> 意味圧縮 // 日本語版
386
+ ```
387
+
388
+ ---
389
+
390
+ ## Benchmarks
391
+
392
+ | Task | Conventional | Rei | Reduction |
393
+ |------|-------------|-----|-----------|
394
+ | Image kernel calculations | 32 lines | 8 lines | **4×** |
395
+ | Multi-dimensional data aggregation | 45 lines | 12 lines | **3.7×** |
396
+ | Graph structure transformation | 52 lines | 14 lines | **3.7×** |
397
+ | **Average** | | | **74%** |
398
+
399
+ ---
400
+
401
+ ## API Reference
402
+
403
+ ### `rei(code: string): ReiValue`
404
+
405
+ Evaluate a string of Rei code. State persists across calls.
406
+
407
+ ### `rei.reset(): void`
408
+
409
+ Clear all variable and function bindings.
410
+
411
+ ### `rei.evaluator(): Evaluator`
412
+
413
+ Access the underlying Evaluator instance (for EventBus, AgentRegistry, etc.).
414
+
415
+ ### Classes
416
+
417
+ | Class | Description |
418
+ |-------|-------------|
419
+ | `Lexer` | Tokenizer |
420
+ | `Parser` | Recursive descent parser |
421
+ | `Evaluator` | AST evaluator with environment/scope chain |
422
+ | `ReiEventBus` | Type-safe event system with flow momentum |
423
+ | `ReiAgent` | Autonomous entity with six attributes |
424
+ | `AgentRegistry` | Agent lifecycle management |
425
+ | `ReiMediator` | Concurrent execution engine with conflict resolution |
426
+
427
+ ### Types
428
+
429
+ | Type | Shape |
430
+ |------|-------|
431
+ | `MultiDimNumber` | `{ center, neighbors, mode, weights? }` |
432
+ | `ReiExtended` | `{ base, order, subscripts, valStar() }` |
433
+ | `GenesisState` | `{ state, omega, history }` |
434
+ | `ReiFunction` | `{ name, params, body, closure }` |
435
+ | `Quad` | `{ value: 'top' \| 'bottom' \| 'topPi' \| 'bottomPi' }` |
436
+ | `ReiEvent` | `{ type, category, action, timestamp, data, source?, depth }` |
437
+ | `AgentSigma` | `{ state, kind, behavior, step, perception, decisions, memory }` |
438
+ | `MediatorSigma` | `{ totalRounds, conflicts, convergenceHistory, agentCount }` |
439
+
440
+ ---
441
+
442
+ ## Bilingual Pipe Commands (日本語対応)
443
+
444
+ All pipe commands have Japanese aliases:
445
+
446
+ | English | 日本語 | Description |
447
+ |---------|--------|-------------|
448
+ | `spawn` | `生成` | Create agent from value |
449
+ | `perceive` | `知覚` | Agent observes environment |
450
+ | `decide` | `判断` | Agent chooses action |
451
+ | `act` | `行動` | Agent executes decision |
452
+ | `agent_sigma` | `自律σ` | Agent metadata |
453
+ | `mediate` | `調停` | Concurrent round execution |
454
+ | `mediate_run` | `調停実行` | Multi-round execution |
455
+ | `mediator_sigma` | `調停σ` | Mediator statistics |
456
+ | `mediate_strategy` | `調停戦略` | Set conflict strategy |
457
+ | `mediate_message` | `調停通信` | Point-to-point message |
458
+ | `mediate_broadcast` | `調停放送` | Broadcast to all agents |
459
+ | `emit` | `発火` | Emit event |
460
+ | `subscribe` | `購読` | Subscribe to events |
461
+ | `bind` | `結合` | Create relation binding |
462
+ | `intend` | `意図` | Set entity intention |
463
+ | `compress` | `圧縮` | RCT compression |
464
+ | `decompress` | `復元` | RCT decompression |
465
+
466
+ ---
467
+
468
+ ## BNF Specification
469
+
470
+ The complete BNF v0.3 specification is available in [`spec/`](./spec/).
471
+
472
+ ---
473
+
474
+ ## Theoretical Foundation
475
+
476
+ Rei is grounded in **D-FUMT** (Dimensional Fujimoto Universal Mathematical Theory), a framework of 66 interconnected theories spanning pure mathematics to philosophy and AI consciousness. The language's core innovation — **center-periphery patterns as language primitives** — derives from D-FUMT's multi-dimensional number system theory.
477
+
478
+ See [`theory/`](./theory/) for the complete theoretical documentation.
479
+
480
+ ---
481
+
482
+ ## ☮️ Peace Use Clause / 平和利用条項
483
+
484
+ Rei is licensed under Apache 2.0 with an additional Peace Use Clause.
485
+ Rei は Apache 2.0 ライセンスに加え、平和利用条項が適用されます。
486
+
487
+ Rooted in the Buddhist concept of "Kū" (空, Emptiness) and D-FUMT's consciousness mathematics, Rei is designed exclusively for the peaceful advancement of humanity. This software may not be used for:
488
+ 仏教の「空」の概念と D-FUMT の意識数学に基づき、Rei は人類の平和的発展のためにのみ設計されています。以下の目的での使用は禁止されています:
489
+
490
+ 🚫 Weapons, military systems, or LAWS / 兵器・軍事システム・自律型致死兵器
491
+ 🚫 Human rights violations / 人権侵害
492
+ 🚫 Intentional environmental destruction / 意図的な環境破壊
493
+
494
+ ✅ Education, research, humanitarian aid, and creative endeavors are encouraged.
495
+ ✅ 教育・研究・人道支援・創造的活動での使用を推奨します。
496
+
497
+ See [PEACE_USE_CLAUSE.md](./PEACE_USE_CLAUSE.md) for full details.
498
+
499
+ Apache 2.0 © Nobuki Fujimoto