@nan0web/communication.app 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,147 @@
1
+ import { ModelError } from '@nan0web/types'
2
+ import { ModelAsApp } from '@nan0web/ui'
3
+
4
+ /** @type {readonly string[]} */
5
+ export const CANONICAL_CIRCLES = [
6
+ '7i',
7
+ 'kinship',
8
+ 'partner',
9
+ 'law',
10
+ 'community',
11
+ 'service',
12
+ 'inbox',
13
+ ]
14
+
15
+ /** @type {readonly string[]} */
16
+ const DAY_ONE_FILES = [
17
+ 'i/README.md',
18
+ 'we/7i/family/todo.md',
19
+ 'we/inbox/README.md',
20
+ 'env/home/shopping.md',
21
+ ]
22
+
23
+ /**
24
+ * Converts soulId like "soul:yaro" into safe filename slug "soul-yaro".
25
+ * @param {string} soulId
26
+ * @returns {string}
27
+ */
28
+ function toSlug(soulId) {
29
+ return String(soulId || '')
30
+ .trim()
31
+ .toLowerCase()
32
+ .replace(/[^a-z0-9_-]+/g, '-')
33
+ .replace(/^-+|-+$/g, '')
34
+ }
35
+
36
+ /**
37
+ * Fractal contact book for 7iOS we/ circles and Triad project governance.
38
+ */
39
+ export class FractalContactBookModel extends ModelAsApp {
40
+ static UI = {
41
+ errorNoDb: 'Database instance ($db) is required',
42
+ errorInvalidCircle: 'Invalid circle: must be one of configured we/ circles',
43
+ errorInvalidSoulId: 'soulId is required',
44
+ errorTriadRule: 'Triad rule violation: partner project requires at least 3 core members',
45
+ }
46
+
47
+ static circles = {
48
+ help: 'Allowed we/ circles (overridable via index config or model options)',
49
+ default: CANONICAL_CIRCLES,
50
+ }
51
+
52
+ /**
53
+ * @param {Partial<FractalContactBookModel>} [data]
54
+ * @param {Partial<import('@nan0web/types').ModelOptions>} [options]
55
+ */
56
+ constructor(data = {}, options = {}) {
57
+ super(data, options)
58
+ /** @type {string[]} Allowed we/ circles */ this.circles
59
+ }
60
+
61
+ /**
62
+ * Resolves active we/ circles from root index document or model options.
63
+ * @returns {Promise<string[]>}
64
+ */
65
+ async resolveCircles() {
66
+ const rootIndex = await this.$db.loadDocument('index', null)
67
+ if (Array.isArray(rootIndex?.circles) && rootIndex.circles.length > 0) {
68
+ return rootIndex.circles.map(String)
69
+ }
70
+ return Array.isArray(this.circles) && this.circles.length > 0
71
+ ? this.circles.map(String)
72
+ : [...CANONICAL_CIRCLES]
73
+ }
74
+
75
+ /**
76
+ * Registers a contact in one of configured we/ circles.
77
+ * @param {{ soulId: string, circle: string, name: string, devices?: string[], dryRun?: boolean }} input
78
+ * @returns {Promise<{ soulId: string, circle: string, name: string, devices: string[] }>}
79
+ */
80
+ async addContact(input) {
81
+ const { soulId, circle, name, devices = [], dryRun = false } = input || {}
82
+ if (!soulId) {
83
+ throw new ModelError({ soulId: FractalContactBookModel.UI.errorInvalidSoulId })
84
+ }
85
+ const allowed = await this.resolveCircles()
86
+ if (!allowed.includes(circle)) {
87
+ throw new ModelError({ circle: FractalContactBookModel.UI.errorInvalidCircle })
88
+ }
89
+ const contact = {
90
+ soulId: String(soulId),
91
+ circle: String(circle),
92
+ name: String(name || soulId),
93
+ devices: Array.isArray(devices) ? devices.map(String) : [],
94
+ }
95
+ if (!dryRun) {
96
+ const uri = this.$db.normalize('we', circle, toSlug(soulId))
97
+ await this.$db.saveDocument(uri, contact)
98
+ }
99
+ return contact
100
+ }
101
+
102
+ /**
103
+ * Creates a shared partner project enforcing the Triad Rule (N >= 3).
104
+ * @param {{ projectId: string, title: string, coreMembers: string[] }} input
105
+ * @returns {Promise<{ projectId: string, title: string, coreMembers: string[] }>}
106
+ */
107
+ async createPartnerProject(input) {
108
+ const { projectId, title, coreMembers = [] } = input || {}
109
+ const uniqueMembers = Array.from(new Set(Array.isArray(coreMembers) ? coreMembers : []))
110
+ if (uniqueMembers.length < 3) {
111
+ throw new ModelError({ coreMembers: FractalContactBookModel.UI.errorTriadRule })
112
+ }
113
+ const project = {
114
+ projectId: toSlug(projectId),
115
+ title: String(title || projectId),
116
+ coreMembers: uniqueMembers.map(String),
117
+ }
118
+ const uri = this.$db.normalize('we', 'partner', project.projectId, 'project')
119
+ await this.$db.saveDocument(uri, project)
120
+ return project
121
+ }
122
+
123
+ /**
124
+ * Bootstraps Day 1 Onboarding tree by copying template files from tourDir.
125
+ * @param {{ tourDir?: string, dryRun?: boolean }} [options]
126
+ * @returns {Promise<{ dryRun: boolean, created: string[], existing: string[] }>}
127
+ */
128
+ async bootstrapDayOneTree(options = {}) {
129
+ const { tourDir = 'docs/uk/tour/01', dryRun = false } = options
130
+ const created = []
131
+ const existing = []
132
+ for (const relUri of DAY_ONE_FILES) {
133
+ const stat = await this.$db.stat(relUri)
134
+ if (stat && stat.exists) {
135
+ existing.push(relUri)
136
+ continue
137
+ }
138
+ const srcUri = this.$db.normalize(tourDir, relUri)
139
+ const content = (await this.$db.loadDocument(srcUri, null)) || `# ${relUri}\n`
140
+ if (!dryRun) {
141
+ await this.$db.saveDocument(relUri, content)
142
+ }
143
+ created.push(relUri)
144
+ }
145
+ return { dryRun: Boolean(dryRun), created, existing }
146
+ }
147
+ }
@@ -0,0 +1,105 @@
1
+ import { ModelError } from '@nan0web/types'
2
+ import { ModelAsApp } from '@nan0web/ui'
3
+
4
+ /**
5
+ * Formats soulId into a branch-safe slug.
6
+ * @param {string} soulId
7
+ * @returns {string}
8
+ */
9
+ function slugifySoul(soulId) {
10
+ return String(soulId || 'anon')
11
+ .trim()
12
+ .toLowerCase()
13
+ .replace(/[^a-z0-9_-]+/g, '-')
14
+ .replace(/^-+|-+$/g, '')
15
+ }
16
+
17
+ /**
18
+ * Conflict-free peer branch synchronization model (refs/heads/peers/<soulId>).
19
+ */
20
+ export class PeerGitSyncModel extends ModelAsApp {
21
+ static BATCH_MODES = ['realtime', 'debounce', 'manual-close']
22
+ static MERGE_POLICIES = ['auto-ort', 'pr-in-chat', 'owner-only']
23
+
24
+ static repo = {
25
+ help: 'Repository base URI',
26
+ default: 'we/7i/default',
27
+ }
28
+
29
+ static batchMode = {
30
+ help: 'Commit batching mode: realtime | debounce | manual-close',
31
+ default: 'realtime',
32
+ }
33
+
34
+ static mergePolicy = {
35
+ help: 'Document merge policy: auto-ort | pr-in-chat | owner-only',
36
+ default: 'auto-ort',
37
+ }
38
+
39
+ /**
40
+ * @param {Partial<PeerGitSyncModel>} [data]
41
+ * @param {Partial<import('@nan0web/ui').ModelAsAppOptions>} [options]
42
+ */
43
+ constructor(data = {}, options = {}) {
44
+ super(data, options)
45
+ /** @type {string} Repository base URI */ this.repo
46
+ /** @type {string} Commit batching mode */ this.batchMode
47
+ /** @type {string} Document merge policy */ this.mergePolicy
48
+ /** @type {any} Optional Git transport port */ this.$git = options.git || null
49
+ }
50
+
51
+ /**
52
+ * Records a peer message commit into refs/heads/peers/<soulId> without conflicts.
53
+ * @param {{ soulId: string, messageUri: string }} input
54
+ * @returns {Promise<{ branch: string, messageUri: string }>}
55
+ */
56
+ async recordPeerCommit(input) {
57
+ const { soulId, messageUri } = input || {}
58
+ if (!soulId || !messageUri) {
59
+ throw new ModelError({ sync: 'soulId and messageUri are required' })
60
+ }
61
+ if (!PeerGitSyncModel.BATCH_MODES.includes(this.batchMode)) {
62
+ throw new ModelError({ batchMode: `Invalid batchMode: ${this.batchMode}` })
63
+ }
64
+ const branch = `refs/heads/peers/${slugifySoul(soulId)}`
65
+ const stateUri = this.$db.normalize(this.repo, '.sync-state')
66
+ const state = (await this.$db.loadDocument(stateUri, null)) || { branches: {} }
67
+ if (!state.branches[branch]) {
68
+ state.branches[branch] = []
69
+ }
70
+ if (!state.branches[branch].includes(messageUri)) {
71
+ state.branches[branch].push(messageUri)
72
+ }
73
+ await this.$db.saveDocument(stateUri, state)
74
+ return { branch, messageUri }
75
+ }
76
+
77
+ /**
78
+ * Returns current peer branches synchronization state.
79
+ * @returns {Promise<{ branches: Record<string, string[]> }>}
80
+ */
81
+ async getSyncState() {
82
+ const stateUri = this.$db.normalize(this.repo, '.sync-state')
83
+ return (await this.$db.loadDocument(stateUri, null)) || { branches: {} }
84
+ }
85
+
86
+ /**
87
+ * Commits and pushes a message file via injected Git transport (if present).
88
+ * @param {{ uri: string, author: string }} input
89
+ * @returns {Promise<{ pushed: boolean }>}
90
+ */
91
+ async pushMessage({ uri, author }) {
92
+ if (!this.$git) return { pushed: false }
93
+ await this.$git.commitAndPush(uri, `chat: message from ${author}`)
94
+ return { pushed: true }
95
+ }
96
+
97
+ /**
98
+ * Fetches and pulls remote updates via injected Git transport (if present).
99
+ * @returns {Promise<string[]>} Newly pulled .md file URIs
100
+ */
101
+ async pullUpdates() {
102
+ if (!this.$git) return []
103
+ return await this.$git.fetchAndPullRebase()
104
+ }
105
+ }
package/src/index.js ADDED
@@ -0,0 +1,13 @@
1
+ export { FractalContactBookModel, CANONICAL_CIRCLES } from './domain/FractalContactBookModel.js'
2
+ export { ChatRepoModel, parseMessageMarkdown, resolveChatShardUri } from './domain/ChatRepoModel.js'
3
+ export { CrystallizeModel } from './domain/CrystallizeModel.js'
4
+ export { PeerGitSyncModel } from './domain/PeerGitSyncModel.js'
5
+ export {
6
+ CommunicationApp,
7
+ InitCommand,
8
+ SendCommand,
9
+ ViewCommand,
10
+ CrystallizeCommand,
11
+ SyncCommand,
12
+ WatchCommand,
13
+ } from './domain/CommunicationApp.js'
@@ -0,0 +1,155 @@
1
+ import { execFile } from 'node:child_process'
2
+ import { promisify } from 'node:util'
3
+
4
+ const execFileAsync = promisify(execFile)
5
+
6
+ /**
7
+ * Structured Git transport error with actionable hint.
8
+ */
9
+ export class GitTransportError extends Error {
10
+ /**
11
+ * @param {string} message
12
+ * @param {{ code: string, hint: string, command: string, cause?: unknown }} meta
13
+ */
14
+ constructor(message, meta) {
15
+ super(message, { cause: meta.cause })
16
+ this.name = 'GitTransportError'
17
+ /** @type {string} */ this.code = meta.code
18
+ /** @type {string} */ this.hint = meta.hint
19
+ /** @type {string} */ this.command = meta.command
20
+ }
21
+ }
22
+
23
+ /**
24
+ * Extracts SSH target (user@host) from git stderr/message if present.
25
+ * @param {string} text
26
+ * @returns {string}
27
+ */
28
+ function extractSshTarget(text) {
29
+ const match = text.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+):/)
30
+ return match ? match[1] : 'git@gitlab.com'
31
+ }
32
+
33
+ /**
34
+ * Classifies raw git CLI errors into structured GitTransportError instances.
35
+ * @param {any} err
36
+ * @param {string} command
37
+ * @returns {GitTransportError}
38
+ */
39
+ export function classifyGitError(err, command = 'git') {
40
+ if (err instanceof GitTransportError) return err
41
+ const raw = [err?.stderr, err?.message].filter(Boolean).join('\n')
42
+
43
+ if (/Permission denied \(publickey\)|Could not read from remote repository|Host key verification failed/i.test(raw)) {
44
+ const target = extractSshTarget(raw)
45
+ const hint = `Check SSH key with "ssh -T ${target}", run "ssh-add", and verify repository access rights.`
46
+ return new GitTransportError(`Git SSH authentication failed (${target}). ${hint}`, {
47
+ code: 'SSH_AUTH_FAILED',
48
+ hint,
49
+ command,
50
+ cause: err,
51
+ })
52
+ }
53
+
54
+ if (/Could not resolve host|Connection timed out|Operation timed out|Connection refused|Network is unreachable|unable to access|Temporary failure in name resolution|kex_exchange_identification/i.test(raw)) {
55
+ const hint = 'Check internet/VPN connection and remote server availability, then retry.'
56
+ return new GitTransportError(`Git network error during "${command}". ${hint}`, {
57
+ code: 'NETWORK_ERROR',
58
+ hint,
59
+ command,
60
+ cause: err,
61
+ })
62
+ }
63
+
64
+ const firstLine = String(err?.message || 'Git command failed').split('\n')[0]
65
+ const hint = 'Check repository state with "git status".'
66
+ return new GitTransportError(`${firstLine}. ${hint}`, {
67
+ code: 'GIT_ERROR',
68
+ hint,
69
+ command,
70
+ cause: err,
71
+ })
72
+ }
73
+
74
+ /**
75
+ * Runs a git command in the given working directory.
76
+ * @param {string[]} args
77
+ * @param {string} cwd
78
+ * @returns {Promise<string>}
79
+ */
80
+ async function runGit(args, cwd) {
81
+ const { stdout } = await execFileAsync('git', args, { cwd })
82
+ return stdout.trim()
83
+ }
84
+
85
+ /**
86
+ * Git CLI transport port for conflict-free message synchronization.
87
+ */
88
+ export class GitTransport {
89
+ /**
90
+ * @param {{ cwd?: string, execGit?: (args: string[], cwd: string) => Promise<string> }} [options]
91
+ */
92
+ constructor(options = {}) {
93
+ this.cwd = options.cwd || '.'
94
+ this.execGit = options.execGit || runGit
95
+ }
96
+
97
+ /**
98
+ * Stages, commits, and pushes a single file (auto-rebases once if remote is ahead).
99
+ * @param {string} filePath
100
+ * @param {string} message
101
+ * @returns {Promise<{ ok: boolean }>}
102
+ */
103
+ async commitAndPush(filePath, message) {
104
+ try {
105
+ await this.execGit(['add', filePath], this.cwd)
106
+ await this.execGit(['commit', '-m', message], this.cwd)
107
+ try {
108
+ await this.execGit(['push'], this.cwd)
109
+ } catch (pushErr) {
110
+ const classified = classifyGitError(pushErr, 'git push')
111
+ if (classified.code === 'SSH_AUTH_FAILED' || classified.code === 'NETWORK_ERROR') {
112
+ throw classified
113
+ }
114
+ await this.execGit(['pull', '--rebase', '--autostash'], this.cwd)
115
+ await this.execGit(['push'], this.cwd)
116
+ }
117
+ return { ok: true }
118
+ } catch (err) {
119
+ throw classifyGitError(err, 'git push')
120
+ }
121
+ }
122
+
123
+ /**
124
+ * Fetches remote updates, detects new .md files, and runs git pull --rebase.
125
+ * @returns {Promise<string[]>} List of newly pulled .md file paths
126
+ */
127
+ async fetchAndPullRebase() {
128
+ try {
129
+ await this.execGit(['fetch'], this.cwd)
130
+ } catch (err) {
131
+ throw classifyGitError(err, 'git fetch')
132
+ }
133
+ let diffOutput = ''
134
+ try {
135
+ diffOutput = await this.execGit(
136
+ ['diff', '--name-only', '--diff-filter=A', 'HEAD..@{u}'],
137
+ this.cwd,
138
+ )
139
+ } catch {
140
+ return []
141
+ }
142
+ const newFiles = diffOutput
143
+ .split('\n')
144
+ .map((s) => s.trim())
145
+ .filter((s) => s.endsWith('.md'))
146
+ if (newFiles.length > 0) {
147
+ try {
148
+ await this.execGit(['pull', '--rebase', '--autostash'], this.cwd)
149
+ } catch (err) {
150
+ throw classifyGitError(err, 'git pull --rebase')
151
+ }
152
+ }
153
+ return newFiles
154
+ }
155
+ }
@@ -0,0 +1,61 @@
1
+ import { execFile } from 'node:child_process'
2
+ import { promisify } from 'node:util'
3
+
4
+ const execFileAsync = promisify(execFile)
5
+
6
+ /**
7
+ * Escapes single quotes for AppleScript / PowerShell inline strings.
8
+ * @param {string} str
9
+ * @returns {string}
10
+ */
11
+ function sanitize(str) {
12
+ return String(str || '').replace(/["'`$\\]/g, ' ').trim()
13
+ }
14
+
15
+ /**
16
+ * Cross-platform desktop notifier (macOS, Windows, Linux) with zero external deps.
17
+ */
18
+ export class Notifier {
19
+ /**
20
+ * @param {{ platform?: string, exec?: (cmd: string, args: string[]) => Promise<any> }} [options]
21
+ */
22
+ constructor(options = {}) {
23
+ this.platform = options.platform || process.platform
24
+ this.exec = options.exec || ((cmd, args) => execFileAsync(cmd, args))
25
+ }
26
+
27
+ /**
28
+ * Sends a desktop notification on macOS, Windows, or Linux.
29
+ * @param {{ title: string, body: string }} payload
30
+ * @returns {Promise<void>}
31
+ */
32
+ async notify({ title, body }) {
33
+ const safeTitle = sanitize(title)
34
+ const safeBody = sanitize(body)
35
+ try {
36
+ if (this.platform === 'darwin') {
37
+ const script = `display notification "${safeBody}" with title "${safeTitle}"`
38
+ await this.exec('osascript', ['-e', script])
39
+ return
40
+ }
41
+ if (this.platform === 'win32') {
42
+ const ps = [
43
+ 'Add-Type -AssemblyName System.Windows.Forms;',
44
+ '$n = New-Object System.Windows.Forms.NotifyIcon;',
45
+ '$n.Icon = [System.Drawing.SystemIcons]::Information;',
46
+ '$n.Visible = $true;',
47
+ `$n.ShowBalloonTip(5000, '${safeTitle}', '${safeBody}', [System.Windows.Forms.ToolTipIcon]::Info);`,
48
+ ].join(' ')
49
+ await this.exec('powershell', ['-NoProfile', '-Command', ps])
50
+ return
51
+ }
52
+ if (this.platform === 'linux') {
53
+ await this.exec('notify-send', [safeTitle, safeBody])
54
+ return
55
+ }
56
+ } catch {
57
+ // Fallback to terminal bell if OS notification fails
58
+ }
59
+ process.stdout.write(`\x07[${safeTitle}] ${safeBody}\n`)
60
+ }
61
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Computes deterministic 2-level prefix shard URI: chats/<xx>/<yy>/<chatId>.
3
+ * @param {string} chatId
4
+ * @param {string} [base='chats']
5
+ * @returns {string}
6
+ */
7
+ export function resolveChatShardUri(chatId: string, base?: string): string;
8
+ /**
9
+ * Parses a serialized chat message Markdown document using @nan0web/markdown.
10
+ * @param {string} raw
11
+ * @returns {{ author: string, timestamp: string, text: string }}
12
+ */
13
+ export function parseMessageMarkdown(raw: string): {
14
+ author: string;
15
+ timestamp: string;
16
+ text: string;
17
+ };
18
+ /**
19
+ * 2D Git-native chat repository with time-sharded Markdown messages.
20
+ */
21
+ export class ChatRepoModel extends ModelAsApp {
22
+ static UI: {
23
+ errorAuthorTextRequired: string;
24
+ };
25
+ static repo: {
26
+ help: string;
27
+ default: string;
28
+ };
29
+ /**
30
+ * @param {Partial<ChatRepoModel>} [data]
31
+ * @param {Partial<import('@nan0web/types').ModelOptions>} [options]
32
+ */
33
+ constructor(data?: Partial<ChatRepoModel>, options?: Partial<import("@nan0web/types").ModelOptions>);
34
+ /** @type {string} Repository base URI */ repo: string;
35
+ /**
36
+ * Sends and persists a message in chat/YYYY/MM/DD/<ts>-<peer>.md and optionally updates README.md.
37
+ * @param {{ author: string, text: string, timestamp?: string, skipIndex?: boolean }} input
38
+ * @returns {Promise<{ uri: string, filename: string, author: string, timestamp: string, text: string }>}
39
+ */
40
+ sendMessage(input: {
41
+ author: string;
42
+ text: string;
43
+ timestamp?: string;
44
+ skipIndex?: boolean;
45
+ }): Promise<{
46
+ uri: string;
47
+ filename: string;
48
+ author: string;
49
+ timestamp: string;
50
+ text: string;
51
+ }>;
52
+ /**
53
+ * Lists all messages for a given YYYY-MM-DD date in chronological order.
54
+ * @param {string} dateStr
55
+ * @returns {Promise<Array<{ uri: string, filename: string, author: string, timestamp: string, text: string }>>}
56
+ */
57
+ listDay(dateStr: string): Promise<Array<{
58
+ uri: string;
59
+ filename: string;
60
+ author: string;
61
+ timestamp: string;
62
+ text: string;
63
+ }>>;
64
+ #private;
65
+ }
66
+ import { ModelAsApp } from '@nan0web/ui';