feat(v2): user-level privilege model + cold DM infra + init-first-agent skill
Replaces the agent-group-centric "main group" concept with user-level
privileges and adds the cold-DM infrastructure needed for proactive
outbound messaging (pairing, approvals, welcome flows).
Privilege model
- New tables: users, user_roles (owner global-only; admin global or
scoped to an agent_group), agent_group_members (explicit non-
privileged access; admin/owner imply membership), user_dms (cold-DM
resolution cache).
- Removed agent_groups.is_admin, messaging_groups.admin_user_id. Replaced
with messaging_groups.unknown_sender_policy (strict | request_approval
| public) for per-chat unknown-sender gating.
- src/access.ts: canAccessAgentGroup, pickApprover, pickApprovalDelivery.
- src/router.ts: access gate on every inbound, honoring
unknown_sender_policy for unknown senders.
- src/channels/telegram.ts: pairing interceptor upserts the paired user
and promotes them to owner if hasAnyOwner() is false (first-pair-wins).
Cold DM infrastructure
- ChannelAdapter.openDM?(handle) — optional method. Chat-SDK-bridge wires
it to chat.openDM() for resolution-required channels (Discord, Slack,
Teams, Webex, gChat); direct-addressable channels (Telegram, WhatsApp,
iMessage, Matrix, Resend) fall through to the handle directly.
- src/user-dm.ts: ensureUserDm(userId) — resolves + caches via user_dms.
Approval routing
- onecli-approvals + delivery use pickApprover + pickApprovalDelivery:
scoped admins → global admins → owners (dedup), first reachable via
ensureUserDm, same-channel-kind tie-break. Approvals land in the
approver's DM, not the origin chat.
Delivery fixes
- delivery.ts ACL rejection now throws instead of returning undefined —
the outer loop previously marked rejected messages as delivered.
- Implicit-origin allow: session.messaging_group_id === target skips the
destination check.
- createMessagingGroupAgent auto-creates the companion agent_destinations
row (normalized local_name from the messaging group's name, collision-
broken within the agent's namespace).
Container
- container-runner.ts: /workspace/global always read-only; drops
NANOCLAW_IS_ADMIN; adds NANOCLAW_ADMIN_USER_IDS (owners + global admins
+ scoped admins for this agent group). Agent-runner poll-loop gates
slash commands against that set.
New skill: /init-first-agent
- Walks the operator through standing up the first agent for a channel:
channel pick → identity lookup (reads each channel SKILL.md's
## Channel Info > how-to-find-id) → DM platform_id resolution (direct-
addressable, cold-DM via "user DMs bot first + sqlite lookup", or
Telegram pair-code fallback) → run scripts/init-first-agent.ts →
verify via tail of nanoclaw.log.
- scripts/init-first-agent.ts: parameterized helper that upserts the
user + grants owner (if none), creates dm-with-<display-name> agent
group + initGroupFilesystem, reuses/creates the DM messaging_group,
wires it (auto-creates destination), resolves the session, and writes
a kind:'chat' / sender:'system' welcome message into inbound.db. Host
sweep wakes the container and the agent DMs the operator via the
normal delivery path.
/manage-channels rewrite
- Drops --is-main / --jid / main-vs-non-main isolation references.
- First-channel flow delegates to /init-first-agent.
- Explains createMessagingGroupAgent auto-creates destinations.
- Adds a privileged-users show section.
setup/
- register.ts: drop --is-main, --jid, --local-name, --trigger
requiresTrigger defaults; call initGroupFilesystem; normalize to
v2 schema (no is_admin, no admin_user_id, sets unknown_sender_policy
'strict'); let createMessagingGroupAgent handle the destination row.
- pair-telegram.ts: emit PAIRED_USER_ID (namespaced "telegram:<id>")
instead of ADMIN_USER_ID; update header comment.
- register.test.ts deleted — was v1-only, tested a registered_groups
table that no longer exists.
Docs
- v2-architecture-diagram.{md,html}: ER diagram updated to drop
is_admin/admin_user_id, add unknown_sender_policy, and include
users/user_roles/agent_group_members/user_dms.
- v2-architecture-draft.md: approval-routing paragraph rewritten for
pickApprover/pickApprovalDelivery/ensureUserDm; SQL schema block
updated; admin-verification paragraph references
NANOCLAW_ADMIN_USER_IDS.
- v2-setup-wiring.md: entity-model sketch rewritten.
- v2-checklist.md: marked privilege refactor / container filtering /
approval routing / unknown-sender gating done; removed obsolete
admin_user_id and main-vs-non-main items.
Scripts
- scripts/init-first-agent.ts (new) replaces scripts/welcome-owner-dm.ts
(removed; welcome-owner was a Discord-specific one-off).
- test-v2-host.ts, test-v2-channel-e2e.ts, seed-discord.ts: drop
is_admin + admin_user_id, use unknown_sender_policy.
Tests
- src/access.test.ts (new): 14 tests for canAccessAgentGroup, role
helpers, pickApprover, ensureUserDm, pickApprovalDelivery.
- src/db/db-v2.test.ts: adds 3 tests for the auto-created
agent_destinations row (normalized name, no duplicates, collision
break within an agent group).
- host-core.test.ts, channel-registry.test.ts: updated fixtures to
use unknown_sender_policy: 'public' where the test exercises routing
rather than the access gate.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -2,8 +2,10 @@
|
||||
* Step: pair-telegram — issue a one-time pairing code and wait for the
|
||||
* operator to send `@botname CODE` from the chat they want to register.
|
||||
*
|
||||
* On success, prints platformId / isGroup / adminUserId / intent. The caller
|
||||
* (skill) then runs `setup --step register` with those values.
|
||||
* On success, prints platformId / isGroup / pairedUserId / intent. The caller
|
||||
* (skill) can then wire the chat to an agent group (e.g. via /init-first-agent
|
||||
* or setup --step register). telegram.ts's inbound interceptor has already
|
||||
* upserted the paired user and granted owner if no owner existed yet.
|
||||
*
|
||||
* The service must already be running so the telegram adapter is polling.
|
||||
*/
|
||||
@@ -93,7 +95,9 @@ export async function run(args: string[]): Promise<void> {
|
||||
INTENT: intentToString(consumed.intent),
|
||||
PLATFORM_ID: consumed.consumed!.platformId,
|
||||
IS_GROUP: consumed.consumed!.isGroup,
|
||||
ADMIN_USER_ID: consumed.consumed!.adminUserId ?? '',
|
||||
PAIRED_USER_ID: consumed.consumed!.adminUserId
|
||||
? `telegram:${consumed.consumed!.adminUserId}`
|
||||
: '',
|
||||
});
|
||||
return;
|
||||
} catch (err) {
|
||||
|
||||
@@ -1,464 +0,0 @@
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { afterEach, describe, it, expect, beforeEach } from 'vitest';
|
||||
|
||||
import Database from 'better-sqlite3';
|
||||
|
||||
/**
|
||||
* Tests for the register step.
|
||||
*
|
||||
* Verifies: parameterized SQL (no injection), file templating,
|
||||
* apostrophe in names, .env updates, CLAUDE.md template copy.
|
||||
*/
|
||||
|
||||
function createTestDb(): Database.Database {
|
||||
const db = new Database(':memory:');
|
||||
db.exec(`CREATE TABLE IF NOT EXISTS registered_groups (
|
||||
jid TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
folder TEXT NOT NULL UNIQUE,
|
||||
trigger_pattern TEXT NOT NULL,
|
||||
added_at TEXT NOT NULL,
|
||||
container_config TEXT,
|
||||
requires_trigger INTEGER DEFAULT 1,
|
||||
is_main INTEGER DEFAULT 0
|
||||
)`);
|
||||
return db;
|
||||
}
|
||||
|
||||
describe('parameterized SQL registration', () => {
|
||||
let db: Database.Database;
|
||||
|
||||
beforeEach(() => {
|
||||
db = createTestDb();
|
||||
});
|
||||
|
||||
it('registers a group with parameterized query', () => {
|
||||
db.prepare(
|
||||
`INSERT OR REPLACE INTO registered_groups
|
||||
(jid, name, folder, trigger_pattern, added_at, container_config, requires_trigger)
|
||||
VALUES (?, ?, ?, ?, ?, NULL, ?)`,
|
||||
).run(
|
||||
'123@g.us',
|
||||
'Test Group',
|
||||
'test-group',
|
||||
'@Andy',
|
||||
'2024-01-01T00:00:00.000Z',
|
||||
1,
|
||||
);
|
||||
|
||||
const row = db
|
||||
.prepare('SELECT * FROM registered_groups WHERE jid = ?')
|
||||
.get('123@g.us') as {
|
||||
jid: string;
|
||||
name: string;
|
||||
folder: string;
|
||||
trigger_pattern: string;
|
||||
requires_trigger: number;
|
||||
};
|
||||
|
||||
expect(row.jid).toBe('123@g.us');
|
||||
expect(row.name).toBe('Test Group');
|
||||
expect(row.folder).toBe('test-group');
|
||||
expect(row.trigger_pattern).toBe('@Andy');
|
||||
expect(row.requires_trigger).toBe(1);
|
||||
});
|
||||
|
||||
it('handles apostrophes in group names safely', () => {
|
||||
const name = "O'Brien's Group";
|
||||
|
||||
db.prepare(
|
||||
`INSERT OR REPLACE INTO registered_groups
|
||||
(jid, name, folder, trigger_pattern, added_at, container_config, requires_trigger)
|
||||
VALUES (?, ?, ?, ?, ?, NULL, ?)`,
|
||||
).run(
|
||||
'456@g.us',
|
||||
name,
|
||||
'obriens-group',
|
||||
'@Andy',
|
||||
'2024-01-01T00:00:00.000Z',
|
||||
0,
|
||||
);
|
||||
|
||||
const row = db
|
||||
.prepare('SELECT name FROM registered_groups WHERE jid = ?')
|
||||
.get('456@g.us') as {
|
||||
name: string;
|
||||
};
|
||||
|
||||
expect(row.name).toBe(name);
|
||||
});
|
||||
|
||||
it('prevents SQL injection in JID field', () => {
|
||||
const maliciousJid = "'; DROP TABLE registered_groups; --";
|
||||
|
||||
db.prepare(
|
||||
`INSERT OR REPLACE INTO registered_groups
|
||||
(jid, name, folder, trigger_pattern, added_at, container_config, requires_trigger)
|
||||
VALUES (?, ?, ?, ?, ?, NULL, ?)`,
|
||||
).run(maliciousJid, 'Evil', 'evil', '@Andy', '2024-01-01T00:00:00.000Z', 1);
|
||||
|
||||
// Table should still exist and have the row
|
||||
const count = db
|
||||
.prepare('SELECT COUNT(*) as count FROM registered_groups')
|
||||
.get() as {
|
||||
count: number;
|
||||
};
|
||||
expect(count.count).toBe(1);
|
||||
|
||||
const row = db.prepare('SELECT jid FROM registered_groups').get() as {
|
||||
jid: string;
|
||||
};
|
||||
expect(row.jid).toBe(maliciousJid);
|
||||
});
|
||||
|
||||
it('handles requiresTrigger=false', () => {
|
||||
db.prepare(
|
||||
`INSERT OR REPLACE INTO registered_groups
|
||||
(jid, name, folder, trigger_pattern, added_at, container_config, requires_trigger)
|
||||
VALUES (?, ?, ?, ?, ?, NULL, ?)`,
|
||||
).run(
|
||||
'789@s.whatsapp.net',
|
||||
'Personal',
|
||||
'main',
|
||||
'@Andy',
|
||||
'2024-01-01T00:00:00.000Z',
|
||||
0,
|
||||
);
|
||||
|
||||
const row = db
|
||||
.prepare('SELECT requires_trigger FROM registered_groups WHERE jid = ?')
|
||||
.get('789@s.whatsapp.net') as { requires_trigger: number };
|
||||
|
||||
expect(row.requires_trigger).toBe(0);
|
||||
});
|
||||
|
||||
it('stores is_main flag', () => {
|
||||
db.prepare(
|
||||
`INSERT OR REPLACE INTO registered_groups
|
||||
(jid, name, folder, trigger_pattern, added_at, container_config, requires_trigger, is_main)
|
||||
VALUES (?, ?, ?, ?, ?, NULL, ?, ?)`,
|
||||
).run(
|
||||
'789@s.whatsapp.net',
|
||||
'Personal',
|
||||
'whatsapp_main',
|
||||
'@Andy',
|
||||
'2024-01-01T00:00:00.000Z',
|
||||
0,
|
||||
1,
|
||||
);
|
||||
|
||||
const row = db
|
||||
.prepare('SELECT is_main FROM registered_groups WHERE jid = ?')
|
||||
.get('789@s.whatsapp.net') as { is_main: number };
|
||||
|
||||
expect(row.is_main).toBe(1);
|
||||
});
|
||||
|
||||
it('defaults is_main to 0', () => {
|
||||
db.prepare(
|
||||
`INSERT OR REPLACE INTO registered_groups
|
||||
(jid, name, folder, trigger_pattern, added_at, container_config, requires_trigger)
|
||||
VALUES (?, ?, ?, ?, ?, NULL, ?)`,
|
||||
).run(
|
||||
'123@g.us',
|
||||
'Some Group',
|
||||
'whatsapp_some-group',
|
||||
'@Andy',
|
||||
'2024-01-01T00:00:00.000Z',
|
||||
1,
|
||||
);
|
||||
|
||||
const row = db
|
||||
.prepare('SELECT is_main FROM registered_groups WHERE jid = ?')
|
||||
.get('123@g.us') as { is_main: number };
|
||||
|
||||
expect(row.is_main).toBe(0);
|
||||
});
|
||||
|
||||
it('upserts on conflict', () => {
|
||||
const stmt = db.prepare(
|
||||
`INSERT OR REPLACE INTO registered_groups
|
||||
(jid, name, folder, trigger_pattern, added_at, container_config, requires_trigger)
|
||||
VALUES (?, ?, ?, ?, ?, NULL, ?)`,
|
||||
);
|
||||
|
||||
stmt.run(
|
||||
'123@g.us',
|
||||
'Original',
|
||||
'main',
|
||||
'@Andy',
|
||||
'2024-01-01T00:00:00.000Z',
|
||||
1,
|
||||
);
|
||||
stmt.run(
|
||||
'123@g.us',
|
||||
'Updated',
|
||||
'main',
|
||||
'@Bot',
|
||||
'2024-02-01T00:00:00.000Z',
|
||||
0,
|
||||
);
|
||||
|
||||
const rows = db.prepare('SELECT * FROM registered_groups').all();
|
||||
expect(rows).toHaveLength(1);
|
||||
|
||||
const row = rows[0] as {
|
||||
name: string;
|
||||
trigger_pattern: string;
|
||||
requires_trigger: number;
|
||||
};
|
||||
expect(row.name).toBe('Updated');
|
||||
expect(row.trigger_pattern).toBe('@Bot');
|
||||
expect(row.requires_trigger).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('file templating', () => {
|
||||
it('replaces assistant name in CLAUDE.md content', () => {
|
||||
let content = '# Andy\n\nYou are Andy, a personal assistant.';
|
||||
|
||||
content = content.replace(/^# Andy$/m, '# Nova');
|
||||
content = content.replace(/You are Andy/g, 'You are Nova');
|
||||
|
||||
expect(content).toBe('# Nova\n\nYou are Nova, a personal assistant.');
|
||||
});
|
||||
|
||||
it('handles names with special regex characters', () => {
|
||||
let content = '# Andy\n\nYou are Andy.';
|
||||
|
||||
const newName = 'C.L.A.U.D.E';
|
||||
content = content.replace(/^# Andy$/m, `# ${newName}`);
|
||||
content = content.replace(/You are Andy/g, `You are ${newName}`);
|
||||
|
||||
expect(content).toContain('# C.L.A.U.D.E');
|
||||
expect(content).toContain('You are C.L.A.U.D.E.');
|
||||
});
|
||||
|
||||
it('updates .env ASSISTANT_NAME line', () => {
|
||||
let envContent = 'SOME_KEY=value\nASSISTANT_NAME="Andy"\nOTHER=test';
|
||||
|
||||
envContent = envContent.replace(
|
||||
/^ASSISTANT_NAME=.*$/m,
|
||||
'ASSISTANT_NAME="Nova"',
|
||||
);
|
||||
|
||||
expect(envContent).toContain('ASSISTANT_NAME="Nova"');
|
||||
expect(envContent).toContain('SOME_KEY=value');
|
||||
});
|
||||
|
||||
it('appends ASSISTANT_NAME to .env if not present', () => {
|
||||
let envContent = 'SOME_KEY=value\n';
|
||||
|
||||
if (!envContent.includes('ASSISTANT_NAME=')) {
|
||||
envContent += '\nASSISTANT_NAME="Nova"';
|
||||
}
|
||||
|
||||
expect(envContent).toContain('ASSISTANT_NAME="Nova"');
|
||||
});
|
||||
});
|
||||
|
||||
describe('CLAUDE.md template copy', () => {
|
||||
let tmpDir: string;
|
||||
let groupsDir: string;
|
||||
|
||||
// Replicates register.ts template copy + name update logic
|
||||
function simulateRegister(
|
||||
folder: string,
|
||||
isMain: boolean,
|
||||
assistantName = 'Andy',
|
||||
): void {
|
||||
const folderDir = path.join(groupsDir, folder);
|
||||
fs.mkdirSync(path.join(folderDir, 'logs'), { recursive: true });
|
||||
|
||||
// Template copy — never overwrite existing (register.ts lines 119-135)
|
||||
const dest = path.join(folderDir, 'CLAUDE.md');
|
||||
if (!fs.existsSync(dest)) {
|
||||
const templatePath = isMain
|
||||
? path.join(groupsDir, 'main', 'CLAUDE.md')
|
||||
: path.join(groupsDir, 'global', 'CLAUDE.md');
|
||||
if (fs.existsSync(templatePath)) {
|
||||
fs.copyFileSync(templatePath, dest);
|
||||
}
|
||||
}
|
||||
|
||||
// Name update across all groups (register.ts lines 140-165)
|
||||
if (assistantName !== 'Andy') {
|
||||
const mdFiles = fs
|
||||
.readdirSync(groupsDir)
|
||||
.map((d) => path.join(groupsDir, d, 'CLAUDE.md'))
|
||||
.filter((f) => fs.existsSync(f));
|
||||
|
||||
for (const mdFile of mdFiles) {
|
||||
let content = fs.readFileSync(mdFile, 'utf-8');
|
||||
content = content.replace(/^# Andy$/m, `# ${assistantName}`);
|
||||
content = content.replace(
|
||||
/You are Andy/g,
|
||||
`You are ${assistantName}`,
|
||||
);
|
||||
fs.writeFileSync(mdFile, content);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function readGroupMd(folder: string): string {
|
||||
return fs.readFileSync(
|
||||
path.join(groupsDir, folder, 'CLAUDE.md'),
|
||||
'utf-8',
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nanoclaw-register-test-'));
|
||||
groupsDir = path.join(tmpDir, 'groups');
|
||||
fs.mkdirSync(path.join(groupsDir, 'main'), { recursive: true });
|
||||
fs.mkdirSync(path.join(groupsDir, 'global'), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(groupsDir, 'main', 'CLAUDE.md'),
|
||||
'# Andy\n\nYou are Andy, a personal assistant.\n\n## Admin Context\n\nThis is the **main channel**.',
|
||||
);
|
||||
fs.writeFileSync(
|
||||
path.join(groupsDir, 'global', 'CLAUDE.md'),
|
||||
'# Andy\n\nYou are Andy, a personal assistant.',
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('copies global template for non-main group', () => {
|
||||
simulateRegister('telegram_dev-team', false);
|
||||
|
||||
const content = readGroupMd('telegram_dev-team');
|
||||
expect(content).toContain('You are Andy');
|
||||
expect(content).not.toContain('Admin Context');
|
||||
});
|
||||
|
||||
it('copies main template for main group', () => {
|
||||
simulateRegister('whatsapp_main', true);
|
||||
|
||||
expect(readGroupMd('whatsapp_main')).toContain('Admin Context');
|
||||
});
|
||||
|
||||
it('each channel can have its own main with admin context', () => {
|
||||
simulateRegister('whatsapp_main', true);
|
||||
simulateRegister('telegram_main', true);
|
||||
simulateRegister('slack_main', true);
|
||||
simulateRegister('discord_main', true);
|
||||
|
||||
for (const folder of [
|
||||
'whatsapp_main',
|
||||
'telegram_main',
|
||||
'slack_main',
|
||||
'discord_main',
|
||||
]) {
|
||||
const content = readGroupMd(folder);
|
||||
expect(content).toContain('Admin Context');
|
||||
expect(content).toContain('You are Andy');
|
||||
}
|
||||
});
|
||||
|
||||
it('non-main groups across channels get global template', () => {
|
||||
simulateRegister('whatsapp_main', true);
|
||||
simulateRegister('telegram_friends', false);
|
||||
simulateRegister('slack_engineering', false);
|
||||
simulateRegister('discord_general', false);
|
||||
|
||||
expect(readGroupMd('whatsapp_main')).toContain('Admin Context');
|
||||
for (const folder of [
|
||||
'telegram_friends',
|
||||
'slack_engineering',
|
||||
'discord_general',
|
||||
]) {
|
||||
const content = readGroupMd(folder);
|
||||
expect(content).toContain('You are Andy');
|
||||
expect(content).not.toContain('Admin Context');
|
||||
}
|
||||
});
|
||||
|
||||
it('custom name propagates to all channels and groups', () => {
|
||||
// Register multiple channels, last one sets custom name
|
||||
simulateRegister('whatsapp_main', true);
|
||||
simulateRegister('telegram_main', true);
|
||||
simulateRegister('slack_devs', false);
|
||||
// Final registration triggers name update across all
|
||||
simulateRegister('discord_main', true, 'Luna');
|
||||
|
||||
for (const folder of [
|
||||
'main',
|
||||
'global',
|
||||
'whatsapp_main',
|
||||
'telegram_main',
|
||||
'slack_devs',
|
||||
'discord_main',
|
||||
]) {
|
||||
const content = readGroupMd(folder);
|
||||
expect(content).toContain('# Luna');
|
||||
expect(content).toContain('You are Luna');
|
||||
expect(content).not.toContain('Andy');
|
||||
}
|
||||
});
|
||||
|
||||
it('never overwrites existing CLAUDE.md on re-registration', () => {
|
||||
simulateRegister('slack_main', true);
|
||||
// User customizes the file extensively (persona, workspace, rules)
|
||||
const mdPath = path.join(groupsDir, 'slack_main', 'CLAUDE.md');
|
||||
fs.writeFileSync(
|
||||
mdPath,
|
||||
'# Gambi\n\nCustom persona with workspace rules and family context.',
|
||||
);
|
||||
// Re-registering same folder (e.g. re-running /add-slack)
|
||||
simulateRegister('slack_main', true);
|
||||
|
||||
const content = readGroupMd('slack_main');
|
||||
expect(content).toContain('Custom persona');
|
||||
expect(content).not.toContain('Admin Context');
|
||||
});
|
||||
|
||||
it('never overwrites when non-main becomes main (isMain changes)', () => {
|
||||
// User registers a family group as non-main
|
||||
simulateRegister('whatsapp_casa', false);
|
||||
// User extensively customizes it (PARA system, task management, etc.)
|
||||
const mdPath = path.join(groupsDir, 'whatsapp_casa', 'CLAUDE.md');
|
||||
fs.writeFileSync(
|
||||
mdPath,
|
||||
'# Casa\n\nFamily group with PARA system, task management, shopping lists.',
|
||||
);
|
||||
// Later, user promotes to main (no trigger required) — CLAUDE.md must be preserved
|
||||
simulateRegister('whatsapp_casa', true);
|
||||
|
||||
const content = readGroupMd('whatsapp_casa');
|
||||
expect(content).toContain('PARA system');
|
||||
expect(content).not.toContain('Admin Context');
|
||||
});
|
||||
|
||||
it('preserves custom CLAUDE.md across channels when changing main', () => {
|
||||
// Real-world scenario: WhatsApp main + customized Discord research channel
|
||||
simulateRegister('whatsapp_main', true);
|
||||
simulateRegister('discord_main', false);
|
||||
const discordPath = path.join(groupsDir, 'discord_main', 'CLAUDE.md');
|
||||
fs.writeFileSync(
|
||||
discordPath,
|
||||
'# Gambi HQ — Research Assistant\n\nResearch workflows for Laura and Ethan.',
|
||||
);
|
||||
|
||||
// Discord becomes main too — custom content must survive
|
||||
simulateRegister('discord_main', true);
|
||||
expect(readGroupMd('discord_main')).toContain('Research Assistant');
|
||||
// WhatsApp main also untouched
|
||||
expect(readGroupMd('whatsapp_main')).toContain('Admin Context');
|
||||
});
|
||||
|
||||
it('handles missing templates gracefully', () => {
|
||||
fs.unlinkSync(path.join(groupsDir, 'global', 'CLAUDE.md'));
|
||||
fs.unlinkSync(path.join(groupsDir, 'main', 'CLAUDE.md'));
|
||||
|
||||
simulateRegister('discord_general', false);
|
||||
|
||||
expect(
|
||||
fs.existsSync(path.join(groupsDir, 'discord_general', 'CLAUDE.md')),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -11,11 +11,6 @@ import { DATA_DIR } from '../src/config.js';
|
||||
import { initDb } from '../src/db/connection.js';
|
||||
import { runMigrations } from '../src/db/migrations/index.js';
|
||||
import { createAgentGroup, getAgentGroupByFolder } from '../src/db/agent-groups.js';
|
||||
import {
|
||||
createDestination,
|
||||
getDestinationByName,
|
||||
normalizeName,
|
||||
} from '../src/db/agent-destinations.js';
|
||||
import {
|
||||
createMessagingGroup,
|
||||
createMessagingGroupAgent,
|
||||
@@ -23,6 +18,7 @@ import {
|
||||
getMessagingGroupAgentByPair,
|
||||
} from '../src/db/messaging-groups.js';
|
||||
import { isValidGroupFolder } from '../src/group-folder.js';
|
||||
import { initGroupFilesystem } from '../src/group-init.js';
|
||||
import { log } from '../src/log.js';
|
||||
import { resolveSession, writeSessionMessage } from '../src/session-manager.js';
|
||||
import { emitStatus } from './status.js';
|
||||
@@ -40,14 +36,10 @@ interface RegisterArgs {
|
||||
channel: string;
|
||||
/** Whether messages require the trigger pattern to activate */
|
||||
requiresTrigger: boolean;
|
||||
/** Whether this is the admin/main agent group */
|
||||
isMain: boolean;
|
||||
/** Display name for the assistant */
|
||||
assistantName: string;
|
||||
/** Session mode: 'shared' (one session per channel) or 'per-thread' */
|
||||
sessionMode: string;
|
||||
/** Optional local name the agent uses for this channel (defaults to normalized messaging group name) */
|
||||
localName: string | null;
|
||||
}
|
||||
|
||||
function parseArgs(args: string[]): RegisterArgs {
|
||||
@@ -58,16 +50,12 @@ function parseArgs(args: string[]): RegisterArgs {
|
||||
folder: '',
|
||||
channel: 'discord',
|
||||
requiresTrigger: true,
|
||||
isMain: false,
|
||||
assistantName: 'Andy',
|
||||
sessionMode: 'shared',
|
||||
localName: null,
|
||||
};
|
||||
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
switch (args[i]) {
|
||||
// Accept both --jid (v1 compat) and --platform-id (v2)
|
||||
case '--jid':
|
||||
case '--platform-id':
|
||||
result.platformId = args[++i] || '';
|
||||
break;
|
||||
@@ -86,18 +74,12 @@ function parseArgs(args: string[]): RegisterArgs {
|
||||
case '--no-trigger-required':
|
||||
result.requiresTrigger = false;
|
||||
break;
|
||||
case '--is-main':
|
||||
result.isMain = true;
|
||||
break;
|
||||
case '--assistant-name':
|
||||
result.assistantName = args[++i] || 'Andy';
|
||||
break;
|
||||
case '--session-mode':
|
||||
result.sessionMode = args[++i] || 'shared';
|
||||
break;
|
||||
case '--local-name':
|
||||
result.localName = args[++i] || null;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -153,7 +135,6 @@ export async function run(args: string[]): Promise<void> {
|
||||
id: agId,
|
||||
name: parsed.assistantName,
|
||||
folder: parsed.folder,
|
||||
is_admin: parsed.isMain ? 1 : 0,
|
||||
agent_provider: null,
|
||||
container_config: null,
|
||||
created_at: new Date().toISOString(),
|
||||
@@ -161,6 +142,7 @@ export async function run(args: string[]): Promise<void> {
|
||||
agentGroup = getAgentGroupByFolder(parsed.folder)!;
|
||||
log.info('Created agent group', { id: agId, folder: parsed.folder });
|
||||
}
|
||||
initGroupFilesystem(agentGroup);
|
||||
|
||||
// 2. Create or find messaging group
|
||||
let messagingGroup = getMessagingGroupByPlatform(parsed.channel, parsed.platformId);
|
||||
@@ -172,14 +154,15 @@ export async function run(args: string[]): Promise<void> {
|
||||
platform_id: parsed.platformId,
|
||||
name: parsed.name,
|
||||
is_group: 1,
|
||||
admin_user_id: null,
|
||||
unknown_sender_policy: 'strict',
|
||||
created_at: new Date().toISOString(),
|
||||
});
|
||||
messagingGroup = getMessagingGroupByPlatform(parsed.channel, parsed.platformId)!;
|
||||
log.info('Created messaging group', { id: mgId, channel: parsed.channel, platformId: parsed.platformId });
|
||||
}
|
||||
|
||||
// 3. Wire agent to messaging group + create destination row for the agent's map
|
||||
// 3. Wire agent to messaging group — createMessagingGroupAgent auto-creates
|
||||
// the companion agent_destinations row so delivery's ACL admits this target.
|
||||
let newlyWired = false;
|
||||
const existing = getMessagingGroupAgentByPair(messagingGroup.id, agentGroup.id);
|
||||
if (!existing) {
|
||||
@@ -198,31 +181,13 @@ export async function run(args: string[]): Promise<void> {
|
||||
trigger_rules: triggerRules,
|
||||
response_scope: 'all',
|
||||
session_mode: parsed.sessionMode,
|
||||
priority: parsed.isMain ? 10 : 0,
|
||||
created_at: new Date().toISOString(),
|
||||
});
|
||||
|
||||
// Create destination row so the agent can address this channel by name.
|
||||
// Auto-suffix on collision within this agent's namespace.
|
||||
const baseLocalName = normalizeName(parsed.localName || parsed.name);
|
||||
let localName = baseLocalName;
|
||||
let suffix = 2;
|
||||
while (getDestinationByName(agentGroup.id, localName)) {
|
||||
localName = `${baseLocalName}-${suffix}`;
|
||||
suffix++;
|
||||
}
|
||||
createDestination({
|
||||
agent_group_id: agentGroup.id,
|
||||
local_name: localName,
|
||||
target_type: 'channel',
|
||||
target_id: messagingGroup.id,
|
||||
priority: 0,
|
||||
created_at: new Date().toISOString(),
|
||||
});
|
||||
log.info('Wired agent to messaging group', {
|
||||
mgaId,
|
||||
agentGroup: agentGroup.id,
|
||||
messagingGroup: messagingGroup.id,
|
||||
localName,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -242,22 +207,7 @@ export async function run(args: string[]): Promise<void> {
|
||||
log.info('Onboarding message written', { sessionId: session.id, channel: parsed.channel });
|
||||
}
|
||||
|
||||
// 5. Create group folders
|
||||
fs.mkdirSync(path.join(projectRoot, 'groups', parsed.folder, 'logs'), { recursive: true });
|
||||
|
||||
// Create CLAUDE.md from template if it doesn't exist
|
||||
const groupClaudeMdPath = path.join(projectRoot, 'groups', parsed.folder, 'CLAUDE.md');
|
||||
if (!fs.existsSync(groupClaudeMdPath)) {
|
||||
const templatePath = parsed.isMain
|
||||
? path.join(projectRoot, 'groups', 'main', 'CLAUDE.md')
|
||||
: path.join(projectRoot, 'groups', 'global', 'CLAUDE.md');
|
||||
if (fs.existsSync(templatePath)) {
|
||||
fs.copyFileSync(templatePath, groupClaudeMdPath);
|
||||
log.info('Created CLAUDE.md from template', { file: groupClaudeMdPath, template: templatePath });
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Update assistant name in CLAUDE.md files if different from default
|
||||
// 5. Update assistant name in CLAUDE.md files if different from default
|
||||
let nameUpdated = false;
|
||||
if (parsed.assistantName !== 'Andy') {
|
||||
log.info('Updating assistant name', { from: 'Andy', to: parsed.assistantName });
|
||||
|
||||
Reference in New Issue
Block a user