Compare commits

...

3 Commits

Author SHA1 Message Date
Hermes Agent
01b05614ff docs(framework): canonize merge-authority policy (hard gate 13 + E2E gate note)
All checks were successful
ci/woodpecker/push/ci Pipeline was successful
ci/woodpecker/pr/ci Pipeline was successful
Coordinated work: post-review merge go-ahead belongs to the active
coordinator/orchestrator session; solo delivery merges without routine
confirmation as before. 'No self-merge' means no UNREVIEWED self-merge.

Previously this policy existed only as per-host local patches to the
preserved ~/.config/mosaic/AGENTS.md (web1 + sb-it-mgr-0-lt rule 38) and
was lost from E2E-DELIVERY.md on every framework sync. Shipping it in
defaults/AGENTS.md + guides/E2E-DELIVERY.md makes it permanent for fresh
installs and upgrades.

Policy: Jason, 2026-06-11.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-11 18:41:59 -05:00
aa221bf92e release(mosaic): bump @mosaicstack/mosaic 0.0.30 -> 0.0.31 (#534)
All checks were successful
ci/woodpecker/push/ci Pipeline was successful
ci/woodpecker/push/publish Pipeline was successful
ci/woodpecker/tag/publish Pipeline was successful
2026-06-11 19:55:43 +00:00
799df40f4e feat(appservice): room provisioning (M4c) (#535)
Some checks failed
ci/woodpecker/push/publish Pipeline was canceled
ci/woodpecker/push/ci Pipeline was canceled
2026-06-11 19:50:55 +00:00
8 changed files with 209 additions and 3 deletions

View File

@@ -137,6 +137,97 @@ describe('AppserviceDaemon routing', () => {
expect(res.status).toBe(405);
});
it('provisions a room as the AS sender with space linking', async () => {
const calls: Array<{ url: URL; body: unknown }> = [];
const fetchMock = vi.fn(async (input: URL | string, init?: RequestInit) => {
const url = new URL(String(input));
calls.push({ url, body: init?.body ? JSON.parse(String(init.body)) : undefined });
if (url.pathname.endsWith('/createRoom'))
return jsonResponse(200, { room_id: '!new:hs.example' });
return jsonResponse(200, {});
});
const daemon = new AppserviceDaemon(cfg, fetchMock as unknown as typeof fetch, () => {});
const res = await daemon.handle(
request({
method: 'POST',
path: '/bridge/v1/provision/rooms',
authorizationHeader: 'Bearer bridge-secret',
body: {
name: 'proj-x',
alias: 'mosaic-proj-x',
invite: ['@jason.woltje:hs.example'],
space_id: '!space:hs.example',
},
}),
);
expect(res.status).toBe(200);
expect(res.body.room_id).toBe('!new:hs.example');
expect(res.body.space_linked).toBe(true);
const create = calls.find((c) => c.url.pathname.endsWith('/createRoom'));
expect(create!.url.searchParams.get('user_id')).toBe('@mosaic-as:hs.example');
const body = create!.body as Record<string, unknown>;
expect(body.room_alias_name).toBe('mosaic-proj-x');
expect((body.power_level_content_override as Record<string, unknown>).users).toEqual({
'@mosaic-as:hs.example': 100,
});
expect(calls.some((c) => c.url.pathname.includes('/state/m.space.child/'))).toBe(true);
expect(calls.some((c) => c.url.pathname.includes('/state/m.space.parent/'))).toBe(true);
});
it('space-link failure still returns the room id (no orphan)', async () => {
const fetchMock = vi.fn(async (input: URL | string) => {
const url = new URL(String(input));
if (url.pathname.endsWith('/createRoom'))
return jsonResponse(200, { room_id: '!new:hs.example' });
if (url.pathname.includes('/state/m.space.child/'))
return jsonResponse(403, { errcode: 'M_FORBIDDEN', error: 'no PL in space' });
return jsonResponse(200, {});
});
const daemon = new AppserviceDaemon(cfg, fetchMock as unknown as typeof fetch, () => {});
const res = await daemon.handle(
request({
method: 'POST',
path: '/bridge/v1/provision/rooms',
authorizationHeader: 'Bearer bridge-secret',
body: { name: 'proj-x', space_id: '!space:hs.example' },
}),
);
expect(res.status).toBe(200);
expect(res.body.room_id).toBe('!new:hs.example');
expect(res.body.space_linked).toBe(false);
expect(String(res.body.space_error)).toContain('403');
});
it('invite list cap enforced', async () => {
const { daemon } = makeDaemon();
const res = await daemon.handle(
request({
method: 'POST',
path: '/bridge/v1/provision/rooms',
authorizationHeader: 'Bearer bridge-secret',
body: { name: 'x', invite: Array.from({ length: 51 }, (_, i) => `@u${i}:hs`) },
}),
);
expect(res.status).toBe(400);
});
it('provision rejects bad payloads and requires auth', async () => {
const { daemon } = makeDaemon();
const noAuth = await daemon.handle(
request({ method: 'POST', path: '/bridge/v1/provision/rooms', body: { name: 'x' } }),
);
expect(noAuth.status).toBe(403);
const bad = await daemon.handle(
request({
method: 'POST',
path: '/bridge/v1/provision/rooms',
authorizationHeader: 'Bearer bridge-secret',
body: { name: '', alias: 'BAD ALIAS' },
}),
);
expect(bad.status).toBe(400);
});
it('empty bridge token list denies everything', async () => {
const daemon = new AppserviceDaemon({ ...cfg, bridgeTokens: [] }, undefined, () => {});
const res = await daemon.handle(

View File

@@ -5,6 +5,7 @@ import {
TransactionHandler,
validateBridgeMessage,
validateBridgeTyping,
validateProvisionRoom,
} from '@mosaicstack/appservice';
import type { AppserviceConfig, MatrixEvent } from '@mosaicstack/appservice';
@@ -109,6 +110,27 @@ export class AppserviceDaemon {
await this.intent.setTyping(req.body.room_id, req.body.agent, req.body.typing);
return { status: 200, body: {} };
}
if (req.method === 'POST' && req.path === '/bridge/v1/provision/rooms') {
validateProvisionRoom(req.body);
const result = await this.intent.createRoom({
name: req.body.name,
alias: req.body.alias,
topic: req.body.topic,
invite: req.body.invite,
spaceId: req.body.space_id,
});
this.log(
`provisioned room ${result.roomId} (${req.body.name}) space_linked=${result.spaceLinked}`,
);
return {
status: 200,
body: {
room_id: result.roomId,
space_linked: result.spaceLinked,
...(result.spaceError ? { space_error: result.spaceError } : {}),
},
};
}
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
this.log(`bridge error ${req.method} ${req.path}: ${message}`);

View File

@@ -50,3 +50,34 @@ export function validateBridgeTyping(input: unknown): asserts input is BridgeTyp
assertAgentSlug(o.agent);
if (typeof o.typing !== 'boolean') throw new Error('typing must be a boolean');
}
export interface ProvisionRoomDto {
name: string;
alias?: string;
topic?: string;
invite?: string[];
space_id?: string;
}
export function validateProvisionRoom(input: unknown): asserts input is ProvisionRoomDto {
const o = input as Partial<ProvisionRoomDto> | null | undefined;
if (!o || typeof o !== 'object') throw new Error('payload must be an object');
if (typeof o.name !== 'string' || o.name.length === 0) throw new Error('name is required');
if (o.alias !== undefined && (!/^[a-z0-9_.-]+$/.test(o.alias) || o.alias.length > 200)) {
throw new Error('alias must match [a-z0-9_.-]+ (max 200 chars)');
}
if (o.invite !== undefined) {
if (
!Array.isArray(o.invite) ||
o.invite.some((u) => typeof u !== 'string' || !u.startsWith('@'))
) {
throw new Error('invite must be a list of Matrix user ids');
}
if (o.invite.length > 50) {
throw new Error('invite list exceeds maximum of 50');
}
}
if (o.space_id !== undefined && (typeof o.space_id !== 'string' || !o.space_id.startsWith('!'))) {
throw new Error('space_id must be a Matrix room id');
}
}

View File

@@ -4,8 +4,12 @@ export { TransactionHandler } from './transactions.js';
export type { TransactionHandlerOptions } from './transactions.js';
export { buildRegistration, registrationToYaml } from './registration.js';
export type { RegistrationOptions } from './registration.js';
export { validateBridgeMessage, validateBridgeTyping } from './bridge.dto.js';
export type { BridgeMessageDto, BridgeTypingDto } from './bridge.dto.js';
export {
validateBridgeMessage,
validateBridgeTyping,
validateProvisionRoom,
} from './bridge.dto.js';
export type { BridgeMessageDto, BridgeTypingDto, ProvisionRoomDto } from './bridge.dto.js';
export type {
AppserviceConfig,
EventHandler,

View File

@@ -172,6 +172,58 @@ export class AppserviceIntent {
});
}
/** Create a room as the AS sender: agents get PL 50 by namespace via the
* sender (PL 100); humans invited at default PL. Optionally link into a
* space (m.space.child + m.space.parent). Returns the room id. */
async createRoom(options: {
name: string;
alias?: string;
topic?: string;
invite?: string[];
spaceId?: string;
}): Promise<{ roomId: string; spaceLinked: boolean; spaceError?: string }> {
const body: Record<string, unknown> = {
name: options.name,
preset: 'private_chat',
invite: options.invite ?? [],
power_level_content_override: {
users: { [this.senderUserId]: 100 },
// state_default 50 stays; the AS sender can grant agents as needed.
},
};
if (options.alias) body.room_alias_name = options.alias;
if (options.topic) body.topic = options.topic;
const res = await this.request('POST', '/_matrix/client/v3/createRoom', {
userId: this.senderUserId,
body,
});
const roomId = res.room_id;
if (typeof roomId !== 'string') throw new Error('createRoom returned no room_id');
if (!options.spaceId) {
return { roomId, spaceLinked: false };
}
// Space-link failures must NOT throw: the room already exists, and an
// exception would hide the room_id (orphaned room, no recovery path).
const encodedSpaceId = encodeURIComponent(options.spaceId);
const encodedRoomId = encodeURIComponent(roomId);
try {
await this.request(
'PUT',
`/_matrix/client/v3/rooms/${encodedSpaceId}/state/m.space.child/${encodedRoomId}`,
{ userId: this.senderUserId, body: { via: [this.cfg.domain], suggested: true } },
);
await this.request(
'PUT',
`/_matrix/client/v3/rooms/${encodedRoomId}/state/m.space.parent/${encodedSpaceId}`,
{ userId: this.senderUserId, body: { via: [this.cfg.domain], canonical: true } },
);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
return { roomId, spaceLinked: false, spaceError: message };
}
return { roomId, spaceLinked: true };
}
/** Set display name for an agent's virtual user. */
async setDisplayName(agent: string, displayName: string): Promise<void> {
const userId = await this.ensureRegistered(agent);

View File

@@ -34,6 +34,7 @@ At session start, additionally:
10. Manual `docker build` / `docker push` for deployment is FORBIDDEN when CI/CD pipelines exist in the repository. CI is the ONLY canonical build path for container images.
11. Before ANY build or deployment action, you MUST check for existing CI/CD pipeline configuration (`.woodpecker/`, `.woodpecker.yml`, `.github/workflows/`, etc.). If pipelines exist, use them — do not build locally.
12. The mandatory intake procedure is NOT conditional on perceived task complexity. A "simple" commit-push-deploy task has the same procedural requirements as a multi-file feature. Skipping intake because a task "seems simple" is the most common framework violation.
13. **Merge authority (coordinated work):** when a coordinator/orchestrator session is active for the work, the post-review MERGE GO-AHEAD is the coordinator's to give — once code has passed the required review gates, request the coordinator's go-ahead and merge on their confirmation; do NOT wait on the human owner personally. Solo (uncoordinated) delivery keeps the default: merge without routine confirmation per gates 2 and 9. A "No self-merge" note on a PR means no UNREVIEWED self-merge — it does not suspend coordinator-authorized merges. (Policy: Jason, 2026-06-11.)
## Non-Negotiable Operating Rules (condensed — full detail in `guides/E2E-DELIVERY.md`)

View File

@@ -88,6 +88,11 @@ For implementation work, you MUST run this cycle in order:
### Post-PR Hard Gate (Execute Sequentially, No Exceptions)
> **Merge authority:** if a coordinator/orchestrator session is active for this
> work, obtain the coordinator's merge go-ahead after review passes, then run
> the gate (AGENTS.md hard gate "Merge authority"). Solo delivery proceeds
> without asking.
1. `~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose merge -B main`
2. `~/.config/mosaic/tools/git/pr-merge.sh -n <PR_NUMBER> -m squash`
3. `~/.config/mosaic/tools/git/pr-ci-wait.sh -n <PR_NUMBER>`

View File

@@ -1,6 +1,6 @@
{
"name": "@mosaicstack/mosaic",
"version": "0.0.30",
"version": "0.0.31",
"repository": {
"type": "git",
"url": "https://git.mosaicstack.dev/mosaicstack/stack.git",