@nan0web/communication.app 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2025, ЯRаСлав (YaRaSLove) <support@yaro.page>
4
+
5
+ Permission to use, copy, modify, and distribute this software for any purpose
6
+ with or without fee is hereby granted, provided that the above copyright notice
7
+ and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
+ PERFORMANCE OF THIS SOFTWARE.
package/bin/nan0com.js ADDED
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * @file CLI entry point for @nan0web/communication.app (nan0com).
4
+ */
5
+ import { bootstrapApp } from '@nan0web/ui-cli'
6
+ import { CommunicationApp } from '../src/domain/CommunicationApp.js'
7
+ import { GitTransport } from '../src/infra/GitTransport.js'
8
+ import { Notifier } from '../src/infra/Notifier.js'
9
+
10
+ const git = new GitTransport()
11
+ const notify = new Notifier()
12
+
13
+ bootstrapApp(CommunicationApp, { root: '.', git, notify }).catch((err) => {
14
+ console.error(err)
15
+ process.exit(1)
16
+ })
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "@nan0web/communication.app",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Sovereign Git-based messenger and co-creation space (7iOS.CoCreation)",
5
+ "type": "module",
6
+ "main": "src/index.js",
7
+ "bin": {
8
+ "nan0com": "./bin/nan0com.js"
9
+ },
10
+ "exports": {
11
+ ".": "./src/index.js"
12
+ },
13
+ "devDependencies": {
14
+ "@types/node": "^25.6.0",
15
+ "knip": "^5.88.1",
16
+ "typescript": "^5.7.3",
17
+ "@nan0web/inspect": "3.11.1",
18
+ "@nan0web/test": "3.4.0"
19
+ },
20
+ "files": [
21
+ "src/**/*.js",
22
+ "types/**/*.d.ts",
23
+ "!src/**/*.{test,story}.js",
24
+ "!src/test/**",
25
+ "README.md"
26
+ ],
27
+ "scripts": {
28
+ "build": "tsc",
29
+ "test": "node --test \"src/**/*.{test,story}.js\"",
30
+ "test:stories": "node --test \"src/**/*.story.js\"",
31
+ "release:spec": "node --test \"releases/0/1/v0.1.0/task.spec.js\"",
32
+ "release:validate": "nan0inspect release --non-interactive",
33
+ "inspect": "nan0inspect domain --non-interactive",
34
+ "knip": "knip --production",
35
+ "test:all": "npm run build && npm run test && npm run release:spec && npm run inspect && npm run knip && npm run release:validate"
36
+ }
6
37
  }
@@ -0,0 +1,157 @@
1
+ import { ModelError } from '@nan0web/types'
2
+ import { ModelAsApp } from '@nan0web/ui'
3
+ import Markdown from '@nan0web/markdown'
4
+
5
+ /**
6
+ * Formats an author identifier into a filename-safe slug.
7
+ * @param {string} author
8
+ * @returns {string}
9
+ */
10
+ function slugifyAuthor(author) {
11
+ return String(author || 'anon')
12
+ .trim()
13
+ .toLowerCase()
14
+ .replace(/[^a-z0-9_-]+/g, '-')
15
+ .replace(/^-+|-+$/g, '')
16
+ }
17
+
18
+ /**
19
+ * Computes deterministic 2-level prefix shard URI: chats/<xx>/<yy>/<chatId>.
20
+ * @param {string} chatId
21
+ * @param {string} [base='chats']
22
+ * @returns {string}
23
+ */
24
+ export function resolveChatShardUri(chatId, base = 'chats') {
25
+ const slug = slugifyAuthor(chatId)
26
+ let hash = 2166136261
27
+ for (let i = 0; i < slug.length; i += 1) {
28
+ hash ^= slug.charCodeAt(i)
29
+ hash = Math.imul(hash, 16777619)
30
+ }
31
+ const hex = (hash >>> 0).toString(16).padStart(8, '0')
32
+ return `${base}/${hex.slice(0, 2)}/${hex.slice(2, 4)}/${slug}`
33
+ }
34
+
35
+ /**
36
+ * Serializes a chat message into Markdown with metadata header.
37
+ * @param {{ author: string, timestamp: string, text: string }} msg
38
+ * @returns {string}
39
+ */
40
+ function formatMessageMarkdown(msg) {
41
+ return [
42
+ '---',
43
+ `author: ${msg.author}`,
44
+ `timestamp: ${msg.timestamp}`,
45
+ '---',
46
+ '',
47
+ msg.text,
48
+ '',
49
+ ].join('\n')
50
+ }
51
+
52
+ /**
53
+ * Parses a serialized chat message Markdown document using @nan0web/markdown.
54
+ * @param {string} raw
55
+ * @returns {{ author: string, timestamp: string, text: string }}
56
+ */
57
+ export function parseMessageMarkdown(raw) {
58
+ const md = new Markdown()
59
+ const { content, metadata } = md.parseFrontmatter(String(raw || ''))
60
+ return {
61
+ author: String(metadata.author || ''),
62
+ timestamp: String(metadata.timestamp || ''),
63
+ text: String(content || '').trim(),
64
+ }
65
+ }
66
+
67
+ /**
68
+ * 2D Git-native chat repository with time-sharded Markdown messages.
69
+ */
70
+ export class ChatRepoModel extends ModelAsApp {
71
+ static UI = {
72
+ errorAuthorTextRequired: 'Author and text are required',
73
+ }
74
+
75
+ static repo = {
76
+ help: 'Repository base URI (e.g. chats/<xx>/<yy>/<chatId> or we/<circle>/<name>)',
77
+ default: '',
78
+ }
79
+
80
+ /**
81
+ * @param {Partial<ChatRepoModel>} [data]
82
+ * @param {Partial<import('@nan0web/types').ModelOptions>} [options]
83
+ */
84
+ constructor(data = {}, options = {}) {
85
+ super(data, options)
86
+ /** @type {string} Repository base URI */ this.repo
87
+ }
88
+
89
+ /**
90
+ * Sends and persists a message in chat/YYYY/MM/DD/<ts>-<peer>.md and optionally updates README.md.
91
+ * @param {{ author: string, text: string, timestamp?: string, skipIndex?: boolean }} input
92
+ * @returns {Promise<{ uri: string, filename: string, author: string, timestamp: string, text: string }>}
93
+ */
94
+ async sendMessage(input) {
95
+ const { author, text, timestamp = new Date().toISOString(), skipIndex = false } = input || {}
96
+ if (!author || !text) {
97
+ throw new ModelError({ message: this._.t(ChatRepoModel.UI.errorAuthorTextRequired) })
98
+ }
99
+ const [datePart, timePart = '00:00:00.000Z'] = String(timestamp).split('T')
100
+ const [year, month, day] = datePart.split('-')
101
+ const tsSlug = timePart.replace(/[:.]/g, '').replace(/Z$/, '')
102
+ const baseName = `${tsSlug}-${slugifyAuthor(author)}`
103
+ const dayDir = this.$db.normalize(this.repo, 'chat', year, month, day)
104
+
105
+ let filename = `${baseName}.md`
106
+ let uri = this.$db.normalize(dayDir, filename)
107
+ let seq = 1
108
+ while (await this.$db.loadDocument(uri, null)) {
109
+ filename = `${baseName}-${seq}.md`
110
+ uri = this.$db.normalize(dayDir, filename)
111
+ seq += 1
112
+ }
113
+
114
+ await this.$db.saveDocument(uri, formatMessageMarkdown({ author, timestamp, text }))
115
+ if (!skipIndex) {
116
+ await this.#appendDayIndex(dayDir, { filename, author, timestamp })
117
+ }
118
+
119
+ return { uri, filename, author, timestamp, text }
120
+ }
121
+
122
+ /**
123
+ * Lists all messages for a given YYYY-MM-DD date in chronological order.
124
+ * @param {string} dateStr
125
+ * @returns {Promise<Array<{ uri: string, filename: string, author: string, timestamp: string, text: string }>>}
126
+ */
127
+ async listDay(dateStr) {
128
+ const [year, month, day] = String(dateStr || '').split('-')
129
+ const dayDir = this.$db.normalize(this.repo, 'chat', year, month, day)
130
+ const entries = await this.$db.listDir(dayDir)
131
+ const files = entries
132
+ .filter((e) => e.isFile && e.name.endsWith('.md') && e.name !== 'README.md')
133
+ .sort((a, b) => a.name.localeCompare(b.name))
134
+
135
+ const messages = []
136
+ for (const entry of files) {
137
+ const uri = this.$db.normalize(dayDir, entry.name)
138
+ const raw = await this.$db.loadDocument(uri, '')
139
+ const parsed = parseMessageMarkdown(String(raw))
140
+ messages.push({ uri, filename: entry.name, ...parsed })
141
+ }
142
+ return messages
143
+ }
144
+
145
+ /**
146
+ * Appends a deterministic index line to chat/YYYY/MM/DD/README.md.
147
+ * @param {string} dayDir
148
+ * @param {{ filename: string, author: string, timestamp: string }} item
149
+ */
150
+ async #appendDayIndex(dayDir, item) {
151
+ const indexUri = this.$db.normalize(dayDir, 'README.md')
152
+ const existing = await this.$db.loadDocument(indexUri, '')
153
+ const header = existing ? String(existing).trimEnd() : `# Chat Index (${dayDir})`
154
+ const line = `- [${item.timestamp}] **${item.author}** -> [${item.filename}](./${item.filename})`
155
+ await this.$db.saveDocument(indexUri, `${header}\n${line}\n`)
156
+ }
157
+ }
@@ -0,0 +1,346 @@
1
+ import { ModelAsApp, show, result } from '@nan0web/ui'
2
+ import { FractalContactBookModel } from './FractalContactBookModel.js'
3
+ import { ChatRepoModel, parseMessageMarkdown, resolveChatShardUri } from './ChatRepoModel.js'
4
+ import { CrystallizeModel } from './CrystallizeModel.js'
5
+ import { PeerGitSyncModel } from './PeerGitSyncModel.js'
6
+
7
+ /**
8
+ * Resolves target repository URI from explicit repo or chatId prefix sharding.
9
+ * @param {string} repo
10
+ * @param {string} chatId
11
+ * @returns {string}
12
+ */
13
+ function resolveTargetRepo(repo, chatId) {
14
+ if (repo) return repo
15
+ if (chatId) return resolveChatShardUri(chatId)
16
+ return resolveChatShardUri('default')
17
+ }
18
+
19
+ /**
20
+ * Subcommand: Register a contact in a 7iOS we/ circle.
21
+ */
22
+ export class InitCommand extends ModelAsApp {
23
+ static alias = 'init'
24
+ static UI = {
25
+ initialized: 'Initialized contact {soulId} in circle {circle}',
26
+ bootstrapped: 'Day 1 tree: {count} files ({mode})',
27
+ }
28
+ static author = { help: 'Contact soulId', default: '' }
29
+ static circle = {
30
+ help: '7iOS circle (7i, kinship, partner, law, community, service, inbox)',
31
+ default: '7i',
32
+ }
33
+ static bootstrap = { help: 'Bootstrap Day 1 tree from tour/01', default: false }
34
+ static tourDir = { help: 'Tour template directory', default: 'docs/uk/tour/01' }
35
+ static dryRun = { help: 'Simulate initialization without writing files', default: false }
36
+
37
+ /**
38
+ * @param {Partial<InitCommand>} [data]
39
+ * @param {Partial<import('@nan0web/ui').ModelAsAppOptions>} [options]
40
+ */
41
+ constructor(data = {}, options = {}) {
42
+ super(data, options)
43
+ /** @type {string} Contact soulId */ this.author
44
+ /** @type {string} 7iOS circle */ this.circle
45
+ /** @type {boolean} Bootstrap Day 1 tree */ this.bootstrap
46
+ /** @type {string} Tour template directory */ this.tourDir
47
+ /** @type {boolean} Dry run mode */ this.dryRun
48
+ }
49
+
50
+ async *run() {
51
+ const book = new FractalContactBookModel({}, { db: this.$db })
52
+ if (this.bootstrap || !this.author) {
53
+ const summary = await book.bootstrapDayOneTree({
54
+ tourDir: this.tourDir,
55
+ dryRun: Boolean(this.dryRun),
56
+ })
57
+ const mode = summary.dryRun ? 'dry-run' : 'created'
58
+ yield show(this._.t(InitCommand.UI.bootstrapped, { count: summary.created.length, mode }), 'success')
59
+ return result({ ok: true, ...summary })
60
+ }
61
+ const contact = await book.addContact({
62
+ soulId: this.author,
63
+ circle: this.circle,
64
+ name: this.author,
65
+ dryRun: Boolean(this.dryRun),
66
+ })
67
+ yield show(this._.t(InitCommand.UI.initialized, contact), 'success')
68
+ return result({ ok: true, dryRun: Boolean(this.dryRun), contact })
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Subcommand: Send a message to a sharded chat repository.
74
+ */
75
+ export class SendCommand extends ModelAsApp {
76
+ static alias = 'send'
77
+ static UI = { sent: 'Message saved: {uri}' }
78
+ static repo = { help: 'Explicit repository URI', default: '' }
79
+ static chatId = { help: 'Chat ID for prefix sharding', default: '' }
80
+ static author = { help: 'Author soulId', default: '' }
81
+ static text = { help: 'Message text', default: '' }
82
+ static timestamp = { help: 'ISO timestamp', default: '' }
83
+ static push = { help: 'Commit and push via Git', default: true }
84
+ static skipIndex = { help: 'Skip updating README.md index', default: true }
85
+
86
+ /**
87
+ * @param {Partial<SendCommand>} [data]
88
+ * @param {Partial<import('@nan0web/ui').ModelAsAppOptions>} [options]
89
+ */
90
+ /**
91
+ * @param {Partial<ViewCommand>} [data]
92
+ * @param {Partial<import('@nan0web/ui').ModelAsAppOptions>} [options]
93
+ */
94
+ /**
95
+ * @param {Partial<SyncCommand>} [data]
96
+ * @param {Partial<import('@nan0web/ui').ModelAsAppOptions>} [options]
97
+ */
98
+ constructor(data = {}, options = {}) {
99
+ super(data, options)
100
+ /** @type {string} Explicit repository URI */ this.repo
101
+ /** @type {string} Chat ID for prefix sharding */ this.chatId
102
+ /** @type {string} Author soulId */ this.author
103
+ /** @type {string} Message text */ this.text
104
+ /** @type {string} ISO timestamp */ this.timestamp
105
+ /** @type {boolean} Commit and push via Git */ this.push
106
+ /** @type {boolean} Skip updating README.md index */ this.skipIndex
107
+ /** @type {any} Optional Git transport port */ this.$git = options.git || null
108
+ }
109
+
110
+ async *run() {
111
+ const targetRepo = resolveTargetRepo(this.repo, this.chatId)
112
+ const opts = { db: this.$db, git: this.$git }
113
+ const chat = new ChatRepoModel({ repo: targetRepo }, opts)
114
+ const msg = await chat.sendMessage({
115
+ author: this.author,
116
+ text: this.text,
117
+ timestamp: this.timestamp || new Date().toISOString(),
118
+ skipIndex: Boolean(this.skipIndex),
119
+ })
120
+ const sync = new PeerGitSyncModel({ repo: targetRepo }, opts)
121
+ await sync.recordPeerCommit({ soulId: this.author, messageUri: msg.uri })
122
+ if (this.push && this.$git) {
123
+ await sync.pushMessage({ uri: msg.uri, author: this.author })
124
+ }
125
+ yield show(this._.t(SendCommand.UI.sent, { uri: msg.uri }), 'success')
126
+ return result({ ok: true, message: msg })
127
+ }
128
+ }
129
+
130
+ /**
131
+ * Subcommand: View messages for a given date.
132
+ */
133
+ export class ViewCommand extends ModelAsApp {
134
+ static alias = 'view'
135
+ static repo = { help: 'Explicit repository URI', default: '' }
136
+ static chatId = { help: 'Chat ID for prefix sharding', default: '' }
137
+ static date = { help: 'Date YYYY-MM-DD', default: '' }
138
+
139
+ /**
140
+ * @param {Partial<ViewCommand>} [data]
141
+ * @param {Partial<import('@nan0web/ui').ModelAsAppOptions>} [options]
142
+ */
143
+ constructor(data = {}, options = {}) {
144
+ super(data, options)
145
+ /** @type {string} Explicit repository URI */ this.repo
146
+ /** @type {string} Chat ID for prefix sharding */ this.chatId
147
+ /** @type {string} Date YYYY-MM-DD */ this.date
148
+ }
149
+
150
+ async *run() {
151
+ const targetRepo = resolveTargetRepo(this.repo, this.chatId)
152
+ const chat = new ChatRepoModel({ repo: targetRepo }, { db: this.$db })
153
+ const dateStr = this.date || new Date().toISOString().slice(0, 10)
154
+ const messages = await chat.listDay(dateStr)
155
+ if (messages.length === 0) {
156
+ yield show(`No messages for ${dateStr}`, 'info')
157
+ } else {
158
+ for (const msg of messages) {
159
+ yield show(`[${msg.timestamp}] ${msg.author}: ${msg.text}`, 'info')
160
+ }
161
+ }
162
+ return result({ ok: true, date: dateStr, messages })
163
+ }
164
+ }
165
+
166
+ /**
167
+ * Subcommand: Crystallize a chat message into a document or todo.md.
168
+ */
169
+ export class CrystallizeCommand extends ModelAsApp {
170
+ static alias = 'crystallize'
171
+ static UI = { crystallized: 'Crystallized into {targetDocUri}' }
172
+ static msgUri = { help: 'Source message URI', default: '' }
173
+ static targetDocUri = { help: 'Target document URI', default: '' }
174
+ static kind = { help: 'Entry kind: todo | note', default: 'todo' }
175
+
176
+ /**
177
+ * @param {Partial<CrystallizeCommand>} [data]
178
+ * @param {Partial<import('@nan0web/ui').ModelAsAppOptions>} [options]
179
+ */
180
+ constructor(data = {}, options = {}) {
181
+ super(data, options)
182
+ /** @type {string} Source message URI */ this.msgUri
183
+ /** @type {string} Target document URI */ this.targetDocUri
184
+ /** @type {string} Entry kind */ this.kind
185
+ }
186
+
187
+ async *run() {
188
+ const crystallizer = new CrystallizeModel({}, { db: this.$db })
189
+ const entry = await crystallizer.crystallize({
190
+ msgUri: this.msgUri,
191
+ targetDocUri: this.targetDocUri,
192
+ kind: this.kind === 'todo' ? 'todo' : 'note',
193
+ })
194
+ yield show(this._.t(CrystallizeCommand.UI.crystallized, { targetDocUri: this.targetDocUri }), 'success')
195
+ return result({ ok: true, entry })
196
+ }
197
+ }
198
+
199
+ /**
200
+ * Subcommand: Inspect peer branch sync state.
201
+ */
202
+ export class SyncCommand extends ModelAsApp {
203
+ static alias = 'sync'
204
+ static UI = { synced: 'Sync state: {count} peer branches' }
205
+ static repo = { help: 'Explicit repository URI', default: '' }
206
+ static chatId = { help: 'Chat ID for prefix sharding', default: '' }
207
+
208
+ /**
209
+ * @param {Partial<SendCommand>} [data]
210
+ * @param {Partial<import('@nan0web/ui').ModelAsAppOptions>} [options]
211
+ */
212
+ /**
213
+ * @param {Partial<ViewCommand>} [data]
214
+ * @param {Partial<import('@nan0web/ui').ModelAsAppOptions>} [options]
215
+ */
216
+ /**
217
+ * @param {Partial<SyncCommand>} [data]
218
+ * @param {Partial<import('@nan0web/ui').ModelAsAppOptions>} [options]
219
+ */
220
+ constructor(data = {}, options = {}) {
221
+ super(data, options)
222
+ /** @type {string} Explicit repository URI */ this.repo
223
+ /** @type {string} Chat ID for prefix sharding */ this.chatId
224
+ }
225
+
226
+ async *run() {
227
+ const targetRepo = resolveTargetRepo(this.repo, this.chatId)
228
+ const sync = new PeerGitSyncModel({ repo: targetRepo }, { db: this.$db })
229
+ const state = await sync.getSyncState()
230
+ const count = Object.keys(state.branches).length
231
+ yield show(this._.t(SyncCommand.UI.synced, { count }), 'info')
232
+ return result({ ok: true, state })
233
+ }
234
+ }
235
+
236
+ /**
237
+ * Subcommand: Poll remote Git repository for new messages and notify.
238
+ */
239
+ export class WatchCommand extends ModelAsApp {
240
+ static alias = 'watch'
241
+ static UI = {
242
+ watching: 'Watching {repo} every {interval}s...',
243
+ received: '[{author}] {text}',
244
+ }
245
+ static repo = { help: 'Explicit repository URI', default: '.' }
246
+ static chatId = { help: 'Chat ID for prefix sharding', default: '' }
247
+ static interval = { help: 'Polling interval in seconds (10-15 recommended)', default: 12 }
248
+ static once = { help: 'Run a single poll tick and exit', default: false }
249
+
250
+ /**
251
+ * @param {Partial<WatchCommand>} [data]
252
+ * @param {Partial<import('@nan0web/ui').ModelAsAppOptions> & { git?: any, notify?: any }} [options]
253
+ */
254
+ /**
255
+ * @param {Partial<SendCommand>} [data]
256
+ * @param {Partial<import('@nan0web/ui').ModelAsAppOptions>} [options]
257
+ */
258
+ /**
259
+ * @param {Partial<ViewCommand>} [data]
260
+ * @param {Partial<import('@nan0web/ui').ModelAsAppOptions>} [options]
261
+ */
262
+ /**
263
+ * @param {Partial<SyncCommand>} [data]
264
+ * @param {Partial<import('@nan0web/ui').ModelAsAppOptions>} [options]
265
+ */
266
+ constructor(data = {}, options = {}) {
267
+ super(data, options)
268
+ /** @type {string} Explicit repository URI */ this.repo
269
+ /** @type {string} Chat ID for prefix sharding */ this.chatId
270
+ /** @type {number} Polling interval in seconds */ this.interval
271
+ /** @type {boolean} Run a single poll tick and exit */ this.once
272
+ /** @type {any} Optional Git transport port */ this.$git = options.git || null
273
+ /** @type {any} Optional Notifier port */ this.$notify = options.notify || null
274
+ }
275
+
276
+ /**
277
+ * Polls remote Git repository and yields received messages.
278
+ * @returns {AsyncGenerator<import('@nan0web/ui').Intent, any, any>}
279
+ */
280
+ async *run() {
281
+ const targetRepo = resolveTargetRepo(this.repo, this.chatId)
282
+ const sync = new PeerGitSyncModel({ repo: targetRepo }, { db: this.$db, git: this.$git })
283
+ yield show(this._.t(WatchCommand.UI.watching, { repo: targetRepo, interval: this.interval }), 'info')
284
+
285
+ const received = []
286
+ do {
287
+ const newFiles = await sync.pullUpdates()
288
+ for (const uri of newFiles) {
289
+ const raw = await this.$db.loadDocument(uri, '')
290
+ const parsed = parseMessageMarkdown(String(raw))
291
+ const item = { uri, ...parsed }
292
+ received.push(item)
293
+ yield show(this._.t(WatchCommand.UI.received, {
294
+ author: parsed.author || 'peer',
295
+ text: parsed.text || uri,
296
+ }), 'success')
297
+ if (this.$notify) {
298
+ await this.$notify.notify({
299
+ title: parsed.author || 'New message',
300
+ body: parsed.text || uri,
301
+ })
302
+ }
303
+ }
304
+ if (!this.once) {
305
+ await new Promise((r) => setTimeout(r, Number(this.interval || 12) * 1000))
306
+ }
307
+ } while (!this.once)
308
+
309
+ return result({ ok: true, received })
310
+ }
311
+ }
312
+
313
+ /**
314
+ * Main polymorphic OLMUI application controller for @nan0web/communication.app.
315
+ */
316
+ export class CommunicationApp extends ModelAsApp {
317
+ static alias = 'nan0com'
318
+ static UI = { title: '7iOS.CoCreation — Sovereign Git Messenger' }
319
+
320
+ static command = {
321
+ help: 'Command to execute',
322
+ options: [InitCommand, SendCommand, ViewCommand, CrystallizeCommand, SyncCommand, WatchCommand],
323
+ positional: true,
324
+ default: ViewCommand,
325
+ }
326
+
327
+ /**
328
+ * @param {Partial<CommunicationApp>} [data]
329
+ * @param {Partial<import('@nan0web/ui').ModelAsAppOptions>} [options]
330
+ */
331
+ constructor(data = {}, options = {}) {
332
+ super(data, options)
333
+ /** @type {ModelAsApp} Active subcommand instance */ this.command
334
+ }
335
+
336
+ /**
337
+ * Delegates execution polymorphically to the active subcommand model.
338
+ * @returns {AsyncGenerator<import('@nan0web/ui').Intent, any, any>}
339
+ */
340
+ async *run() {
341
+ if (this.help || !this.command || typeof this.command.run !== 'function') {
342
+ return yield* super.run()
343
+ }
344
+ return yield* this.command.run()
345
+ }
346
+ }
@@ -0,0 +1,58 @@
1
+ import { ModelError } from '@nan0web/types'
2
+ import { ModelAsApp } from '@nan0web/ui'
3
+ import { parseMessageMarkdown } from './ChatRepoModel.js'
4
+
5
+ /**
6
+ * Formats a crystallized entry for todo.md or docs/*.md with $ref and authorship.
7
+ * @param {{ text: string, author: string, msgUri: string, kind: string }} data
8
+ * @returns {string}
9
+ */
10
+ function formatCrystallizedEntry({ text, author, msgUri, kind }) {
11
+ if (kind === 'todo') {
12
+ return `- [ ] ${text} [author:${author}] [$ref:${msgUri}]`
13
+ }
14
+ return `> ${text}\n>\n> — **${author}** ([$ref](${msgUri}))`
15
+ }
16
+
17
+ /**
18
+ * Crystallizes ephemeral chat messages into structured project documents or todo.md.
19
+ */
20
+ export class CrystallizeModel extends ModelAsApp {
21
+ static UI = {
22
+ errorNoDb: 'Database instance ($db) is required',
23
+ errorMsgNotFound: 'Source message not found',
24
+ }
25
+
26
+ /**
27
+ * Moves/projects a chat message into targetDocUri preserving authorship and $ref.
28
+ * @param {{ msgUri: string, targetDocUri: string, kind?: 'todo' | 'note' }} input
29
+ * @returns {Promise<{ author: string, $ref: string, targetDocUri: string, kind: string, text: string }>}
30
+ */
31
+ async crystallize(input) {
32
+ const { msgUri, targetDocUri, kind = 'note' } = input || {}
33
+ const stat = await this.$db.stat(msgUri)
34
+ if (!stat || !stat.exists) {
35
+ throw new ModelError({ msgUri: `${CrystallizeModel.UI.errorMsgNotFound}: ${msgUri}` })
36
+ }
37
+ const rawMsg = await this.$db.loadDocument(msgUri, '')
38
+ const parsed = parseMessageMarkdown(String(rawMsg))
39
+ const entryText = formatCrystallizedEntry({
40
+ text: parsed.text,
41
+ author: parsed.author,
42
+ msgUri,
43
+ kind,
44
+ })
45
+
46
+ const existingDoc = await this.$db.loadDocument(targetDocUri, '')
47
+ const prefix = existingDoc ? `${String(existingDoc).trimEnd()}\n` : ''
48
+ await this.$db.saveDocument(targetDocUri, `${prefix}${entryText}\n`)
49
+
50
+ return {
51
+ author: parsed.author,
52
+ $ref: msgUri,
53
+ targetDocUri,
54
+ kind,
55
+ text: parsed.text,
56
+ }
57
+ }
58
+ }