wip(sync): merge main into next with combined resolutions

This commit is contained in:
2026-08-02 23:11:22 -05:00
628 changed files with 126796 additions and 4189 deletions
+261
View File
@@ -0,0 +1,261 @@
import { describe, expect, it, vi } from 'vitest';
import type {
ConnectorExecutionContext,
ConnectorExecutionGrant,
ConnectorLease,
ConnectorLeaseAuditEvent,
ConnectorLeaseStore,
FencedConnectorAdapter,
LogicalAgentBinding,
} from '@mosaicstack/types';
import {
ConnectorLeaseCoordinator,
MAX_CONNECTOR_GRANT_TTL_MS,
MAX_CONNECTOR_LEASE_TTL_MS,
} from './connector-lease.js';
import type { ConnectorLeaseError } from './connector-lease.js';
const identity = { tenantId: 'tenant-a', logicalAgentId: 'mos' } as const;
const binding: LogicalAgentBinding = { identity, bindingId: 'operator-chat' };
const activeLease: ConnectorLease = {
...binding,
leaseId: '00000000-0000-4000-8000-000000000001',
connectorId: 'connector-a',
scopes: ['runtime.send', 'tool.execute'],
leaseEpoch: '3',
acquiredAt: '2026-07-14T17:00:00.000Z',
heartbeatAt: '2026-07-14T17:00:00.000Z',
expiresAt: '2026-07-14T17:10:00.000Z',
};
class FakeLeaseStore implements ConnectorLeaseStore {
lease: ConnectorLease | null = activeLease;
readonly audits: ConnectorLeaseAuditEvent[] = [];
async acquire(): Promise<ConnectorLease> {
if (!this.lease) throw new Error('fixture has no lease');
return this.lease;
}
async takeover(): Promise<ConnectorLease> {
if (!this.lease) throw new Error('fixture has no lease');
return this.lease;
}
async heartbeat(): Promise<ConnectorLease> {
if (!this.lease) throw new Error('fixture has no lease');
return this.lease;
}
async release(): Promise<void> {}
async findCurrent(): Promise<ConnectorLease | null> {
return this.lease;
}
async recordAudit(event: ConnectorLeaseAuditEvent): Promise<void> {
this.audits.push(event);
}
}
describe('ConnectorLeaseCoordinator fencing', (): void => {
it('validates a server-minted grant immediately before invoking an adapter side effect', async (): Promise<void> => {
const store = new FakeLeaseStore();
const coordinator = new ConnectorLeaseCoordinator(store, {
now: (): Date => new Date('2026-07-14T17:01:00.000Z'),
});
const grant = await coordinator.issueGrant({
lease: activeLease,
scopes: ['runtime.send'],
ttlMs: 30_000,
correlationId: 'correlation-1',
});
const execute = vi.fn(async (_input: string, context: ConnectorExecutionContext) => context);
const adapter: FencedConnectorAdapter<string, ConnectorExecutionContext> = { execute };
const context = await coordinator.executeGrant(grant, 'runtime.send', 'hello', adapter);
expect(execute).toHaveBeenCalledOnce();
expect(context).toMatchObject({
identity,
bindingId: 'operator-chat',
connectorId: 'connector-a',
leaseEpoch: '3',
scopes: ['runtime.send'],
});
});
it('caps grant expiry to the durable current lease instead of submitted metadata', async (): Promise<void> => {
const store = new FakeLeaseStore();
store.lease = { ...activeLease, expiresAt: '2026-07-14T17:01:05.000Z' };
const coordinator = new ConnectorLeaseCoordinator(store, {
now: (): Date => new Date('2026-07-14T17:01:00.000Z'),
});
const grant = await coordinator.issueGrant({
lease: { ...activeLease, expiresAt: '2026-07-14T18:00:00.000Z' },
scopes: ['runtime.send'],
ttlMs: 30_000,
correlationId: 'correlation-durable-expiry',
});
expect(grant.expiresAt).toBe('2026-07-14T17:01:05.000Z');
});
it.each([
['forged clone', (grant: ConnectorExecutionGrant): ConnectorExecutionGrant => ({ ...grant })],
[
'cross-tenant clone',
(grant: ConnectorExecutionGrant): ConnectorExecutionGrant => ({
...grant,
identity: { ...grant.identity, tenantId: 'tenant-b' },
}),
],
[
'cross-agent clone',
(grant: ConnectorExecutionGrant): ConnectorExecutionGrant => ({
...grant,
identity: { ...grant.identity, logicalAgentId: 'other-agent' },
}),
],
[
'cross-binding clone',
(grant: ConnectorExecutionGrant): ConnectorExecutionGrant => ({
...grant,
bindingId: 'other-binding',
}),
],
[
'cross-connector clone',
(grant: ConnectorExecutionGrant): ConnectorExecutionGrant => ({
...grant,
connectorId: 'connector-b',
}),
],
])('denies and audits a %s before adapter invocation', async (_label, forge): Promise<void> => {
const store = new FakeLeaseStore();
const coordinator = new ConnectorLeaseCoordinator(store, {
now: (): Date => new Date('2026-07-14T17:01:00.000Z'),
});
const grant = await coordinator.issueGrant({
lease: activeLease,
scopes: ['runtime.send'],
ttlMs: 30_000,
correlationId: 'correlation-forged',
});
const adapter = { execute: vi.fn().mockResolvedValue(undefined) };
await expect(
coordinator.executeGrant(forge(grant), 'runtime.send', undefined, adapter),
).rejects.toMatchObject({ code: 'forged_grant' } satisfies Partial<ConnectorLeaseError>);
expect(adapter.execute).not.toHaveBeenCalled();
expect(store.audits.at(-1)).toMatchObject({
event: 'reject',
outcome: 'denied',
reason: 'forged_grant',
correlationId: 'correlation-forged',
});
});
it('denies malformed forged grants with sanitized audit metadata', async (): Promise<void> => {
const store = new FakeLeaseStore();
const coordinator = new ConnectorLeaseCoordinator(store, {
now: (): Date => new Date('2026-07-14T17:01:00.000Z'),
});
const adapter = { execute: vi.fn().mockResolvedValue(undefined) };
await expect(
coordinator.executeGrant(
// @ts-expect-error Deliberately exercise malformed runtime input at the trust boundary.
{},
'runtime.send',
undefined,
adapter,
),
).rejects.toMatchObject({ code: 'forged_grant' } satisfies Partial<ConnectorLeaseError>);
expect(adapter.execute).not.toHaveBeenCalled();
expect(store.audits).toContainEqual(
expect.objectContaining({
identity: { tenantId: 'untrusted', logicalAgentId: 'untrusted' },
bindingId: 'untrusted',
connectorId: 'untrusted',
correlationId: 'untrusted',
reason: 'forged_grant',
}),
);
});
it('rejects lease and grant TTLs above server-side safety caps', async (): Promise<void> => {
const store = new FakeLeaseStore();
const coordinator = new ConnectorLeaseCoordinator(store, {
now: (): Date => new Date('2026-07-14T17:01:00.000Z'),
});
expect(
() =>
new ConnectorLeaseCoordinator(store, {
maxLeaseTtlMs: MAX_CONNECTOR_LEASE_TTL_MS + 1,
}),
).toThrow(/no greater than/);
await expect(
coordinator.acquire({
identity,
bindingId: 'operator-chat',
connectorId: 'connector-a',
scopes: ['runtime.send'],
ttlMs: MAX_CONNECTOR_LEASE_TTL_MS + 1,
correlationId: 'correlation-ttl',
}),
).rejects.toThrow(/no greater than/);
await expect(
coordinator.issueGrant({
lease: activeLease,
scopes: ['runtime.send'],
ttlMs: MAX_CONNECTOR_GRANT_TTL_MS + 1,
correlationId: 'correlation-ttl',
}),
).rejects.toThrow(/no greater than/);
});
it('denies stale epoch, expired grant, and unauthorized scope before side effects', async (): Promise<void> => {
let now = new Date('2026-07-14T17:01:00.000Z');
const store = new FakeLeaseStore();
const coordinator = new ConnectorLeaseCoordinator(store, { now: (): Date => now });
const stale = await coordinator.issueGrant({
lease: activeLease,
scopes: ['runtime.send'],
ttlMs: 30_000,
correlationId: 'correlation-stale',
});
store.lease = { ...activeLease, leaseEpoch: '4', connectorId: 'connector-b' };
const adapter = { execute: vi.fn().mockResolvedValue(undefined) };
await expect(
coordinator.executeGrant(stale, 'runtime.send', undefined, adapter),
).rejects.toMatchObject({ code: 'stale_epoch' } satisfies Partial<ConnectorLeaseError>);
store.lease = activeLease;
const expiring = await coordinator.issueGrant({
lease: activeLease,
scopes: ['runtime.send'],
ttlMs: 1_000,
correlationId: 'correlation-expired',
});
now = new Date('2026-07-14T17:01:02.000Z');
await expect(
coordinator.executeGrant(expiring, 'runtime.send', undefined, adapter),
).rejects.toMatchObject({ code: 'grant_expired' } satisfies Partial<ConnectorLeaseError>);
now = new Date('2026-07-14T17:01:00.000Z');
const scoped = await coordinator.issueGrant({
lease: activeLease,
scopes: ['runtime.send'],
ttlMs: 30_000,
correlationId: 'correlation-scope',
});
await expect(
coordinator.executeGrant(scoped, 'tool.execute', undefined, adapter),
).rejects.toMatchObject({ code: 'scope_denied' } satisfies Partial<ConnectorLeaseError>);
expect(adapter.execute).not.toHaveBeenCalled();
});
});
+381
View File
@@ -0,0 +1,381 @@
import { randomUUID } from 'node:crypto';
import {
normalizeConnectorId,
normalizeConnectorScope,
normalizeConnectorScopes,
normalizeCorrelationId,
normalizeLeaseEpoch,
normalizeLogicalAgentIdentity,
normalizeLogicalBindingId,
type AcquireConnectorLeaseInput,
type ConnectorExecutionContext,
type ConnectorExecutionGrant,
type ConnectorLease,
type ConnectorLeaseAuditEvent,
type ConnectorLeaseRejectReason,
type ConnectorLeaseStore,
type FencedConnectorAdapter,
type HeartbeatConnectorLeaseInput,
type IssueConnectorExecutionGrantInput,
type LogicalAgentBinding,
type ReleaseConnectorLeaseInput,
type TakeoverConnectorLeaseInput,
} from '@mosaicstack/types';
export const MAX_CONNECTOR_LEASE_TTL_MS = 5 * 60 * 1000;
export const MAX_CONNECTOR_GRANT_TTL_MS = 30 * 1000;
export interface ConnectorLeaseCoordinatorOptions {
readonly now?: () => Date;
readonly maxLeaseTtlMs?: number;
readonly maxGrantTtlMs?: number;
}
export class ConnectorLeaseError extends Error {
constructor(
readonly code: ConnectorLeaseRejectReason,
message: string,
) {
super(message);
this.name = ConnectorLeaseError.name;
}
}
/**
* Runtime-neutral lease coordinator. Durable CAS lives in the store adapter;
* grant provenance remains process-local so a restart fails closed and mints
* fresh grants from the durable current lease.
*/
export class ConnectorLeaseCoordinator {
private readonly issuedGrants = new WeakSet<object>();
private readonly now: () => Date;
private readonly maxLeaseTtlMs: number;
private readonly maxGrantTtlMs: number;
constructor(
private readonly store: ConnectorLeaseStore,
options: ConnectorLeaseCoordinatorOptions = {},
) {
this.now = options.now ?? (() => new Date());
this.maxLeaseTtlMs = normalizeTtlLimit(
options.maxLeaseTtlMs ?? MAX_CONNECTOR_LEASE_TTL_MS,
MAX_CONNECTOR_LEASE_TTL_MS,
'lease',
);
this.maxGrantTtlMs = normalizeTtlLimit(
options.maxGrantTtlMs ?? MAX_CONNECTOR_GRANT_TTL_MS,
MAX_CONNECTOR_GRANT_TTL_MS,
'grant',
);
}
async acquire(input: AcquireConnectorLeaseInput): Promise<ConnectorLease> {
const command = normalizeAcquireInput(input, this.maxLeaseTtlMs);
const now = this.now();
return this.store.acquire({
...command,
leaseId: randomUUID(),
now: now.toISOString(),
expiresAt: expiresAt(now, command.ttlMs),
});
}
async takeover(input: TakeoverConnectorLeaseInput): Promise<ConnectorLease> {
const command = normalizeAcquireInput(input, this.maxLeaseTtlMs);
const now = this.now();
return this.store.takeover({
...command,
expectedEpoch: normalizeLeaseEpoch(input.expectedEpoch),
leaseId: randomUUID(),
now: now.toISOString(),
expiresAt: expiresAt(now, command.ttlMs),
});
}
async heartbeat(input: HeartbeatConnectorLeaseInput): Promise<ConnectorLease> {
const now = this.now();
const lease = normalizeConnectorLease(input.lease);
const ttlMs = normalizeTtl(input.ttlMs, this.maxLeaseTtlMs, 'lease');
return this.store.heartbeat({
lease,
ttlMs,
correlationId: normalizeCorrelationId(input.correlationId),
now: now.toISOString(),
expiresAt: expiresAt(now, ttlMs),
});
}
async release(input: ReleaseConnectorLeaseInput): Promise<void> {
await this.store.release({
lease: normalizeConnectorLease(input.lease),
correlationId: normalizeCorrelationId(input.correlationId),
now: this.now().toISOString(),
});
}
async current(binding: LogicalAgentBinding): Promise<ConnectorLease | null> {
return this.store.findCurrent(normalizeBinding(binding));
}
async issueGrant(input: IssueConnectorExecutionGrantInput): Promise<ConnectorExecutionGrant> {
const now = this.now();
const lease = normalizeConnectorLease(input.lease);
const scopes = normalizeConnectorScopes(input.scopes);
const correlationId = normalizeCorrelationId(input.correlationId);
const ttlMs = normalizeTtl(input.ttlMs, this.maxGrantTtlMs, 'grant');
const current = await this.store.findCurrent(lease);
await this.assertCurrentLease(current, lease, now, correlationId);
if (!current) throw new ConnectorLeaseError('lease_missing', 'Connector lease is unavailable');
if (!isScopeSubset(scopes, lease.scopes) || !isScopeSubset(scopes, current.scopes)) {
await this.reject(lease, correlationId, now, 'scope_denied');
}
const requestedExpiry = new Date(now.getTime() + ttlMs);
const leaseExpiry = new Date(current.expiresAt);
const grantExpiry = requestedExpiry < leaseExpiry ? requestedExpiry : leaseExpiry;
const grant: ConnectorExecutionGrant = Object.freeze({
identity: current.identity,
bindingId: current.bindingId,
leaseId: current.leaseId,
connectorId: current.connectorId,
scopes,
leaseEpoch: current.leaseEpoch,
issuedAt: now.toISOString(),
expiresAt: grantExpiry.toISOString(),
correlationId,
});
this.issuedGrants.add(grant);
return grant;
}
async executeGrant<TInput, TOutput>(
grant: ConnectorExecutionGrant,
requiredScope: string,
input: TInput,
adapter: FencedConnectorAdapter<TInput, TOutput>,
): Promise<TOutput> {
const now = this.now();
const normalizedScope = normalizeConnectorScope(requiredScope);
if (!this.issuedGrants.has(grant)) {
await this.rejectForgedGrant(grant, now);
}
if (new Date(grant.expiresAt) <= now) {
await this.rejectGrant(grant, now, 'grant_expired');
}
const current = await this.store.findCurrent(normalizeBinding(grant));
await this.assertCurrentLease(current, grant, now, grant.correlationId);
if (!grant.scopes.includes(normalizedScope) || !current?.scopes.includes(normalizedScope)) {
await this.rejectGrant(grant, now, 'scope_denied');
}
if (!current) throw new ConnectorLeaseError('lease_missing', 'Connector lease is unavailable');
const context: ConnectorExecutionContext = Object.freeze({
identity: current.identity,
bindingId: current.bindingId,
leaseId: current.leaseId,
connectorId: current.connectorId,
scopes: Object.freeze([...grant.scopes]),
leaseEpoch: current.leaseEpoch,
correlationId: grant.correlationId,
grantExpiresAt: grant.expiresAt,
});
return adapter.execute(input, context);
}
private async assertCurrentLease(
current: ConnectorLease | null,
authority: ConnectorLease | ConnectorExecutionGrant,
now: Date,
correlationId: string,
): Promise<void> {
if (!current) await this.reject(authority, correlationId, now, 'lease_missing');
if (!current) throw new ConnectorLeaseError('lease_missing', 'Connector lease is unavailable');
if (current.releasedAt) await this.reject(authority, correlationId, now, 'lease_released');
if (new Date(current.expiresAt) <= now) {
await this.store.recordAudit(auditEvent(current, correlationId, now, 'expiry', 'succeeded'));
await this.reject(authority, correlationId, now, 'lease_expired');
}
if (current.leaseEpoch !== authority.leaseEpoch) {
await this.reject(authority, correlationId, now, 'stale_epoch');
}
if (current.leaseId !== authority.leaseId || current.connectorId !== authority.connectorId) {
await this.reject(authority, correlationId, now, 'connector_mismatch');
}
}
private async rejectGrant(
grant: ConnectorExecutionGrant,
now: Date,
reason: ConnectorLeaseRejectReason,
): Promise<never> {
return this.reject(grant, grant.correlationId, now, reason);
}
private async rejectForgedGrant(grant: unknown, now: Date): Promise<never> {
const event = safeForgedGrantAudit(grant, now);
await this.store.recordAudit(event);
throw new ConnectorLeaseError('forged_grant', safeReasonMessage('forged_grant'));
}
private async reject(
authority: LogicalAgentBinding & {
readonly connectorId: string;
readonly leaseId?: string;
readonly leaseEpoch?: string;
},
correlationId: string,
now: Date,
reason: ConnectorLeaseRejectReason,
): Promise<never> {
await this.store.recordAudit(
auditEvent(authority, correlationId, now, 'reject', 'denied', reason),
);
throw new ConnectorLeaseError(reason, safeReasonMessage(reason));
}
}
function normalizeAcquireInput(
input: AcquireConnectorLeaseInput,
maxLeaseTtlMs: number,
): AcquireConnectorLeaseInput {
return {
identity: normalizeLogicalAgentIdentity(input.identity),
bindingId: normalizeLogicalBindingId(input.bindingId),
connectorId: normalizeConnectorId(input.connectorId),
scopes: normalizeConnectorScopes(input.scopes),
ttlMs: normalizeTtl(input.ttlMs, maxLeaseTtlMs, 'lease'),
correlationId: normalizeCorrelationId(input.correlationId),
};
}
function normalizeBinding(input: LogicalAgentBinding): LogicalAgentBinding {
return {
identity: normalizeLogicalAgentIdentity(input.identity),
bindingId: normalizeLogicalBindingId(input.bindingId),
};
}
export function normalizeConnectorLease(lease: ConnectorLease): ConnectorLease {
const binding = normalizeBinding(lease);
return Object.freeze({
...binding,
leaseId: lease.leaseId,
connectorId: normalizeConnectorId(lease.connectorId),
scopes: normalizeConnectorScopes(lease.scopes),
leaseEpoch: normalizeLeaseEpoch(lease.leaseEpoch),
acquiredAt: normalizeTimestamp(lease.acquiredAt, 'lease acquisition'),
heartbeatAt: normalizeTimestamp(lease.heartbeatAt, 'lease heartbeat'),
expiresAt: normalizeTimestamp(lease.expiresAt, 'lease expiry'),
...(lease.releasedAt
? { releasedAt: normalizeTimestamp(lease.releasedAt, 'lease release') }
: {}),
});
}
function normalizeTtl(ttlMs: number, maximum: number, kind: 'lease' | 'grant'): number {
if (!Number.isSafeInteger(ttlMs) || ttlMs <= 0 || ttlMs > maximum) {
throw new Error(
`Connector ${kind} TTL must be a positive safe integer no greater than ${maximum}ms`,
);
}
return ttlMs;
}
function normalizeTtlLimit(ttlMs: number, hardMaximum: number, kind: 'lease' | 'grant'): number {
if (!Number.isSafeInteger(ttlMs) || ttlMs <= 0 || ttlMs > hardMaximum) {
throw new Error(
`Maximum connector ${kind} TTL must be a positive safe integer no greater than ${hardMaximum}ms`,
);
}
return ttlMs;
}
function normalizeTimestamp(value: string, label: string): string {
const date = new Date(value);
if (Number.isNaN(date.getTime())) throw new Error(`${label} timestamp is invalid`);
return date.toISOString();
}
function expiresAt(now: Date, ttlMs: number): string {
const expiry = new Date(now.getTime() + ttlMs);
if (Number.isNaN(expiry.getTime())) throw new Error('Connector lease TTL exceeds date range');
return expiry.toISOString();
}
function isScopeSubset(requested: readonly string[], allowed: readonly string[]): boolean {
return requested.every((scope) => allowed.includes(scope));
}
function auditEvent(
authority: LogicalAgentBinding & {
readonly connectorId: string;
readonly leaseId?: string;
readonly leaseEpoch?: string;
},
correlationId: string,
now: Date,
event: ConnectorLeaseAuditEvent['event'],
outcome: ConnectorLeaseAuditEvent['outcome'],
reason?: ConnectorLeaseRejectReason,
): ConnectorLeaseAuditEvent {
return {
identity: authority.identity,
bindingId: authority.bindingId,
connectorId: authority.connectorId,
correlationId,
occurredAt: now.toISOString(),
event,
outcome,
...(authority.leaseId ? { leaseId: authority.leaseId } : {}),
...(authority.leaseEpoch ? { leaseEpoch: authority.leaseEpoch } : {}),
...(reason ? { reason } : {}),
};
}
function safeForgedGrantAudit(grant: unknown, now: Date): ConnectorLeaseAuditEvent {
const fallback: ConnectorLeaseAuditEvent = {
identity: { tenantId: 'untrusted', logicalAgentId: 'untrusted' },
bindingId: 'untrusted',
connectorId: 'untrusted',
correlationId: 'untrusted',
occurredAt: now.toISOString(),
event: 'reject',
outcome: 'denied',
reason: 'forged_grant',
};
if (typeof grant !== 'object' || grant === null || !('identity' in grant)) return fallback;
const identity = grant.identity;
if (typeof identity !== 'object' || identity === null) return fallback;
if (!('tenantId' in identity) || !('logicalAgentId' in identity)) return fallback;
if (!('bindingId' in grant) || !('connectorId' in grant) || !('correlationId' in grant)) {
return fallback;
}
if (
typeof identity.tenantId !== 'string' ||
typeof identity.logicalAgentId !== 'string' ||
typeof grant.bindingId !== 'string' ||
typeof grant.connectorId !== 'string' ||
typeof grant.correlationId !== 'string'
) {
return fallback;
}
try {
return {
identity: normalizeLogicalAgentIdentity({
tenantId: identity.tenantId,
logicalAgentId: identity.logicalAgentId,
}),
bindingId: normalizeLogicalBindingId(grant.bindingId),
connectorId: normalizeConnectorId(grant.connectorId),
correlationId: normalizeCorrelationId(grant.correlationId),
occurredAt: now.toISOString(),
event: 'reject',
outcome: 'denied',
reason: 'forged_grant',
};
} catch {
return fallback;
}
}
function safeReasonMessage(reason: ConnectorLeaseRejectReason): string {
return `Connector authority denied: ${reason}`;
}
+305
View File
@@ -0,0 +1,305 @@
import { describe, expect, it } from 'vitest';
import {
DurableSessionCoordinator,
InMemoryDurableSessionStore,
type DurableSessionIdentity,
} from './durable-session.js';
const IDENTITY: DurableSessionIdentity = {
agentName: 'Nova',
sessionId: 'tess-session-1',
tenantId: 'tenant-1',
ownerId: 'owner-1',
providerId: 'fleet',
runtimeSessionId: 'nova',
};
describe('DurableSessionCoordinator', () => {
it('reconstructs an exact session identity, pending inbox/outbox, checkpoint, and handoff after a simulated process restart', async () => {
const store = new InMemoryDurableSessionStore();
const beforeRestart = new DurableSessionCoordinator(store);
await beforeRestart.create(IDENTITY);
await beforeRestart.receive({
sessionId: IDENTITY.sessionId,
idempotencyKey: 'ingress-1',
correlationId: 'correlation-1',
content: 'continue the session',
});
await beforeRestart.enqueueOutbox({
sessionId: IDENTITY.sessionId,
idempotencyKey: 'outbox-1',
correlationId: 'correlation-1',
channelId: 'cli',
kind: 'provider.send',
content: 'resumable response',
});
await beforeRestart.checkpoint({
sessionId: IDENTITY.sessionId,
checkpointId: 'checkpoint-1',
cursor: 'cursor-42',
summary: 'operator asked for recovery proof',
compactionEpoch: 0,
});
await beforeRestart.handoff({
sessionId: IDENTITY.sessionId,
handoffId: 'handoff-1',
destination: 'mos',
correlationId: 'correlation-1',
checkpointId: 'checkpoint-1',
status: 'pending',
});
// Simulate an ungraceful process death: no in-memory coordinator state survives.
const afterRestart = new DurableSessionCoordinator(store);
const recovered = await afterRestart.recover(IDENTITY.sessionId);
expect(recovered.identity).toEqual(IDENTITY);
expect(recovered.inbox).toMatchObject([{ idempotencyKey: 'ingress-1', status: 'pending' }]);
expect(recovered.outbox).toMatchObject([{ idempotencyKey: 'outbox-1', status: 'pending' }]);
expect(recovered.checkpoint).toMatchObject({
checkpointId: 'checkpoint-1',
cursor: 'cursor-42',
});
expect(recovered.handoffs).toMatchObject([{ handoffId: 'handoff-1', status: 'pending' }]);
});
it('rebinds a recovered runtime while preserving the immutable conversation owner scope', async () => {
const coordinator = new DurableSessionCoordinator(new InMemoryDurableSessionStore());
await coordinator.create(IDENTITY);
await coordinator.create({
...IDENTITY,
providerId: 'fleet-next',
runtimeSessionId: 'nova-next',
});
await expect(coordinator.snapshot(IDENTITY.sessionId)).resolves.toMatchObject({
identity: { ...IDENTITY, providerId: 'fleet-next', runtimeSessionId: 'nova-next' },
});
await expect(coordinator.create({ ...IDENTITY, ownerId: 'other-owner' })).rejects.toThrow(
/identity conflict/,
);
});
it('deduplicates duplicate ingress and never reprocesses an inbox record after restart or compaction', async () => {
const store = new InMemoryDurableSessionStore();
const firstProcess = new DurableSessionCoordinator(store);
const handled: string[] = [];
await firstProcess.create(IDENTITY);
await expect(
firstProcess.receive({
sessionId: IDENTITY.sessionId,
idempotencyKey: 'ingress-duplicate',
correlationId: 'correlation-2',
content: 'only process me once',
}),
).resolves.toMatchObject({ accepted: true });
await expect(
firstProcess.receive({
sessionId: IDENTITY.sessionId,
idempotencyKey: 'ingress-duplicate',
correlationId: 'correlation-2',
content: 'only process me once',
}),
).resolves.toMatchObject({ accepted: false, status: 'pending' });
await expect(
firstProcess.receive({
sessionId: IDENTITY.sessionId,
idempotencyKey: 'ingress-duplicate',
correlationId: 'forged-correlation',
content: 'only process me once',
}),
).rejects.toThrow(/idempotency conflict/);
await firstProcess.drainInbox(IDENTITY.sessionId, async (entry) => {
handled.push(entry.idempotencyKey);
});
await firstProcess.checkpoint({
sessionId: IDENTITY.sessionId,
checkpointId: 'checkpoint-after-inbox',
cursor: 'cursor-43',
summary: 'safe to compact',
compactionEpoch: 1,
});
const afterRestartAndCompaction = new DurableSessionCoordinator(store);
await afterRestartAndCompaction.recover(IDENTITY.sessionId);
await afterRestartAndCompaction.drainInbox(IDENTITY.sessionId, async (entry) => {
handled.push(entry.idempotencyKey);
});
expect(handled).toEqual(['ingress-duplicate']);
});
it('does not redispatch an already applied outbox side effect after replay, restart, or compaction', async () => {
const store = new InMemoryDurableSessionStore();
const beforeRestart = new DurableSessionCoordinator(store);
const appliedEffects: string[] = [];
await beforeRestart.create(IDENTITY);
await beforeRestart.enqueueOutbox({
sessionId: IDENTITY.sessionId,
idempotencyKey: 'effect-1',
correlationId: 'correlation-3',
channelId: 'cli',
kind: 'provider.send',
content: 'send exactly once',
});
await expect(
beforeRestart.enqueueOutbox({
sessionId: IDENTITY.sessionId,
idempotencyKey: 'effect-1',
correlationId: 'correlation-3',
channelId: 'cli',
kind: 'provider.send',
content: 'send exactly once',
}),
).resolves.toMatchObject({ accepted: false, status: 'pending' });
await beforeRestart.dispatchOutbox(IDENTITY.sessionId, async (entry) => {
appliedEffects.push(entry.idempotencyKey);
});
await beforeRestart.checkpoint({
sessionId: IDENTITY.sessionId,
checkpointId: 'checkpoint-after-effect',
cursor: 'cursor-44',
summary: 'effect persisted before compaction',
compactionEpoch: 1,
});
const afterRestartAndCompaction = new DurableSessionCoordinator(store);
await afterRestartAndCompaction.recover(IDENTITY.sessionId);
await afterRestartAndCompaction.dispatchOutbox(IDENTITY.sessionId, async (entry) => {
appliedEffects.push(entry.idempotencyKey);
});
expect(appliedEffects).toEqual(['effect-1']);
});
it('rejects outbox idempotency-key reuse when immutable effect data differs', async () => {
const store = new InMemoryDurableSessionStore();
const coordinator = new DurableSessionCoordinator(store);
await coordinator.create(IDENTITY);
await coordinator.enqueueOutbox({
sessionId: IDENTITY.sessionId,
idempotencyKey: 'outbox-conflict',
correlationId: 'correlation-outbox',
channelId: 'cli',
kind: 'provider.send',
content: 'original effect',
});
await expect(
coordinator.enqueueOutbox({
sessionId: IDENTITY.sessionId,
idempotencyKey: 'outbox-conflict',
correlationId: 'correlation-outbox',
channelId: 'forged-channel',
kind: 'provider.send',
content: 'original effect',
}),
).rejects.toThrow(/idempotency conflict/);
});
it('retains an ambiguous failed provider effect as processing until explicit recovery', async () => {
const store = new InMemoryDurableSessionStore();
const beforeRestart = new DurableSessionCoordinator(store);
await beforeRestart.create(IDENTITY);
await beforeRestart.enqueueOutbox({
sessionId: IDENTITY.sessionId,
idempotencyKey: 'ambiguous-effect',
correlationId: 'correlation-ambiguous',
channelId: 'cli',
kind: 'provider.send',
content: 'preserve this effect claim',
});
await expect(
beforeRestart.dispatchOutbox(IDENTITY.sessionId, async (): Promise<void> => {
throw new Error('provider connection dropped after submit');
}),
).rejects.toThrow(/connection dropped/);
const afterRestart = new DurableSessionCoordinator(store);
await afterRestart.recover(IDENTITY.sessionId);
const calls: string[] = [];
await afterRestart.dispatchOutbox(IDENTITY.sessionId, async (entry): Promise<void> => {
calls.push(entry.idempotencyKey);
});
expect(calls).toEqual([]);
expect(await afterRestart.snapshot(IDENTITY.sessionId)).toMatchObject({
outbox: [{ idempotencyKey: 'ambiguous-effect', status: 'processing' }],
});
});
it('rejects a handoff-id replay with different immutable state', async () => {
const store = new InMemoryDurableSessionStore();
const coordinator = new DurableSessionCoordinator(store);
await coordinator.create(IDENTITY);
await coordinator.checkpoint({
sessionId: IDENTITY.sessionId,
checkpointId: 'checkpoint-conflict',
cursor: 'cursor-conflict',
summary: 'handoff conflict proof',
compactionEpoch: 0,
});
await coordinator.handoff({
sessionId: IDENTITY.sessionId,
handoffId: 'handoff-conflict',
destination: 'mos',
correlationId: 'correlation-conflict',
checkpointId: 'checkpoint-conflict',
status: 'pending',
});
await expect(
coordinator.handoff({
sessionId: IDENTITY.sessionId,
handoffId: 'handoff-conflict',
destination: 'forged-destination',
correlationId: 'correlation-conflict',
checkpointId: 'checkpoint-conflict',
status: 'pending',
}),
).rejects.toThrow(/identity conflict/);
});
it('keeps a handoff portable and resumes it from its durable checkpoint without process-local references', async () => {
const store = new InMemoryDurableSessionStore();
const source = new DurableSessionCoordinator(store);
await source.create(IDENTITY);
await source.checkpoint({
sessionId: IDENTITY.sessionId,
checkpointId: 'checkpoint-handoff',
cursor: 'cursor-45',
summary: 'portable state',
compactionEpoch: 2,
});
await source.handoff({
sessionId: IDENTITY.sessionId,
handoffId: 'handoff-portable',
destination: 'mos',
correlationId: 'correlation-4',
checkpointId: 'checkpoint-handoff',
status: 'pending',
});
await source.checkpoint({
sessionId: IDENTITY.sessionId,
checkpointId: 'checkpoint-later',
cursor: 'cursor-46',
summary: 'newer compacted state must not strand the handoff',
compactionEpoch: 3,
});
const receivingProcess = new DurableSessionCoordinator(store);
const handoff = await receivingProcess.resumeHandoff('handoff-portable');
expect(handoff.identity).toEqual(IDENTITY);
expect(handoff.checkpoint).toMatchObject({ checkpointId: 'checkpoint-handoff' });
expect(handoff.handoff).toMatchObject({ handoffId: 'handoff-portable', destination: 'mos' });
});
});
+498
View File
@@ -0,0 +1,498 @@
export interface DurableSessionIdentity {
/** Provisioned roster identity; isolates durable state between named agents. */
agentName: string;
sessionId: string;
tenantId: string;
ownerId: string;
providerId: string;
runtimeSessionId: string;
}
export type DurableInboxStatus = 'pending' | 'processing' | 'processed';
export type DurableOutboxStatus = 'pending' | 'processing' | 'delivered';
export interface DurableInboxInput {
sessionId: string;
idempotencyKey: string;
correlationId: string;
content: string;
}
export interface DurableInboxEntry extends DurableInboxInput {
status: DurableInboxStatus;
}
export interface DurableOutboxInput {
sessionId: string;
idempotencyKey: string;
correlationId: string;
channelId: string;
kind: string;
content: string;
}
export interface DurableOutboxEntry extends DurableOutboxInput {
status: DurableOutboxStatus;
}
export interface DurableCheckpointInput {
sessionId: string;
checkpointId: string;
cursor: string;
summary: string;
compactionEpoch: number;
}
export interface DurableCheckpoint extends DurableCheckpointInput {}
export interface DurableHandoffInput {
sessionId: string;
handoffId: string;
destination: string;
correlationId: string;
checkpointId: string;
status: 'pending' | 'accepted';
}
export interface DurableHandoff extends DurableHandoffInput {}
export interface DurableSessionSnapshot {
identity: DurableSessionIdentity;
inbox: DurableInboxEntry[];
outbox: DurableOutboxEntry[];
checkpoint?: DurableCheckpoint;
handoffs: DurableHandoff[];
}
export interface DurableHandoffRecovery {
identity: DurableSessionIdentity;
checkpoint: DurableCheckpoint;
handoff: DurableHandoff;
}
export interface DurableEnqueueResult<TStatus extends string> {
accepted: boolean;
status: TStatus;
}
/**
* A durable-state port. Implementations must atomically claim and complete work
* records. Recovery may requeue interrupted inbox work, but never an
* externally visible outbox effect: an ambiguous provider result remains
* claimed until a separately authorized reconciliation proves it safe.
*/
export interface DurableSessionStore {
create(identity: DurableSessionIdentity): Promise<void>;
snapshot(sessionId: string): Promise<DurableSessionSnapshot | null>;
enqueueInbox(input: DurableInboxInput): Promise<DurableEnqueueResult<DurableInboxStatus>>;
claimInbox(sessionId: string): Promise<DurableInboxEntry | null>;
completeInbox(sessionId: string, idempotencyKey: string): Promise<void>;
releaseInbox(sessionId: string, idempotencyKey: string): Promise<void>;
enqueueOutbox(input: DurableOutboxInput): Promise<DurableEnqueueResult<DurableOutboxStatus>>;
claimOutbox(sessionId: string): Promise<DurableOutboxEntry | null>;
claimOutboxByKey(sessionId: string, idempotencyKey: string): Promise<DurableOutboxEntry | null>;
completeOutbox(sessionId: string, idempotencyKey: string): Promise<void>;
releaseOutbox(sessionId: string, idempotencyKey: string): Promise<void>;
checkpoint(input: DurableCheckpointInput): Promise<void>;
findCheckpoint(sessionId: string, checkpointId: string): Promise<DurableCheckpoint | null>;
handoff(input: DurableHandoffInput): Promise<void>;
findHandoff(handoffId: string): Promise<DurableHandoff | null>;
requeueInFlight(sessionId: string): Promise<void>;
}
export class DurableSessionNotFoundError extends Error {
constructor(sessionId: string) {
super(`Durable session not found: ${sessionId}`);
this.name = 'DurableSessionNotFoundError';
}
}
export class DurableSessionCoordinator {
constructor(private readonly store: DurableSessionStore) {}
async create(identity: DurableSessionIdentity): Promise<void> {
this.assertIdentity(identity);
await this.store.create(identity);
}
async receive(input: DurableInboxInput): Promise<DurableEnqueueResult<DurableInboxStatus>> {
this.assertRecord(input.sessionId, input.idempotencyKey, input.correlationId, input.content);
return this.store.enqueueInbox(input);
}
async enqueueOutbox(
input: DurableOutboxInput,
): Promise<DurableEnqueueResult<DurableOutboxStatus>> {
this.assertRecord(
input.sessionId,
input.idempotencyKey,
input.correlationId,
input.channelId,
input.content,
);
if (input.kind.trim().length === 0) throw new Error('Durable outbox kind is required');
return this.store.enqueueOutbox(input);
}
async checkpoint(input: DurableCheckpointInput): Promise<void> {
this.assertRecord(input.sessionId, input.checkpointId, input.cursor, input.summary);
if (!Number.isInteger(input.compactionEpoch) || input.compactionEpoch < 0) {
throw new Error('Durable checkpoint compaction epoch must be a non-negative integer');
}
await this.store.checkpoint(input);
}
async handoff(input: DurableHandoffInput): Promise<void> {
this.assertRecord(input.sessionId, input.handoffId, input.destination, input.correlationId);
if (input.checkpointId.trim().length === 0)
throw new Error('Durable handoff checkpoint is required');
await this.store.handoff(input);
}
/** Read durable state without changing claim status; safe during normal operation. */
async snapshot(sessionId: string): Promise<DurableSessionSnapshot> {
const snapshot = await this.store.snapshot(sessionId);
if (!snapshot) throw new DurableSessionNotFoundError(sessionId);
return snapshot;
}
/** Requeue interrupted inbox work during recovery; preserve ambiguous outbox claims. */
async recover(sessionId: string): Promise<DurableSessionSnapshot> {
await this.store.requeueInFlight(sessionId);
return this.snapshot(sessionId);
}
async drainInbox(
sessionId: string,
handler: (entry: DurableInboxEntry) => Promise<void>,
): Promise<void> {
for (;;) {
const entry = await this.store.claimInbox(sessionId);
if (!entry) return;
try {
await handler(entry);
} catch (error: unknown) {
await this.store.releaseInbox(sessionId, entry.idempotencyKey);
throw error;
}
// If this write fails after the handler succeeded, leave the record
// processing. A recovery path can retry it with its stable idempotency key.
await this.store.completeInbox(sessionId, entry.idempotencyKey);
}
}
async dispatchOutbox(
sessionId: string,
dispatcher: (entry: DurableOutboxEntry) => Promise<void>,
): Promise<void> {
for (;;) {
const entry = await this.store.claimOutbox(sessionId);
if (!entry) return;
// A provider failure can be ambiguous: it may occur after the receiver
// accepted the idempotency key. Preserve the claim for reconciliation.
await dispatcher(entry);
// Do not requeue an effect after it has been applied but before its
// terminal state could be persisted; recovery preserves the claim.
await this.store.completeOutbox(sessionId, entry.idempotencyKey);
}
}
async dispatchOutboxEntry(
sessionId: string,
idempotencyKey: string,
dispatcher: (entry: DurableOutboxEntry) => Promise<void>,
): Promise<void> {
const entry = await this.store.claimOutboxByKey(sessionId, idempotencyKey);
if (!entry) return;
// A provider failure can be ambiguous, so this stays processing until
// separately authorized reconciliation proves it safe to resolve.
await dispatcher(entry);
await this.store.completeOutbox(sessionId, entry.idempotencyKey);
}
async resumeHandoff(handoffId: string): Promise<DurableHandoffRecovery> {
const handoff = await this.store.findHandoff(handoffId);
if (!handoff) throw new Error(`Durable handoff not found: ${handoffId}`);
const snapshot = await this.snapshot(handoff.sessionId);
const checkpoint = await this.store.findCheckpoint(handoff.sessionId, handoff.checkpointId);
if (!checkpoint) {
throw new Error(`Durable handoff checkpoint is unavailable: ${handoff.checkpointId}`);
}
return { identity: snapshot.identity, checkpoint, handoff };
}
private assertIdentity(identity: DurableSessionIdentity): void {
this.assertRecord(
identity.agentName,
identity.sessionId,
identity.tenantId,
identity.ownerId,
identity.providerId,
);
if (identity.runtimeSessionId.trim().length === 0) {
throw new Error('Durable runtime session identity is required');
}
}
private assertRecord(...values: string[]): void {
if (values.some((value: string): boolean => value.trim().length === 0)) {
throw new Error('Durable session records require non-empty fields');
}
}
}
interface InMemorySessionState {
identity: DurableSessionIdentity;
inbox: Map<string, DurableInboxEntry>;
outbox: Map<string, DurableOutboxEntry>;
checkpoints: Map<string, DurableCheckpoint>;
handoffs: Map<string, DurableHandoff>;
}
/** Reference store for deterministic domain tests; production uses the gateway DB adapter. */
export class InMemoryDurableSessionStore implements DurableSessionStore {
private readonly sessions = new Map<string, InMemorySessionState>();
async create(identity: DurableSessionIdentity): Promise<void> {
const existing = this.sessions.get(identity.sessionId);
if (existing) {
if (!sameEnrollmentScope(existing.identity, identity)) {
throw new Error(`Durable session identity conflict: ${identity.sessionId}`);
}
existing.identity.providerId = identity.providerId;
existing.identity.runtimeSessionId = identity.runtimeSessionId;
return;
}
this.sessions.set(identity.sessionId, {
identity: copyIdentity(identity),
inbox: new Map(),
outbox: new Map(),
checkpoints: new Map(),
handoffs: new Map(),
});
}
async snapshot(sessionId: string): Promise<DurableSessionSnapshot | null> {
const state = this.sessions.get(sessionId);
if (!state) return null;
const checkpoint = latestCheckpoint(state.checkpoints);
return {
identity: copyIdentity(state.identity),
inbox: [...state.inbox.values()].map(copyInbox),
outbox: [...state.outbox.values()].map(copyOutbox),
...(checkpoint ? { checkpoint: copyCheckpoint(checkpoint) } : {}),
handoffs: [...state.handoffs.values()].map(copyHandoff),
};
}
async enqueueInbox(input: DurableInboxInput): Promise<DurableEnqueueResult<DurableInboxStatus>> {
const state = this.require(input.sessionId);
const existing = state.inbox.get(input.idempotencyKey);
if (existing) {
if (!sameInbox(existing, input)) {
throw new Error(`Durable inbox idempotency conflict: ${input.idempotencyKey}`);
}
return { accepted: false, status: existing.status };
}
state.inbox.set(input.idempotencyKey, { ...input, status: 'pending' });
return { accepted: true, status: 'pending' };
}
async claimInbox(sessionId: string): Promise<DurableInboxEntry | null> {
const state = this.require(sessionId);
const entry = [...state.inbox.values()].find(
(candidate: DurableInboxEntry): boolean => candidate.status === 'pending',
);
if (!entry) return null;
entry.status = 'processing';
return copyInbox(entry);
}
async completeInbox(sessionId: string, idempotencyKey: string): Promise<void> {
this.requireEntry(this.require(sessionId).inbox, idempotencyKey, 'inbox').status = 'processed';
}
async releaseInbox(sessionId: string, idempotencyKey: string): Promise<void> {
this.requireEntry(this.require(sessionId).inbox, idempotencyKey, 'inbox').status = 'pending';
}
async enqueueOutbox(
input: DurableOutboxInput,
): Promise<DurableEnqueueResult<DurableOutboxStatus>> {
const state = this.require(input.sessionId);
const existing = state.outbox.get(input.idempotencyKey);
if (existing) {
if (!sameOutbox(existing, input)) {
throw new Error(`Durable outbox idempotency conflict: ${input.idempotencyKey}`);
}
return { accepted: false, status: existing.status };
}
state.outbox.set(input.idempotencyKey, { ...input, status: 'pending' });
return { accepted: true, status: 'pending' };
}
async claimOutbox(sessionId: string): Promise<DurableOutboxEntry | null> {
const state = this.require(sessionId);
const entry = [...state.outbox.values()].find(
(candidate: DurableOutboxEntry): boolean => candidate.status === 'pending',
);
if (!entry) return null;
entry.status = 'processing';
return copyOutbox(entry);
}
async claimOutboxByKey(
sessionId: string,
idempotencyKey: string,
): Promise<DurableOutboxEntry | null> {
const entry = this.require(sessionId).outbox.get(idempotencyKey);
if (!entry || entry.status !== 'pending') return null;
entry.status = 'processing';
return copyOutbox(entry);
}
async completeOutbox(sessionId: string, idempotencyKey: string): Promise<void> {
this.requireEntry(this.require(sessionId).outbox, idempotencyKey, 'outbox').status =
'delivered';
}
async releaseOutbox(sessionId: string, idempotencyKey: string): Promise<void> {
this.requireEntry(this.require(sessionId).outbox, idempotencyKey, 'outbox').status = 'pending';
}
async checkpoint(input: DurableCheckpointInput): Promise<void> {
const checkpoints = this.require(input.sessionId).checkpoints;
const existing = checkpoints.get(input.checkpointId);
if (existing && !sameCheckpoint(existing, input)) {
throw new Error(`Durable checkpoint identity conflict: ${input.checkpointId}`);
}
if (!existing) checkpoints.set(input.checkpointId, { ...input });
}
async findCheckpoint(sessionId: string, checkpointId: string): Promise<DurableCheckpoint | null> {
const checkpoint = this.require(sessionId).checkpoints.get(checkpointId);
return checkpoint ? copyCheckpoint(checkpoint) : null;
}
async handoff(input: DurableHandoffInput): Promise<void> {
const state = this.require(input.sessionId);
if (!state.checkpoints.has(input.checkpointId)) {
throw new Error(`Durable handoff checkpoint is unavailable: ${input.checkpointId}`);
}
const existing = state.handoffs.get(input.handoffId);
if (existing && !sameHandoff(existing, input)) {
throw new Error(`Durable handoff identity conflict: ${input.handoffId}`);
}
if (!existing) state.handoffs.set(input.handoffId, { ...input });
}
async findHandoff(handoffId: string): Promise<DurableHandoff | null> {
for (const state of this.sessions.values()) {
const handoff = state.handoffs.get(handoffId);
if (handoff) return copyHandoff(handoff);
}
return null;
}
async requeueInFlight(sessionId: string): Promise<void> {
const state = this.require(sessionId);
for (const entry of state.inbox.values()) {
if (entry.status === 'processing') entry.status = 'pending';
}
}
private require(sessionId: string): InMemorySessionState {
const state = this.sessions.get(sessionId);
if (!state) throw new DurableSessionNotFoundError(sessionId);
return state;
}
private requireEntry<T extends { status: string }>(
records: Map<string, T>,
idempotencyKey: string,
kind: string,
): T {
const entry = records.get(idempotencyKey);
if (!entry) throw new Error(`Durable ${kind} entry not found: ${idempotencyKey}`);
return entry;
}
}
function sameEnrollmentScope(left: DurableSessionIdentity, right: DurableSessionIdentity): boolean {
return (
left.agentName === right.agentName &&
left.sessionId === right.sessionId &&
left.tenantId === right.tenantId &&
left.ownerId === right.ownerId
);
}
function sameInbox(left: DurableInboxEntry, right: DurableInboxInput): boolean {
return (
left.sessionId === right.sessionId &&
left.idempotencyKey === right.idempotencyKey &&
left.correlationId === right.correlationId &&
left.content === right.content
);
}
function sameOutbox(left: DurableOutboxEntry, right: DurableOutboxInput): boolean {
return (
left.sessionId === right.sessionId &&
left.idempotencyKey === right.idempotencyKey &&
left.correlationId === right.correlationId &&
left.channelId === right.channelId &&
left.kind === right.kind &&
left.content === right.content
);
}
function sameCheckpoint(left: DurableCheckpoint, right: DurableCheckpointInput): boolean {
return (
left.sessionId === right.sessionId &&
left.checkpointId === right.checkpointId &&
left.cursor === right.cursor &&
left.summary === right.summary &&
left.compactionEpoch === right.compactionEpoch
);
}
function latestCheckpoint(
checkpoints: Map<string, DurableCheckpoint>,
): DurableCheckpoint | undefined {
return [...checkpoints.values()].sort(
(left: DurableCheckpoint, right: DurableCheckpoint): number =>
right.compactionEpoch - left.compactionEpoch,
)[0];
}
function sameHandoff(left: DurableHandoff, right: DurableHandoffInput): boolean {
return (
left.sessionId === right.sessionId &&
left.handoffId === right.handoffId &&
left.destination === right.destination &&
left.correlationId === right.correlationId &&
left.checkpointId === right.checkpointId &&
left.status === right.status
);
}
function copyIdentity(identity: DurableSessionIdentity): DurableSessionIdentity {
return { ...identity };
}
function copyInbox(entry: DurableInboxEntry): DurableInboxEntry {
return { ...entry };
}
function copyOutbox(entry: DurableOutboxEntry): DurableOutboxEntry {
return { ...entry };
}
function copyCheckpoint(checkpoint: DurableCheckpoint): DurableCheckpoint {
return { ...checkpoint };
}
function copyHandoff(handoff: DurableHandoff): DurableHandoff {
return { ...handoff };
}
@@ -0,0 +1,77 @@
import { describe, expect, it, vi } from 'vitest';
import type { RuntimeScope } from '@mosaicstack/types';
import { HermesRuntimeProvider, type HermesRuntimeTransport } from './hermes-runtime-provider.js';
const scope: RuntimeScope = { actorId: 'a', tenantId: 't', channelId: 'c', correlationId: 'r' };
const transport = (capabilities = ['session.list', 'session.tree']): HermesRuntimeTransport => ({
capabilities: vi.fn(async () => capabilities),
health: vi.fn(async () => ({ status: 'healthy' })),
sessions: vi.fn(async () => [
{
conversation_id: 'child',
agent_id: 'hermes-a',
parent_conversation_id: 'parent',
status: 'running',
created_at: '2026-01-01T00:00:00Z',
updated_at: '2026-01-01T00:00:00Z',
},
{
conversation_id: 'parent',
agent_id: 'hermes-a',
status: 'unknown',
created_at: '2026-01-01T00:00:00Z',
updated_at: '2026-01-01T00:00:00Z',
},
]),
stream: async function* () {},
send: vi.fn(),
attach: vi.fn(),
detach: vi.fn(),
terminate: vi.fn(),
});
describe('HermesRuntimeProvider normalization boundary', () => {
it('returns an exhaustive fail-closed transitional capability matrix', async () => {
const provider = new HermesRuntimeProvider(transport());
await expect(provider.transitionalCapabilityMatrix(scope)).resolves.toEqual([
{ capability: 'kanban', status: 'unsupported' },
{ capability: 'skills', status: 'unsupported' },
{ capability: 'memory', status: 'unsupported' },
{ capability: 'tools', status: 'unsupported' },
{ capability: 'cron', status: 'unsupported' },
]);
});
it('denies unsupported transitional capabilities without calling Hermes', async () => {
const hermes = transport();
const provider = new HermesRuntimeProvider(hermes);
await expect(provider.assertTransitionalCapability('memory', scope)).rejects.toMatchObject({
code: 'capability_unsupported',
});
expect(hermes.capabilities).not.toHaveBeenCalled();
});
it('normalizes legacy sessions without exposing legacy fields', async () => {
const provider = new HermesRuntimeProvider(transport());
await expect(provider.listSessions(scope)).resolves.toEqual(
expect.arrayContaining([
expect.objectContaining({ id: 'child', runtimeId: 'hermes-a', state: 'active' }),
]),
);
const result = await provider.listSessions(scope);
expect(result[0]).not.toHaveProperty('conversation_id');
});
it('forms normalized hierarchy and fails closed for unbridged operations', async () => {
const provider = new HermesRuntimeProvider(transport());
await expect(provider.getSessionTree(scope)).resolves.toEqual([
expect.objectContaining({
session: expect.objectContaining({ id: 'parent', state: 'failed' }),
children: [expect.objectContaining({ session: expect.objectContaining({ id: 'child' }) })],
}),
]);
await expect(
provider.sendMessage('parent', { content: 'x', idempotencyKey: 'i' }, scope),
).rejects.toMatchObject({ code: 'capability_unsupported' });
});
});
@@ -0,0 +1,217 @@
import type {
AgentRuntimeProvider,
RuntimeAttachHandle,
RuntimeAttachMode,
RuntimeCapability,
RuntimeCapabilitySet,
RuntimeHealth,
RuntimeMessage,
RuntimeScope,
RuntimeSession,
RuntimeSessionState,
RuntimeSessionTree,
RuntimeStreamEvent,
TransitionalCapabilityInventoryEntry,
TransitionalCapabilityInventoryProvider,
TransitionalRuntimeCapability,
} from '@mosaicstack/types';
const HERMES_PROVIDER_ID = 'runtime.hermes';
const TRANSITIONAL_CAPABILITIES: readonly TransitionalRuntimeCapability[] = [
'kanban',
'skills',
'memory',
'tools',
'cron',
];
const RUNTIME_CAPABILITIES: readonly RuntimeCapability[] = [
'session.list',
'session.tree',
'session.stream',
'session.send',
'session.attach',
'session.terminate',
];
/** Legacy transport boundary. These shapes are intentionally adapter-local. */
export interface HermesLegacySession {
conversation_id: string;
agent_id: string;
parent_conversation_id?: string;
status: string;
created_at: string;
updated_at: string;
}
export interface HermesRuntimeTransport {
capabilities(scope: RuntimeScope): Promise<string[]>;
health(scope: RuntimeScope): Promise<{ status: string; detail?: string }>;
sessions(scope: RuntimeScope): Promise<HermesLegacySession[]>;
stream(
sessionId: string,
cursor: string | undefined,
scope: RuntimeScope,
): AsyncIterable<RuntimeStreamEvent>;
send(sessionId: string, message: RuntimeMessage, scope: RuntimeScope): Promise<void>;
attach(
sessionId: string,
mode: RuntimeAttachMode,
scope: RuntimeScope,
): Promise<RuntimeAttachHandle>;
detach(attachmentId: string, scope: RuntimeScope): Promise<void>;
terminate(sessionId: string, approvalRef: string, scope: RuntimeScope): Promise<void>;
}
export class HermesRuntimeProviderError extends Error {
constructor(
readonly code: 'capability_unsupported' | 'invalid_request',
message: string,
) {
super(message);
this.name = HermesRuntimeProviderError.name;
}
}
/**
* Transitional Hermes adapter. Legacy identifiers and schemas do not cross this
* boundary: callers only observe Mosaic AgentRuntimeProvider contracts.
*/
export class HermesRuntimeProvider
implements AgentRuntimeProvider, TransitionalCapabilityInventoryProvider
{
readonly id = HERMES_PROVIDER_ID;
constructor(private readonly transport: HermesRuntimeTransport) {}
/**
* Full AC-TESS-05 migration inventory. These operations are deliberately
* unsupported until their Mosaic-owned plugin contracts exist.
*/
async transitionalCapabilityMatrix(
_scope: RuntimeScope,
): Promise<TransitionalCapabilityInventoryEntry[]> {
return TRANSITIONAL_CAPABILITIES.map((capability) => ({ capability, status: 'unsupported' }));
}
async assertTransitionalCapability(
capability: TransitionalRuntimeCapability,
scope: RuntimeScope,
): Promise<void> {
const entry = (await this.transitionalCapabilityMatrix(scope)).find(
(candidate) => candidate.capability === capability,
);
if (!entry || entry.status !== 'supported') {
throw new HermesRuntimeProviderError(
'capability_unsupported',
`Hermes transitional capability is unsupported: ${capability}`,
);
}
}
async capabilities(scope: RuntimeScope): Promise<RuntimeCapabilitySet> {
const legacyCapabilities = await this.transport.capabilities(scope);
return {
supported: RUNTIME_CAPABILITIES.filter((capability) =>
legacyCapabilities.includes(capability),
),
};
}
async health(scope: RuntimeScope): Promise<RuntimeHealth> {
const health = await this.transport.health(scope);
return {
status: health.status === 'healthy' || health.status === 'degraded' ? health.status : 'down',
checkedAt: new Date().toISOString(),
...(health.detail ? { detail: health.detail } : {}),
};
}
async listSessions(scope: RuntimeScope): Promise<RuntimeSession[]> {
await this.requireCapability('session.list', scope);
return (await this.transport.sessions(scope)).map((session) => this.session(session));
}
async getSessionTree(scope: RuntimeScope): Promise<RuntimeSessionTree[]> {
await this.requireCapability('session.tree', scope);
const sessions = (await this.transport.sessions(scope)).map((session) => this.session(session));
const nodes = new Map<string, RuntimeSessionTree>(
sessions.map((session) => [session.id, { session, children: [] }]),
);
const roots: RuntimeSessionTree[] = [];
for (const session of sessions) {
const node = nodes.get(session.id)!;
const parent = session.parentSessionId ? nodes.get(session.parentSessionId) : undefined;
if (parent) parent.children.push(node);
else roots.push(node);
}
return roots;
}
async *streamSession(
sessionId: string,
cursor: string | undefined,
scope: RuntimeScope,
): AsyncIterable<RuntimeStreamEvent> {
await this.requireCapability('session.stream', scope);
yield* this.transport.stream(sessionId, cursor, scope);
}
async sendMessage(
sessionId: string,
message: RuntimeMessage,
scope: RuntimeScope,
): Promise<void> {
await this.requireCapability('session.send', scope);
if (!message.content.trim())
throw new HermesRuntimeProviderError('invalid_request', 'Message content is required');
await this.transport.send(sessionId, message, scope);
}
async attach(
sessionId: string,
mode: RuntimeAttachMode,
scope: RuntimeScope,
): Promise<RuntimeAttachHandle> {
await this.requireCapability('session.attach', scope);
return this.transport.attach(sessionId, mode, scope);
}
async detach(attachmentId: string, scope: RuntimeScope): Promise<void> {
await this.transport.detach(attachmentId, scope);
}
async terminate(sessionId: string, approvalRef: string, scope: RuntimeScope): Promise<void> {
await this.requireCapability('session.terminate', scope);
if (!approvalRef.trim())
throw new HermesRuntimeProviderError('invalid_request', 'Termination approval is required');
await this.transport.terminate(sessionId, approvalRef, scope);
}
private async requireCapability(
capability: RuntimeCapability,
scope: RuntimeScope,
): Promise<void> {
if (!(await this.capabilities(scope)).supported.includes(capability)) {
throw new HermesRuntimeProviderError(
'capability_unsupported',
`Hermes does not bridge ${capability}`,
);
}
}
private session(value: HermesLegacySession): RuntimeSession {
return {
id: value.conversation_id,
providerId: this.id,
runtimeId: value.agent_id,
...(value.parent_conversation_id ? { parentSessionId: value.parent_conversation_id } : {}),
state: state(value.status),
createdAt: value.created_at,
updatedAt: value.updated_at,
};
}
}
function state(value: string): RuntimeSessionState {
return (
(
{ running: 'active', waiting: 'idle', starting: 'starting', stopped: 'stopped' } as Record<
string,
RuntimeSessionState
>
)[value] ?? 'failed'
);
}
+7
View File
@@ -1 +1,8 @@
export const VERSION = '0.0.0';
export * from './runtime-provider-registry.js';
export * from './tmux-fleet-runtime-provider.js';
export * from './hermes-runtime-provider.js';
export * from './matrix-native-runtime-provider.js';
export * from './durable-session.js';
export * from './connector-lease.js';
@@ -0,0 +1,153 @@
import { describe, expect, it, vi } from 'vitest';
import type { RuntimeScope, RuntimeStreamEvent } from '@mosaicstack/types';
import {
type MatrixRuntimeSession,
type MatrixRuntimeTransport,
MatrixNativeRuntimeProvider,
type MatrixReadAuthority,
type MatrixWriteAuthority,
} from './matrix-native-runtime-provider.js';
const scope: RuntimeScope = {
actorId: 'operator-1',
tenantId: 'tenant-a',
channelId: 'matrix-control',
correlationId: 'corr-1',
};
const session: MatrixRuntimeSession = {
id: 'native-1',
runtimeId: '@worker:example.test',
state: 'active',
createdAt: '2026-07-13T00:00:00.000Z',
updatedAt: '2026-07-13T00:00:00.000Z',
};
function transport(): MatrixRuntimeTransport {
return {
health: vi.fn(async () => ({
status: 'healthy' as const,
checkedAt: '2026-07-13T00:00:00.000Z',
})),
listSessions: vi.fn(async () => [session]),
verifySession: vi.fn(async (sessionId) => {
if (sessionId !== session.id) throw new Error('unexpected session');
return session;
}),
stream: vi.fn(async function* (): AsyncIterable<RuntimeStreamEvent> {
yield {
type: 'message.delta',
sessionId: 'native-1',
cursor: 'cursor-1',
occurredAt: '2026-07-13T00:00:00.000Z',
content: 'hello',
};
}),
send: vi.fn(async () => undefined),
terminate: vi.fn(async () => undefined),
};
}
function readAuthority(): MatrixReadAuthority {
return { canRead: vi.fn(async () => true) };
}
function writeAuthority(): MatrixWriteAuthority {
return {
canWrite: vi.fn(async () => true),
assertAuthorized: vi.fn(async () => undefined),
};
}
describe('MatrixNativeRuntimeProvider contract boundary', (): void => {
it('advertises the concrete Matrix operations and returns only normalized sessions', async (): Promise<void> => {
const provider = new MatrixNativeRuntimeProvider({
transport: transport(),
readAuthority: readAuthority(),
});
await expect(provider.capabilities(scope)).resolves.toEqual({
supported: [
'session.list',
'session.tree',
'session.stream',
'session.send',
'session.attach',
'session.terminate',
],
});
await expect(provider.listSessions(scope)).resolves.toEqual([
expect.objectContaining({ id: 'native-1', providerId: 'runtime.matrix' }),
]);
});
it('binds read attachments to immutable scope and rejects control mode before transport access', async (): Promise<void> => {
const matrix = transport();
const provider = new MatrixNativeRuntimeProvider({
transport: matrix,
readAuthority: readAuthority(),
attachmentIdFactory: () => 'attachment-1',
now: () => new Date('2026-07-13T00:00:00.000Z'),
});
await expect(provider.attach('native-1', 'control', scope)).rejects.toMatchObject({
code: 'forbidden',
});
expect(matrix.verifySession).not.toHaveBeenCalled();
await provider.attach('native-1', 'read', scope);
await expect(
provider.detach('attachment-1', { ...scope, tenantId: 'other' }),
).rejects.toMatchObject({
code: 'forbidden',
});
});
it('validates messages and applies exact Matrix authority after bound-session verification', async (): Promise<void> => {
const matrix = transport();
const writes = writeAuthority();
const provider = new MatrixNativeRuntimeProvider({
transport: matrix,
readAuthority: readAuthority(),
writeAuthority: writes,
});
await expect(
provider.sendMessage('native-1', { content: '', idempotencyKey: 'msg-1' }, scope),
).rejects.toMatchObject({
code: 'invalid_request',
});
expect(matrix.verifySession).not.toHaveBeenCalled();
await provider.sendMessage('native-1', { content: 'hello', idempotencyKey: 'msg-1' }, scope);
expect(writes.assertAuthorized).toHaveBeenCalledWith({
operation: 'session.send',
sessionId: 'native-1',
scope,
});
expect(matrix.send).toHaveBeenCalledWith(
'native-1',
{ content: 'hello', idempotencyKey: 'msg-1' },
scope,
);
});
it('streams only after exact read authorization', async (): Promise<void> => {
const matrix = transport();
const provider = new MatrixNativeRuntimeProvider({
transport: matrix,
readAuthority: readAuthority(),
});
await expect(collect(provider.streamSession('native-1', 'cursor-0', scope))).resolves.toEqual([
expect.objectContaining({ type: 'message.delta', sessionId: 'native-1' }),
]);
expect(matrix.stream).toHaveBeenCalledWith('native-1', 'cursor-0', scope);
});
});
async function collect(stream: AsyncIterable<RuntimeStreamEvent>): Promise<RuntimeStreamEvent[]> {
const values: RuntimeStreamEvent[] = [];
for await (const value of stream) values.push(value);
return values;
}
@@ -0,0 +1,351 @@
import { randomUUID } from 'node:crypto';
import type {
AgentRuntimeProvider,
RuntimeAttachHandle,
RuntimeAttachMode,
RuntimeCapabilitySet,
RuntimeHealth,
RuntimeMessage,
RuntimeScope,
RuntimeSession,
RuntimeSessionTree,
RuntimeStreamEvent,
} from '@mosaicstack/types';
const MATRIX_PROVIDER_ID = 'runtime.matrix';
const ATTACHMENT_TTL_MS = 5 * 60 * 1_000;
/** A verified native runtime session. Matrix room and event details remain transport-local. */
export interface MatrixRuntimeSession {
id: string;
runtimeId: string;
parentSessionId?: string;
state: RuntimeSession['state'];
createdAt: string;
updatedAt: string;
}
/**
* Narrow native Matrix boundary. The concrete Mosaic transport owns homeserver
* authentication, exact room mapping, Matrix identity checks, and replay cursors.
*/
export interface MatrixRuntimeTransport {
health(scope: RuntimeScope): Promise<RuntimeHealth>;
listSessions(scope: RuntimeScope): Promise<MatrixRuntimeSession[]>;
verifySession(sessionId: string, scope: RuntimeScope): Promise<MatrixRuntimeSession>;
stream(
sessionId: string,
cursor: string | undefined,
scope: RuntimeScope,
): AsyncIterable<RuntimeStreamEvent>;
send(sessionId: string, message: RuntimeMessage, scope: RuntimeScope): Promise<void>;
terminate(sessionId: string, approvalRef: string, scope: RuntimeScope): Promise<void>;
}
export type MatrixRuntimeProviderErrorCode =
| 'capability_unsupported'
| 'forbidden'
| 'invalid_request'
| 'not_found';
export class MatrixRuntimeProviderError extends Error {
constructor(
readonly code: MatrixRuntimeProviderErrorCode,
message: string,
) {
super(message);
this.name = MatrixRuntimeProviderError.name;
}
}
export type MatrixReadOperation =
| 'runtime.health'
| 'session.list'
| 'session.tree'
| 'session.stream'
| 'session.attach';
export interface MatrixReadAuthority {
canRead(input: {
operation: MatrixReadOperation;
scope: RuntimeScope;
sessionId?: string;
}): Promise<boolean>;
}
export interface MatrixWriteAuthority {
canWrite(input: {
operation: 'session.send' | 'session.terminate';
sessionId: string;
scope: RuntimeScope;
approvalRef?: string;
}): Promise<boolean>;
assertAuthorized(input: {
operation: 'session.send' | 'session.terminate';
sessionId: string;
scope: RuntimeScope;
approvalRef?: string;
}): Promise<void>;
}
export interface MatrixNativeRuntimeProviderOptions {
transport: MatrixRuntimeTransport;
readAuthority?: MatrixReadAuthority;
writeAuthority?: MatrixWriteAuthority;
attachmentIdFactory?: () => string;
now?: () => Date;
attachmentTtlMs?: number;
}
interface Attachment {
sessionId: string;
scope: RuntimeScope;
expiresAtMs: number;
}
class DenyMatrixReadAuthority implements MatrixReadAuthority {
async canRead(): Promise<boolean> {
return false;
}
}
class DenyMatrixWriteAuthority implements MatrixWriteAuthority {
async canWrite(): Promise<boolean> {
return false;
}
async assertAuthorized(): Promise<void> {
throw new MatrixRuntimeProviderError(
'forbidden',
'Matrix runtime writes require orchestrator authority',
);
}
}
/**
* Native Matrix adapter behind the Mosaic runtime contract. It accepts only
* stable session IDs; room identifiers, Matrix event schemas, and credentials
* are deliberately confined to the concrete transport implementation.
*/
export class MatrixNativeRuntimeProvider implements AgentRuntimeProvider {
readonly id = MATRIX_PROVIDER_ID;
private readonly readAuthority: MatrixReadAuthority;
private readonly writeAuthority: MatrixWriteAuthority;
private readonly attachmentIdFactory: () => string;
private readonly now: () => Date;
private readonly attachmentTtlMs: number;
private readonly attachments = new Map<string, Attachment>();
constructor(private readonly options: MatrixNativeRuntimeProviderOptions) {
this.readAuthority = options.readAuthority ?? new DenyMatrixReadAuthority();
this.writeAuthority = options.writeAuthority ?? new DenyMatrixWriteAuthority();
this.attachmentIdFactory = options.attachmentIdFactory ?? randomUUID;
this.now = options.now ?? (() => new Date());
this.attachmentTtlMs = options.attachmentTtlMs ?? ATTACHMENT_TTL_MS;
}
async capabilities(_scope: RuntimeScope): Promise<RuntimeCapabilitySet> {
return {
supported: [
'session.list',
'session.tree',
'session.stream',
'session.send',
'session.attach',
'session.terminate',
],
};
}
async health(scope: RuntimeScope): Promise<RuntimeHealth> {
await this.assertRead('runtime.health', undefined, scope);
return this.options.transport.health(scope);
}
async listSessions(scope: RuntimeScope): Promise<RuntimeSession[]> {
await this.assertRead('session.list', undefined, scope);
const sessions = await this.options.transport.listSessions(scope);
const visible = await Promise.all(
sessions.map((session) =>
this.readAuthority.canRead({ operation: 'session.list', sessionId: session.id, scope }),
),
);
return sessions
.filter((_session, index) => visible[index] === true)
.map((session) => this.runtimeSession(session));
}
async getSessionTree(scope: RuntimeScope): Promise<RuntimeSessionTree[]> {
await this.assertRead('session.tree', undefined, scope);
const sessions = await this.options.transport.listSessions(scope);
const visible = await Promise.all(
sessions.map((session) =>
this.readAuthority.canRead({ operation: 'session.tree', sessionId: session.id, scope }),
),
);
const runtimeSessions = sessions
.filter((_session, index) => visible[index] === true)
.map((session) => this.runtimeSession(session));
const nodes = new Map<string, RuntimeSessionTree>(
runtimeSessions.map((session) => [session.id, { session, children: [] }]),
);
const roots: RuntimeSessionTree[] = [];
for (const session of runtimeSessions) {
const node = nodes.get(session.id)!;
const parent = session.parentSessionId ? nodes.get(session.parentSessionId) : undefined;
if (parent) parent.children.push(node);
else roots.push(node);
}
return roots;
}
async *streamSession(
sessionId: string,
cursor: string | undefined,
scope: RuntimeScope,
): AsyncIterable<RuntimeStreamEvent> {
await this.assertRead('session.stream', sessionId, scope);
const session = await this.options.transport.verifySession(sessionId, scope);
await this.assertRead('session.stream', session.id, scope);
yield* this.options.transport.stream(session.id, cursor, scope);
}
async sendMessage(
sessionId: string,
message: RuntimeMessage,
scope: RuntimeScope,
): Promise<void> {
if (!message.content.trim()) {
throw new MatrixRuntimeProviderError(
'invalid_request',
'Matrix runtime message content is required',
);
}
await this.assertWritePermitted('session.send', sessionId, scope);
const session = await this.options.transport.verifySession(sessionId, scope);
await this.assertWriteAuthorized('session.send', session.id, scope);
await this.options.transport.send(session.id, message, scope);
}
async attach(
sessionId: string,
mode: RuntimeAttachMode,
scope: RuntimeScope,
): Promise<RuntimeAttachHandle> {
if (mode !== 'read') {
throw new MatrixRuntimeProviderError('forbidden', 'Matrix control attach is not permitted');
}
await this.assertRead('session.attach', sessionId, scope);
const session = await this.options.transport.verifySession(sessionId, scope);
await this.assertRead('session.attach', session.id, scope);
const nowMs = this.now().getTime();
this.pruneExpired(nowMs);
const attachmentId = this.attachmentIdFactory();
const expiresAtMs = nowMs + this.attachmentTtlMs;
this.attachments.set(attachmentId, {
sessionId: session.id,
scope: snapshotScope(scope),
expiresAtMs,
});
return {
attachmentId,
sessionId: session.id,
mode,
expiresAt: new Date(expiresAtMs).toISOString(),
};
}
async detach(attachmentId: string, scope: RuntimeScope): Promise<void> {
const attachment = this.attachments.get(attachmentId);
if (!attachment)
throw new MatrixRuntimeProviderError('not_found', 'Matrix attachment is not active');
if (this.now().getTime() >= attachment.expiresAtMs) {
this.attachments.delete(attachmentId);
throw new MatrixRuntimeProviderError('forbidden', 'Matrix attachment has expired');
}
if (!sameScope(attachment.scope, scope)) {
throw new MatrixRuntimeProviderError('forbidden', 'Matrix attachment scope does not match');
}
this.attachments.delete(attachmentId);
}
async terminate(sessionId: string, approvalRef: string, scope: RuntimeScope): Promise<void> {
if (!approvalRef.trim()) {
throw new MatrixRuntimeProviderError(
'invalid_request',
'Matrix termination approval is required',
);
}
await this.assertWritePermitted('session.terminate', sessionId, scope, approvalRef);
const session = await this.options.transport.verifySession(sessionId, scope);
await this.assertWriteAuthorized('session.terminate', session.id, scope, approvalRef);
await this.options.transport.terminate(session.id, approvalRef, scope);
}
private runtimeSession(session: MatrixRuntimeSession): RuntimeSession {
return { ...session, providerId: this.id };
}
private async assertRead(
operation: MatrixReadOperation,
sessionId: string | undefined,
scope: RuntimeScope,
): Promise<void> {
const allowed = await this.readAuthority.canRead({
operation,
scope,
...(sessionId ? { sessionId } : {}),
});
if (!allowed)
throw new MatrixRuntimeProviderError('forbidden', 'Matrix runtime read is not authorized');
}
private async assertWritePermitted(
operation: 'session.send' | 'session.terminate',
sessionId: string,
scope: RuntimeScope,
approvalRef?: string,
): Promise<void> {
const allowed = await this.writeAuthority.canWrite({
operation,
sessionId,
scope,
...(approvalRef ? { approvalRef } : {}),
});
if (!allowed)
throw new MatrixRuntimeProviderError('forbidden', 'Matrix runtime write is not authorized');
}
private async assertWriteAuthorized(
operation: 'session.send' | 'session.terminate',
sessionId: string,
scope: RuntimeScope,
approvalRef?: string,
): Promise<void> {
await this.writeAuthority.assertAuthorized({
operation,
sessionId,
scope,
...(approvalRef ? { approvalRef } : {}),
});
}
private pruneExpired(nowMs: number): void {
for (const [id, attachment] of this.attachments) {
if (attachment.expiresAtMs <= nowMs) this.attachments.delete(id);
}
}
}
function snapshotScope(scope: RuntimeScope): RuntimeScope {
return Object.freeze({ ...scope });
}
function sameScope(left: RuntimeScope, right: RuntimeScope): boolean {
return (
left.actorId === right.actorId &&
left.tenantId === right.tenantId &&
left.channelId === right.channelId &&
left.correlationId === right.correlationId
);
}
@@ -0,0 +1,176 @@
import { describe, expect, it, vi } from 'vitest';
import type { AgentRuntimeProvider, RuntimeScope } from '@mosaicstack/types';
import {
MatrixNativeRuntimeProvider,
type MatrixRuntimeTransport,
} from './matrix-native-runtime-provider.js';
import {
TmuxFleetRuntimeProvider,
type FleetRuntimeTransport,
} from './tmux-fleet-runtime-provider.js';
const scope: RuntimeScope = {
actorId: 'operator-1',
tenantId: 'tenant-a',
channelId: 'cli',
correlationId: 'corr-1',
};
interface ProviderFixture {
name: string;
provider: AgentRuntimeProvider;
providerId: string;
verifySession: unknown;
send: unknown;
}
function fixtures(): ProviderFixture[] {
const fleetTransport: FleetRuntimeTransport = {
verifySession: vi.fn(async () => ({
id: 'session-1',
runtimeId: 'native-1',
socketName: 'fleet',
})),
listSessions: vi.fn(async () => [
{ id: 'session-1', runtimeId: 'native-1', socketName: 'fleet' },
]),
sendMessage: vi.fn(async () => undefined),
terminate: vi.fn(async () => undefined),
};
const fleet = new TmuxFleetRuntimeProvider({
transport: fleetTransport,
readAuthority: { canRead: vi.fn(async () => true) },
writeAuthority: {
canWrite: vi.fn(async () => true),
assertAuthorized: vi.fn(async () => undefined),
},
attachmentIdFactory: () => 'attachment-1',
now: () => new Date('2026-07-13T00:00:00.000Z'),
});
const matrixTransport: MatrixRuntimeTransport = {
health: vi.fn(async () => ({
status: 'healthy' as const,
checkedAt: '2026-07-13T00:00:00.000Z',
})),
verifySession: vi.fn(async () => ({
id: 'session-1',
runtimeId: 'native-1',
state: 'active' as const,
createdAt: '2026-07-13T00:00:00.000Z',
updatedAt: '2026-07-13T00:00:00.000Z',
})),
listSessions: vi.fn(async () => [
{
id: 'session-1',
runtimeId: 'native-1',
state: 'active' as const,
createdAt: '2026-07-13T00:00:00.000Z',
updatedAt: '2026-07-13T00:00:00.000Z',
},
]),
stream: async function* () {},
send: vi.fn(async () => undefined),
terminate: vi.fn(async () => undefined),
};
const matrix = new MatrixNativeRuntimeProvider({
transport: matrixTransport,
readAuthority: { canRead: vi.fn(async () => true) },
writeAuthority: {
canWrite: vi.fn(async () => true),
assertAuthorized: vi.fn(async () => undefined),
},
attachmentIdFactory: () => 'attachment-1',
now: () => new Date('2026-07-13T00:00:00.000Z'),
});
return [
{
name: 'tmux/fleet',
provider: fleet,
providerId: 'fleet.tmux',
verifySession: fleetTransport.verifySession,
send: fleetTransport.sendMessage,
},
{
name: 'Matrix/native',
provider: matrix,
providerId: 'runtime.matrix',
verifySession: matrixTransport.verifySession,
send: matrixTransport.send,
},
];
}
/** Shared contract tests for the migration-safe provider intersection. */
describe('tmux/fleet and Matrix/native provider parity', (): void => {
it.each(fixtures())(
'%s exposes the shared runtime operations',
async (fixture): Promise<void> => {
await expect(fixture.provider.capabilities(scope)).resolves.toEqual(
expect.objectContaining({
supported: expect.arrayContaining([
'session.list',
'session.tree',
'session.send',
'session.attach',
'session.terminate',
]),
}),
);
await expect(fixture.provider.listSessions(scope)).resolves.toEqual([
expect.objectContaining({
id: 'session-1',
providerId: fixture.providerId,
runtimeId: 'native-1',
}),
]);
},
);
it.each(fixtures())(
'%s rejects empty messages before touching its transport',
async (fixture): Promise<void> => {
await expect(
fixture.provider.sendMessage(
'session-1',
{ content: '', idempotencyKey: 'message-1' },
scope,
),
).rejects.toMatchObject({ code: 'invalid_request' });
expect(fixture.verifySession).not.toHaveBeenCalled();
expect(fixture.send).not.toHaveBeenCalled();
},
);
it.each(fixtures())(
'%s rejects an empty termination approval before touching its transport',
async (fixture): Promise<void> => {
await expect(fixture.provider.terminate('session-1', '', scope)).rejects.toMatchObject({
code: 'invalid_request',
});
expect(fixture.verifySession).not.toHaveBeenCalled();
},
);
it.each(fixtures())(
'%s creates a read-only handle bound to immutable scope',
async (fixture): Promise<void> => {
await expect(fixture.provider.attach('session-1', 'control', scope)).rejects.toMatchObject({
code: 'forbidden',
});
expect(fixture.verifySession).not.toHaveBeenCalled();
await expect(fixture.provider.attach('session-1', 'read', scope)).resolves.toEqual(
expect.objectContaining({
attachmentId: 'attachment-1',
sessionId: 'session-1',
mode: 'read',
}),
);
await expect(
fixture.provider.detach('attachment-1', { ...scope, actorId: 'operator-2' }),
).rejects.toMatchObject({ code: 'forbidden' });
},
);
});
@@ -0,0 +1,95 @@
import { describe, expect, it } from 'vitest';
import type {
AgentRuntimeProvider,
RuntimeAttachHandle,
RuntimeAttachMode,
RuntimeCapabilitySet,
RuntimeHealth,
RuntimeMessage,
RuntimeScope,
RuntimeSession,
RuntimeSessionTree,
RuntimeStreamEvent,
} from '@mosaicstack/types';
import { AgentRuntimeProviderRegistry } from './runtime-provider-registry.js';
class TestRuntimeProvider implements AgentRuntimeProvider {
readonly id = 'test-runtime';
async capabilities(_scope: RuntimeScope): Promise<RuntimeCapabilitySet> {
return { supported: ['session.list'] };
}
async health(_scope: RuntimeScope): Promise<RuntimeHealth> {
return { status: 'healthy', checkedAt: '2026-07-12T00:00:00.000Z' };
}
async listSessions(_scope: RuntimeScope): Promise<RuntimeSession[]> {
return [];
}
async getSessionTree(_scope: RuntimeScope): Promise<RuntimeSessionTree[]> {
return [];
}
async *streamSession(
_sessionId: string,
_cursor: string | undefined,
_scope: RuntimeScope,
): AsyncIterable<RuntimeStreamEvent> {
return;
}
async sendMessage(
_sessionId: string,
_message: RuntimeMessage,
_scope: RuntimeScope,
): Promise<void> {}
async attach(
_sessionId: string,
_mode: RuntimeAttachMode,
_scope: RuntimeScope,
): Promise<RuntimeAttachHandle> {
return {
attachmentId: 'attachment-1',
sessionId: 'session-1',
mode: 'read',
expiresAt: '2026-07-12T00:00:00.000Z',
};
}
async detach(_attachmentId: string, _scope: RuntimeScope): Promise<void> {}
async terminate(_sessionId: string, _approvalRef: string, _scope: RuntimeScope): Promise<void> {}
}
describe('AgentRuntimeProviderRegistry', (): void => {
it('resolves only registered runtime providers', (): void => {
const registry = new AgentRuntimeProviderRegistry();
const provider = new TestRuntimeProvider();
registry.register(provider);
expect(registry.get(provider.id)).toBe(provider);
expect(registry.get('unknown-runtime')).toBeUndefined();
expect(registry.list()).toEqual([provider]);
});
it('rejects duplicate and blank provider identities rather than silently replacing a runtime', (): void => {
const registry = new AgentRuntimeProviderRegistry();
const provider = new TestRuntimeProvider();
registry.register(provider);
expect((): void => {
registry.register(provider);
}).toThrow(/already registered/);
expect((): void => {
registry.require('');
}).toThrow(/provider ID is required/);
expect((): void => {
registry.require('unknown-runtime');
}).toThrow(/not registered/);
});
});
@@ -0,0 +1,40 @@
import type { AgentRuntimeProvider } from '@mosaicstack/types';
/**
* Registry for runtime providers. Registration is explicit and replacement is
* forbidden so a provider identity cannot be silently hijacked at runtime.
*/
export class AgentRuntimeProviderRegistry {
private readonly providers = new Map<string, AgentRuntimeProvider>();
register(provider: AgentRuntimeProvider): void {
const providerId = provider.id.trim();
if (providerId.length === 0) {
throw new Error('Runtime provider ID is required');
}
if (this.providers.has(providerId)) {
throw new Error(`Runtime provider is already registered: ${providerId}`);
}
this.providers.set(providerId, provider);
}
get(providerId: string): AgentRuntimeProvider | undefined {
return this.providers.get(providerId);
}
require(providerId: string): AgentRuntimeProvider {
const normalizedProviderId = providerId.trim();
if (normalizedProviderId.length === 0) {
throw new Error('Runtime provider ID is required');
}
const provider = this.providers.get(normalizedProviderId);
if (!provider) {
throw new Error(`Runtime provider is not registered: ${normalizedProviderId}`);
}
return provider;
}
list(): AgentRuntimeProvider[] {
return Array.from(this.providers.values());
}
}
@@ -0,0 +1,274 @@
import { describe, expect, it, vi } from 'vitest';
import type { RuntimeScope } from '@mosaicstack/types';
import {
type FleetReadAuthority,
type FleetWriteAuthority,
TmuxFleetRuntimeProvider,
} from './tmux-fleet-runtime-provider.js';
import type {
FleetRuntimeProviderError,
FleetRuntimeTarget,
FleetRuntimeTransport,
} from './tmux-fleet-runtime-provider.js';
const scope: RuntimeScope = {
actorId: 'operator-1',
tenantId: 'tenant-a',
channelId: 'discord-1',
correlationId: 'corr-1',
};
const target: FleetRuntimeTarget = {
id: 'coder0',
runtimeId: 'codex',
socketName: 'tess-fleet',
};
function transport(): FleetRuntimeTransport {
return {
verifySession: vi.fn(async (): Promise<FleetRuntimeTarget> => target),
listSessions: vi.fn(async (): Promise<FleetRuntimeTarget[]> => [target]),
sendMessage: vi.fn(async (): Promise<void> => undefined),
terminate: vi.fn(async (): Promise<void> => undefined),
};
}
function readAuthority(): FleetReadAuthority {
return { canRead: vi.fn(async (): Promise<boolean> => true) };
}
describe('TmuxFleetRuntimeProvider security policy', (): void => {
it('advertises only fleet operations it can safely implement', async (): Promise<void> => {
const provider = new TmuxFleetRuntimeProvider({ transport: transport() });
await expect(provider.capabilities(scope)).resolves.toEqual({
supported: [
'session.list',
'session.tree',
'session.send',
'session.attach',
'session.terminate',
],
});
});
it('rejects control attach without consulting the tmux transport', async (): Promise<void> => {
const fleet = transport();
const provider = new TmuxFleetRuntimeProvider({ transport: fleet });
await expect(provider.attach('coder0', 'control', scope)).rejects.toMatchObject({
code: 'forbidden',
} satisfies Partial<FleetRuntimeProviderError>);
expect(fleet.verifySession).not.toHaveBeenCalled();
});
it('denies fleet listing without an exact-scope read authority decision', async (): Promise<void> => {
const fleet = transport();
const provider = new TmuxFleetRuntimeProvider({ transport: fleet });
await expect(provider.listSessions(scope)).rejects.toMatchObject({
code: 'forbidden',
} satisfies Partial<FleetRuntimeProviderError>);
expect(fleet.listSessions).not.toHaveBeenCalled();
});
it('denies read attachment without an exact-scope read authority decision', async (): Promise<void> => {
const fleet = transport();
const provider = new TmuxFleetRuntimeProvider({ transport: fleet });
await expect(provider.attach('coder0', 'read', scope)).rejects.toMatchObject({
code: 'forbidden',
} satisfies Partial<FleetRuntimeProviderError>);
expect(fleet.verifySession).not.toHaveBeenCalled();
});
it('creates a read-only attachment only after exact target verification', async (): Promise<void> => {
const fleet = transport();
const provider = new TmuxFleetRuntimeProvider({
transport: fleet,
readAuthority: readAuthority(),
attachmentIdFactory: (): string => 'attachment-1',
now: (): Date => new Date('2026-07-12T00:00:00.000Z'),
});
await expect(provider.attach('coder0', 'read', scope)).resolves.toEqual({
attachmentId: 'attachment-1',
sessionId: 'coder0',
mode: 'read',
expiresAt: '2026-07-12T00:05:00.000Z',
});
expect(fleet.verifySession).toHaveBeenCalledWith('coder0');
});
it('denies attachment-handle replay from another immutable actor scope', async (): Promise<void> => {
const fleet = transport();
const provider = new TmuxFleetRuntimeProvider({
transport: fleet,
readAuthority: readAuthority(),
attachmentIdFactory: (): string => 'attachment-1',
now: (): Date => new Date('2026-07-12T00:00:00.000Z'),
});
await provider.attach('coder0', 'read', scope);
await expect(
provider.detach('attachment-1', { ...scope, actorId: 'operator-2' }),
).rejects.toMatchObject({
code: 'forbidden',
} satisfies Partial<FleetRuntimeProviderError>);
});
it('keeps attachment scope immutable after caller-side scope mutation', async (): Promise<void> => {
const mutableScope = { ...scope };
const provider = new TmuxFleetRuntimeProvider({
transport: transport(),
readAuthority: readAuthority(),
attachmentIdFactory: (): string => 'attachment-1',
now: (): Date => new Date('2026-07-12T00:00:00.000Z'),
});
await provider.attach('coder0', 'read', mutableScope);
mutableScope.actorId = 'operator-2';
await expect(provider.detach('attachment-1', scope)).resolves.toBeUndefined();
});
it('denies expired attachment handles and removes them', async (): Promise<void> => {
let now = new Date('2026-07-12T00:00:00.000Z');
const provider = new TmuxFleetRuntimeProvider({
transport: transport(),
readAuthority: readAuthority(),
attachmentIdFactory: (): string => 'attachment-1',
now: (): Date => now,
});
await provider.attach('coder0', 'read', scope);
now = new Date('2026-07-12T00:05:00.001Z');
await expect(provider.detach('attachment-1', scope)).rejects.toMatchObject({
code: 'forbidden',
} satisfies Partial<FleetRuntimeProviderError>);
await expect(provider.detach('attachment-1', scope)).rejects.toMatchObject({
code: 'not_found',
} satisfies Partial<FleetRuntimeProviderError>);
});
it('prunes expired attachment handles before creating a new handle', async (): Promise<void> => {
let now = new Date('2026-07-12T00:00:00.000Z');
let attachmentSequence = 0;
const provider = new TmuxFleetRuntimeProvider({
transport: transport(),
readAuthority: readAuthority(),
attachmentIdFactory: (): string => `attachment-${++attachmentSequence}`,
now: (): Date => now,
});
await provider.attach('coder0', 'read', scope);
now = new Date('2026-07-12T00:05:00.001Z');
await provider.attach('coder0', 'read', scope);
await expect(provider.detach('attachment-1', scope)).rejects.toMatchObject({
code: 'not_found',
} satisfies Partial<FleetRuntimeProviderError>);
});
it('rejects an empty message before consulting write authority or tmux', async (): Promise<void> => {
const fleet = transport();
const writeAuthority: FleetWriteAuthority = {
canWrite: vi.fn(async (): Promise<boolean> => true),
assertAuthorized: vi.fn(async (): Promise<void> => undefined),
};
const provider = new TmuxFleetRuntimeProvider({ transport: fleet, writeAuthority });
await expect(
provider.sendMessage('coder0', { content: '', idempotencyKey: 'message-1' }, scope),
).rejects.toMatchObject({
code: 'invalid_request',
} satisfies Partial<FleetRuntimeProviderError>);
expect(writeAuthority.canWrite).not.toHaveBeenCalled();
expect(writeAuthority.assertAuthorized).not.toHaveBeenCalled();
expect(fleet.verifySession).not.toHaveBeenCalled();
expect(fleet.sendMessage).not.toHaveBeenCalled();
});
it('denies fleet writes by default before probing the tmux transport', async (): Promise<void> => {
const fleet = transport();
const provider = new TmuxFleetRuntimeProvider({ transport: fleet });
await expect(
provider.sendMessage('coder0', { content: 'hello', idempotencyKey: 'message-1' }, scope),
).rejects.toMatchObject({ code: 'forbidden' } satisfies Partial<FleetRuntimeProviderError>);
await expect(provider.terminate('coder0', 'approval-1', scope)).rejects.toMatchObject({
code: 'forbidden',
} satisfies Partial<FleetRuntimeProviderError>);
expect(fleet.verifySession).not.toHaveBeenCalled();
expect(fleet.sendMessage).not.toHaveBeenCalled();
expect(fleet.terminate).not.toHaveBeenCalled();
});
it('rejects an unverified target before consulting orchestrator write authority', async (): Promise<void> => {
const fleet = transport();
fleet.verifySession = vi.fn(async (): Promise<FleetRuntimeTarget> => {
throw new Error('target identity mismatch');
});
const writeAuthority: FleetWriteAuthority = {
canWrite: vi.fn(async (): Promise<boolean> => true),
assertAuthorized: vi.fn(async (): Promise<void> => undefined),
};
const provider = new TmuxFleetRuntimeProvider({ transport: fleet, writeAuthority });
await expect(
provider.sendMessage('coder', { content: 'hello', idempotencyKey: 'message-1' }, scope),
).rejects.toThrow('target identity mismatch');
expect(writeAuthority.assertAuthorized).not.toHaveBeenCalled();
expect(fleet.sendMessage).not.toHaveBeenCalled();
});
it('uses the role-neutral interaction source label by default', async (): Promise<void> => {
const fleet = transport();
const writeAuthority: FleetWriteAuthority = {
canWrite: vi.fn(async (): Promise<boolean> => true),
assertAuthorized: vi.fn(async (): Promise<void> => undefined),
};
const provider = new TmuxFleetRuntimeProvider({ transport: fleet, writeAuthority });
await provider.sendMessage('coder0', { content: 'hello', idempotencyKey: 'message-1' }, scope);
expect(fleet.sendMessage).toHaveBeenCalledWith('coder0', 'hello', 'interaction');
});
it('passes an exact session ID to the fleet transport only through orchestrator-authorized writes', async (): Promise<void> => {
const fleet = transport();
const writeAuthority: FleetWriteAuthority = {
canWrite: vi.fn(async (): Promise<boolean> => true),
assertAuthorized: vi.fn(async (): Promise<void> => undefined),
};
const provider = new TmuxFleetRuntimeProvider({
transport: fleet,
sourceLabel: 'operator',
writeAuthority,
});
await provider.sendMessage('coder0', { content: 'hello', idempotencyKey: 'message-1' }, scope);
await provider.terminate('coder0', 'approval-1', scope);
expect(writeAuthority.assertAuthorized).toHaveBeenCalledWith({
operation: 'session.send',
sessionId: 'coder0',
scope,
});
expect(writeAuthority.assertAuthorized).toHaveBeenCalledWith({
operation: 'session.terminate',
sessionId: 'coder0',
scope,
approvalRef: 'approval-1',
});
expect(fleet.sendMessage).toHaveBeenCalledWith('coder0', 'hello', 'operator');
expect(fleet.terminate).toHaveBeenCalledWith('coder0');
});
it('fails closed when consumers ask for session streaming', async (): Promise<void> => {
const provider = new TmuxFleetRuntimeProvider({ transport: transport() });
const stream = provider.streamSession('coder0', undefined, scope)[Symbol.asyncIterator]();
await expect(stream.next()).rejects.toMatchObject({
code: 'capability_unsupported',
} satisfies Partial<FleetRuntimeProviderError>);
});
});
@@ -0,0 +1,368 @@
import { randomUUID } from 'node:crypto';
import type {
AgentRuntimeProvider,
RuntimeAttachHandle,
RuntimeAttachMode,
RuntimeCapabilitySet,
RuntimeHealth,
RuntimeMessage,
RuntimeScope,
RuntimeSession,
RuntimeSessionTree,
RuntimeStreamEvent,
} from '@mosaicstack/types';
const FLEET_PROVIDER_ID = 'fleet.tmux';
const ATTACHMENT_TTL_MS = 5 * 60 * 1_000;
export type FleetRuntimeProviderErrorCode =
| 'capability_unsupported'
| 'forbidden'
| 'invalid_request'
| 'not_found';
/** A roster-bound target verified by the concrete fleet transport. */
export interface FleetRuntimeTarget {
id: string;
runtimeId: string;
socketName: string;
}
/**
* Narrow transport boundary implemented by the Mosaic tmux adapter. Keeping it
* here prevents the runtime package from depending on the Mosaic CLI package.
*/
export interface FleetRuntimeTransport {
verifySession(sessionId: string): Promise<FleetRuntimeTarget>;
listSessions(): Promise<FleetRuntimeTarget[]>;
sendMessage(sessionId: string, message: string, sourceLabel: string): Promise<void>;
terminate(sessionId: string): Promise<void>;
}
export type FleetReadOperation =
| 'runtime.health'
| 'session.list'
| 'session.tree'
| 'session.attach';
export interface FleetReadAuthorization {
operation: FleetReadOperation;
scope: RuntimeScope;
sessionId?: string;
}
/** Authorization for fleet inspection and read-only attachments. */
export interface FleetReadAuthority {
canRead(authorization: FleetReadAuthorization): Promise<boolean>;
}
export interface FleetWriteAuthorization {
operation: 'session.send' | 'session.terminate';
sessionId: string;
scope: RuntimeScope;
/** Present only for terminate; authority adapters bind it to the exact action. */
approvalRef?: string;
}
/**
* The orchestrator is the only authority that may permit interaction-plane write/control requests to a
* fleet peer. Gateway records the request and denial/success around provider
* invocation; the default authority prevents direct interaction-plane writes by design.
*/
export interface FleetWriteAuthority {
/** Non-consuming preflight used before probing the fleet transport. */
canWrite(authorization: FleetWriteAuthorization): Promise<boolean>;
/** Final exact-target authorization; may consume an orchestrator grant. */
assertAuthorized(authorization: FleetWriteAuthorization): Promise<void>;
}
export interface TmuxFleetRuntimeProviderOptions {
transport: FleetRuntimeTransport;
readAuthority?: FleetReadAuthority;
writeAuthority?: FleetWriteAuthority;
sourceLabel?: string;
attachmentIdFactory?: () => string;
now?: () => Date;
attachmentTtlMs?: number;
}
interface FleetAttachment {
sessionId: string;
scope: RuntimeScope;
expiresAtMs: number;
}
/** A typed, fail-closed provider error that callers can normalize at the boundary. */
export class FleetRuntimeProviderError extends Error {
constructor(
readonly code: FleetRuntimeProviderErrorCode,
message: string,
) {
super(message);
this.name = FleetRuntimeProviderError.name;
}
}
class DenyFleetReadAuthority implements FleetReadAuthority {
async canRead(_authorization: FleetReadAuthorization): Promise<boolean> {
return false;
}
}
class DenyFleetWriteAuthority implements FleetWriteAuthority {
async canWrite(_authorization: FleetWriteAuthorization): Promise<boolean> {
return false;
}
async assertAuthorized(_authorization: FleetWriteAuthorization): Promise<void> {
throw new FleetRuntimeProviderError(
'forbidden',
'Fleet writes require an explicit orchestrator authority decision',
);
}
}
/**
* A capability-limited provider for rostered local fleet peers. It never
* permits raw tmux socket/target selection, interactive control attach, or
* direct interaction-plane writes; all side effects pass through exact transport checks.
*/
export class TmuxFleetRuntimeProvider implements AgentRuntimeProvider {
readonly id = FLEET_PROVIDER_ID;
private readonly attachments = new Map<string, FleetAttachment>();
private readonly readAuthority: FleetReadAuthority;
private readonly writeAuthority: FleetWriteAuthority;
private readonly sourceLabel: string;
private readonly attachmentIdFactory: () => string;
private readonly now: () => Date;
private readonly attachmentTtlMs: number;
constructor(private readonly options: TmuxFleetRuntimeProviderOptions) {
this.readAuthority = options.readAuthority ?? new DenyFleetReadAuthority();
this.writeAuthority = options.writeAuthority ?? new DenyFleetWriteAuthority();
this.sourceLabel = options.sourceLabel ?? 'interaction';
this.attachmentIdFactory = options.attachmentIdFactory ?? randomUUID;
this.now = options.now ?? (() => new Date());
this.attachmentTtlMs = options.attachmentTtlMs ?? ATTACHMENT_TTL_MS;
}
async capabilities(_scope: RuntimeScope): Promise<RuntimeCapabilitySet> {
return {
supported: [
'session.list',
'session.tree',
'session.send',
'session.attach',
'session.terminate',
],
};
}
async health(scope: RuntimeScope): Promise<RuntimeHealth> {
const targets = await this.readTargets('runtime.health', scope);
return {
status: targets.length > 0 ? 'healthy' : 'down',
checkedAt: this.now().toISOString(),
detail:
targets.length > 0
? 'Authorized rostered fleet peers are reachable'
: 'No authorized rostered fleet peers are reachable',
};
}
async listSessions(scope: RuntimeScope): Promise<RuntimeSession[]> {
const targets = await this.readTargets('session.list', scope);
return this.toRuntimeSessions(targets);
}
async getSessionTree(scope: RuntimeScope): Promise<RuntimeSessionTree[]> {
const targets = await this.readTargets('session.tree', scope);
return this.toRuntimeSessions(targets).map(
(session): RuntimeSessionTree => ({
session,
children: [],
}),
);
}
async *streamSession(
_sessionId: string,
_cursor: string | undefined,
_scope: RuntimeScope,
): AsyncIterable<RuntimeStreamEvent> {
throw new FleetRuntimeProviderError(
'capability_unsupported',
'Fleet session streaming is not supported by the tmux provider',
);
}
async sendMessage(
sessionId: string,
message: RuntimeMessage,
scope: RuntimeScope,
): Promise<void> {
if (message.content.length === 0) {
throw new FleetRuntimeProviderError('invalid_request', 'Fleet message content is required');
}
await this.assertWritePermitted('session.send', sessionId, scope);
const target = await this.options.transport.verifySession(sessionId);
await this.assertWriteAuthorized('session.send', target.id, scope);
await this.options.transport.sendMessage(target.id, message.content, this.sourceLabel);
}
async attach(
sessionId: string,
mode: RuntimeAttachMode,
scope: RuntimeScope,
): Promise<RuntimeAttachHandle> {
if (mode !== 'read') {
throw new FleetRuntimeProviderError('forbidden', 'Fleet control attach is not permitted');
}
await this.assertReadAuthorized('session.attach', sessionId, scope);
const target = await this.options.transport.verifySession(sessionId);
await this.assertReadAuthorized('session.attach', target.id, scope);
const attachmentId = this.attachmentIdFactory();
const nowMs = this.now().getTime();
this.pruneExpiredAttachments(nowMs);
const expiresAtMs = nowMs + this.attachmentTtlMs;
this.attachments.set(attachmentId, {
sessionId: target.id,
scope: snapshotScope(scope),
expiresAtMs,
});
return {
attachmentId,
sessionId: target.id,
mode,
expiresAt: new Date(expiresAtMs).toISOString(),
};
}
async detach(attachmentId: string, scope: RuntimeScope): Promise<void> {
const attachment = this.attachments.get(attachmentId);
if (!attachment) {
throw new FleetRuntimeProviderError('not_found', 'Fleet attachment is not active');
}
if (this.now().getTime() >= attachment.expiresAtMs) {
this.attachments.delete(attachmentId);
throw new FleetRuntimeProviderError('forbidden', 'Fleet attachment has expired');
}
if (!sameScope(attachment.scope, scope)) {
throw new FleetRuntimeProviderError('forbidden', 'Fleet attachment scope does not match');
}
this.attachments.delete(attachmentId);
}
async terminate(sessionId: string, approvalRef: string, scope: RuntimeScope): Promise<void> {
if (approvalRef.trim().length === 0) {
throw new FleetRuntimeProviderError(
'invalid_request',
'Fleet termination approval is required',
);
}
await this.assertWritePermitted('session.terminate', sessionId, scope, approvalRef);
const target = await this.options.transport.verifySession(sessionId);
await this.assertWriteAuthorized('session.terminate', target.id, scope, approvalRef);
await this.options.transport.terminate(target.id);
}
private async readTargets(
operation: FleetReadOperation,
scope: RuntimeScope,
): Promise<FleetRuntimeTarget[]> {
await this.assertReadAuthorized(operation, undefined, scope);
const targets = await this.options.transport.listSessions();
const authorization = await Promise.all(
targets.map(
async (target): Promise<boolean> =>
this.readAuthority.canRead({ operation, sessionId: target.id, scope }),
),
);
return targets.filter((_target, index): boolean => authorization[index] === true);
}
private toRuntimeSessions(targets: FleetRuntimeTarget[]): RuntimeSession[] {
const timestamp = this.now().toISOString();
return targets.map(
(target): RuntimeSession => ({
id: target.id,
providerId: this.id,
runtimeId: target.runtimeId,
state: 'active',
createdAt: timestamp,
updatedAt: timestamp,
}),
);
}
private async assertReadAuthorized(
operation: FleetReadOperation,
sessionId: string | undefined,
scope: RuntimeScope,
): Promise<void> {
const allowed = await this.readAuthority.canRead({
operation,
scope,
...(sessionId ? { sessionId } : {}),
});
if (!allowed) {
throw new FleetRuntimeProviderError('forbidden', 'Fleet read is not authorized');
}
}
private pruneExpiredAttachments(nowMs: number): void {
for (const [attachmentId, attachment] of this.attachments) {
if (attachment.expiresAtMs <= nowMs) {
this.attachments.delete(attachmentId);
}
}
}
private async assertWritePermitted(
operation: FleetWriteAuthorization['operation'],
sessionId: string,
scope: RuntimeScope,
approvalRef?: string,
): Promise<void> {
const permitted = await this.writeAuthority.canWrite({
operation,
sessionId,
scope,
...(approvalRef ? { approvalRef } : {}),
});
if (!permitted) {
throw new FleetRuntimeProviderError('forbidden', 'Fleet write is not authorized');
}
}
private async assertWriteAuthorized(
operation: FleetWriteAuthorization['operation'],
sessionId: string,
scope: RuntimeScope,
approvalRef?: string,
): Promise<void> {
await this.writeAuthority.assertAuthorized({
operation,
sessionId,
scope,
...(approvalRef ? { approvalRef } : {}),
});
}
}
function snapshotScope(scope: RuntimeScope): RuntimeScope {
return Object.freeze({
actorId: scope.actorId,
tenantId: scope.tenantId,
channelId: scope.channelId,
correlationId: scope.correlationId,
});
}
function sameScope(left: RuntimeScope, right: RuntimeScope): boolean {
return (
left.actorId === right.actorId &&
left.tenantId === right.tenantId &&
left.channelId === right.channelId &&
left.correlationId === right.correlationId
);
}
+41
View File
@@ -0,0 +1,41 @@
# @mosaicstack/comms
MACP presence SDK — the **P1 (presence)** slice of RFC-001 (§4.5 liveness,
§4.2 event envelope). Minimal by design: set Matrix presence, run the
`mosaic.presence` heartbeat, and compute **deterministic** fleet liveness.
Out of P1 scope (later phases): enrollment/auto-detect, room taxonomy,
per-agent token minting, signed-authorship, federation.
## API
- `classifyLiveness(ageMs, policy)` / `computeFleetLiveness(observations, now, policy)`
— pure, deterministic online/away/offline from heartbeat age. The
authoritative liveness source (RFC-001 §4.5): native Matrix presence is _not_
relied upon.
- `HeartbeatEmitter` / `startHeartbeatLoop(...)` — build and drive the
`mosaic.presence` heartbeat (monotonic `seq`, `interval_ms`).
- `MinimalMatrixClient` — tiny C-S client: `setPresence`, `sendHeartbeat`,
`readHeartbeats`, `joinRoom`. Supports Application-Service masquerade
(`actAsUserId`) for the P1 provisioner, or a per-agent `accessToken`.
- `PresenceAgent` — high-level: join the fleet room, go present, heartbeat.
`pauseHeartbeat()` models a crash (no graceful signal).
- `FleetLivenessReader` — reads the fleet room and computes the liveness board
(`read()` / `formatBoard()`), the surface a human or watchdog reads.
## Liveness policy (RFC-001 §4.5)
```
online : age <= heartbeatIntervalMs * missTolerance
away : age < darkThresholdMs
offline: otherwise (or never-seen / non-finite age -> fail safe to offline)
```
Defaults: interval 30s, miss-tolerance 2, dark-threshold 10min
(`DEFAULT_LIVENESS_POLICY`). All runtime-tunable per RFC-002 §5.3.
## Tests
`pnpm --filter @mosaicstack/comms test` — the liveness core is written
RED-FIRST; an end-to-end proof against a real Synapse lives in
`tools/matrix-presence-harness`.
+37
View File
@@ -0,0 +1,37 @@
{
"name": "@mosaicstack/comms",
"version": "0.0.1",
"type": "module",
"repository": {
"type": "git",
"url": "https://git.mosaicstack.dev/mosaicstack/stack.git",
"directory": "packages/comms"
},
"main": "dist/index.js",
"types": "dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"scripts": {
"build": "tsc",
"lint": "eslint src",
"typecheck": "tsc --noEmit",
"test": "vitest run --passWithNoTests"
},
"devDependencies": {
"@types/node": "^22.0.0",
"@vitest/coverage-v8": "^2.0.0",
"typescript": "^5.8.0",
"vitest": "^2.0.0"
},
"publishConfig": {
"registry": "https://git.mosaicstack.dev/api/packages/mosaicstack/npm/",
"access": "public"
},
"files": [
"dist"
]
}
@@ -0,0 +1,90 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { HeartbeatEmitter, startHeartbeatLoop } from '../heartbeat.js';
import type { PresenceHeartbeatContent } from '../types.js';
const agent = { mxid: '@agent-alpha:matrix.localhost', slug: 'alpha', harness: 'claude-code' };
describe('HeartbeatEmitter', () => {
it('increments seq starting at 1 and stamps the envelope', () => {
let t = 1000;
const em = new HeartbeatEmitter({ agent, intervalMs: 5000, now: () => t });
const a = em.next();
t = 6000;
const b = em.next('away');
expect(a.seq).toBe(1);
expect(a.ts).toBe(1000);
expect(a.status).toBe('online');
expect(a.macp_type).toBe('presence');
expect(a.msgtype).toBe('mosaic.presence');
expect(a.macp_version).toBe('1.0');
expect(a.interval_ms).toBe(5000);
expect(a.agent).toEqual(agent);
expect(a.body).toContain('alpha');
expect(b.seq).toBe(2);
expect(b.ts).toBe(6000);
expect(b.status).toBe('away');
expect(em.currentSeq).toBe(2);
});
it('includes mission_id only when provided', () => {
const withMission = new HeartbeatEmitter({
agent,
intervalMs: 1000,
missionId: 'KBN-101',
}).next();
const without = new HeartbeatEmitter({ agent, intervalMs: 1000 }).next();
expect(withMission.mission_id).toBe('KBN-101');
expect(without.mission_id).toBeUndefined();
});
});
describe('startHeartbeatLoop', () => {
afterEach(() => vi.useRealTimers());
it('emits immediately, then once per interval, until stopped', () => {
vi.useFakeTimers();
const sent: PresenceHeartbeatContent[] = [];
const em = new HeartbeatEmitter({ agent, intervalMs: 1000, now: () => Date.now() });
const loop = startHeartbeatLoop({
emitter: em,
intervalMs: 1000,
send: (c) => {
sent.push(c);
},
});
expect(sent).toHaveLength(1); // immediate beat
vi.advanceTimersByTime(3000);
expect(sent).toHaveLength(4); // +3 beats
expect(sent.map((s) => s.seq)).toEqual([1, 2, 3, 4]);
loop.stop();
vi.advanceTimersByTime(5000);
expect(sent).toHaveLength(4); // no more after stop
loop.stop(); // idempotent
});
it('routes a rejected async send to onError without killing the loop', async () => {
vi.useFakeTimers();
const onError = vi.fn();
let n = 0;
const em = new HeartbeatEmitter({ agent, intervalMs: 1000 });
const loop = startHeartbeatLoop({
emitter: em,
intervalMs: 1000,
onError,
send: () => {
n += 1;
return Promise.reject(new Error(`boom ${n}`));
},
});
await vi.advanceTimersByTimeAsync(2000); // immediate + 2
expect(n).toBe(3);
expect(onError).toHaveBeenCalledTimes(3);
loop.stop();
});
});
@@ -0,0 +1,89 @@
import { describe, expect, it } from 'vitest';
import { classifyLiveness, computeFleetLiveness } from '../liveness.js';
import type { HeartbeatObservation, LivenessPolicy } from '../types.js';
// Small, dev-scale policy so the arithmetic is obvious:
// online window = interval * missTolerance = 1000 * 2 = 2000ms
// dark threshold = 5000ms
const policy: LivenessPolicy = {
heartbeatIntervalMs: 1000,
missTolerance: 2,
darkThresholdMs: 5000,
};
describe('classifyLiveness (deterministic, heartbeat-age based — RFC-001 §4.5)', () => {
it('is online when age is within interval * missTolerance', () => {
expect(classifyLiveness(0, policy)).toBe('online');
expect(classifyLiveness(1999, policy)).toBe('online');
expect(classifyLiveness(2000, policy)).toBe('online'); // inclusive boundary
});
it('is away when past the online window but before dark threshold', () => {
expect(classifyLiveness(2001, policy)).toBe('away');
expect(classifyLiveness(4999, policy)).toBe('away');
});
it('is offline/dark at or past the dark threshold', () => {
expect(classifyLiveness(5000, policy)).toBe('offline');
expect(classifyLiveness(50_000, policy)).toBe('offline');
});
it('treats a never-seen agent (Infinity age) as offline', () => {
expect(classifyLiveness(Number.POSITIVE_INFINITY, policy)).toBe('offline');
});
it('never returns online for a negative-but-huge misconfig (guards NaN)', () => {
// A NaN age must fail safe to offline, not silently report online.
expect(classifyLiveness(Number.NaN, policy)).toBe('offline');
});
});
describe('computeFleetLiveness (A2/A3 core)', () => {
const now = 100_000;
const obs = (slug: string, lastSeenTs: number, lastSeq = 1): HeartbeatObservation => ({
slug,
mxid: `@agent-${slug}:matrix.localhost`,
lastSeenTs,
lastSeq,
assertedStatus: 'online',
});
it('classifies a live fleet: fresh=online, stale=away, dark=offline', () => {
const result = computeFleetLiveness(
[
obs('alpha', now - 500), // 500ms old -> online
obs('bravo', now - 3000), // 3000ms old -> away
obs('charlie', now - 8000), // 8000ms old -> offline
],
now,
policy,
);
const byslug = Object.fromEntries(result.map((r) => [r.slug, r.status]));
expect(byslug).toEqual({ alpha: 'online', bravo: 'away', charlie: 'offline' });
});
it('A3: a previously-online agent flips to offline once age crosses dark threshold', () => {
const lastBeat = 100_000; // agent was hard-killed right after this beat
// Just before the threshold it is still merely "away"...
const justBefore = computeFleetLiveness([obs('victim', lastBeat, 7)], lastBeat + 4999, policy);
expect(justBefore[0]?.status).toBe('away');
// ...and the instant age reaches darkThresholdMs it is deterministically offline,
// with no dependence on native Matrix presence timeouts.
const atThreshold = computeFleetLiveness([obs('victim', lastBeat, 7)], lastBeat + 5000, policy);
expect(atThreshold[0]?.status).toBe('offline');
expect(atThreshold[0]?.ageMs).toBe(5000);
expect(atThreshold[0]?.lastSeq).toBe(7);
});
it('reports ageMs and preserves mxid/slug/seq for the human view', () => {
const [row] = computeFleetLiveness([obs('alpha', now - 1200, 42)], now, policy);
expect(row).toMatchObject({
slug: 'alpha',
mxid: '@agent-alpha:matrix.localhost',
ageMs: 1200,
lastSeq: 42,
status: 'online',
});
});
});
@@ -0,0 +1,131 @@
import { describe, expect, it, vi } from 'vitest';
import { MatrixError, MinimalMatrixClient, toMatrixPresence } from '../matrix-client.js';
const jsonResponse = (status: number, body: unknown): Response =>
new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
// A fetch mock typed with the (URL, RequestInit?) shape the client actually
// calls, so mock.calls has a proper tuple type under noUncheckedIndexedAccess.
const mkFetch = (impl: (url: URL, init?: RequestInit) => Promise<Response>) => vi.fn(impl);
const cfg = {
homeserverUrl: 'https://matrix.localhost:8448',
accessToken: 'as-secret',
actAsUserId: '@agent-alpha:matrix.localhost',
};
describe('toMatrixPresence', () => {
it('maps liveness states to native presence EDU values', () => {
expect(toMatrixPresence('online')).toBe('online');
expect(toMatrixPresence('away')).toBe('unavailable');
expect(toMatrixPresence('offline')).toBe('offline');
});
});
describe('MinimalMatrixClient', () => {
it('setPresence PUTs native presence and masquerades via user_id', async () => {
const fetchMock = mkFetch(async () => jsonResponse(200, {}));
const client = new MinimalMatrixClient(cfg, fetchMock as unknown as typeof fetch);
await client.setPresence('@agent-alpha:matrix.localhost', 'away', 'hb');
const [url, init] = fetchMock.mock.calls[0]!;
const u = new URL((url as URL).toString());
expect(u.pathname).toBe('/_matrix/client/v3/presence/%40agent-alpha%3Amatrix.localhost/status');
expect(u.searchParams.get('user_id')).toBe('@agent-alpha:matrix.localhost');
expect(JSON.parse((init as RequestInit).body as string)).toEqual({
presence: 'unavailable',
status_msg: 'hb',
});
expect((init as RequestInit).method).toBe('PUT');
});
it('sendHeartbeat posts an m.room.message and returns the event_id', async () => {
const fetchMock = mkFetch(async () => jsonResponse(200, { event_id: '$evt1' }));
const client = new MinimalMatrixClient(cfg, fetchMock as unknown as typeof fetch);
const id = await client.sendHeartbeat('!room:matrix.localhost', {
macp_version: '1.0',
macp_type: 'presence',
msgtype: 'mosaic.presence',
agent: { mxid: cfg.actAsUserId, slug: 'alpha', harness: 'claude-code' },
ts: 1,
body: 'alpha online (seq 1)',
status: 'online',
seq: 1,
interval_ms: 1000,
});
expect(id).toBe('$evt1');
const [url] = fetchMock.mock.calls[0]!;
expect((url as URL).pathname).toContain('/rooms/!room%3Amatrix.localhost/send/m.room.message/');
});
it('throws a MatrixError carrying errcode on a non-2xx', async () => {
const fetchMock = mkFetch(async () =>
jsonResponse(403, { errcode: 'M_FORBIDDEN', error: 'nope' }),
);
const client = new MinimalMatrixClient(cfg, fetchMock as unknown as typeof fetch);
await expect(client.whoami()).rejects.toMatchObject({
name: 'MatrixError',
status: 403,
errcode: 'M_FORBIDDEN',
});
await expect(client.whoami()).rejects.toBeInstanceOf(MatrixError);
});
it('readHeartbeats reduces the timeline to the latest beat per agent', async () => {
// Timeline (dir=b => most-recent first). alpha has two beats; keep highest seq.
const chunk = [
{
sender: '@agent-bravo:matrix.localhost',
origin_server_ts: 9000,
content: {
msgtype: 'mosaic.presence',
agent: { slug: 'bravo', mxid: '@agent-bravo:matrix.localhost' },
seq: 5,
status: 'online',
ts: 8999,
},
},
{
sender: '@agent-alpha:matrix.localhost',
origin_server_ts: 8000,
content: {
msgtype: 'mosaic.presence',
agent: { slug: 'alpha', mxid: '@agent-alpha:matrix.localhost' },
seq: 12,
status: 'online',
ts: 7999,
},
},
{
// an ordinary chat message must be ignored
sender: '@human:matrix.localhost',
origin_server_ts: 7000,
content: { msgtype: 'm.text', body: 'hi' },
},
{
sender: '@agent-alpha:matrix.localhost',
origin_server_ts: 6000,
content: {
msgtype: 'mosaic.presence',
agent: { slug: 'alpha', mxid: '@agent-alpha:matrix.localhost' },
seq: 11,
status: 'online',
ts: 5999,
},
},
];
const fetchMock = mkFetch(async () => jsonResponse(200, { chunk }));
const client = new MinimalMatrixClient(cfg, fetchMock as unknown as typeof fetch);
const obs = await client.readHeartbeats('!room:matrix.localhost');
const bySlug = Object.fromEntries(obs.map((o) => [o.slug, o]));
expect(Object.keys(bySlug).sort()).toEqual(['alpha', 'bravo']);
expect(bySlug.alpha).toMatchObject({ lastSeq: 12, lastSeenTs: 8000 }); // highest seq wins, server ts
expect(bySlug.bravo).toMatchObject({ lastSeq: 5, lastSeenTs: 9000 });
const [url] = fetchMock.mock.calls[0]!;
const u = new URL((url as URL).toString());
expect(u.searchParams.get('dir')).toBe('b');
});
});
@@ -0,0 +1,151 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { FleetLivenessReader } from '../liveness-reader.js';
import type { MinimalMatrixClient } from '../matrix-client.js';
import { PresenceAgent } from '../presence-agent.js';
import type { HeartbeatObservation, LivenessPolicy, PresenceStatus } from '../types.js';
/**
* An in-memory fake homeserver room: records heartbeats with a controllable
* server clock and reduces them exactly like the real readHeartbeats. Lets us
* prove the PresenceAgent -> room -> FleetLivenessReader flow (including the A3
* hard-kill -> offline transition) deterministically, with no network.
*/
class FakeRoomClient {
readonly beats: Array<{
slug: string;
mxid: string;
seq: number;
ts: number;
status: PresenceStatus;
}> = [];
presence: Record<string, PresenceStatus> = {};
constructor(private readonly clock: () => number) {}
async joinRoom(roomId: string): Promise<string> {
return roomId;
}
async setPresence(userId: string, status: PresenceStatus): Promise<void> {
this.presence[userId] = status;
}
async sendHeartbeat(
_roomId: string,
content: { agent: { slug: string; mxid: string }; seq: number; status: PresenceStatus },
): Promise<string> {
this.beats.push({
slug: content.agent.slug,
mxid: content.agent.mxid,
seq: content.seq,
ts: this.clock(), // server receive time
status: content.status,
});
return `$evt${this.beats.length}`;
}
async readHeartbeats(): Promise<HeartbeatObservation[]> {
const bySlug = new Map<string, HeartbeatObservation>();
for (const b of this.beats) {
const prev = bySlug.get(b.slug);
if (!prev || b.seq > prev.lastSeq) {
bySlug.set(b.slug, {
slug: b.slug,
mxid: b.mxid,
lastSeenTs: b.ts,
lastSeq: b.seq,
assertedStatus: b.status,
});
}
}
return [...bySlug.values()];
}
}
const policy: LivenessPolicy = {
heartbeatIntervalMs: 1000,
missTolerance: 2,
darkThresholdMs: 5000,
};
describe('presence flow (A2 + A3 at unit level)', () => {
afterEach(() => vi.useRealTimers());
it('shows agents online while beating, then A3: a hard-killed agent goes offline within dark_threshold', async () => {
vi.useFakeTimers();
vi.setSystemTime(0);
const fake = new FakeRoomClient(() => Date.now());
const client = fake as unknown as MinimalMatrixClient;
const reader = new FleetLivenessReader({
client,
roomId: '!fleet',
policy,
now: () => Date.now(),
});
const mk = (slug: string) =>
new PresenceAgent({
client,
agent: { mxid: `@agent-${slug}:matrix.localhost`, slug, harness: 'claude-code' },
roomId: '!fleet',
intervalMs: 1000,
policy,
});
const alpha = mk('alpha');
const bravo = mk('bravo');
const charlie = mk('charlie');
for (const a of [alpha, bravo, charlie]) {
await a.connect();
a.start();
}
// native presence set online for all three (Element dot)
expect(fake.presence['@agent-alpha:matrix.localhost']).toBe('online');
// let a couple of beats flow — all three fresh => online (A2)
await vi.advanceTimersByTimeAsync(1500);
const board1 = Object.fromEntries((await reader.read()).map((r) => [r.slug, r.status]));
expect(board1).toEqual({ alpha: 'online', bravo: 'online', charlie: 'online' });
// HARD-KILL charlie: stop its loop, no more beats. alpha/bravo keep beating.
charlie.pauseHeartbeat(); // hard-kill: no graceful presence signal
// advance to just before dark threshold from charlie's last beat...
await vi.advanceTimersByTimeAsync(3000);
const mid = Object.fromEntries((await reader.read()).map((r) => [r.slug, r.status]));
expect(mid.alpha).toBe('online');
expect(mid.charlie).not.toBe('online'); // already stale (away)
// ...advance past dark_threshold: charlie is deterministically offline.
await vi.advanceTimersByTimeAsync(4000);
const final = await reader.read();
const byslug = Object.fromEntries(final.map((r) => [r.slug, r]));
expect(byslug.charlie!.status).toBe('offline');
expect(byslug.alpha!.status).toBe('online');
expect(byslug.bravo!.status).toBe('online');
for (const a of [alpha, bravo]) await a.stop();
});
it('formatBoard renders a human-readable liveness board (A4)', async () => {
const fake = new FakeRoomClient(() => 10_000);
fake.beats.push({
slug: 'alpha',
mxid: '@agent-alpha:matrix.localhost',
seq: 3,
ts: 9_500,
status: 'online',
});
const reader = new FleetLivenessReader({
client: fake as unknown as MinimalMatrixClient,
roomId: '!fleet',
policy,
now: () => 10_000,
});
const board = await reader.formatBoard();
expect(board).toContain('Fleet presence');
expect(board).toContain('alpha');
expect(board).toContain('online');
expect(board).toContain('online=1');
});
});
+124
View File
@@ -0,0 +1,124 @@
/**
* `mosaic.presence` heartbeat construction and loop (RFC-001 §4.2/§4.5).
*
* The emitter is deterministic and side-effect free (easy to unit test): it
* owns the monotonic `seq` and stamps each beat. The loop wires the emitter to
* a sender on an interval; timers are injectable so the loop is testable with
* fake clocks.
*/
import { MACP_VERSION, type PresenceHeartbeatContent, type PresenceStatus } from './types.js';
export interface HeartbeatAgentIdentity {
mxid: string;
slug: string;
harness: string;
}
export interface HeartbeatEmitterOptions {
agent: HeartbeatAgentIdentity;
/** Nominal interval advertised in each beat (interval_ms). */
intervalMs: number;
/** Optional mission correlation (RFC-001 §4.2 envelope). */
missionId?: string;
/** Injectable clock for deterministic tests. Default Date.now. */
now?: () => number;
}
/**
* Produces successive heartbeat contents with a monotonically increasing seq.
* The first `next()` returns seq=1.
*/
export class HeartbeatEmitter {
private seq = 0;
private readonly now: () => number;
constructor(private readonly opts: HeartbeatEmitterOptions) {
this.now = opts.now ?? Date.now;
}
/** Current sequence number (0 before the first beat). */
get currentSeq(): number {
return this.seq;
}
/** Build the next heartbeat content, advancing the sequence. */
next(status: PresenceStatus = 'online'): PresenceHeartbeatContent {
this.seq += 1;
const ts = this.now();
const content: PresenceHeartbeatContent = {
macp_version: MACP_VERSION,
macp_type: 'presence',
msgtype: 'mosaic.presence',
agent: {
mxid: this.opts.agent.mxid,
slug: this.opts.agent.slug,
harness: this.opts.agent.harness,
},
ts,
body: `${this.opts.agent.slug} ${status} (seq ${this.seq})`,
status,
seq: this.seq,
interval_ms: this.opts.intervalMs,
};
if (this.opts.missionId !== undefined) {
content.mission_id = this.opts.missionId;
}
return content;
}
}
export type HeartbeatSender = (content: PresenceHeartbeatContent) => void | Promise<void>;
export interface HeartbeatLoopOptions {
emitter: HeartbeatEmitter;
send: HeartbeatSender;
intervalMs: number;
/** Status supplier evaluated each beat. Default: always 'online'. */
status?: () => PresenceStatus;
/** Called if a beat's send rejects (so a transient failure doesn't kill the loop). */
onError?: (err: unknown) => void;
/** Injectable timer (tests). Defaults to global setInterval/clearInterval. */
setIntervalFn?: (cb: () => void, ms: number) => unknown;
clearIntervalFn?: (handle: unknown) => void;
}
/** A running heartbeat loop; call stop() to end it. */
export interface HeartbeatLoopHandle {
stop: () => void;
}
/**
* Start a heartbeat loop: emits one beat immediately, then every intervalMs.
* Returns a handle whose `stop()` is idempotent.
*/
export function startHeartbeatLoop(opts: HeartbeatLoopOptions): HeartbeatLoopHandle {
const status = opts.status ?? (() => 'online' as PresenceStatus);
const onError = opts.onError ?? (() => {});
const setIntervalFn = opts.setIntervalFn ?? ((cb, ms) => setInterval(cb, ms));
const clearIntervalFn =
opts.clearIntervalFn ?? ((h) => clearInterval(h as ReturnType<typeof setInterval>));
const beat = (): void => {
try {
const result = opts.send(opts.emitter.next(status()));
if (result instanceof Promise) {
result.catch(onError);
}
} catch (err) {
onError(err);
}
};
beat(); // immediate first beat so liveness is fresh at once
const handle = setIntervalFn(beat, opts.intervalMs);
let stopped = false;
return {
stop: () => {
if (stopped) return;
stopped = true;
clearIntervalFn(handle);
},
};
}
+42
View File
@@ -0,0 +1,42 @@
/**
* @mosaicstack/comms — MACP presence SDK (RFC-001 P1).
*
* Minimal, dev-validated slice: set Matrix presence, run the `mosaic.presence`
* heartbeat, and compute deterministic fleet liveness. Enrollment, room
* taxonomy, token minting and signed-authorship are explicitly out of P1.
*/
export { classifyLiveness, computeFleetLiveness } from './liveness.js';
export {
HeartbeatEmitter,
startHeartbeatLoop,
type HeartbeatAgentIdentity,
type HeartbeatEmitterOptions,
type HeartbeatSender,
type HeartbeatLoopOptions,
type HeartbeatLoopHandle,
} from './heartbeat.js';
export {
MinimalMatrixClient,
MatrixError,
toMatrixPresence,
type MatrixClientConfig,
} from './matrix-client.js';
export { FleetLivenessReader, type FleetLivenessReaderOptions } from './liveness-reader.js';
export { PresenceAgent, type PresenceAgentOptions } from './presence-agent.js';
export {
DEFAULT_LIVENESS_POLICY,
MACP_VERSION,
type AgentLiveness,
type HeartbeatObservation,
type LivenessPolicy,
type MacpEnvelope,
type MatrixPresence,
type PresenceHeartbeatContent,
type PresenceStatus,
} from './types.js';
+58
View File
@@ -0,0 +1,58 @@
/**
* Fleet liveness reader (RFC-001 §4.5, A2/A4).
*
* Reads `mosaic.presence` heartbeats from the fleet presence room and computes
* deterministic online/away/offline for every agent. This is the surface a
* human (or the escalation watchdog, P2+) reads to answer "who's alive?".
*/
import { computeFleetLiveness } from './liveness.js';
import type { MinimalMatrixClient } from './matrix-client.js';
import { DEFAULT_LIVENESS_POLICY, type AgentLiveness, type LivenessPolicy } from './types.js';
export interface FleetLivenessReaderOptions {
client: MinimalMatrixClient;
/** The fleet presence room (id or resolved id). */
roomId: string;
policy?: LivenessPolicy;
/** Injectable clock for tests. Default Date.now. */
now?: () => number;
/** How many timeline events to scan back. Default 200. */
scanLimit?: number;
}
export class FleetLivenessReader {
private readonly policy: LivenessPolicy;
private readonly now: () => number;
constructor(private readonly opts: FleetLivenessReaderOptions) {
this.policy = opts.policy ?? DEFAULT_LIVENESS_POLICY;
this.now = opts.now ?? Date.now;
}
/** Read the room and compute current liveness for every seen agent. */
async read(): Promise<AgentLiveness[]> {
const observations = await this.opts.client.readHeartbeats(
this.opts.roomId,
this.opts.scanLimit ?? 200,
);
return computeFleetLiveness(observations, this.now(), this.policy);
}
/** A compact human-readable liveness board (A4 CLI view). */
async formatBoard(): Promise<string> {
const rows = await this.read();
rows.sort((a, b) => a.slug.localeCompare(b.slug));
const dot: Record<string, string> = { online: '🟢', away: '🟡', offline: '🔴' };
const lines = rows.map(
(r) =>
`${dot[r.status] ?? '⚪'} ${r.slug.padEnd(16)} ${r.status.padEnd(8)} ` +
`age=${(r.ageMs / 1000).toFixed(1)}s seq=${r.lastSeq} ${r.mxid}`,
);
const summary =
`online=${rows.filter((r) => r.status === 'online').length} ` +
`away=${rows.filter((r) => r.status === 'away').length} ` +
`offline=${rows.filter((r) => r.status === 'offline').length}`;
return [`Fleet presence — ${summary}`, ...lines].join('\n');
}
}
+63
View File
@@ -0,0 +1,63 @@
/**
* Deterministic liveness computation (RFC-001 §4.5).
*
* The authoritative liveness signal is the `mosaic.presence` heartbeat, NOT
* native Matrix presence. Given the age of an agent's last heartbeat and a
* policy, these pure functions classify online/away/offline the same way every
* time — which is exactly what makes the A3 "hard-killed agent flips to
* offline within dark_threshold" guarantee deterministic and testable without
* standing up a homeserver.
*/
import type {
AgentLiveness,
HeartbeatObservation,
LivenessPolicy,
PresenceStatus,
} from './types.js';
/**
* Classify a single agent from the age (ms) of its last heartbeat.
*
* - `age <= heartbeatIntervalMs * missTolerance` → **online**
* - `age < darkThresholdMs` → **away**
* - otherwise (or non-finite age) → **offline / dark**
*
* A non-finite age (never seen / NaN) fails safe to `offline`: we never assert
* a liveness we cannot substantiate.
*/
export function classifyLiveness(ageMs: number, policy: LivenessPolicy): PresenceStatus {
if (!Number.isFinite(ageMs)) {
return 'offline';
}
const onlineWindowMs = policy.heartbeatIntervalMs * policy.missTolerance;
if (ageMs <= onlineWindowMs) {
return 'online';
}
if (ageMs < policy.darkThresholdMs) {
return 'away';
}
return 'offline';
}
/**
* Compute liveness for every observed agent at wall-clock `nowMs`.
* The result order mirrors the input order (stable for display).
*/
export function computeFleetLiveness(
observations: readonly HeartbeatObservation[],
nowMs: number,
policy: LivenessPolicy,
): AgentLiveness[] {
return observations.map((o) => {
const ageMs = nowMs - o.lastSeenTs;
return {
slug: o.slug,
mxid: o.mxid,
status: classifyLiveness(ageMs, policy),
lastSeenTs: o.lastSeenTs,
ageMs,
lastSeq: o.lastSeq,
};
});
}
+204
View File
@@ -0,0 +1,204 @@
/**
* Minimal Matrix Client-Server API client for the P1 presence slice.
*
* Deliberately tiny: only the calls presence needs (whoami, set native
* presence, send a timeline event, read recent timeline). Auth is a single
* bearer token; an optional `actAsUserId` enables Application-Service
* masquerade (`?user_id=`) so the P1 provisioner can drive several virtual
* agents with one as_token in dev (RFC-001 §2.2 step 4/Appendix A). Agents
* holding their own access_token simply omit `actAsUserId`.
*
* `fetch` is injectable for unit tests.
*/
import crypto from 'node:crypto';
import type {
HeartbeatObservation,
MatrixPresence,
PresenceHeartbeatContent,
PresenceStatus,
} from './types.js';
export interface MatrixClientConfig {
/** Client-Server API base, e.g. https://matrix.localhost:8448 */
homeserverUrl: string;
/** Bearer token (a per-agent access_token, or an as_token for masquerade). */
accessToken: string;
/** If set, all calls masquerade as this MXID via ?user_id= (AS mode). */
actAsUserId?: string;
}
export class MatrixError extends Error {
constructor(
readonly status: number,
readonly errcode: string | undefined,
message: string,
) {
super(message);
this.name = 'MatrixError';
}
}
type FetchLike = typeof fetch;
/** Map our authoritative liveness state to the native Matrix presence EDU. */
export function toMatrixPresence(status: PresenceStatus): MatrixPresence {
switch (status) {
case 'online':
return 'online';
case 'away':
return 'unavailable';
case 'offline':
return 'offline';
}
}
export class MinimalMatrixClient {
private readonly fetchImpl: FetchLike;
constructor(
private readonly cfg: MatrixClientConfig,
fetchImpl?: FetchLike,
) {
this.fetchImpl = fetchImpl ?? fetch;
}
private async request(
method: string,
path: string,
options: { query?: Record<string, string>; body?: unknown } = {},
): Promise<Record<string, unknown>> {
const url = new URL(this.cfg.homeserverUrl.replace(/\/$/, '') + path);
if (this.cfg.actAsUserId) {
url.searchParams.set('user_id', this.cfg.actAsUserId);
}
for (const [k, v] of Object.entries(options.query ?? {})) {
url.searchParams.set(k, v);
}
const res = await this.fetchImpl(url, {
method,
headers: {
Authorization: `Bearer ${this.cfg.accessToken}`,
'Content-Type': 'application/json',
},
body: options.body === undefined ? undefined : JSON.stringify(options.body),
});
const text = await res.text();
const data = (text ? JSON.parse(text) : {}) as Record<string, unknown>;
if (!res.ok) {
throw new MatrixError(
res.status,
typeof data.errcode === 'string' ? data.errcode : undefined,
`${method} ${path} -> ${res.status}: ${text.slice(0, 300)}`,
);
}
return data;
}
/** GET /account/whoami — resolves the acting MXID. */
async whoami(): Promise<string> {
const data = await this.request('GET', '/_matrix/client/v3/account/whoami');
if (typeof data.user_id !== 'string') {
throw new MatrixError(500, undefined, 'whoami returned no user_id');
}
return data.user_id;
}
/**
* Set the native Matrix presence EDU (so Element shows the right dot for
* humans). NOT the authoritative liveness signal — the heartbeat is.
*/
async setPresence(userId: string, status: PresenceStatus, statusMsg?: string): Promise<void> {
const user = encodeURIComponent(userId);
await this.request('PUT', `/_matrix/client/v3/presence/${user}/status`, {
body: {
presence: toMatrixPresence(status),
...(statusMsg ? { status_msg: statusMsg } : {}),
},
});
}
/** Send an arbitrary timeline event; returns its event_id. */
async sendEvent(
roomId: string,
eventType: string,
content: Record<string, unknown>,
): Promise<string> {
const room = encodeURIComponent(roomId);
const txn = `mosaic-comms-${crypto.randomUUID()}`;
const data = await this.request(
'PUT',
`/_matrix/client/v3/rooms/${room}/send/${encodeURIComponent(eventType)}/${txn}`,
{ body: content },
);
if (typeof data.event_id !== 'string') {
throw new MatrixError(500, undefined, 'send returned no event_id');
}
return data.event_id;
}
/** Post a `mosaic.presence` heartbeat (m.room.message carrier) to the room. */
async sendHeartbeat(roomId: string, content: PresenceHeartbeatContent): Promise<string> {
return this.sendEvent(roomId, 'm.room.message', content as unknown as Record<string, unknown>);
}
/** Join a room (by id or alias). Idempotent on the server. */
async joinRoom(roomIdOrAlias: string): Promise<string> {
const data = await this.request(
'POST',
`/_matrix/client/v3/join/${encodeURIComponent(roomIdOrAlias)}`,
{ body: {} },
);
if (typeof data.room_id !== 'string') {
throw new MatrixError(500, undefined, 'join returned no room_id');
}
return data.room_id;
}
/**
* Read recent `mosaic.presence` heartbeats from a room and reduce them to the
* latest observation per agent. Walks the timeline backwards (most-recent
* first) and keeps, per slug, the beat with the highest seq.
*
* `lastSeenTs` uses the server's `origin_server_ts` (honest "when we last
* heard from it"), falling back to the agent-stamped envelope `ts`.
*/
async readHeartbeats(roomId: string, limit = 200): Promise<HeartbeatObservation[]> {
const room = encodeURIComponent(roomId);
const data = await this.request('GET', `/_matrix/client/v3/rooms/${room}/messages`, {
query: { dir: 'b', limit: String(limit) },
});
const chunk = Array.isArray(data.chunk) ? (data.chunk as Array<Record<string, unknown>>) : [];
const bySlug = new Map<string, HeartbeatObservation>();
for (const ev of chunk) {
const content = ev.content as Record<string, unknown> | undefined;
if (!content || content.msgtype !== 'mosaic.presence') continue;
const agent = content.agent as Record<string, unknown> | undefined;
const slug = agent && typeof agent.slug === 'string' ? agent.slug : undefined;
const mxid =
agent && typeof agent.mxid === 'string'
? agent.mxid
: typeof ev.sender === 'string'
? ev.sender
: undefined;
if (!slug || !mxid) continue;
const seq = typeof content.seq === 'number' ? content.seq : 0;
const serverTs = typeof ev.origin_server_ts === 'number' ? ev.origin_server_ts : undefined;
const envelopeTs = typeof content.ts === 'number' ? content.ts : undefined;
const lastSeenTs = serverTs ?? envelopeTs ?? 0;
const assertedStatus =
content.status === 'online' || content.status === 'away' || content.status === 'offline'
? (content.status as PresenceStatus)
: 'offline';
const prev = bySlug.get(slug);
if (!prev || seq > prev.lastSeq) {
bySlug.set(slug, { slug, mxid, lastSeenTs, lastSeq: seq, assertedStatus });
}
}
return [...bySlug.values()];
}
}
+92
View File
@@ -0,0 +1,92 @@
/**
* High-level presence agent (RFC-001 §4.1 steps 1011, §4.5).
*
* Ties the pieces together for one agent: join the fleet presence room, set
* native Matrix presence online (for Element's dot), and run the authoritative
* `mosaic.presence` heartbeat loop. This is the P1 slice of what a harness does
* on spin — no enrollment/token-minting/introductions (those are P2).
*/
import {
HeartbeatEmitter,
startHeartbeatLoop,
type HeartbeatAgentIdentity,
type HeartbeatLoopHandle,
} from './heartbeat.js';
import type { MinimalMatrixClient } from './matrix-client.js';
import { DEFAULT_LIVENESS_POLICY, type LivenessPolicy, type PresenceStatus } from './types.js';
export interface PresenceAgentOptions {
client: MinimalMatrixClient;
agent: HeartbeatAgentIdentity;
/** Fleet presence room id (or alias) to heartbeat into. */
roomId: string;
/** Heartbeat cadence; defaults to the policy interval. */
intervalMs?: number;
policy?: LivenessPolicy;
missionId?: string;
onError?: (err: unknown) => void;
}
export class PresenceAgent {
private readonly intervalMs: number;
private readonly emitter: HeartbeatEmitter;
private loop: HeartbeatLoopHandle | undefined;
private resolvedRoomId: string | undefined;
constructor(private readonly opts: PresenceAgentOptions) {
const policy = opts.policy ?? DEFAULT_LIVENESS_POLICY;
this.intervalMs = opts.intervalMs ?? policy.heartbeatIntervalMs;
this.emitter = new HeartbeatEmitter({
agent: opts.agent,
intervalMs: this.intervalMs,
missionId: opts.missionId,
});
}
/** Join the fleet room and go present. Returns the resolved room id. */
async connect(): Promise<string> {
this.resolvedRoomId = await this.opts.client.joinRoom(this.opts.roomId);
await this.opts.client.setPresence(this.opts.agent.mxid, 'online', 'mosaic.presence heartbeat');
return this.resolvedRoomId;
}
/** Start the heartbeat loop (emits immediately, then every intervalMs). */
start(status: () => PresenceStatus = () => 'online'): void {
const roomId = this.resolvedRoomId ?? this.opts.roomId;
this.loop = startHeartbeatLoop({
emitter: this.emitter,
intervalMs: this.intervalMs,
status,
onError: this.opts.onError,
send: async (content) => {
await this.opts.client.sendHeartbeat(roomId, content);
},
});
}
get currentSeq(): number {
return this.emitter.currentSeq;
}
/**
* Stop only the heartbeat loop, sending NO graceful signal. This models a
* hard crash/kill: the authoritative liveness path must detect it purely from
* the absence of heartbeats (RFC-001 §4.5, A3), not from any native presence
* change. Idempotent.
*/
pauseHeartbeat(): void {
this.loop?.stop();
this.loop = undefined;
}
/** Graceful stop: stop heartbeating and drop native presence to offline. */
async stop(): Promise<void> {
this.pauseHeartbeat();
try {
await this.opts.client.setPresence(this.opts.agent.mxid, 'offline');
} catch (err) {
this.opts.onError?.(err);
}
}
}
+99
View File
@@ -0,0 +1,99 @@
/**
* @mosaicstack/comms — MACP P1 (presence) types.
*
* Implements the presence/liveness slice of RFC-001 §4.5 and the MACP event
* envelope of RFC-001 §4.2. P1 scope only: presence heartbeat + deterministic
* liveness. No enrollment, room-taxonomy, token-minting or signed-authorship
* (those are P2+).
*/
/** The three human-visible liveness states (RFC-001 §4.5). */
export type PresenceStatus = 'online' | 'away' | 'offline';
/**
* Native Matrix presence EDU states. We still emit these (so Element shows the
* right dot for humans, RFC-001 §4.5) but they are NOT the authoritative
* liveness source — the heartbeat is.
*/
export type MatrixPresence = 'online' | 'unavailable' | 'offline';
/**
* Common MACP event envelope carried in `content` on every custom event
* (RFC-001 §4.2). P1 uses only the fields the presence heartbeat needs; the
* `signature` field (gate actions, §4.4) is intentionally absent in P1.
*/
export interface MacpEnvelope {
macp_version: string;
macp_type: string;
agent: {
mxid: string;
slug: string;
harness: string;
};
ts: number;
mission_id?: string;
}
/**
* `mosaic.presence` heartbeat content (RFC-001 §4.2 "presence" row + §4.5).
* Carried as an `m.room.message` with `msgtype: "mosaic.presence"` and a
* human-visible `body` fallback, posted into the fleet presence room.
*/
export interface PresenceHeartbeatContent extends MacpEnvelope {
macp_type: 'presence';
msgtype: 'mosaic.presence';
/** Human-visible fallback so the event renders in a stock client. */
body: string;
/** Liveness state the agent asserts about itself. */
status: PresenceStatus;
/** Monotonic per-agent sequence number, increments once per beat. */
seq: number;
/** The agent's configured heartbeat interval, so readers can reason. */
interval_ms: number;
}
/**
* Deterministic liveness policy (RFC-001 §4.5). Defaults per §4.5/§5.3:
* interval 30s, miss-tolerance 2, dark threshold a policy value (10 min in
* prod §5; small in dev harness).
*/
export interface LivenessPolicy {
/** Nominal heartbeat interval in ms. Default 30_000. */
heartbeatIntervalMs: number;
/** How many intervals may be missed before "away". Default 2. */
missTolerance: number;
/** Age past which an agent is declared offline/dark. Default 600_000. */
darkThresholdMs: number;
}
/** A single agent's last observed heartbeat, as read from the fleet room. */
export interface HeartbeatObservation {
slug: string;
mxid: string;
/** Wall-clock ms of the last heartbeat seen for this agent. */
lastSeenTs: number;
/** Last seq observed (monotonic per agent). */
lastSeq: number;
/** The status the agent last asserted about itself. */
assertedStatus: PresenceStatus;
}
/** Computed liveness for one agent (what a human/watchdog reads). */
export interface AgentLiveness {
slug: string;
mxid: string;
/** Authoritative, heartbeat-derived status. */
status: PresenceStatus;
lastSeenTs: number;
/** now - lastSeenTs, in ms. */
ageMs: number;
lastSeq: number;
}
export const DEFAULT_LIVENESS_POLICY: LivenessPolicy = {
heartbeatIntervalMs: 30_000,
missTolerance: 2,
darkThresholdMs: 600_000,
};
export const MACP_VERSION = '1.0';
+9
View File
@@ -0,0 +1,9 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "dist",
"rootDir": "src"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
+13
View File
@@ -0,0 +1,13 @@
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
globals: true,
environment: 'node',
coverage: {
provider: 'v8',
include: ['src/**/*.ts'],
exclude: ['src/index.ts'],
},
},
});
@@ -0,0 +1,154 @@
import { describe, expect, it, vi } from 'vitest';
import {
InMemoryInteractionCoordinationPort,
InteractionCoordinationClient,
type CoordinationScope,
type InteractionCoordinationAuthorityError,
type InteractionCoordinationPort,
} from '../index.js';
const scope: CoordinationScope = {
actorId: 'operator-1',
tenantId: 'tenant-a',
correlationId: 'corr-1',
requesterAgentId: 'Nova',
};
function client(
port: InteractionCoordinationPort,
handoffIdFactory: () => string = (): string => 'handoff-1',
): InteractionCoordinationClient {
return new InteractionCoordinationClient(
{ interactionAgentId: 'Nova', orchestrationAgentId: 'Conductor' },
port,
handoffIdFactory,
);
}
describe('InteractionCoordinationClient', (): void => {
it('round-trips handoff, observation, and result through the native port with identities as data', async (): Promise<void> => {
const adapter = new InMemoryInteractionCoordinationPort();
const coordination = client(adapter);
await expect(
coordination.handoff(
{ idempotencyKey: 'handoff-request-1', summary: 'Implement the requested feature' },
scope,
),
).resolves.toEqual({
handoffId: 'handoff-1',
targetAgentId: 'Conductor',
status: 'queued',
correlationId: 'corr-1',
});
adapter.recordActivity('handoff-1', 'running', 'Orchestrator accepted the request');
adapter.recordResult('handoff-1', 'completed', 'Merged by orchestrator');
await expect(coordination.observe('handoff-1', scope)).resolves.toMatchObject({
status: 'completed',
targetAgentId: 'Conductor',
activity: expect.arrayContaining([
expect.objectContaining({ status: 'queued' }),
expect.objectContaining({ status: 'running' }),
expect.objectContaining({ status: 'completed' }),
]),
});
await expect(coordination.result('handoff-1', scope)).resolves.toEqual({
handoffId: 'handoff-1',
targetAgentId: 'Conductor',
status: 'completed',
correlationId: 'corr-1',
summary: 'Merged by orchestrator',
});
expect(coordination).not.toHaveProperty('dispatch');
expect(coordination).not.toHaveProperty('assign');
expect(coordination).not.toHaveProperty('review');
expect(coordination).not.toHaveProperty('merge');
expect(coordination).not.toHaveProperty('cancel');
});
it('fails closed before delivery when an unconfigured agent requests orchestrator work', async (): Promise<void> => {
const adapter = new InMemoryInteractionCoordinationPort();
await expect(
client(adapter).handoff(
{ idempotencyKey: 'handoff-request-1', summary: 'Implement the requested feature' },
{ ...scope, requesterAgentId: 'Untrusted' },
),
).rejects.toMatchObject({
code: 'requester_forbidden',
} satisfies Partial<InteractionCoordinationAuthorityError>);
});
it('rejects self-delegation configuration before constructing a client', (): void => {
expect(
(): InteractionCoordinationClient =>
new InteractionCoordinationClient(
{ interactionAgentId: 'Nova', orchestrationAgentId: 'Nova' },
new InMemoryInteractionCoordinationPort(),
),
).toThrow('Interaction and orchestration identities must differ');
});
it('rejects whitespace-equivalent self-delegation identities', (): void => {
expect(
(): InteractionCoordinationClient =>
new InteractionCoordinationClient(
{ interactionAgentId: 'Nova ', orchestrationAgentId: 'Nova' },
new InMemoryInteractionCoordinationPort(),
),
).toThrow('Interaction and orchestration identities must differ');
});
it('does not expose another tenant handoff to observe or result', async (): Promise<void> => {
const adapter = new InMemoryInteractionCoordinationPort();
const coordination = client(adapter);
await coordination.handoff(
{ idempotencyKey: 'handoff-request-1', summary: 'Implement the requested feature' },
scope,
);
const otherTenantScope = { ...scope, tenantId: 'tenant-b' };
await expect(coordination.observe('handoff-1', otherTenantScope)).rejects.toMatchObject({
code: 'forbidden',
});
await expect(coordination.result('handoff-1', otherTenantScope)).rejects.toMatchObject({
code: 'forbidden',
});
});
it('bounds native handoff retention by evicting the oldest handoff', async (): Promise<void> => {
const adapter = new InMemoryInteractionCoordinationPort({ maxHandoffs: 1 });
const first = client(adapter, (): string => 'handoff-1');
const second = client(adapter, (): string => 'handoff-2');
await first.handoff({ idempotencyKey: 'handoff-request-1', summary: 'First request' }, scope);
await second.handoff({ idempotencyKey: 'handoff-request-2', summary: 'Second request' }, scope);
await expect(first.observe('handoff-1', scope)).rejects.toMatchObject({ code: 'not_found' });
await expect(second.observe('handoff-2', scope)).resolves.toMatchObject({ status: 'queued' });
});
it('fails closed when a transport reports target drift', async (): Promise<void> => {
const adapter: InteractionCoordinationPort = {
handoff: vi.fn(async () => ({
handoffId: 'handoff-1',
targetAgentId: 'Unexpected',
status: 'accepted' as const,
correlationId: 'corr-1',
})),
observe: vi.fn(),
result: vi.fn(),
};
await expect(
client(adapter).handoff(
{ idempotencyKey: 'handoff-request-1', summary: 'Implement the requested feature' },
scope,
),
).rejects.toMatchObject({
code: 'target_drift',
} satisfies Partial<InteractionCoordinationAuthorityError>);
});
});
@@ -0,0 +1,41 @@
import { describe, expect, it } from 'vitest';
import { resolveLaunchCommand } from '../runner.js';
describe('coord consequential-runtime launch gate', () => {
it('routes default and direct configured Claude commands through mosaic', () => {
expect(resolveLaunchCommand('claude', 'continue', undefined)).toEqual([
'mosaic',
'claude',
'-p',
'continue',
]);
expect(resolveLaunchCommand('claude', 'continue', ['claude', '-p', '{prompt}'])).toEqual([
'mosaic',
'claude',
'-p',
'continue',
]);
});
it('preserves an already-gated Claude command and rejects unknown launchers', () => {
expect(
resolveLaunchCommand('claude', 'continue', ['mosaic', 'yolo', 'claude', '{prompt}']),
).toEqual(['mosaic', 'yolo', 'claude', 'continue']);
expect(() => resolveLaunchCommand('claude', 'continue', ['custom-launcher'])).toThrow(
/must use `mosaic claude`/,
);
});
it('does not change the out-of-scope Codex command contract', () => {
expect(resolveLaunchCommand('codex', 'continue', undefined)).toEqual([
'codex',
'-p',
'continue',
]);
expect(resolveLaunchCommand('codex', 'continue', ['codex', '{prompt}'])).toEqual([
'codex',
'continue',
]);
});
});
@@ -0,0 +1,208 @@
import {
type CoordinationObservation,
type CoordinationResult,
type CoordinationScope,
type InteractionCoordinationActivity,
type InteractionCoordinationPort,
type Handoff,
type HandoffReceipt,
type HandoffStatus,
} from './interaction-coordination.js';
const DEFAULT_HANDOFF_TTL_MS = 60 * 60 * 1_000;
const DEFAULT_MAX_HANDOFFS = 1_000;
interface StoredHandoff {
readonly handoff: Handoff;
status: HandoffStatus;
readonly activity: InteractionCoordinationActivity[];
readonly expiresAt: number;
result?: CoordinationResult;
}
export interface InMemoryInteractionCoordinationPortOptions {
now?: () => Date;
handoffTtlMs?: number;
maxHandoffs?: number;
}
/**
* Native deterministic queue/port adapter for the coordination boundary.
* It intentionally has no fleet/tmux dependency. A future deployment adapter
* implements InteractionCoordinationPort without changing interaction-plane callers.
*/
export class InMemoryInteractionCoordinationPort implements InteractionCoordinationPort {
private readonly handoffs = new Map<string, StoredHandoff>();
private readonly now: () => Date;
private readonly handoffTtlMs: number;
private readonly maxHandoffs: number;
constructor(options: InMemoryInteractionCoordinationPortOptions = {}) {
this.now = options.now ?? (() => new Date());
this.handoffTtlMs = options.handoffTtlMs ?? DEFAULT_HANDOFF_TTL_MS;
this.maxHandoffs = options.maxHandoffs ?? DEFAULT_MAX_HANDOFFS;
}
async handoff(handoff: Handoff): Promise<HandoffReceipt> {
this.pruneExpiredHandoffs();
const existing = this.handoffs.get(handoff.handoffId);
if (existing !== undefined) {
this.assertSameHandoff(existing.handoff, handoff);
return this.receipt(existing.handoff, existing.status);
}
const stored: StoredHandoff = {
handoff: snapshotHandoff(handoff),
status: 'queued',
activity: [activity('queued', 'Handoff accepted by the native coordination queue', this.now)],
expiresAt: this.now().getTime() + this.handoffTtlMs,
};
this.handoffs.set(handoff.handoffId, stored);
this.enforceHandoffLimit();
return this.receipt(stored.handoff, stored.status);
}
async observe(handoffId: string, scope: CoordinationScope): Promise<CoordinationObservation> {
this.pruneExpiredHandoffs();
const stored = this.requireScopedHandoff(handoffId, scope);
return {
handoffId: stored.handoff.handoffId,
targetAgentId: stored.handoff.targetAgentId,
status: stored.status,
correlationId: stored.handoff.scope.correlationId,
activity: stored.activity.map(copyActivity),
};
}
async result(handoffId: string, scope: CoordinationScope): Promise<CoordinationResult> {
this.pruneExpiredHandoffs();
const stored = this.requireScopedHandoff(handoffId, scope);
return (
stored.result ?? {
handoffId: stored.handoff.handoffId,
targetAgentId: stored.handoff.targetAgentId,
status: 'pending',
correlationId: stored.handoff.scope.correlationId,
}
);
}
/** Host-side progression seam; interaction clients never receive this capability. */
recordActivity(handoffId: string, status: HandoffStatus, summary: string): void {
this.pruneExpiredHandoffs();
const stored = this.requireHandoff(handoffId);
stored.status = status;
stored.activity.push(activity(status, summary, this.now));
}
/** Host-side result seam for deterministic qualification; not an orchestrator consumer. */
recordResult(handoffId: string, status: 'completed' | 'failed', summary: string): void {
this.pruneExpiredHandoffs();
const stored = this.requireHandoff(handoffId);
stored.status = status;
stored.activity.push(activity(status, summary, this.now));
stored.result = {
handoffId: stored.handoff.handoffId,
targetAgentId: stored.handoff.targetAgentId,
status,
correlationId: stored.handoff.scope.correlationId,
summary,
};
}
private receipt(handoff: Handoff, status: HandoffStatus): HandoffReceipt {
return {
handoffId: handoff.handoffId,
targetAgentId: handoff.targetAgentId,
status: status === 'accepted' ? 'accepted' : 'queued',
correlationId: handoff.scope.correlationId,
};
}
private pruneExpiredHandoffs(): void {
const nowMs = this.now().getTime();
for (const [handoffId, handoff] of this.handoffs) {
if (handoff.expiresAt <= nowMs) this.handoffs.delete(handoffId);
}
}
private enforceHandoffLimit(): void {
while (this.handoffs.size > this.maxHandoffs) {
const oldest = this.handoffs.keys().next().value;
if (typeof oldest !== 'string') return;
this.handoffs.delete(oldest);
}
}
private requireScopedHandoff(handoffId: string, scope: CoordinationScope): StoredHandoff {
const stored = this.requireHandoff(handoffId);
if (
stored.handoff.scope.tenantId !== scope.tenantId ||
stored.handoff.scope.actorId !== scope.actorId ||
stored.handoff.scope.requesterAgentId !== scope.requesterAgentId
) {
throw new InMemoryInteractionCoordinationError('forbidden', 'Handoff scope does not match');
}
return stored;
}
private requireHandoff(handoffId: string): StoredHandoff {
const stored = this.handoffs.get(handoffId);
if (stored === undefined) {
throw new InMemoryInteractionCoordinationError('not_found', 'Handoff was not found');
}
return stored;
}
private assertSameHandoff(existing: Handoff, incoming: Handoff): void {
if (
existing.targetAgentId !== incoming.targetAgentId ||
existing.request.idempotencyKey !== incoming.request.idempotencyKey ||
existing.request.summary !== incoming.request.summary ||
existing.request.context !== incoming.request.context ||
existing.request.missionId !== incoming.request.missionId ||
existing.scope.actorId !== incoming.scope.actorId ||
existing.scope.tenantId !== incoming.scope.tenantId ||
existing.scope.correlationId !== incoming.scope.correlationId ||
existing.scope.requesterAgentId !== incoming.scope.requesterAgentId
) {
throw new InMemoryInteractionCoordinationError(
'conflict',
'Handoff ID is already bound to different immutable input',
);
}
}
}
export type InMemoryInteractionCoordinationErrorCode = 'conflict' | 'forbidden' | 'not_found';
export class InMemoryInteractionCoordinationError extends Error {
constructor(
readonly code: InMemoryInteractionCoordinationErrorCode,
message: string,
) {
super(message);
this.name = InMemoryInteractionCoordinationError.name;
}
}
function activity(
status: HandoffStatus,
summary: string,
now: () => Date,
): InteractionCoordinationActivity {
return { occurredAt: now().toISOString(), status, summary };
}
function copyActivity(entry: InteractionCoordinationActivity): InteractionCoordinationActivity {
return { ...entry };
}
function snapshotHandoff(handoff: Handoff): Handoff {
return Object.freeze({
handoffId: handoff.handoffId,
targetAgentId: handoff.targetAgentId,
request: Object.freeze({ ...handoff.request }),
scope: Object.freeze({ ...handoff.scope }),
});
}
+20
View File
@@ -2,6 +2,26 @@ export { createMission, loadMission, missionFilePath, saveMission } from './miss
export { parseTasksFile, updateTaskStatus, writeTasksFile } from './tasks-file.js';
export { runTask, resumeTask } from './runner.js';
export { getMissionStatus, getTaskStatus } from './status.js';
export {
InMemoryInteractionCoordinationError,
InMemoryInteractionCoordinationPort,
} from './in-memory-interaction-coordination-port.js';
export {
InteractionCoordinationAuthorityError,
InteractionCoordinationClient,
} from './interaction-coordination.js';
export type {
CoordinationObservation,
CoordinationResult,
CoordinationScope,
InteractionCoordinationActivity,
InteractionCoordinationIdentity,
InteractionCoordinationPort,
Handoff,
HandoffReceipt,
HandoffRequest,
HandoffStatus,
} from './interaction-coordination.js';
export type {
CreateMissionOptions,
Mission,
@@ -0,0 +1,209 @@
export type HandoffStatus = 'queued' | 'accepted' | 'running' | 'completed' | 'failed';
export interface CoordinationScope {
readonly actorId: string;
readonly tenantId: string;
readonly correlationId: string;
/** Trusted gateway/configuration identity; never supplied by a channel client. */
readonly requesterAgentId: string;
}
export interface InteractionCoordinationIdentity {
readonly interactionAgentId: string;
readonly orchestrationAgentId: string;
}
export interface HandoffRequest {
readonly idempotencyKey: string;
readonly summary: string;
readonly context?: string;
readonly missionId?: string;
}
export interface Handoff {
readonly handoffId: string;
readonly targetAgentId: string;
readonly request: HandoffRequest;
readonly scope: CoordinationScope;
}
export interface HandoffReceipt {
readonly handoffId: string;
readonly targetAgentId: string;
readonly status: 'queued' | 'accepted';
readonly correlationId: string;
}
export interface InteractionCoordinationActivity {
readonly occurredAt: string;
readonly status: HandoffStatus;
readonly summary: string;
}
export interface CoordinationObservation {
readonly handoffId: string;
readonly targetAgentId: string;
readonly status: HandoffStatus;
readonly correlationId: string;
readonly activity: readonly InteractionCoordinationActivity[];
}
export interface CoordinationResult {
readonly handoffId: string;
readonly targetAgentId: string;
readonly status: 'completed' | 'failed' | 'pending';
readonly correlationId: string;
readonly summary?: string;
}
/**
* Transport-neutral boundary. The interaction plane can request work and read
* its progress/result, but it cannot issue worker, review, merge, or other
* general orchestration commands.
*/
export interface InteractionCoordinationPort {
handoff(handoff: Handoff): Promise<HandoffReceipt>;
observe(handoffId: string, scope: CoordinationScope): Promise<CoordinationObservation>;
result(handoffId: string, scope: CoordinationScope): Promise<CoordinationResult>;
}
export type InteractionCoordinationAuthorityErrorCode =
| 'invalid_identity'
| 'requester_forbidden'
| 'target_drift'
| 'correlation_drift';
export class InteractionCoordinationAuthorityError extends Error {
constructor(
readonly code: InteractionCoordinationAuthorityErrorCode,
message: string,
) {
super(message);
this.name = InteractionCoordinationAuthorityError.name;
}
}
/**
* Enforces the interaction-to-orchestration authority boundary before a
* transport is reached. Identity names remain configuration data.
*/
export class InteractionCoordinationClient {
private readonly identity: InteractionCoordinationIdentity;
constructor(
identity: InteractionCoordinationIdentity,
private readonly port: InteractionCoordinationPort,
private readonly handoffIdFactory: () => string = (): string => crypto.randomUUID(),
) {
this.identity = normalizeIdentity(identity);
}
async handoff(request: HandoffRequest, scope: CoordinationScope): Promise<HandoffReceipt> {
this.assertRequester(scope);
const handoff: Handoff = {
handoffId: this.handoffIdFactory(),
targetAgentId: this.identity.orchestrationAgentId,
request: snapshotRequest(request),
scope: snapshotScope(scope),
};
const receipt = await this.port.handoff(handoff);
if (
receipt.handoffId !== handoff.handoffId ||
receipt.targetAgentId !== handoff.targetAgentId
) {
throw new InteractionCoordinationAuthorityError(
'target_drift',
'Interaction coordination transport returned a mismatched handoff target',
);
}
if (receipt.correlationId !== handoff.scope.correlationId) {
throw new InteractionCoordinationAuthorityError(
'correlation_drift',
'Interaction coordination transport returned a mismatched correlation ID',
);
}
return receipt;
}
async observe(handoffId: string, scope: CoordinationScope): Promise<CoordinationObservation> {
this.assertRequester(scope);
return this.assertObservation(await this.port.observe(handoffId, snapshotScope(scope)), scope);
}
async result(handoffId: string, scope: CoordinationScope): Promise<CoordinationResult> {
this.assertRequester(scope);
return this.assertResult(await this.port.result(handoffId, snapshotScope(scope)), scope);
}
private assertRequester(scope: CoordinationScope): void {
if (scope.requesterAgentId !== this.identity.interactionAgentId) {
throw new InteractionCoordinationAuthorityError(
'requester_forbidden',
'Requester is not the configured interaction agent',
);
}
}
private assertObservation(
observation: CoordinationObservation,
scope: CoordinationScope,
): CoordinationObservation {
if (observation.targetAgentId !== this.identity.orchestrationAgentId) {
throw new InteractionCoordinationAuthorityError(
'target_drift',
'Interaction coordination transport returned an unexpected observation target',
);
}
if (observation.correlationId !== scope.correlationId) {
throw new InteractionCoordinationAuthorityError(
'correlation_drift',
'Interaction coordination transport returned a mismatched observation correlation ID',
);
}
return observation;
}
private assertResult(result: CoordinationResult, scope: CoordinationScope): CoordinationResult {
if (result.targetAgentId !== this.identity.orchestrationAgentId) {
throw new InteractionCoordinationAuthorityError(
'target_drift',
'Interaction coordination transport returned an unexpected result target',
);
}
if (result.correlationId !== scope.correlationId) {
throw new InteractionCoordinationAuthorityError(
'correlation_drift',
'Interaction coordination transport returned a mismatched result correlation ID',
);
}
return result;
}
}
function normalizeIdentity(
identity: InteractionCoordinationIdentity,
): InteractionCoordinationIdentity {
const interactionAgentId = identity.interactionAgentId.trim();
const orchestrationAgentId = identity.orchestrationAgentId.trim();
if (interactionAgentId.length === 0 || orchestrationAgentId.length === 0) {
throw new InteractionCoordinationAuthorityError(
'invalid_identity',
'Interaction and orchestration identities are required',
);
}
if (interactionAgentId === orchestrationAgentId) {
throw new InteractionCoordinationAuthorityError(
'invalid_identity',
'Interaction and orchestration identities must differ',
);
}
return Object.freeze({ interactionAgentId, orchestrationAgentId });
}
function snapshotRequest(request: HandoffRequest): HandoffRequest {
return Object.freeze({ ...request });
}
function snapshotScope(scope: CoordinationScope): CoordinationScope {
return Object.freeze({ ...scope });
}
+16 -7
View File
@@ -179,32 +179,41 @@ function buildContinuationPrompt(params: {
`3. Read \`${mission.scratchpadFile}\` for session history and decisions`,
`4. Read \`${mission.tasksFile}\` for current task state`,
'5. `git pull --rebase` to sync latest changes',
`6. Launch runtime with \`${runtime} -p\``,
`6. Launch runtime with \`mosaic ${runtime} -p\``,
`7. Continue execution from task **${taskId}**`,
'8. Follow Two-Phase Completion Protocol',
`9. You are the SOLE writer of \`${mission.tasksFile}\``,
].join('\n');
}
function resolveLaunchCommand(
export function resolveLaunchCommand(
runtime: 'claude' | 'codex',
prompt: string,
configuredCommand: string[] | undefined,
): string[] {
if (configuredCommand === undefined || configuredCommand.length === 0) {
return [runtime, '-p', prompt];
return runtime === 'claude' ? ['mosaic', 'claude', '-p', prompt] : [runtime, '-p', prompt];
}
const hasPromptPlaceholder = configuredCommand.some((value) => value === '{prompt}');
const withInterpolation = configuredCommand.map((value) =>
value === '{prompt}' ? prompt : value,
);
const command = hasPromptPlaceholder ? withInterpolation : [...withInterpolation, prompt];
if (hasPromptPlaceholder) {
return withInterpolation;
if (runtime !== 'claude') return command;
if (
command[0] === 'mosaic' &&
(command[1] === 'claude' || (command[1] === 'yolo' && command[2] === 'claude'))
) {
return command;
}
return [...withInterpolation, prompt];
if (command[0] === 'claude') {
return ['mosaic', 'claude', ...command.slice(1)];
}
throw new Error(
'Custom Claude task commands must use `mosaic claude` so lease registration cannot be bypassed.',
);
}
async function writeAtomicJson(filePath: string, payload: unknown): Promise<void> {
@@ -0,0 +1,71 @@
CREATE TYPE "public"."interaction_handoff_status" AS ENUM('pending', 'accepted');--> statement-breakpoint
CREATE TYPE "public"."interaction_inbox_status" AS ENUM('pending', 'processing', 'processed');--> statement-breakpoint
CREATE TYPE "public"."interaction_outbox_status" AS ENUM('pending', 'processing', 'delivered');--> statement-breakpoint
CREATE TABLE "interaction_checkpoints" (
"session_id" text PRIMARY KEY NOT NULL,
"checkpoint_id" text NOT NULL,
"cursor" text NOT NULL,
"summary" text NOT NULL,
"compaction_epoch" integer NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
CONSTRAINT "interaction_checkpoints_checkpoint_id_unique" UNIQUE("checkpoint_id")
);
--> statement-breakpoint
CREATE TABLE "interaction_handoffs" (
"handoff_id" text PRIMARY KEY NOT NULL,
"session_id" text NOT NULL,
"destination" text NOT NULL,
"correlation_id" text NOT NULL,
"checkpoint_id" text NOT NULL,
"status" "interaction_handoff_status" DEFAULT 'pending' NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "interaction_inbox" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"session_id" text NOT NULL,
"idempotency_key" text NOT NULL,
"correlation_id" text NOT NULL,
"content" text NOT NULL,
"content_digest" text NOT NULL,
"status" "interaction_inbox_status" DEFAULT 'pending' NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "interaction_outbox" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"session_id" text NOT NULL,
"idempotency_key" text NOT NULL,
"correlation_id" text NOT NULL,
"kind" text NOT NULL,
"content" text NOT NULL,
"content_digest" text NOT NULL,
"status" "interaction_outbox_status" DEFAULT 'pending' NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "interaction_sessions" (
"id" text PRIMARY KEY NOT NULL,
"agent_name" text NOT NULL,
"tenant_id" text NOT NULL,
"owner_id" text NOT NULL,
"provider_id" text NOT NULL,
"runtime_session_id" text NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
ALTER TABLE "interaction_checkpoints" ADD CONSTRAINT "interaction_checkpoints_session_id_interaction_sessions_id_fk" FOREIGN KEY ("session_id") REFERENCES "public"."interaction_sessions"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "interaction_handoffs" ADD CONSTRAINT "interaction_handoffs_session_id_interaction_sessions_id_fk" FOREIGN KEY ("session_id") REFERENCES "public"."interaction_sessions"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "interaction_inbox" ADD CONSTRAINT "interaction_inbox_session_id_interaction_sessions_id_fk" FOREIGN KEY ("session_id") REFERENCES "public"."interaction_sessions"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "interaction_outbox" ADD CONSTRAINT "interaction_outbox_session_id_interaction_sessions_id_fk" FOREIGN KEY ("session_id") REFERENCES "public"."interaction_sessions"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "interaction_sessions" ADD CONSTRAINT "interaction_sessions_owner_id_users_id_fk" FOREIGN KEY ("owner_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
CREATE INDEX "interaction_handoffs_session_status_idx" ON "interaction_handoffs" USING btree ("session_id","status");--> statement-breakpoint
CREATE UNIQUE INDEX "interaction_inbox_session_idempotency_idx" ON "interaction_inbox" USING btree ("session_id","idempotency_key");--> statement-breakpoint
CREATE INDEX "interaction_inbox_session_status_created_idx" ON "interaction_inbox" USING btree ("session_id","status","created_at");--> statement-breakpoint
CREATE UNIQUE INDEX "interaction_outbox_session_idempotency_idx" ON "interaction_outbox" USING btree ("session_id","idempotency_key");--> statement-breakpoint
CREATE INDEX "interaction_outbox_session_status_created_idx" ON "interaction_outbox" USING btree ("session_id","status","created_at");
@@ -0,0 +1,5 @@
ALTER TABLE "interaction_checkpoints" DROP CONSTRAINT "interaction_checkpoints_checkpoint_id_unique";--> statement-breakpoint
ALTER TABLE "interaction_checkpoints" DROP CONSTRAINT "interaction_checkpoints_pkey";--> statement-breakpoint
ALTER TABLE "interaction_checkpoints" ADD COLUMN "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL;--> statement-breakpoint
CREATE UNIQUE INDEX "interaction_checkpoints_session_idempotency_idx" ON "interaction_checkpoints" USING btree ("session_id","checkpoint_id");--> statement-breakpoint
CREATE INDEX "interaction_checkpoints_session_epoch_idx" ON "interaction_checkpoints" USING btree ("session_id","compaction_epoch");
@@ -0,0 +1,5 @@
ALTER TABLE "interaction_outbox" ADD COLUMN "channel_id" text;
--> statement-breakpoint
UPDATE "interaction_outbox" SET "channel_id" = 'legacy:unknown' WHERE "channel_id" IS NULL;
--> statement-breakpoint
ALTER TABLE "interaction_outbox" ALTER COLUMN "channel_id" SET NOT NULL;
@@ -0,0 +1,3 @@
ALTER TABLE "interaction_checkpoints" ADD COLUMN "content_digest" text;--> statement-breakpoint
UPDATE "interaction_checkpoints" SET "content_digest" = 'legacy' WHERE "content_digest" IS NULL;--> statement-breakpoint
ALTER TABLE "interaction_checkpoints" ALTER COLUMN "content_digest" SET NOT NULL;
@@ -0,0 +1,36 @@
CREATE TABLE "connector_lease_audit_log" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"tenant_id" text NOT NULL,
"logical_agent_id" text NOT NULL,
"binding_id" text NOT NULL,
"connector_id" text NOT NULL,
"lease_id" uuid,
"lease_epoch" bigint,
"event" text NOT NULL,
"outcome" text NOT NULL,
"reason" text,
"correlation_id" text NOT NULL,
"occurred_at" timestamp with time zone NOT NULL
);
--> statement-breakpoint
CREATE TABLE "logical_agent_connector_leases" (
"lease_id" uuid PRIMARY KEY NOT NULL,
"tenant_id" text NOT NULL,
"logical_agent_id" text NOT NULL,
"binding_id" text NOT NULL,
"connector_id" text NOT NULL,
"scopes" jsonb NOT NULL,
"lease_epoch" bigint NOT NULL,
"acquired_at" timestamp with time zone NOT NULL,
"heartbeat_at" timestamp with time zone NOT NULL,
"expires_at" timestamp with time zone NOT NULL,
"released_at" timestamp with time zone,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE INDEX "connector_lease_audit_binding_occurred_idx" ON "connector_lease_audit_log" USING btree ("tenant_id","logical_agent_id","binding_id","occurred_at" DESC NULLS LAST);--> statement-breakpoint
CREATE INDEX "connector_lease_audit_correlation_idx" ON "connector_lease_audit_log" USING btree ("correlation_id");--> statement-breakpoint
CREATE UNIQUE INDEX "logical_agent_connector_lease_binding_idx" ON "logical_agent_connector_leases" USING btree ("tenant_id","logical_agent_id","binding_id");--> statement-breakpoint
CREATE INDEX "logical_agent_connector_lease_expiry_idx" ON "logical_agent_connector_leases" USING btree ("expires_at");--> statement-breakpoint
CREATE INDEX "logical_agent_connector_lease_connector_idx" ON "logical_agent_connector_leases" USING btree ("connector_id");
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+35
View File
@@ -85,6 +85,41 @@
"when": 1782310438919,
"tag": "0011_bitter_gateway",
"breakpoints": true
},
{
"idx": 12,
"version": "7",
"when": 1783911983447,
"tag": "0012_interaction_durable_state",
"breakpoints": true
},
{
"idx": 13,
"version": "7",
"when": 1783913232578,
"tag": "0013_interaction_checkpoint_history",
"breakpoints": true
},
{
"idx": 14,
"version": "7",
"when": 1783913398006,
"tag": "0014_interaction_outbox_channel_scope",
"breakpoints": true
},
{
"idx": 15,
"version": "7",
"when": 1783942610000,
"tag": "0015_interaction_checkpoint_payload_digest",
"breakpoints": true
},
{
"idx": 16,
"version": "7",
"when": 1784050648841,
"tag": "0016_salty_morlocks",
"breakpoints": true
}
]
}
+177
View File
@@ -15,6 +15,7 @@ import {
uniqueIndex,
real,
integer,
bigint,
customType,
} from 'drizzle-orm/pg-core';
@@ -487,6 +488,182 @@ export const agentLogs = pgTable(
],
);
// ─── Logical agent connector authority ──────────────────────────────────────
// One durable row is the current authority for a tenant/logical-agent/binding.
// Runtime-native session identifiers never enter these core tables.
export const logicalAgentConnectorLeases = pgTable(
'logical_agent_connector_leases',
{
leaseId: uuid('lease_id').primaryKey(),
tenantId: text('tenant_id').notNull(),
logicalAgentId: text('logical_agent_id').notNull(),
bindingId: text('binding_id').notNull(),
connectorId: text('connector_id').notNull(),
scopes: jsonb('scopes').notNull().$type<string[]>(),
leaseEpoch: bigint('lease_epoch', { mode: 'bigint' }).notNull(),
acquiredAt: timestamp('acquired_at', { withTimezone: true }).notNull(),
heartbeatAt: timestamp('heartbeat_at', { withTimezone: true }).notNull(),
expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(),
releasedAt: timestamp('released_at', { withTimezone: true }),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
},
(t) => [
uniqueIndex('logical_agent_connector_lease_binding_idx').on(
t.tenantId,
t.logicalAgentId,
t.bindingId,
),
index('logical_agent_connector_lease_expiry_idx').on(t.expiresAt),
index('logical_agent_connector_lease_connector_idx').on(t.connectorId),
],
);
/** Append-only, credential-safe lease lifecycle and fencing denial metadata. */
export const connectorLeaseAuditLog = pgTable(
'connector_lease_audit_log',
{
id: uuid('id').primaryKey().defaultRandom(),
tenantId: text('tenant_id').notNull(),
logicalAgentId: text('logical_agent_id').notNull(),
bindingId: text('binding_id').notNull(),
connectorId: text('connector_id').notNull(),
leaseId: uuid('lease_id'),
leaseEpoch: bigint('lease_epoch', { mode: 'bigint' }),
event: text('event', {
enum: ['acquire', 'renew', 'takeover', 'reject', 'release', 'expiry'],
}).notNull(),
outcome: text('outcome', { enum: ['succeeded', 'denied'] }).notNull(),
reason: text('reason'),
correlationId: text('correlation_id').notNull(),
occurredAt: timestamp('occurred_at', { withTimezone: true }).notNull(),
},
(t) => [
index('connector_lease_audit_binding_occurred_idx').on(
t.tenantId,
t.logicalAgentId,
t.bindingId,
t.occurredAt.desc(),
),
index('connector_lease_audit_correlation_idx').on(t.correlationId),
],
);
// ─── Tess durable session state ─────────────────────────────────────────────
// PostgreSQL is canonical for restart-safe Tess session recovery. The state
// machine lives in @mosaicstack/agent; these records are its durable adapter.
export const interactionInboxStatusEnum = pgEnum('interaction_inbox_status', [
'pending',
'processing',
'processed',
]);
export const interactionOutboxStatusEnum = pgEnum('interaction_outbox_status', [
'pending',
'processing',
'delivered',
]);
export const interactionHandoffStatusEnum = pgEnum('interaction_handoff_status', [
'pending',
'accepted',
]);
export const interactionSessions = pgTable('interaction_sessions', {
id: text('id').primaryKey(),
agentName: text('agent_name').notNull(),
tenantId: text('tenant_id').notNull(),
ownerId: text('owner_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
providerId: text('provider_id').notNull(),
runtimeSessionId: text('runtime_session_id').notNull(),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
});
export const interactionInbox = pgTable(
'interaction_inbox',
{
id: uuid('id').primaryKey().defaultRandom(),
sessionId: text('session_id')
.notNull()
.references(() => interactionSessions.id, { onDelete: 'cascade' }),
idempotencyKey: text('idempotency_key').notNull(),
correlationId: text('correlation_id').notNull(),
content: text('content').notNull(),
contentDigest: text('content_digest').notNull(),
status: interactionInboxStatusEnum('status').notNull().default('pending'),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
},
(t) => [
uniqueIndex('interaction_inbox_session_idempotency_idx').on(t.sessionId, t.idempotencyKey),
index('interaction_inbox_session_status_created_idx').on(t.sessionId, t.status, t.createdAt),
],
);
export const interactionOutbox = pgTable(
'interaction_outbox',
{
id: uuid('id').primaryKey().defaultRandom(),
sessionId: text('session_id')
.notNull()
.references(() => interactionSessions.id, { onDelete: 'cascade' }),
idempotencyKey: text('idempotency_key').notNull(),
correlationId: text('correlation_id').notNull(),
channelId: text('channel_id').notNull(),
kind: text('kind').notNull(),
content: text('content').notNull(),
contentDigest: text('content_digest').notNull(),
status: interactionOutboxStatusEnum('status').notNull().default('pending'),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
},
(t) => [
uniqueIndex('interaction_outbox_session_idempotency_idx').on(t.sessionId, t.idempotencyKey),
index('interaction_outbox_session_status_created_idx').on(t.sessionId, t.status, t.createdAt),
],
);
export const interactionCheckpoints = pgTable(
'interaction_checkpoints',
{
id: uuid('id').primaryKey().defaultRandom(),
sessionId: text('session_id')
.notNull()
.references(() => interactionSessions.id, { onDelete: 'cascade' }),
checkpointId: text('checkpoint_id').notNull(),
contentDigest: text('content_digest').notNull(),
cursor: text('cursor').notNull(),
summary: text('summary').notNull(),
compactionEpoch: integer('compaction_epoch').notNull(),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
},
(t) => [
uniqueIndex('interaction_checkpoints_session_idempotency_idx').on(t.sessionId, t.checkpointId),
index('interaction_checkpoints_session_epoch_idx').on(t.sessionId, t.compactionEpoch),
],
);
export const interactionHandoffs = pgTable(
'interaction_handoffs',
{
handoffId: text('handoff_id').primaryKey(),
sessionId: text('session_id')
.notNull()
.references(() => interactionSessions.id, { onDelete: 'cascade' }),
destination: text('destination').notNull(),
correlationId: text('correlation_id').notNull(),
checkpointId: text('checkpoint_id').notNull(),
status: interactionHandoffStatusEnum('status').notNull().default('pending'),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
},
(t) => [index('interaction_handoffs_session_status_idx').on(t.sessionId, t.status)],
);
// ─── Skills ─────────────────────────────────────────────────────────────────
export const skills = pgTable(
+20 -1
View File
@@ -58,9 +58,28 @@ export function createAgentLogsRepo(db: Db) {
return rows[0];
},
/**
* Transition hot logs for one session to warm tier. Session retention is
* default-deny: no other session's logs can be changed by this operation.
*/
async promoteSessionToWarm(sessionId: string, olderThan: Date): Promise<number> {
const result = await db
.update(agentLogs)
.set({ tier: 'warm', summarizedAt: new Date() })
.where(
and(
eq(agentLogs.sessionId, sessionId),
eq(agentLogs.tier, 'hot'),
lt(agentLogs.createdAt, olderThan),
),
)
.returning();
return result.length;
},
/**
* Transition hot logs older than the cutoff to warm tier.
* Returns the number of logs transitioned.
* Reserved for a separately authorized global retention job.
*/
async promoteToWarm(olderThan: Date): Promise<number> {
const result = await db
+12
View File
@@ -10,3 +10,15 @@ export {
type LogQuery,
} from './agent-logs.js';
export { registerLogCommand } from './cli.js';
export {
redactSensitiveContent,
type RedactionResult,
type SensitiveClassification,
} from './redaction.js';
export {
createRuntimeAuditLogEntry,
type RuntimeAuditEvent,
type RuntimeAuditErrorCode,
type RuntimeAuditOperation,
type RuntimeAuditOutcome,
} from './runtime-audit.js';
+25
View File
@@ -0,0 +1,25 @@
import { describe, expect, it } from 'vitest';
import { redactSensitiveContent } from './redaction.js';
describe('redactSensitiveContent', (): void => {
it('redacts seeded secret and PII canaries before persistence or egress', (): void => {
const result = redactSensitiveContent(
'email [email protected] token=sk_CANARY12345678 phone +1 555 555 1212',
);
expect(result.content).not.toContain('[email protected]');
expect(result.content).not.toContain('sk_CANARY12345678');
expect(result.content).not.toContain('+1 555 555 1212');
expect(result.classifications).toEqual(['secret', 'pii']);
});
it('redacts common provider credential formats', (): void => {
const result = redactSensitiveContent(
'Authorization: Bearer canary.bearer.token jwt eyJcanary.eyJpayload.eyJsignature aws AKIACANARY1234567890',
);
expect(result.content).not.toContain('canary.bearer.token');
expect(result.content).not.toContain('eyJcanary.eyJpayload.eyJsignature');
expect(result.content).not.toContain('AKIACANARY1234567890');
expect(result.classifications).toEqual(['secret']);
});
});
+40
View File
@@ -0,0 +1,40 @@
export type SensitiveClassification = 'secret' | 'pii';
export interface RedactionResult {
content: string;
classifications: SensitiveClassification[];
}
const SECRET_PATTERNS: RegExp[] = [
/\b(?:sk|ghp|gitea)_[A-Za-z0-9_-]{8,}\b/g,
/\b(?:api[_-]?key|token|password|secret)\s*[:=]\s*[^\s,;]+/gi,
/\b(?:authorization\s*:\s*)?bearer\s+[A-Za-z0-9._~+/-]+=*/gi,
/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,
/\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g,
/-----BEGIN(?: [A-Z]+)* KEY-----[\s\S]*?-----END(?: [A-Z]+)* KEY-----/g,
/https?:\/\/[^\s?#]+[^\s]*[?&](?:token|key|secret|signature|sig)=[^\s&#]+/gi,
];
const PII_PATTERNS: RegExp[] = [
/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi,
/\b\+?\d[\d(). -]{7,}\d\b/g,
];
export function redactSensitiveContent(content: string): RedactionResult {
let redacted = content;
const classifications: SensitiveClassification[] = [];
for (const pattern of SECRET_PATTERNS) {
if (pattern.test(redacted)) {
classifications.push('secret');
redacted = redacted.replace(pattern, '[REDACTED_SECRET]');
}
pattern.lastIndex = 0;
}
for (const pattern of PII_PATTERNS) {
if (pattern.test(redacted)) {
classifications.push('pii');
redacted = redacted.replace(pattern, '[REDACTED_PII]');
}
pattern.lastIndex = 0;
}
return { content: redacted, classifications: [...new Set(classifications)] };
}
+52
View File
@@ -0,0 +1,52 @@
import { describe, expect, it } from 'vitest';
import { createRuntimeAuditLogEntry } from './runtime-audit.js';
describe('createRuntimeAuditLogEntry', (): void => {
it('serializes only allowlisted runtime audit metadata', (): void => {
const entry = createRuntimeAuditLogEntry({
providerId: 'fleet',
operation: 'session.send',
outcome: 'succeeded',
actorId: 'actor-1',
tenantId: 'tenant-1',
channelId: 'discord',
correlationId: 'correlation-1',
resourceId: 'session-1',
durationMs: 12,
});
expect(entry).toMatchObject({
sessionId: 'runtime:fleet',
userId: 'actor-1',
level: 'info',
category: 'tool_use',
content: 'runtime.provider.audit',
metadata: {
providerId: 'fleet',
operation: 'session.send',
outcome: 'succeeded',
correlationId: 'correlation-1',
resourceId: expect.stringMatching(/^sha256:/),
durationMs: 12,
},
});
expect(JSON.stringify(entry)).not.toContain('approvalRef');
});
it('hashes every resource ID without blocking a runtime audit or persisting its raw value', (): void => {
const entry = createRuntimeAuditLogEntry({
providerId: 'fleet',
operation: 'session.send',
outcome: 'succeeded',
actorId: 'actor-1',
tenantId: 'tenant-1',
channelId: 'discord',
correlationId: 'correlation-1',
resourceId: 'credential-canary:secret-value',
durationMs: 12,
});
expect(entry.metadata).toMatchObject({ resourceId: expect.stringMatching(/^sha256:/) });
expect(JSON.stringify(entry)).not.toContain('secret-value');
});
});
+87
View File
@@ -0,0 +1,87 @@
import { createHash } from 'node:crypto';
import type { NewAgentLog } from './agent-logs.js';
export type RuntimeAuditOperation =
| 'session.list'
| 'session.tree'
| 'session.stream'
| 'session.send'
| 'session.attach'
| 'session.terminate'
| 'runtime.capabilities'
| 'runtime.health'
| 'runtime.transitional-capabilities';
export type RuntimeAuditOutcome = 'requested' | 'succeeded' | 'denied' | 'failed';
export type RuntimeAuditErrorCode = 'policy_denied' | 'provider_error';
/**
* Deliberately metadata-only runtime audit record. It has no fields for message
* content, credentials, approval references, tool arguments, or tool output.
*/
export interface RuntimeAuditEvent {
providerId: string;
operation: RuntimeAuditOperation;
outcome: RuntimeAuditOutcome;
actorId: string;
tenantId: string;
channelId: string;
correlationId: string;
resourceId?: string;
durationMs?: number;
errorCode?: RuntimeAuditErrorCode;
}
const SAFE_IDENTIFIER = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
function safeIdentifier(value: string): string {
if (SAFE_IDENTIFIER.test(value)) return value;
return hashIdentifier(value);
}
function hashIdentifier(value: string): string {
return `sha256:${createHash('sha256').update(value).digest('hex')}`;
}
/**
* Converts a typed audit event into a durable log entry using an explicit
* allowlist. Values that could carry credentials or untrusted content are
* rejected before persistence or structured log emission.
*/
export function createRuntimeAuditLogEntry(event: RuntimeAuditEvent): NewAgentLog {
const providerId = safeIdentifier(event.providerId);
const actorId = safeIdentifier(event.actorId);
const tenantId = safeIdentifier(event.tenantId);
const channelId = safeIdentifier(event.channelId);
const correlationId = safeIdentifier(event.correlationId);
// Provider resource identifiers may be opaque or user-derived, so never persist them raw.
const resourceId = event.resourceId ? hashIdentifier(event.resourceId) : undefined;
const persistedUserId = SAFE_IDENTIFIER.test(event.actorId) ? event.actorId : null;
if (
event.durationMs !== undefined &&
(!Number.isInteger(event.durationMs) || event.durationMs < 0)
) {
throw new Error('Runtime audit duration must be a non-negative integer');
}
return {
sessionId: `runtime:${providerId}`,
userId: persistedUserId,
level: event.outcome === 'failed' ? 'error' : event.outcome === 'denied' ? 'warn' : 'info',
category: event.operation.startsWith('session.') ? 'tool_use' : 'general',
content: 'runtime.provider.audit',
metadata: {
providerId,
operation: event.operation,
outcome: event.outcome,
actorId,
tenantId,
channelId,
correlationId,
...(resourceId ? { resourceId } : {}),
...(event.durationMs !== undefined ? { durationMs: event.durationMs } : {}),
...(event.errorCode ? { errorCode: event.errorCode } : {}),
},
};
}
@@ -274,6 +274,20 @@ describe('KeywordAdapter', () => {
expect(results).toHaveLength(1);
});
it('should return all scoped insights for the explicit wildcard query', async () => {
await adapter.storeInsight({
userId: 'u1',
content: 'A literal * marker is still ordinary content',
source: 'chat',
category: 'technical',
relevanceScore: 0.7,
});
const results = await adapter.searchInsights('u1', '*');
expect(results).toHaveLength(4);
expect(results.every((result) => result.score === 1)).toBe(true);
});
it('should return empty for empty query', async () => {
const results = await adapter.searchInsights('u1', ' ');
expect(results).toHaveLength(0);
+10 -6
View File
@@ -132,19 +132,23 @@ export class KeywordAdapter implements MemoryAdapter {
opts?: { limit?: number; embedding?: number[] },
): Promise<InsightSearchResult[]> {
const limit = opts?.limit ?? 10;
const words = query
.toLowerCase()
.split(/\s+/)
.filter((w) => w.length > 0);
const normalizedQuery = query.trim();
const matchAll = normalizedQuery === '*';
const words = matchAll
? []
: normalizedQuery
.toLowerCase()
.split(/\s+/)
.filter((word) => word.length > 0);
if (words.length === 0) return [];
if (words.length === 0 && !matchAll) return [];
const rows = await this.storage.find<InsightRecord>(INSIGHTS, { userId });
const scored: InsightSearchResult[] = [];
for (const row of rows) {
const content = row.content.toLowerCase();
let score = 0;
let score = matchAll ? 1 : 0;
for (const word of words) {
if (content.includes(word)) score++;
}
+7
View File
@@ -22,6 +22,13 @@ export type {
InsightSearchResult,
} from './types.js';
export { createMemoryAdapter, registerMemoryAdapter } from './factory.js';
export {
createOperatorMemoryPlugin,
type OperatorMemoryPlugin,
type OperatorMemoryScope,
type OperatorMemoryConfig,
type OperatorMemoryResult,
} from './operator-memory-plugin.js';
export { PgVectorAdapter } from './adapters/pgvector.js';
export { KeywordAdapter } from './adapters/keyword.js';
@@ -0,0 +1,147 @@
import { describe, expect, it, vi } from 'vitest';
import { createOperatorMemoryPlugin } from './operator-memory-plugin.js';
import type { Insight, InsightSearchResult, NewInsight } from './types.js';
function adapter() {
return {
name: 'test',
embedder: null,
storeInsight: vi.fn(
async (value: NewInsight): Promise<Insight> => ({
...value,
id: '1',
createdAt: new Date(),
}),
),
searchInsights: vi.fn(async (): Promise<InsightSearchResult[]> => []),
getInsight: vi.fn(),
deleteInsight: vi.fn(),
getPreference: vi.fn(),
setPreference: vi.fn(),
deletePreference: vi.fn(),
listPreferences: vi.fn(),
close: vi.fn(),
};
}
describe('OperatorMemoryPlugin', () => {
it('isolates configured namespace storage across server-derived tenant, owner, and session scopes', async () => {
const memory = adapter();
const plugin = createOperatorMemoryPlugin({
adapter: memory,
instanceId: 'Nova',
namespace: 'operator-memory',
redact: (value) => value,
});
await plugin.capture(
{ tenantId: 'tenant-a', ownerId: 'owner-a', sessionId: 'session-a' },
{ content: 'one', source: 'test', category: 'note' },
);
await plugin.capture(
{ tenantId: 'tenant-b', ownerId: 'owner-a', sessionId: 'session-a' },
{ content: 'two', source: 'test', category: 'note' },
);
await plugin.capture(
{ tenantId: 'tenant-a', ownerId: 'owner-a', sessionId: 'session-b' },
{ content: 'three', source: 'test', category: 'note' },
);
expect(
memory.storeInsight.mock.calls.map((call: unknown[]) => (call[0] as NewInsight).userId),
).toEqual([
'["operator-memory","tenant-a","owner-a","session-a"]',
'["operator-memory","tenant-b","owner-a","session-a"]',
'["operator-memory","tenant-a","owner-a","session-b"]',
]);
});
it('rejects an incomplete runtime scope before it can produce a shared storage key', async () => {
const memory = adapter();
const plugin = createOperatorMemoryPlugin({
adapter: memory,
instanceId: 'Nova',
namespace: 'operator-memory',
redact: (value) => value,
});
await expect(
plugin.capture(
{ tenantId: 'tenant-a', ownerId: 'owner-a', sessionId: ' ' },
{ content: 'note', source: 'test', category: 'note' },
),
).rejects.toThrow('Operator memory session ID is required');
expect(memory.storeInsight).not.toHaveBeenCalled();
});
it('uses a differently named configured instance in retrieval provenance', async () => {
const memory = adapter();
memory.searchInsights.mockResolvedValue([
{ id: '1', content: 'x', score: 1, metadata: { source: 'project' } },
]);
const plugin = createOperatorMemoryPlugin({
adapter: memory,
instanceId: 'Nova',
namespace: 'operator-memory',
redact: (value) => value,
});
const results = await plugin.search({ tenantId: 't', ownerId: 'o', sessionId: 's' }, 'x');
expect(results[0]?.provenance).toEqual({
instanceId: 'Nova',
namespace: 'operator-memory',
source: 'project',
});
});
it('orders startup context with project and flat-file truth before retrieved material', async () => {
const memory = adapter();
memory.searchInsights.mockResolvedValue([
{ id: 'retrieval', content: 'retrieval', score: 1 },
{ id: 'flat-file', content: 'flat-file', score: 1, metadata: { source: 'flat-file' } },
{ id: 'project', content: 'project', score: 1, metadata: { source: 'project' } },
]);
const plugin = createOperatorMemoryPlugin({
adapter: memory,
instanceId: 'Nova',
namespace: 'operator-memory',
maxStartupContext: 2,
redact: (value) => value,
});
const context = await plugin.startupContext({
tenantId: 'tenant-a',
ownerId: 'owner-a',
sessionId: 'session-a',
});
expect(context.map((result) => result.id)).toEqual(['project', 'flat-file']);
expect(memory.searchInsights).toHaveBeenCalledWith(expect.any(String), '*', { limit: 64 });
});
it('redacts content before adapter persistence and records configured provenance metadata', async () => {
const memory = adapter();
const plugin = createOperatorMemoryPlugin({
adapter: memory,
instanceId: 'Nova',
namespace: 'operator-memory',
redact: (value) => value.replace('secret', '[REDACTED]'),
});
await plugin.capture(
{ tenantId: 'tenant-a', ownerId: 'owner-a', sessionId: 'session-a' },
{ content: 'secret note', source: 'project', category: 'note' },
);
expect(memory.storeInsight).toHaveBeenCalledWith(
expect.objectContaining({
content: '[REDACTED] note',
metadata: {
instanceId: 'Nova',
namespace: 'operator-memory',
source: 'project',
},
}),
);
});
});
@@ -0,0 +1,154 @@
import type { Insight, InsightSearchResult, MemoryAdapter } from './types.js';
const STARTUP_CONTEXT_CANDIDATE_LIMIT = 64;
/** Immutable server-derived boundary; callers never choose an adapter namespace. */
export interface OperatorMemoryScope {
readonly tenantId: string;
readonly ownerId: string;
readonly sessionId: string;
}
export interface OperatorMemoryConfig {
/** Adapter injection is deployment/lifecycle configuration, never caller input. */
readonly adapter: MemoryAdapter;
/** Configured agent identity; it is metadata rather than a storage key default. */
readonly instanceId: string;
/** Configured storage partition; callers cannot select a namespace. */
readonly namespace: string;
readonly maxStartupContext?: number;
redact(content: string): string;
}
export interface OperatorMemoryResult extends InsightSearchResult {
provenance: { instanceId: string; namespace: string; source: string };
}
export interface OperatorMemoryPlugin {
capture(
scope: OperatorMemoryScope,
input: { content: string; source: string; category: string },
): Promise<Insight>;
search(
scope: OperatorMemoryScope,
query: string,
limit?: number,
): Promise<OperatorMemoryResult[]>;
recent(scope: OperatorMemoryScope, limit?: number): Promise<OperatorMemoryResult[]>;
stats(scope: OperatorMemoryScope): Promise<{ namespace: string; resultCount: number }>;
startupContext(scope: OperatorMemoryScope): Promise<OperatorMemoryResult[]>;
}
function scopedUserId(scope: OperatorMemoryScope, namespace: string): string {
const normalizedScope = normalizeScope(scope);
// JSON tuple encoding avoids delimiter collisions between independently scoped IDs.
return JSON.stringify([
namespace,
normalizedScope.tenantId,
normalizedScope.ownerId,
normalizedScope.sessionId,
]);
}
function normalizeScope(scope: OperatorMemoryScope): OperatorMemoryScope {
if (typeof scope !== 'object' || scope === null) {
throw new Error('Operator memory scope is required');
}
return Object.freeze({
tenantId: requiredScopeId(scope.tenantId, 'tenant ID'),
ownerId: requiredScopeId(scope.ownerId, 'owner ID'),
sessionId: requiredScopeId(scope.sessionId, 'session ID'),
});
}
function requiredScopeId(value: unknown, field: string): string {
if (typeof value !== 'string' || value.trim().length === 0) {
throw new Error(`Operator memory ${field} is required`);
}
return value.trim();
}
function compareStartupContext(left: OperatorMemoryResult, right: OperatorMemoryResult): number {
return (
startupSourcePriority(left.provenance.source) - startupSourcePriority(right.provenance.source)
);
}
function startupSourcePriority(source: string): number {
if (source === 'project') return 0;
if (source === 'flat-file') return 1;
return 2;
}
function normalizeConfig(config: OperatorMemoryConfig): OperatorMemoryConfig {
const instanceId = config.instanceId.trim();
const namespace = config.namespace.trim();
const maxStartupContext = config.maxStartupContext ?? 8;
if (instanceId.length === 0 || namespace.length === 0) {
throw new Error('Operator memory instance ID and namespace must be configured');
}
if (!Number.isSafeInteger(maxStartupContext) || maxStartupContext < 1) {
throw new Error('Operator memory startup context limit must be a positive integer');
}
return Object.freeze({ ...config, instanceId, namespace, maxStartupContext });
}
/** Creates a leaf-package, replaceable memory adapter facade. */
export function createOperatorMemoryPlugin(config: OperatorMemoryConfig): OperatorMemoryPlugin {
const pluginConfig = normalizeConfig(config);
const mapResult = (result: InsightSearchResult): OperatorMemoryResult => ({
...result,
provenance: {
instanceId: pluginConfig.instanceId,
namespace: pluginConfig.namespace,
source: String(result.metadata?.['source'] ?? 'retrieval'),
},
});
const search = async (
scope: OperatorMemoryScope,
query: string,
limit = 10,
): Promise<OperatorMemoryResult[]> =>
(
await pluginConfig.adapter.searchInsights(
scopedUserId(scope, pluginConfig.namespace),
query,
{
limit,
},
)
).map(mapResult);
return {
async capture(scope, input) {
return pluginConfig.adapter.storeInsight({
userId: scopedUserId(scope, pluginConfig.namespace),
content: pluginConfig.redact(input.content),
source: input.source,
category: input.category,
relevanceScore: 1,
metadata: {
namespace: pluginConfig.namespace,
instanceId: pluginConfig.instanceId,
source: input.source,
},
});
},
search,
async recent(scope, limit = 10) {
return search(scope, '*', limit);
},
async stats(scope) {
return {
namespace: pluginConfig.namespace,
resultCount: (await search(scope, '*', 100)).length,
};
},
async startupContext(scope) {
const maxStartupContext = pluginConfig.maxStartupContext ?? 8;
// Prioritize authoritative sources within a bounded candidate window.
const candidateLimit = Math.max(maxStartupContext, STARTUP_CONTEXT_CANDIDATE_LIMIT);
const context = await search(scope, '*', candidateLimit);
return [...context].sort(compareStartupContext).slice(0, maxStartupContext);
},
};
}
+4
View File
@@ -49,6 +49,10 @@ export interface MemoryAdapter {
// Insights
storeInsight(insight: NewInsight): Promise<Insight>;
getInsight(id: string): Promise<Insight | null>;
/**
* Searches within one scoped user ID. The reserved `*` query returns scoped
* recent/all results rather than performing backend-specific wildcard parsing.
*/
searchInsights(
userId: string,
query: string,
+55
View File
@@ -47,6 +47,61 @@ export MOSAIC_ADMIN_PASSWORD="securepass123"
mosaic gateway install
```
## Runtime launchers
```bash
mosaic claude # Launch Claude Code with Mosaic injection
mosaic yolo claude # …with --dangerously-skip-permissions
mosaic codex | opencode | pi
```
### `mosaic claudex` (EXPERIMENTAL)
Runs GPT models **inside the Claude Code harness** by pointing Claude Code at a
local [`claude-code-proxy`](https://github.com/raine/claude-code-proxy) that
translates the Anthropic Messages API to a ChatGPT-subscription (Codex OAuth)
backend. This is **not Anthropic Claude** — model behavior, tool use, and output
quality may differ. Intended for evaluation, not production delivery.
```bash
mosaic claudex # launch (prompts through the proxy readiness gate)
mosaic yolo claudex # …with --dangerously-skip-permissions
mosaic claudex --print "hello" # trailing args are forwarded to Claude Code
```
**Prerequisite:** the `claude-code-proxy` binary must be installed and
authenticated (`claude-code-proxy codex auth …`). `mosaic claudex` runs a
preflight that verifies the binary, the OAuth state (triggering a device re-auth
if needed), and a trusted local listener before launching; it **fails closed**
if the proxy cannot be brought up with a verified identity.
**Isolation (never touches your real Claude state).** claudex always launches
against an isolated `CLAUDE_CONFIG_DIR` (default `~/.config/mosaic/claudex/home`).
The ambient `CLAUDE_CONFIG_DIR` is deliberately ignored, and a guard proves the
resolved dir can never be — or live under — the real `~/.claude`. A claudex
session therefore cannot mutate your normal Claude Code config.
**No token leakage.** claudex never reads the proxy's credential file. Claude
Code is handed only `ANTHROPIC_AUTH_TOKEN=unused` pointed at the loopback proxy;
the entire credential-bearing env family (`ANTHROPIC_*`, `AWS_*`, `GOOGLE_CLOUD_*`,
`GOOGLE_APPLICATION_CREDENTIALS`, `*_TOKEN`, `*_KEY`, `*_SECRET`, …) is stripped
from the composed environment. The Bedrock/Vertex routing switches
(`CLAUDE_CODE_USE_BEDROCK`, `CLAUDE_CODE_USE_VERTEX`, and the `_SKIP_*_AUTH`
pair) are force-removed regardless of value — otherwise their mere presence
would route Claude Code to the real Anthropic API via AWS/GCP and bypass the
proxy. The proxy holds the real OAuth credential.
**Model tiers (override via env).**
| Tier | Env var | Default |
| --------------------- | ---------------------------- | -------------- |
| primary (opus/sonnet) | `ANTHROPIC_MODEL` | `gpt-5.6-sol` |
| small/fast (haiku) | `ANTHROPIC_SMALL_FAST_MODEL` | `gpt-5.6-luna` |
Operator-provided values win over the defaults. Additional overrides:
`MOSAIC_CLAUDEX_CONFIG_DIR` (isolated config dir), `ANTHROPIC_BASE_URL` (proxy
endpoint).
## Hooks management
After running `mosaic wizard`, Claude hooks are installed in `~/.claude/hooks-config.json`.
+12 -3
View File
@@ -189,15 +189,24 @@ bash tools/install.sh --dev # Contributor lane: source build at --ref/ma
bash tools/install.sh --ref v1.0 # Install from a specific git ref (--ref wins over --next)
```
The installer rejects unrecognized flags or positional arguments before making changes and prints the supported-option usage.
## Universal Skills
The installer syncs skills from `mosaic/agent-skills` into `~/.config/mosaic/skills/`, then links each skill into runtime directories.
The installer syncs skills from `mosaic/agent-skills` into `~/.config/mosaic/skills/`. Install, wizard finalization, and `mosaic update` automatically reconcile every canonical skill into Claude Code's `~/.claude/skills/` directory.
```bash
mosaic sync # Full sync (clone + link)
~/.config/mosaic/tools/_scripts/mosaic-sync-skills --link-only # Re-link only
mosaic sync # Full canonical catalog sync
~/.config/mosaic/tools/_scripts/mosaic-sync-skills --link-only # Re-link only
mosaic skill list # Show registered, missing, dangling, and foreign entries
mosaic skill register <name> # Register or repair one canonical Claude link
mosaic skill unregister <name> # Remove one Mosaic-owned Claude link
```
Skill names are direct children using `[A-Za-z0-9][A-Za-z0-9._-]*`, not paths. Registration rejects traversal/control characters and never replaces foreign files, directories, or symlinks; unregister removes only links that point inside the canonical Mosaic skill root. After registering during a running Claude Code session, use `/reload-skills` or start a new session.
M1 lifecycle management targets Claude Code. Pi can discover the canonical Mosaic root through its launcher configuration. Codex parity remains follow-up scope and continues to use the existing full skill-sync linker.
## Health Audit
```bash
+10 -10
View File
@@ -5,20 +5,20 @@ Tool suites live at `~/.config/mosaic/tools/<suite>/`. This is the index only.
read it (or the relevant service guide) when your task actually touches that service.
Project-specific tooling belongs in the project's `AGENTS.md`, not here.
## Most-used fleet tools (reach for these FIRST — don't hand-roll)
## Most-used fleet tools (reach for these first)
You are a Mosaic fleet agent. These cover the highest-frequency cross-agent and git-provider
tasks — use them before improvising with raw `tmux send-keys`, raw `tea`/`gh`/`glab`, or `curl`.
<!-- fleet-comms-contract: 1 -->
**1. Message another agent** → `tools/tmux/agent-send.sh` (NOT raw `tmux send-keys`):
You are a Mosaic fleet agent. Use the runtime-composed **Fleet Comms — authoritative exact targets**
section for inter-agent messaging. It renders your authoritative local host, exact agent/session, resolved
tmux socket, installed helper path, generation, and one executable command per known peer.
```bash
tools/tmux/agent-send.sh -s <target-session> -m "message" # or -f <file> to send a file's contents
```
Select only a peer row rendered for your exact roster identity. Never invent, substitute, or fuzzy-match
a host, session, socket, SSH destination, or helper path. If a peer is absent, stop and run the exact
self-scoped discovery command shown in that composed section; report the peer as unknown if it remains
absent. Do not use raw `tmux send-keys` for fleet messaging.
The coordinator session is `mos-claude` — send status, findings, and questions there.
**2. Issues / PRs / milestones** → `tools/git/*.sh` wrappers (before raw `tea`/`gh`/`glab`):
**Issues / PRs / milestones** → `tools/git/*.sh` wrappers (before raw `tea`/`gh`/`glab`):
```bash
tools/git/pr-create.sh ... tools/git/issue-create.sh ... tools/git/pr-merge.sh ...
@@ -0,0 +1,170 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://mosaicstack.dev/schemas/wake-watch-list.schema.json",
"title": "Mosaic Wake Watch-List",
"description": "Declarative watch-list for the wake/heartbeat detector (EPIC #892). The SCHEMA is framework-owned; the VALUES are operator-supplied (repos, board files, lane anchors, per-class SLOs). This is the W2 schema contract only — the detector (W4) and digest renderer (W3) consume it. Per CONVERGED-DESIGN §1.4: 'operator repo; schema is framework, values are operator.'",
"type": "object",
"required": ["schema_version", "watches"],
"additionalProperties": false,
"properties": {
"schema_version": {
"type": "integer",
"minimum": 1,
"description": "Watch-list schema version. The wake component's manifest.txt declares the supported range (schema_min/schema_max, Gate B); a watch-list outside that range is rejected by the component, not silently coerced."
},
"host": {
"type": "string",
"description": "Optional operator label for the host this watch-list serves. Per-host single-instance detector (§1.1). Operator-supplied; no semantic meaning to the schema."
},
"repos": {
"type": "array",
"description": "Git repositories to watch. Source SHAs are descriptors, not the cursor (§2.4).",
"items": {
"type": "object",
"required": ["id"],
"additionalProperties": false,
"properties": {
"id": {
"type": "string",
"description": "Operator-chosen stable identifier for this repo watch."
},
"remote": {
"type": "string",
"description": "Remote/clone locator (operator-supplied). No credentials inline; secrets are by-name via load_credentials."
},
"branches": {
"type": "array",
"items": { "type": "string" },
"description": "Branch refs to track. Empty => default branch."
},
"class": { "$ref": "#/$defs/class" },
"slo": { "$ref": "#/$defs/slo_ref" },
"aba_sensitive": {
"type": "boolean",
"default": false,
"description": "If true, this source needs an event-stream/webhook rather than poll-only (intra-poll ABA mitigation, §2.4 / gate G5). Poll-only remains a mitigation, not elimination."
}
}
}
},
"board_files": {
"type": "array",
"description": "Board / decision files whose edits must be caught (repo-section/anchor-scoped hashing, §1.1). Human-decision file edits, not just API-visible state.",
"items": {
"type": "object",
"required": ["id", "path"],
"additionalProperties": false,
"properties": {
"id": { "type": "string" },
"repo": {
"type": "string",
"description": "Optional reference to a repos[].id this file lives in."
},
"path": {
"type": "string",
"description": "File path (operator-supplied). Locators are hard: repo/issue#/SHA/file:anchor (§2.1)."
},
"class": { "$ref": "#/$defs/class" },
"slo": { "$ref": "#/$defs/slo_ref" }
}
}
},
"lane_anchors": {
"type": "array",
"description": "In-file anchors (headings/markers) scoping a lane's obligations, so a file edit outside the lane's anchor does not wake it.",
"items": {
"type": "object",
"required": ["id", "anchor"],
"additionalProperties": false,
"properties": {
"id": { "type": "string" },
"board_file": {
"type": "string",
"description": "Optional reference to a board_files[].id this anchor lives in."
},
"anchor": {
"type": "string",
"description": "Anchor text/marker delimiting the lane's section within the file."
},
"class": { "$ref": "#/$defs/class" },
"slo": { "$ref": "#/$defs/slo_ref" }
}
}
},
"slos": {
"type": "object",
"description": "Named per-class urgency SLO tiers. SYMBOLIC — the operator sets concrete durations; the schema only fixes the shape and the class ordering intent (§4: security/lease/CI = tight; board = tens of minutes; routine = hours). No numeric parameters are baked into the framework.",
"additionalProperties": {
"type": "object",
"additionalProperties": false,
"properties": {
"class": { "$ref": "#/$defs/class" },
"fallback_bound": {
"type": "string",
"description": "Operator-supplied duration (e.g. '5m', '30m', '4h'). Symbolic tier is set by the operator, not the framework."
},
"fallback_cadence": {
"type": "string",
"description": "OPTIONAL, additive (schema_version 1, backward-compatible — omitting it is valid). The per-class cadence bound for the framework-shipped canon FALLBACK WAKE (F7 replacement-before-retirement, EPIC #892): the low-frequency SAFETY-wake timer (mosaic-wake-fallback.timer) that fires the canon drain INDEPENDENT of the event-driven detector, so a stalled detector cannot silently starve delivery. The A10 installer reads this per-class value and writes it as the fallback timer's OnUnitActiveSec via the blank-reset drop-in (exactly one effective OnUnitActiveUSec). SYMBOLIC — an operator-supplied duration (e.g. '30m', '1h', '4h'); the framework bakes in no numeric. Config, not code. Should be no tighter than this tier's `fallback_bound` (the safety wake is a floor, never the primary mechanism)."
},
"quiet_hours_may_suppress": {
"type": "boolean",
"default": false,
"description": "If true, quiet-hours may suppress the cold fallback for this tier. MUST remain false for actionable/critical classes (§3: quiet-hours never gate an actionable/critical class)."
},
"measure_to": {
"type": "string",
"enum": ["consumed", "qualified-action-or-handoff"],
"description": "Terminal the SLO is measured to (§4/G8): CONSUMED measures reading; qualified-action-or-handoff measures doing. Actionable/critical classes measure to the action terminal."
}
}
}
},
"watches": {
"type": "array",
"description": "The declared source-coverage inventory: a lane-by-lane list of every operational source the lane depends on, so an omitted source cannot make the retirement vector pass vacuously (§4/G3 parity inventory). Each entry references a source declared above by kind+id.",
"items": {
"type": "object",
"required": ["lane", "sources"],
"additionalProperties": false,
"properties": {
"lane": {
"type": "string",
"description": "Operator lane identifier this watch serves."
},
"sources": {
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"required": ["kind", "id"],
"additionalProperties": false,
"properties": {
"kind": {
"type": "string",
"enum": ["repo", "board_file", "lane_anchor"],
"description": "Which top-level collection the id refers to."
},
"id": {
"type": "string",
"description": "Reference to repos[].id / board_files[].id / lane_anchors[].id."
}
}
}
}
}
}
}
},
"$defs": {
"class": {
"type": "string",
"enum": ["digest", "actionable", "human", "terminal-log", "reaction"],
"description": "Wake class (§2.3). Only `digest` coalesces (cumulative-state replace); actionable/human APPEND. ALL classes are durable. Absent class => the consumer treats it as `actionable` (fail-safe)."
},
"slo_ref": {
"type": "string",
"description": "Name of an entry in the top-level `slos` map to apply to this source."
}
}
}
+28 -1
View File
@@ -9,12 +9,39 @@ package, normally at:
```
The default tmux socket is `mosaic-fleet` so fleet commands do not touch the
default tmux server.
default tmux server. The roster is the desired-state authority; generated environment files are
rebuildable projections, never a second source of configuration.
## Examples
- `examples/minimal.yaml` starts one local canary slot.
- `examples/local-canary.yaml` starts a small generic dogfood fleet.
- `examples/operator-interaction.yaml` is an example Pi operator-interaction
service; replace its example agent name before provisioning.
## Operator interaction service
`services/operator-interaction.yaml` pins the Pi runtime, GPT-5.6 Sol model,
high reasoning, and the `operator-interaction` tool policy. The agent identity
is provisioning data: choose a roster name, generate its per-agent environment
file, then start the matching generic systemd instance. The service fails before
launch if the configured identity does not match the instance or any pinned
policy field drifts.
The installed `tools/fleet/print-interaction-effective-policy.sh` prints only
the resolved name, runtime, model, reasoning, and tool policy. It never reads
or prints credential variables.
## Generated agent environment boundary
`mosaic fleet install` writes a private deterministic projection at
`~/.config/mosaic/fleet/agents/<agent>.env.generated`. It may relocate only approved local machine
data to `<agent>.env.local`; generated keys, arbitrary commands, secret-like keys, duplicate keys,
unknown keys, and unsafe permissions fail before a tmux session is created. Legacy `.env` input is
regenerated, relocated, or quarantined and is not a launch authority.
See [`docs/fleet/reference/generated-env-boundary.md`](../../../../docs/fleet/reference/generated-env-boundary.md)
for allowed local keys and the USC downstream interface evidence.
Initialize a roster:
@@ -0,0 +1,19 @@
# Example instance only. Replace `Tess` with the chosen provisioned identity.
version: 1
transport: tmux
tmux:
socket_name: mosaic-fleet
holder_session: _holder
defaults:
working_directory: ~/src
runtimes:
pi:
reset_command: /new
agents:
- name: Tess
runtime: pi
class: operator-interaction
model_hint: openai/gpt-5.6-sol
reasoning_level: high
tool_policy: operator-interaction
persistent_persona: true
@@ -12,19 +12,22 @@ on demand. Engineering personas have no explicit `domain:` marker (they are the
implicit `engineering` domain); cross-domain personas carry a `domain:` key in
their intro so tooling can group them.
> This file is an index only — no code imports it. To add a persona, drop a new
> `*.md` next to the others (mirroring the existing structure) and add a row here.
> This file is an index, not an authority source. The fleet persona resolver reads
> its rows for discovery compatibility, then requires a readable `*.md` contract;
> authority is derived from canonical class metadata in code, never from this prose.
## engineering
| Persona | Purpose |
| --------------- | ------------------------------------------------------------------------------ |
| orchestrator | Always-on coordinator — runs the supervisor loop, dispatches ready work |
| team-leader | Coordinates only orchestrator-leased capacity for one bounded project |
| board | Multi-lens deliberation panel; owns the mission's direction, not its execution |
| planner | Turns ratified objectives into a phased FR plan wired into a `depends_on` DAG |
| decomposition | Splits FRs into one-PR-each cards wired with `depends_on` edges |
| code | Primary executor — one card, one branch, one PR to green CI |
| review | Correctness reviewer — judges an open PR on correctness, scope, and coverage |
| validator | Independent final evidence certificate; never approves-to-land or merges |
| security-review | Second line of review — secrets, auth, and forbidden-path safety |
| site-tester | Runtime verifier — runs the change and checks behavior vs. acceptance criteria |
| documentation | Prose maintainer — keeps human-facing docs and projections in sync |
@@ -33,6 +36,7 @@ their intro so tooling can group them.
| operator | Escalation and control surface — owns exceptions and the fleet pause switch |
| session-review | Post-task retrospective — turns finished work into improvement signals |
| enhancer | Continuous-improvement loop — upgrades the fleet's tools, skills, and harness |
| interaction | Operator request/status surface; routes orchestration and merge decisions |
## executive
@@ -0,0 +1,16 @@
# Interaction — fleet role definition
The **interaction** role (`class: interaction`) is the operator-facing request and status surface for Mosaic.
## Mandate
1. Receive operator requests and present observable fleet or runtime status.
2. Route orchestration requests to the orchestrator and merge decisions to the merge-gate.
3. Report supported actions and their outcomes without claiming another role's authority.
## Boundaries
- Request/status only; it does not orchestrate, issue leases, approve-to-land, or merge.
- It does not mutate roster configuration, role authority, or credentials.
- A configured instance name such as Tess is display data, never a class or authority source.
- `operator-interaction` remains a compatibility alias for this canonical class.
@@ -13,7 +13,14 @@ It is a **gate** role: the one and only merge path.
2. **Use the wrapped scripts as the ONLY merge path** — the merge-gate merges
**exclusively** by calling **`pr-merge.sh`** (the merge action, which carries the
authoritative forbidden-path guard) and **`pr-ci-wait.sh`** (to wait for green
CI before merging). These two scripts are the _only_ sanctioned merge path.
CI before merging). Before issuing a verdict, scan the full JSON/API child-step
record (including `clone`) with **`verify-terminal-green.py --expect-commit
<current-provider-PR-head>`** and record the equal expected/observed full-40
commits, exact step count, anomalies, and named exemptions. Missing or mismatched
commit binding is a hard refusal. The verifier's sole interim
exemption is `WP-K8S-1000-CI-POSTGRES-TEARDOWN`; it is signature-scoped, tracked
by #1000, and retires when #1000 is fixed. These scripts are the _only_
sanctioned merge path.
3. **Never call the raw API** — the merge-gate **does NOT** call `tea`, the raw
Gitea/forge HTTP API, or any other merge mechanism directly. Only `pr-merge.sh`
and `pr-ci-wait.sh`.
@@ -0,0 +1,11 @@
# Operator Interaction — fleet role definition
The **operator-interaction** role is the authorized human interaction plane for
Mosaic. It presents runtime and fleet state, mediates approved actions, and
hands coding or general orchestration work to the orchestrator.
## Boundaries
- It does not claim orchestrator-owned coding or general orchestration work.
- It exposes only the configured, observable tool policy.
- It does not receive or surface credentials in its effective policy.
@@ -0,0 +1,16 @@
# Team leader — fleet role definition
The **team-leader** (`class: team-leader`) coordinates a bounded project team using only capacity granted by an orchestrator-issued lease.
## Mandate
1. Direct the leased coder, reviewer, and validator capacity for the assigned project scope.
2. Track delivery status and return results or blockers to the orchestrator.
3. Stop using capacity when the lease or assignment ends.
## Boundaries
- Leased capacity only; this role does not issue or expand its own lease.
- It cannot change fleet roster membership, role authority, fleet configuration, or credentials.
- It cannot approve-to-land or merge.
- It does not displace the orchestrator's topology and lease authority.
@@ -0,0 +1,16 @@
# Validator — fleet role definition
The **validator** (`class: validator`) is the independent final evidence seat. It examines the accepted requirements, test evidence, review record, and candidate head and may issue a validation certificate for that exact evidence set.
## Mandate
1. Validate acceptance evidence independently from the implementation author.
2. Issue or withhold a final validation certificate for the reviewed candidate.
3. Report missing, stale, or contradictory evidence without altering it.
## Boundaries
- **Certificate only:** the validator does not approve-to-land or merge.
- It does not replace correctness or security review.
- It does not write product code, mutate the roster, issue leases, or access credentials.
- A configured instance name such as Ultron is display data, never a class or authority source.
@@ -75,6 +75,14 @@
"type": "string",
"pattern": "^[A-Za-z0-9_.-]+$"
},
"alias": {
"description": "Optional operator-defined display name for the agent.",
"type": "string"
},
"provider": {
"description": "Optional agent runtime provider identifier such as openai-codex.",
"type": "string"
},
"runtime": {
"type": "string"
},
@@ -86,11 +94,11 @@
"type": "string"
},
"ssh": {
"description": "SSH target (user@host) for a cross-host peer, so onboarding renders the `agent-send.sh -H <user@host>` form. Optional; only needed for agents on a different host than the fleet.",
"description": "Explicit SSH target (normally user@host) for a cross-host inventory peer. Exact comms rendering requires this whenever the peer's resolved host differs from the current agent's host; the host value is never substituted as an SSH destination.",
"type": "string"
},
"socket": {
"description": "tmux socket the agent's session runs on. Onboarding renders `-L <socket>` when set; absent = the default socket (no `-L`). Must match the LIVE socket, not blindly inherit the roster's tmux.socket_name.",
"description": "Optional compatibility declaration of the fleet-wide tmux socket. When present it must exactly equal tmux.socket_name; independent per-agent sockets are rejected because the local fleet runtime provisions every session on the fleet-wide socket.",
"type": "string"
},
"working_directory": {
@@ -105,6 +113,18 @@
"modelHint": {
"type": "string"
},
"reasoning_level": {
"type": "string"
},
"reasoningLevel": {
"type": "string"
},
"tool_policy": {
"type": "string"
},
"toolPolicy": {
"type": "string"
},
"persistent_persona": {
"oneOf": [{ "type": "boolean" }, { "type": "string" }]
},
@@ -130,29 +150,67 @@
"description": "Orchestrator chat connector (F4). Optional — absent means tmux (back-compat). Secrets (access/bot tokens) come from the environment, never this file.",
"type": "object",
"additionalProperties": false,
"required": ["kind"],
"properties": {
"kind": {
"enum": ["tmux", "discord", "matrix"]
},
"matrix": {
"type": "object",
"additionalProperties": false,
"required": ["homeserver_url", "user_id", "room_id"],
"properties": {
"homeserver_url": { "type": "string" },
"user_id": { "type": "string" },
"room_id": { "type": "string" }
"oneOf": [
{
"properties": { "kind": { "const": "tmux" } },
"required": ["kind"],
"not": {
"anyOf": [{ "required": ["discord"] }, { "required": ["matrix"] }]
}
},
"discord": {
"type": "object",
"additionalProperties": false,
"required": ["channel_id"],
{
"properties": {
"channel_id": { "type": "string" }
}
"kind": { "const": "discord" },
"discord": {
"type": "object",
"additionalProperties": false,
"required": ["channel_id"],
"properties": {
"channel_id": {
"type": "string",
"minLength": 1,
"pattern": "\\S"
}
}
}
},
"required": ["kind", "discord"],
"not": { "required": ["matrix"] }
},
{
"properties": {
"kind": { "const": "matrix" },
"matrix": {
"type": "object",
"additionalProperties": false,
"required": ["homeserver_url", "user_id", "room_id"],
"properties": {
"homeserver_url": {
"type": "string",
"minLength": 1,
"pattern": "\\S"
},
"user_id": {
"type": "string",
"minLength": 1,
"pattern": "\\S"
},
"room_id": {
"type": "string",
"minLength": 1,
"pattern": "\\S"
}
}
}
},
"required": ["kind", "matrix"],
"not": { "required": ["discord"] }
}
],
"properties": {
"kind": { "enum": ["tmux", "discord", "matrix"] },
"matrix": { "type": "object" },
"discord": { "type": "object" }
}
}
}
@@ -0,0 +1,5 @@
# Generic service policy. Provisioning supplies the agent name as data.
runtime: pi
model: openai/gpt-5.6-sol
reasoning: high
tool_policy: operator-interaction
@@ -0,0 +1,90 @@
# Mosaic framework path-ownership manifest — SSOT for the updater.
#
# This single file is the source of truth consumed by BOTH the bash installer
# (packages/mosaic/framework/install.sh) and the TypeScript config adapter
# (packages/mosaic/src/config/file-adapter.ts). A parity test asserts both
# paths resolve the same ownership from this file, so the two can never drift
# (the failure mode that #631 patched by hand in two places).
#
# Format: one glob per line, relative to the mosaic home (~/.config/mosaic).
# - Lines starting with '#' and blank lines are ignored.
# - '[framework]' / '[operator]' switch the active section.
# - '**' matches any depth; '*' matches within a single path segment.
#
# Ownership resolution for a path P (deny-wins / fail-safe):
# 1. P matches an [operator] glob -> operator-owned.
# 2. else P matches a [framework] glob -> framework-owned.
# 3. else (matches neither) -> OPERATOR-OWNED BY DEFAULT.
#
# Rule 3 is the root-cause fix for #791: a path the manifest authors never
# anticipated is protected because UNKNOWN defaults to operator. The updater
# may only ever create/overwrite framework-owned paths, and may only prune a
# framework-owned path that lives inside a shipped framework subtree and is
# absent from the current framework source (a genuinely retired file).
# Operator-owned and unknown paths are structurally unreachable by pruning.
[framework]
# Top-level framework contract files (also reconciled from defaults/ on upgrade).
CONSTITUTION.md
AGENTS.md
STANDARDS.md
# Shipped framework subtrees — pruning is scoped to these roots.
adapters/**
constitution/**
CONTRIBUTING.md
defaults/**
examples/**
guides/**
# Shipped framework subtree — canonical skills are upgrade-reconciled.
skills/**
install.sh
install.ps1
LICENSE
profiles/**
runtime/**
systemd/**
templates/**
tools/**
# Fleet: only the framework-seeded fleet subtrees are framework-owned.
fleet/README.md
fleet/examples/**
fleet/profiles/**
fleet/roles/**
fleet/roster.schema.json
fleet/services/**
# The manifest itself is framework-owned.
framework-manifest.txt
[operator]
# Identity / user-seeded contract files — generated by the wizard or seeded
# once from defaults/, then owned by the operator. Never overwritten on upgrade.
SOUL.md
USER.md
TOOLS.md
# Local overlays (tighten-only) authored by the operator.
*.local.md
# Operator-owned trees the updater must never write over or prune.
agents/**
policy/**
memory/**
sources/**
credentials/**
# Operator-authored/customized skills live separately from canonical skills/ and
# must remain structurally unprunable even as skills/** is framework-owned.
skills-local/**
# Secret-bearing operator file INSIDE the framework-owned tools/ subtree.
# Listed explicitly so the deny-wins rule carves it out of tools/**.
tools/_lib/credentials.json
# Operator-owned fleet state (roster SSOT, per-agent env, heartbeats, backlog,
# persona overrides). Losing these silently downgrades a running fleet (#791).
fleet/roster.yaml
fleet/roster.json
fleet/agents/**
# Runtime state, incl. the #797 Runtime Session Ledger at fleet/run/sessions/
# (events.ndjson journal + ledger.json projection). This carve-out is the
# mechanism that makes the ledger upgrade-safe: an upgrade that wiped it would
# defeat its reason to exist. The HARD GATE (test-upgrade-manifest-guard.sh)
# proves a populated ledger survives byte-identical + mtime-unchanged.
fleet/run/**
fleet/backlog/**
fleet/roles.local/**
@@ -15,6 +15,22 @@ This guide covers how to bootstrap a project so AI agents (Claude, Codex, etc.)
7. Branching/merging is consistent: `branch -> main` via PR with squash-only merges
8. Steered-autonomy execution is enabled so agents can run end-to-end with escalation-only human intervention
## Agent Host Prerequisites
Agent hosts must provide the Python runtime shape that runtime agents and
Mosaic automation assume is present.
For Debian/Ubuntu hosts:
```bash
sudo apt-get update
# #561: bare python invocations from agents must resolve.
sudo apt-get install -y python3 python-is-python3
```
For non-Debian hosts, install the equivalent Python 3 runtime and ensure
`/usr/bin/python` resolves to `python3` (for example, via a managed symlink).
## Quick Start
```bash
@@ -868,6 +868,38 @@ steps:
7. **Test on a short-lived non-main branch first** — open a PR and verify quality gates before merging to `main`
8. **Verify images appear** in Gitea Packages tab after successful pipeline
## Terminal-Green Full-Step Contract
A successful pipeline summary is not sufficient: verification MUST consume the full JSON/API child-step record, including `clone`.
```bash
PR_HEAD=<full-40-hex-provider-head>
~/.config/mosaic/tools/woodpecker/pipeline-status.sh \
-r mosaicstack/stack -n <pipeline-number> -f json \
| ~/.config/mosaic/tools/woodpecker/verify-terminal-green.py \
--expect-commit "$PR_HEAD" -
```
`PR_HEAD` MUST come from the current provider PR metadata and MUST be the full 40-hex head, not a local branch guess. The verifier fails if the argument is missing, malformed, absent from the pipeline record, or differs from that record.
The verifier reports the expected and observed commits, total step count, state counts, anomalies, and any applied exemption. Exit `0` means the record satisfies the contract; exit `1` means the commit binding or at least one pipeline, workflow, or child-step state blocks terminal-green; exit `2` means the invocation or JSON input could not be verified.
### Named interim exemption: `WP-K8S-1000-CI-POSTGRES-TEARDOWN`
Only this exact conjunction is exempted:
- pipeline and workflow state are `success`;
- exactly one non-success child exists;
- its name is `ci-postgres` and type is `service`;
- its state is `failure`, exit code is the JSON integer `0` (not boolean, float, string, or null); and
- its error exactly matches `pods "wp-svc-<ULID>-ci-postgres" not found`.
Every near miss remains blocking, including non-zero service exits, startup failures, post-readiness crashes, connection errors, image-pull errors, skipped steps, another failed child, malformed pod names, duplicate matches, or a non-success pipeline/workflow.
**Boundary in both directions:** this exemption recognizes the observed Woodpecker Kubernetes reconciliation miss after an otherwise-successful run. It does not prove that every future PostgreSQL or Kubernetes failure is distinguishable. It does prove, through provider controls, that a deterministic startup failure (`exit_code=1`) and an armed post-readiness postmaster crash (`exit_code=137`, dependent probe `Connection refused`) do not match and remain red.
**Tracking and retirement:** [mosaicstack/stack#1000](https://git.mosaicstack.dev/mosaicstack/stack/issues/1000) owns the provider-seam fix. This exemption MUST be removed when #1000 is fixed. It is not authority to retry or re-trigger a pipeline, and no per-PR re-roll is part of the contract.
## Post-Merge CI Monitoring (Hard Rule)
For source-code delivery, completion is not allowed at "PR opened" stage.
@@ -893,14 +925,16 @@ Woodpecker note:
Before pushing a branch or merging a PR, guard against overlapping project pipelines:
```bash
~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose push -B main
~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose merge -B main
~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose push
~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose merge -B <PR_HEAD_BRANCH> -R <PR_HEAD_OWNER/REPO> --sha <PR_HEAD_FULL_SHA>
```
Behavior:
- If pipeline state is running/queued/pending, wait until queue clears.
- If timeout or API/auth failure occurs, treat as `blocked`, report exact failed wrapper command, and stop.
- If pipeline state is running/queued/pending, wait until queue clears; timeout is `ASSERTED_NOT_READY` and exits nonzero.
- Failure, missing status, malformed status, or any other provider-asserted non-green state is `ASSERTED_NOT_READY` and exits nonzero.
- Credential, transport, or provider unavailability is `CANNOT_ASSERT`: the guard emits a loud diagnostic and durable JSONL audit record. For push it exits 0 so recovery work is not bricked. For merge it returns distinct retryable exit 75 and holds until provider recovery; rerunning then self-clears without manual reset. This result is never evidence that CI was clear. If the audit cannot be written, the guard exits nonzero.
- `pr-merge.sh` resolves and guards the exact PR head repository and full SHA automatically, including fork PRs.
## Gitea as Unified Platform
@@ -13,7 +13,7 @@ Merge strategy enforcement (HARD RULE):
- PR target for delivery is `main`.
- Direct pushes to `main` are prohibited.
- Merge to `main` MUST be squash-only.
- Use `~/.config/mosaic/tools/git/pr-merge.sh -n {PR_NUMBER} -m squash` (or PowerShell equivalent).
- Use `~/.config/mosaic/tools/git/pr-merge.sh -n {PR_NUMBER} -m squash --expect-head {approved_full_sha}` (or PowerShell equivalent).
## Review Checklist
@@ -79,7 +79,7 @@ For implementation work, you MUST run this cycle in order:
8. `pre-push queue guard` - before pushing, wait for running/queued project pipelines to clear: `~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose push`.
9. `push` - push immediately after queue guard passes.
10. `PR integration` - if external git provider is available, create/update PR to `main` and merge with required strategy via Mosaic wrappers.
11. `pre-merge queue guard` - before merging PR, wait for running/queued project pipelines to clear: `~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose merge`.
11. `pre-merge queue guard` - before merging PR, wait for running/queued project pipelines on the exact PR head to clear: `~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose merge -B <PR_HEAD_BRANCH> -R <PR_HEAD_OWNER/REPO> --sha <PR_HEAD_FULL_SHA>`.
12. `CI/pipeline verification` - wait for terminal CI status and require green before completion (`~/.config/mosaic/tools/git/pr-ci-wait.sh` for PR-based workflow).
13. `issue closure` - close linked external issue (or close internal `docs/TASKS.md` task ref when provider is unavailable).
14. `greenfield situational test` - validate required user flows in a clean environment/startup path (post-merge for trunk workflow changes).
@@ -93,8 +93,8 @@ For implementation work, you MUST run this cycle in order:
> 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`
1. `~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose merge -B <PR_HEAD_BRANCH> -R <PR_HEAD_OWNER/REPO> --sha <PR_HEAD_FULL_SHA>`
2. `~/.config/mosaic/tools/git/pr-merge.sh -n <PR_NUMBER> -m squash --expect-head <APPROVED_FULL_SHA>`
3. `~/.config/mosaic/tools/git/pr-ci-wait.sh -n <PR_NUMBER>`
4. `~/.config/mosaic/tools/git/issue-close.sh -i <ISSUE_NUMBER>` (or close internal `docs/TASKS.md` ref when no provider exists)
5. If any step fails: set status `blocked`, report the exact failed wrapper command, and stop.
@@ -3,7 +3,7 @@
When spawning workers, include skill loading in the kickstart:
```bash
claude -p "Read ~/.config/mosaic/skills/nestjs-best-practices/SKILL.md then implement..."codex exec "Read ~/.config/mosaic/skills/nestjs-best-practices/SKILL.md then implement..."
mosaic claude -p "Read ~/.config/mosaic/skills/nestjs-best-practices/SKILL.md then implement..."codex exec "Read ~/.config/mosaic/skills/nestjs-best-practices/SKILL.md then implement..."
```
#### **MANDATORY**
@@ -425,11 +425,11 @@ git push
and checklist completed (`~/.config/mosaic/templates/docs/DOCUMENTATION-CHECKLIST.md`) when applicable.
13. **PR + CI + Issue Closure Gate** (HARD RULE for source-code tasks):
- Before merging, run queue guard:
`~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose merge -B main`
`~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose merge -B <PR_HEAD_BRANCH> -R <PR_HEAD_OWNER/REPO> --sha <PR_HEAD_FULL_SHA>`
- Ensure PR exists for the task branch (create/update via wrappers if needed):
`~/.config/mosaic/tools/git/pr-create.sh ... -B main`
- Merge via wrapper:
`~/.config/mosaic/tools/git/pr-merge.sh -n {PR_NUMBER} -m squash`
`~/.config/mosaic/tools/git/pr-merge.sh -n {PR_NUMBER} -m squash --expect-head {approved_full_sha}`
- Wait for terminal CI status:
`~/.config/mosaic/tools/git/pr-ci-wait.sh -n {PR_NUMBER}`
- Close linked issue after merge + green CI:
@@ -630,7 +630,7 @@ Construct this from the task row and pass to worker via Task tool:
**MANDATORY:** This ALWAYS includes linting. If the project has a linter configured
(ESLint, Biome, ruff, etc.), you MUST run it and fix ALL violations in files you touched.
Do NOT leave lint warnings or errors for someone else to clean up. 6. Run REQUIRED situational tests based on changed surfaces (see `~/.config/mosaic/guides/E2E-DELIVERY.md` and `~/.config/mosaic/guides/QA-TESTING.md`). 7. If task is bug fix/security/auth/critical business logic, apply REQUIRED TDD discipline per `~/.config/mosaic/guides/QA-TESTING.md`. 8. If gates or required situational tests fail: Fix and retry. Do NOT report success with failures. 9. Commit: `git commit -m "fix({finding_id}): brief description"` 10. Before push, run queue guard: `~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose push -B main` 11. Push: `git push origin {branch}` 12. Report result as JSON (see format below)
Do NOT leave lint warnings or errors for someone else to clean up. 6. Run REQUIRED situational tests based on changed surfaces (see `~/.config/mosaic/guides/E2E-DELIVERY.md` and `~/.config/mosaic/guides/QA-TESTING.md`). 7. If task is bug fix/security/auth/critical business logic, apply REQUIRED TDD discipline per `~/.config/mosaic/guides/QA-TESTING.md`. 8. If gates or required situational tests fail: Fix and retry. Do NOT report success with failures. 9. Commit: `git commit -m "fix({finding_id}): brief description"` 10. Before push, run queue guard: `~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose push -B {branch}` 11. Push: `git push origin {branch}` 12. Report result as JSON (see format below)
## Git Scripts
@@ -638,8 +638,9 @@ For issue/PR/milestone operations, use scripts (NOT raw tea/gh):
- `~/.config/mosaic/tools/git/issue-view.sh -i {N}`
- `~/.config/mosaic/tools/git/pr-create.sh -t "Title" -b "Desc" -B main`
- `~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose push|merge -B main`
- `~/.config/mosaic/tools/git/pr-merge.sh -n {PR_NUMBER} -m squash`
- Push: `~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose push -B {task_branch}`
- Merge: `~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose merge -B {pr_head_branch} -R {pr_head_owner/repo} --sha {pr_head_full_sha}`
- `~/.config/mosaic/tools/git/pr-merge.sh -n {PR_NUMBER} -m squash --expect-head {approved_full_sha}`
- `~/.config/mosaic/tools/git/pr-ci-wait.sh -n {PR_NUMBER}`
- `~/.config/mosaic/tools/git/issue-close.sh -i {N}`
@@ -23,10 +23,12 @@ Mosaic wrappers at `~/.config/mosaic/tools/git/*.sh` handle platform detection a
# Milestones
~/.config/mosaic/tools/git/milestone-create.sh
# CI queue guard (required before push/merge)
# CI queue guard (required before push/merge; defaults to the checked-out branch)
~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose push|merge
```
The guard exits nonzero for any provider-asserted non-green, missing, or malformed CI state. If credentials or the provider are unavailable, it emits `CANNOT_ASSERT` and writes a JSONL audit record. Push degrades to exit 0 so recovery work is not bricked; merge holds with retryable exit 75 until the provider recovers, then self-clears without manual reset. Neither outcome is evidence that CI was clear. `pr-merge.sh` automatically inspects the exact PR head repository and full commit SHA rather than its `main` base; this also handles fork PRs without branch-name ambiguity. Pass `--expect-head <approved-full-sha>` to bind a commit-specific review or merge-gate verdict; Gitea uses atomic `head_commit_id` and GitHub uses `--match-head-commit`.
### Code Review (Codex)
```bash
@@ -0,0 +1,31 @@
# Wake Doctrine
This is the canonical fleet wake/heartbeat doctrine, extracted verbatim from the ratified
converged wake/heartbeat design (`docs/scratchpads/heartbeat-planning/CONVERGED-DESIGN.md`). It
governs when agents wake and how a wake is delivered, consumed, and retired.
**Wake only on a real, un-consumed, lane-relevant obligation.** Fixed-interval heartbeats are
forbidden as the primary wake mechanism; they survive only as a **per-class fallback cadence**
bounded by urgency SLO, never as the steady state.
**A digest is cumulative state since the last CONSUMED ack**, not an event delta. It is
self-orienting (who / lane / board-head) and decides the no-op case with **zero tool calls**.
Actionable facts are **claims-to-verify** carrying a **hard locator** (repo/issue#/SHA/file);
self-sufficiency never exempts a consequential action from its live gate.
**Consumption is a consumer act, not a delivery act.** Split RECEIVED (delivery; `wake_id`-deduped)
from CONSUMED (durable capture of a contiguous prefix). Never ack-then-crash-before-capture. Acks
are local-write-only and cumulative; a turn never blocks on the network to ack.
**Durability is unconditional; coalescing is optional.** Every delivered class is durably stored
and acked; only machine `digest` wakes coalesce. A parked or absent pane must never lose a human
or peer message.
**Park is two-phase:** flush-and-checkpoint (recording the CONSUMED cursor) _before_ `/clear`.
**Liveness is independent of work-triggering:** an off-host dead-man beacon, alarming on absence —
never a same-host sibling, never a pane scrape.
**Retire the old net LAST:** run new alongside old, compare ledgers, and cut over only when the
per-host safety vector (no-op-rate ↓ AND canary-FN=0 AND source-parity-inventory-complete AND
reconcile=0 AND p95 event→CONSUMED≤SLO AND p95 event→qualified-action≤SLO) passes.
+472 -84
View File
@@ -1,5 +1,10 @@
#!/usr/bin/env bash
set -euo pipefail
# -E (errtrace): the ERR trap must propagate INTO functions and command
# substitutions. Without it the `trap restore_snapshot ERR` set below is dead
# code for any failure inside sync_framework_keep() (its whole body runs in a
# function) — a mid-sync failure would abort with a half-written target and NO
# rollback (#791 B1). Keep -E first so every later function inherits the trap.
set -Eeuo pipefail
# ─── Mosaic Framework Installer ──────────────────────────────────────────────
#
@@ -13,38 +18,55 @@ set -euo pipefail
# MOSAIC_INSTALL_MODE — prompt|keep|overwrite (default: prompt)
# MOSAIC_ALLOW_MISSING_SEQUENTIAL_THINKING — 1 to bypass MCP check
# MOSAIC_SKIP_SKILLS_SYNC — 1 to skip skill sync
#
# Flags (CLI args, NOT environment variables — see #869 Point-1 C2):
# --allow-inactive-enforcement Explicit, per-invocation opt-out that lets the
# lease-enforcement hooks (mutator-gate.py,
# receipt-observer-client.py) be wired into
# ~/.claude/settings.json even when this host
# cannot confirm it can ACTIVATE them. Loud on
# use (see mosaic-link-runtime-assets). Default
# (flag absent) is fail-loud: the enforcement
# hooks are NOT wired and the framework's
# runtime-asset-link step reports a failure.
# ──────────────────────────────────────────────────────────────────────────────
SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TARGET_DIR="${MOSAIC_HOME:-$HOME/.config/mosaic}"
INSTALL_MODE="${MOSAIC_INSTALL_MODE:-prompt}"
# Files/dirs protected from rsync --delete during sync. NOTE: framework-owned
# entries (CONSTITUTION/AGENTS/STANDARDS) ARE re-applied afterward by
# reconcile_framework_files (overwrite + backup-once); the rest stay user-owned.
# User-created content in these paths survives rsync --delete.
#
# fleet/* — the framework SEEDS fleet/examples, fleet/roles, fleet/profiles, and
# fleet/roster.schema.json (synced normally — every fleet/roles/*.md role contract
# and fleet/profiles/*.yaml system-type profile lands automatically via this sync,
# so no per-file entry is needed; the preserved "fleet/*.yaml" glob is anchored to
# the top level only and does NOT shadow fleet/profiles/*.yaml). The user's
# own fleet files MUST
# survive `mosaic update` (which runs this sync automatically): the active
# roster (`fleet/roster.yaml` + any other `fleet/*.yaml`), per-agent env
# (`fleet/agents/`), heartbeat run dir (`fleet/run/`), and the Mosaic-native
# backlog-of-record store (`fleet/backlog/` — embedded PGlite data dir; see
# packages/mosaic/src/commands/fleet-backlog.ts). Without these, an update
# wipes the operator's fleet AND their backlog. Glob entries are honored by
# both the rsync path (`--exclude`) and the glob-aware cp fallback below.
#
# fleet/roles.local — the persona OVERRIDE layer (H4). Baseline personas in
# fleet/roles/ are reseeded normally on every update (delivering new baseline
# personas), so any local edit there would be clobbered. User customizations
# and user-ADDED personas instead live in fleet/roles.local/ and MUST survive
# `mosaic update` — they win over the baseline on merge (AC-NS-7; see
# packages/mosaic/src/commands/fleet-personas.ts).
PRESERVE_PATHS=("CONSTITUTION.md" "AGENTS.md" "SOUL.md" "USER.md" "TOOLS.md" "STANDARDS.md" "memory" "sources" "credentials" "fleet/*.yaml" "fleet/agents" "fleet/run" "fleet/backlog" "fleet/roles.local")
# Deliberately parsed from "$@" (a real, explicit, per-invocation argument) —
# never an environment variable — so this opt-out can never sit silently
# inherited in a shell profile. See #869 Point-1 C2.
ALLOW_INACTIVE_ENFORCEMENT=0
# Component-scoped install (#892 W7): `install.sh --component <name>` runs an
# additive, self-contained component installer and EXITS — it never enters the
# full-framework sync below and never modifies framework-manifest ownership
# behavior (#869: the diff is ADDITIVE). Parsed as a two-token flag here.
COMPONENT=""
_prev_arg=""
for _arg in "$@"; do
case "$_arg" in
--allow-inactive-enforcement) ALLOW_INACTIVE_ENFORCEMENT=1 ;;
--component=*) COMPONENT="${_arg#--component=}" ;;
esac
[[ "$_prev_arg" == "--component" ]] && COMPONENT="$_arg"
_prev_arg="$_arg"
done
# Shared framework path-ownership manifest reader (#791). Parity with
# packages/mosaic/src/framework/manifest.ts — both consume framework-manifest.txt.
# Sourcing does not run its CLI dispatch (guarded by BASH_SOURCE==$0).
# shellcheck source=tools/_lib/manifest.sh
source "$SOURCE_DIR/tools/_lib/manifest.sh"
# Which paths a keep-mode upgrade may touch is no longer a hand-maintained
# denylist. It is derived from the shared framework-manifest.txt (#791): the
# updater only ever creates/overwrites framework-owned paths and only prunes a
# retired framework file inside a shipped framework subtree. Everything else —
# every operator file, and every path the manifest never anticipated — is
# operator-owned by default (fail-safe) and is never written or deleted. See
# sync_framework_keep() below and packages/mosaic/src/framework/manifest.ts.
# Framework-owned contract files: re-copied from defaults/ on every upgrade (the
# user must not edit them; a divergent copy is backed up once before overwrite).
@@ -75,17 +97,267 @@ step() { echo -e "\n${BOLD}$1${RESET}"; }
SNAPSHOT_DIR=""
make_snapshot() {
is_existing_install || return 0
# mktemp -d creates the dir 0700 — the snapshot (which mirrors operator config,
# possibly including secrets) is never world-readable.
SNAPSHOT_DIR="$(mktemp -d "${TMPDIR:-/tmp}/mosaic-snapshot-XXXXXX")"
cp -a "$TARGET_DIR/." "$SNAPSHOT_DIR/" 2>/dev/null || true
# The snapshot MUST be complete: restore rebuilds the target from it, so a
# partial capture (unreadable file, disk-full, I/O error) would silently
# discard whatever it missed. If cp -a cannot copy the whole tree, abort NOW —
# before the restore trap is armed and before anything is mutated. Fail closed
# rather than proceed with a snapshot we cannot trust (#791 blocker-2).
if ! cp -a "$TARGET_DIR/." "$SNAPSHOT_DIR/"; then
fail "Could not capture a complete pre-upgrade snapshot of $TARGET_DIR — aborting before any changes were made (fail-closed)."
rm -rf "$SNAPSHOT_DIR"; SNAPSHOT_DIR=""
exit 1
fi
}
restore_snapshot() {
# Disarm the trap first: restore runs under `set -e`, and a non-zero step
# inside it must not re-enter this handler (errtrace makes ERR fire in
# functions now). One restore attempt, then let the script exit non-zero.
trap - ERR INT TERM
[[ -n "$SNAPSHOT_DIR" && -d "$SNAPSHOT_DIR" ]] || return 0
fail "Install interrupted/failed — restoring previous state from snapshot"
rm -rf "$TARGET_DIR"; mkdir -p "$TARGET_DIR"
cp -a "$SNAPSHOT_DIR/." "$TARGET_DIR/" 2>/dev/null || true
# Reset the target before rebuilding from the snapshot — but CHECK it. Under
# `set -e` (trap already disarmed) a bare `rm -rf; mkdir -p` that fails would
# exit the whole script immediately, after `rm` may have deleted part of the
# target, WITHOUT ever printing the recovery pointer below — the operator would
# be left with a half-removed target and no idea the snapshot survives in /tmp.
# Test the reset explicitly (like the cp -a below), and on failure keep the
# snapshot and tell the operator where it is (#791 blocker-D2).
if ! rm -rf "$TARGET_DIR" || ! mkdir -p "$TARGET_DIR"; then
fail "Snapshot restore could not reset $TARGET_DIR. Your previous configuration is preserved at: $SNAPSHOT_DIR — copy it back into $TARGET_DIR manually."
return 1
fi
# Surface an incomplete restore instead of swallowing it: the snapshot is the
# last good copy, so if cp cannot fully rebuild the target we must NOT delete
# the snapshot — point the operator at it for manual recovery (#791 blocker-2).
if ! cp -a "$SNAPSHOT_DIR/." "$TARGET_DIR/"; then
fail "Snapshot restore did not complete cleanly. Your previous configuration is preserved at: $SNAPSHOT_DIR — copy it back into $TARGET_DIR manually."
return 1
fi
}
cleanup_snapshot() { [[ -n "$SNAPSHOT_DIR" && -d "$SNAPSHOT_DIR" ]] && rm -rf "$SNAPSHOT_DIR"; SNAPSHOT_DIR=""; }
# ─── durable operator-config snapshot (#791 PR2) ─────────────────────────────
# A SECOND, independent safety layer, distinct from SNAPSHOT_DIR above:
# • SNAPSHOT_DIR is ephemeral (/tmp, deleted on success) and mirrors the WHOLE
# target for CRASH rollback if the sync aborts mid-write.
# • DURABLE_SNAPSHOT_DIR is RETAINED, holds only the operator-owned surface, and
# lives OUTSIDE the framework tree and any repo. It exists for the failure the
# crash-rollback cannot see: a sync that finishes "successfully" yet a
# manifest/logic bug let it modify an operator file. verify_operator_surface()
# (post-sync) heals from it; `mosaic restore` recovers from it days later.
# Path convention is mirrored in packages/mosaic/src/commands/restore.ts — keep
# the two in sync (there is no shared code across the bash/TS boundary).
DURABLE_SNAPSHOT_DIR=""
backup_root() { printf '%s/mosaic/backups' "${XDG_STATE_HOME:-$HOME/.local/state}"; }
# Relative paths that a migration INTENTIONALLY removes from the target (e.g. the
# legacy bin/ tree). Such a path is operator-classified by the manifest (unknown⇒
# operator), so the durable snapshot captures it — but its post-migration absence
# is correct, NOT a manifest bug. run_migrations() records each removal here so
# verify_operator_surface() does not "heal" it back and silently undo the
# migration (which would then be skipped forever once the version is stamped).
MIGRATION_REMOVED_PATHS=()
# True (0) if $1 (a path relative to TARGET_DIR) equals or lives under a path a
# migration deliberately removed this run.
is_migration_removed() {
local rel="$1" removed
for removed in ${MIGRATION_REMOVED_PATHS[@]+"${MIGRATION_REMOVED_PATHS[@]}"}; do
[[ -n "$removed" ]] || continue
[[ "$rel" == "$removed" || "$rel" == "$removed"/* ]] && return 0
done
return 1
}
# True (0) if any parent directory of $1 (relative to TARGET_DIR) is a symlink.
# Restoring THROUGH a symlinked ancestor would let cp write snapshot contents —
# possibly secrets — outside the target (CWE-59), so the verify net refuses it.
has_symlinked_parent() {
local rel="$1" dir p seg
dir="$(dirname "$rel")"
[[ "$dir" == "." ]] && return 1
p="$TARGET_DIR"
local IFS='/'
for seg in $dir; do
[[ -n "$seg" ]] || continue
p="$p/$seg"
[[ -L "$p" ]] && return 0
done
return 1
}
# Emit (NUL-delimited, into file $1) the operator-owned relative paths that exist
# under TARGET_DIR, classified via the shared manifest (deny-wins; unknown⇒
# operator). Returns non-zero if the filesystem walk itself failed — we must
# NEVER snapshot from a truncated scan (a `< <(find …)` process substitution
# would hide that error; capture-then-check does not — cf. #791 blocker-D1).
enumerate_operator_files() {
local out="$1" scan abs rel
scan="$(mktemp)"
if ! find "$TARGET_DIR" -type f -print0 > "$scan"; then
rm -f "$scan"
return 1 # OP-SCAN-GUARD
fi
: > "$out"
while IFS= read -r -d '' abs; do
rel="${abs#"$TARGET_DIR"/}"
# Not operator config: version marker and any VCS metadata.
case "$rel" in .framework-version|.git|.git/*) continue ;; esac
manifest_is_framework "$rel" || printf '%s\0' "$rel" >> "$out"
done < "$scan"
rm -f "$scan"
}
# Retain only the newest MOSAIC_BACKUP_RETENTION (default 5) snapshots. The
# pre-update-<UTC-ts> names sort lexicographically = chronologically, so a
# reverse sort is newest-first. Pruning failures are non-fatal (they only leave
# extra old backups); the enclosing find's status is still honored, not swallowed.
prune_durable_snapshots() {
local root keep list d i=0
root="$(backup_root)"
keep="${MOSAIC_BACKUP_RETENTION:-5}"
[[ "$keep" =~ ^[0-9]+$ ]] && (( keep >= 1 )) || keep=5
list="$(mktemp)"
if ! find "$root" -maxdepth 1 -type d -name 'pre-update-*' > "$list"; then
rm -f "$list"; return 0
fi
# Newest-first ordering needs `sort` (`-o` writes back in place — no `mv`
# dependency); if it is somehow unavailable, leave the backups untouched rather
# than risk pruning in an undefined order.
if ! LC_ALL=C sort -r -o "$list" "$list" 2>/dev/null; then
rm -f "$list"; return 0
fi
while IFS= read -r d; do
[[ -n "$d" ]] || continue
i=$((i + 1))
(( i > keep )) && rm -rf "$d"
done < "$list"
rm -f "$list"
}
# Take the durable pre-update snapshot BEFORE any mutation. Fail-OPEN: the durable
# snapshot is a recovery bonus on top of the manifest (which already keeps the
# sync out of operator paths) and the crash-rollback — so an un-writable backup
# location warns and continues rather than blocking the upgrade. Everything it
# creates is private (umask 077 + explicit 0700 dirs / 0600 files): the snapshot
# mirrors operator config, which may hold secrets, and must never be world-readable.
make_durable_snapshot() {
is_existing_install || return 0
local root ts dir list rel src dst count=0 old_umask
root="$(backup_root)"
# Fail-open if we cannot even stamp a timestamp: the durable snapshot is a
# recovery bonus and must never be the thing that aborts an upgrade.
ts="$(date -u +%Y%m%dT%H%M%SZ 2>/dev/null || true)"
if [[ -z "$ts" ]]; then
warn "Durable snapshot skipped: no UTC timestamp available (upgrade continues)."
return 0
fi
# umask 077 makes every dir/file the snapshot creates private from birth (it
# mirrors operator config, which may hold secrets). It is PROCESS-global, so we
# save and restore it around exactly this block — otherwise every later sync
# copy and new framework dir would inherit 0600/0700 instead of 0644/0755.
old_umask="$(umask)"
umask 077
if ! mkdir -p "$root"; then
umask "$old_umask"
warn "Durable snapshot skipped: cannot create backup dir $root (upgrade continues; operator files remain manifest-protected)."
return 0
fi
chmod 700 "$root" 2>/dev/null || true
dir="$root/pre-update-$ts"
if [[ -e "$dir" ]]; then # same-second re-run: disambiguate
local n=1; while [[ -e "$dir-$n" ]]; do n=$((n + 1)); done; dir="$dir-$n"
fi
if ! mkdir -p "$dir"; then
umask "$old_umask"
warn "Durable snapshot skipped: cannot create $dir (upgrade continues)."
return 0
fi
chmod 700 "$dir"
list="$(mktemp)"
if ! enumerate_operator_files "$list"; then
umask "$old_umask"
warn "Durable snapshot skipped: could not enumerate operator files (upgrade continues)."
rm -f "$list"; rmdir "$dir" 2>/dev/null || true
return 0
fi
while IFS= read -r -d '' rel; do
src="$TARGET_DIR/$rel"; dst="$dir/$rel"
[[ -f "$src" ]] || continue
mkdir -p "$(dirname "$dst")"
if ! cp "$src" "$dst"; then
warn "Durable snapshot: could not copy operator file '$rel' (skipped)."
continue
fi
chmod 600 "$dst" 2>/dev/null || true
count=$((count + 1))
done < "$list"
rm -f "$list"
# Tighten every dir the copy created (mkdir -p honors umask, but be explicit).
find "$dir" -type d -exec chmod 700 {} + 2>/dev/null || true
umask "$old_umask" # UMASK-RESTORE-NORMAL — restore before the upgrade proper resumes (see above)
DURABLE_SNAPSHOT_DIR="$dir"
ok "Durable pre-update snapshot: $count operator file(s) saved to $dir (recover with: mosaic restore --list)"
prune_durable_snapshots
}
# Post-sync safety net: a keep-mode upgrade must NEVER modify an operator file.
# Compare every file in the durable snapshot to its current target counterpart;
# any that changed (or vanished) was touched by a framework bug — restore it from
# the snapshot and warn loudly. This does NOT abort: the framework itself synced
# correctly; we only heal the operator collateral. Runs after the restore trap is
# disarmed so its corrective copies can't spuriously trip a full rollback, and
# every step is guarded so `set -e` cannot exit silently mid-heal (cf. blocker-D2).
verify_operator_surface() {
[[ -n "$DURABLE_SNAPSHOT_DIR" && -d "$DURABLE_SNAPSHOT_DIR" ]] || return 0
local scan snap rel cur healed=0
scan="$(mktemp)"
if ! find "$DURABLE_SNAPSHOT_DIR" -type f -print0 > "$scan"; then
rm -f "$scan"
warn "Post-upgrade verify skipped: could not enumerate the pre-update snapshot at $DURABLE_SNAPSHOT_DIR."
return 0
fi
while IFS= read -r -d '' snap; do
rel="${snap#"$DURABLE_SNAPSHOT_DIR"/}"
cur="$TARGET_DIR/$rel"
# A migration may legitimately delete an operator-classified path (e.g. legacy
# bin/). Its absence is intended — do not heal it back, or the migration is
# silently undone and never re-runs once the version is stamped (#791 PR2).
is_migration_removed "$rel" && continue # MIGRATION-SKIP-GUARD
if [[ ! -e "$cur" ]] || ! cmp -s "$snap" "$cur"; then
# Never restore THROUGH a symlink: an operator path swapped for a link would
# otherwise let cp write snapshot contents (possibly secrets) outside the
# target (CWE-59). Refuse a symlinked parent; drop a symlinked leaf and write
# a real file in its place.
if has_symlinked_parent "$rel"; then
warn "Operator path '$rel' has a symlinked parent under $TARGET_DIR; refusing to restore through it (possible tampering) — recover it manually from $DURABLE_SNAPSHOT_DIR."
continue
fi
[[ -L "$cur" ]] && rm -f "$cur" # SYMLINK-LEAF-GUARD
# Guard mkdir too: under set -e (trap already disarmed) a bare failure would
# exit the whole installer before the recovery pointer below is emitted.
if ! mkdir -p "$(dirname "$cur")"; then
warn "Operator file '$rel' was modified by the upgrade but could NOT be auto-restored (parent dir unavailable) — recover it manually from $DURABLE_SNAPSHOT_DIR."
continue
fi
if cp "$snap" "$cur"; then
chmod 600 "$cur" 2>/dev/null || true
warn "Operator file was modified by the upgrade and has been restored from the pre-update snapshot: $rel"
healed=$((healed + 1))
else
warn "Operator file '$rel' was modified by the upgrade but could NOT be auto-restored — recover it manually from $DURABLE_SNAPSHOT_DIR."
fi
fi
done < "$scan"
rm -f "$scan"
if (( healed > 0 )); then
warn "$healed operator file(s) were unexpectedly changed by this upgrade and were restored from the pre-update snapshot. A keep-mode upgrade must never modify operator files — this indicates a framework manifest bug; please report it (#791)."
fi
}
# Reconcile contract files after sync: framework-owned overwrite (backup-once),
# user-seeded seed-if-absent.
reconcile_framework_files() {
@@ -184,63 +456,105 @@ sync_framework() {
return
fi
if command -v rsync >/dev/null 2>&1; then
local rsync_args=(-a --delete --exclude ".git" --exclude ".framework-version" --exclude "*.pre-constitution.bak")
if [[ "$INSTALL_MODE" == "keep" ]]; then
# Anchor to the transfer root (leading /) so we preserve the TOP-LEVEL
# ~/.config/mosaic/<file> without also excluding defaults/<file> from sync
# (reconcile_framework_files needs the freshly-synced defaults/ copies).
for path in "${PRESERVE_PATHS[@]}"; do
rsync_args+=(--exclude "/$path")
done
fi
rsync "${rsync_args[@]}" "$SOURCE_DIR/" "$TARGET_DIR/"
if [[ "$INSTALL_MODE" == "keep" ]]; then
# The `mosaic update` path. Manifest-driven, never-deleting-outside-framework:
# operator config is structurally protected (#791). No rsync --delete here.
# The manifest is already loaded+validated in main() BEFORE the snapshot/trap
# (a fail-closed manifest must abort without ever restoring over operator
# files — see the pre-flight in main, #791 blocker-1).
sync_framework_keep
return
fi
# Fallback: cp-based sync. Glob-aware so entries like "fleet/*.yaml" preserve
# every matching user file (parity with the rsync --exclude path above).
local preserve_tmp=""
if [[ "$INSTALL_MODE" == "keep" ]]; then
preserve_tmp="$(mktemp -d "${TMPDIR:-/tmp}/mosaic-preserve-XXXXXX")"
local match rel
for path in "${PRESERVE_PATHS[@]}"; do
# Unquoted $path lets the glob expand against TARGET_DIR; nullglob makes a
# non-matching pattern vanish instead of staying literal.
shopt -s nullglob
for match in "$TARGET_DIR/"$path; do
[[ -e "$match" ]] || continue
rel="${match#"$TARGET_DIR/"}"
mkdir -p "$preserve_tmp/$(dirname "$rel")"
cp -R "$match" "$preserve_tmp/$rel"
done
shopt -u nullglob
done
fi
# overwrite mode — a full replace, chosen only for a fresh install or when the
# operator explicitly asks to replace everything. No operator state to protect.
sync_framework_overwrite
}
find "$TARGET_DIR" -mindepth 1 -maxdepth 1 ! -name ".git" ! -name ".framework-version" ! -name "*.pre-constitution.bak" -exec rm -rf {} +
# Enumerate a NUL-delimited file list via `find` into the temp file $1, failing
# CLOSED if find errors. We capture to a checked file instead of consuming
# `< <(find …)` directly because a process substitution discards the producer's
# exit status: an EACCES/I/O failure partway through a scan would truncate the
# list yet leave the reading `while` loop exiting 0, so a partial upgrade would
# commit and report success and the ERR/restore trap would never fire. Running
# find to completion first, then checking its status, turns that silent
# truncation into a fail-closed abort that the restore trap can act on (#791
# blocker-D1). $1 after the shift is the scan root — named in the error.
_scan_or_die() {
local out="$1"; shift
if ! find "$@" -print0 > "$out"; then
fail "Could not enumerate framework files under '$1' — aborting before committing an incomplete sync (fail-closed)."
return 1 # D1-GUARD
fi
}
# Keep-mode sync: create/refresh framework-owned files and prune only retired
# framework files inside shipped framework subtrees. Operator-owned and unknown
# paths (fail-safe default) are never written and never deleted — the #791 HARD
# GATE. Single code path (no rsync) so it is byte-for-byte parity-testable.
sync_framework_keep() {
local src="$SOURCE_DIR" dst="$TARGET_DIR" abs rel root list
# 1) Overlay copy — every framework-owned source file, refreshed only when its
# bytes changed (no mtime churn on unchanged files, never on operator files).
# The source scan is captured fail-closed (#791 blocker-D1): a find failure
# aborts the sync (→ ERR trap → restore) rather than silently truncating it.
list="$(mktemp)"
_scan_or_die "$list" "$src" -type f || { rm -f "$list"; return 1; }
while IFS= read -r -d '' abs; do
rel="${abs#"$src"/}"
case "$rel" in
.git|.git/*|.framework-version|*.pre-constitution.bak) continue ;;
esac
manifest_is_framework "$rel" || continue
if [[ -f "$dst/$rel" ]] && cmp -s "$abs" "$dst/$rel"; then continue; fi
[[ "$rel" == */* ]] && mkdir -p "$dst/${rel%/*}"
cp "$abs" "$dst/$rel"
done < "$list"
rm -f "$list"
# 2) Scoped prune — within each shipped framework subtree root, remove
# framework-owned target files the current source no longer ships. Operator
# carve-outs (e.g. tools/_lib/credentials.json) resolve to operator and are
# skipped; unknown paths resolve to operator too — both are unreachable here.
# Each subtree scan is captured fail-closed for the same reason as the copy.
while IFS= read -r root; do
[[ -n "$root" && -d "$dst/$root" ]] || continue
list="$(mktemp)"
_scan_or_die "$list" "$dst/$root" -type f || { rm -f "$list"; return 1; }
while IFS= read -r -d '' abs; do
rel="${abs#"$dst"/}"
case "$rel" in *.pre-constitution.bak) continue ;; esac
[[ -f "$src/$rel" ]] && continue # still shipped
manifest_is_framework "$rel" || continue
rm -f "$abs"
done < "$list"
rm -f "$list"
# Drop framework dirs left empty by the prune (never touches a dir that still
# holds an operator file — those are never emptied). A genuine find failure
# (unreadable dir) is surfaced as a warning rather than silently swallowed;
# the "directory not empty" races we tolerate are ignored via -delete's own
# rc, not by hiding stderr — so a real error is still visible to the operator.
if ! find "$dst/$root" -type d -empty -delete 2>/dev/null; then
warn "prune: could not fully sweep empty framework dirs under $root (left as-is)"
fi
done < <(manifest_subtree_roots)
}
# Overwrite-mode sync: full replace. Only reached for a fresh install or an
# explicit operator "replace everything" choice, so nothing is preserved.
sync_framework_overwrite() {
if command -v rsync >/dev/null 2>&1; then
rsync -a --delete \
--exclude ".git" --exclude ".framework-version" --exclude "*.pre-constitution.bak" \
"$SOURCE_DIR/" "$TARGET_DIR/"
return
fi
find "$TARGET_DIR" -mindepth 1 -maxdepth 1 \
! -name ".git" ! -name ".framework-version" ! -name "*.pre-constitution.bak" \
-exec rm -rf {} +
cp -R "$SOURCE_DIR"/. "$TARGET_DIR"/
rm -rf "$TARGET_DIR/.git"
if [[ -n "$preserve_tmp" ]]; then
# Restore by re-globbing the SAME patterns against preserve_tmp, so each
# preserved item is restored at its own relative path (e.g. only
# fleet/roster.yaml is replaced — the freshly-synced fleet/examples stays).
for path in "${PRESERVE_PATHS[@]}"; do
shopt -s nullglob
for match in "$preserve_tmp/"$path; do
[[ -e "$match" ]] || continue
rel="${match#"$preserve_tmp/"}"
rm -rf "$TARGET_DIR/$rel"
mkdir -p "$TARGET_DIR/$(dirname "$rel")"
cp -R "$match" "$TARGET_DIR/$rel"
done
shopt -u nullglob
done
rm -rf "$preserve_tmp"
fi
}
# ═══════════════════════════════════════════════════════════════════════════════
@@ -261,6 +575,10 @@ run_migrations() {
# Remove bin/ directory — all executables now live in the npm CLI.
# Scripts that were in bin/ are now in tools/_scripts/.
if [[ "$from_version" -lt 2 ]]; then
# bin/ and the rails symlink are operator-classified by the manifest (unknown⇒
# operator) and thus captured in the durable snapshot; record them as
# intentional removals so the post-sync verify net does not restore them.
MIGRATION_REMOVED_PATHS+=("bin" "rails")
if [[ -d "$TARGET_DIR/bin" ]]; then
ok "Removing legacy bin/ directory (executables now in npm CLI)"
rm -rf "$TARGET_DIR/bin"
@@ -296,6 +614,46 @@ run_migrations() {
fi
}
# ═══════════════════════════════════════════════════════════════════════════════
# Component-scoped install (#892 W7) — additive early dispatch.
# ═══════════════════════════════════════════════════════════════════════════════
# `install.sh --component <name>` delegates to the component's own idempotent,
# fail-closed installer and EXITS. This path is ADDITIVE (#869): it does NOT run
# the full-framework sync, does NOT alter framework-manifest ownership behavior,
# and touches NOTHING the #869 install-ordering-guard covers (no runtime-asset
# linking, no lease-enforcement hook wiring). Each component installer is
# INTERSECTED-AND-VALIDATED against the single SSOT framework-manifest.txt, so a
# component manifest can never authorize a write outside framework ownership.
run_component_install() {
local name="$1"
case "$name" in
wake)
local wi="$SOURCE_DIR/tools/wake/wake-install.sh"
if [[ ! -x "$wi" && ! -f "$wi" ]]; then
fail "Component 'wake' installer not found at $wi"
exit 1
fi
step "Installing Mosaic component: wake"
WAKE_INSTALL_SOURCE="$SOURCE_DIR" WAKE_INSTALL_TARGET="$TARGET_DIR" \
bash "$wi" install
;;
"")
fail "--component requires a name (e.g. --component wake)."
exit 1
;;
*)
fail "Unknown component '$name'. Supported: wake."
exit 1
;;
esac
}
if [[ -n "$COMPONENT" ]]; then
mkdir -p "$TARGET_DIR"
run_component_install "$COMPONENT"
exit 0
fi
# ═══════════════════════════════════════════════════════════════════════════════
# Main
# ═══════════════════════════════════════════════════════════════════════════════
@@ -311,9 +669,26 @@ else
ok "Install mode: overwrite"
fi
# Pre-flight (keep mode): load + validate the framework manifest BEFORE taking a
# snapshot or arming the restore trap. A fail-closed manifest (missing / empty /
# malformed) must abort here WITHOUT deleting or restoring over operator files —
# the snapshot/restore path exists only for a genuine mid-sync mutation failure,
# not for a validation failure that has touched nothing yet (#791 blocker-1).
if [[ "$INSTALL_MODE" == "keep" ]]; then
manifest_load
# Durable, operator-scoped backup taken BEFORE any mutation (#791 PR2). Kept
# outside the framework tree; recovered later via `mosaic restore`. Fail-open.
make_durable_snapshot
fi
# Snapshot before any destructive file operation; restore on interrupt/failure.
# The trap MUST exit after restoring: a bash INT/TERM handler that merely returns
# does NOT terminate the script — execution would resume past the interrupt,
# clear the snapshot, and report success, leaving a partial post-interrupt update
# (#791 blocker-A). `restore_snapshot; exit 1` guarantees a non-zero exit for
# both the errtrace (ERR) and signal (INT/TERM) paths.
make_snapshot
trap 'restore_snapshot' ERR INT TERM
trap 'restore_snapshot; exit 1' ERR INT TERM
sync_framework
@@ -334,6 +709,10 @@ reconcile_framework_files
# Ensure tool scripts are executable
find "$TARGET_DIR/tools" -name "*.sh" -exec chmod +x {} + 2>/dev/null || true
find "$TARGET_DIR/tools/_scripts" -type f -exec chmod +x {} + 2>/dev/null || true
# git-credential-mosaic (per-agent Gitea identity helper) ships without a .sh
# suffix — git resolves credential helpers by exact name/path, not extension —
# so the *.sh glob above does not cover it; chmod it explicitly.
[[ -f "$TARGET_DIR/tools/git/git-credential-mosaic" ]] && chmod +x "$TARGET_DIR/tools/git/git-credential-mosaic" 2>/dev/null || true
ok "Framework synced to $TARGET_DIR"
@@ -342,6 +721,10 @@ run_migrations
# File-system phase complete and consistent — clear the restore trap.
trap - ERR INT TERM
# Post-sync safety net: heal any operator file a manifest bug let the sync touch,
# using the durable pre-update snapshot (#791 PR2). Runs with the trap disarmed so
# a corrective copy can't spuriously trigger a full rollback.
verify_operator_surface # VERIFY-NET (#791 PR2)
cleanup_snapshot
# Testability / minimal-install hook: stop after the file-system phase, before any
@@ -357,10 +740,15 @@ step "Post-install tasks"
SCRIPTS="$TARGET_DIR/tools/_scripts"
if [[ -x "$SCRIPTS/mosaic-link-runtime-assets" ]]; then
if "$SCRIPTS/mosaic-link-runtime-assets" >/dev/null 2>&1; then
link_args=()
[[ "$ALLOW_INACTIVE_ENFORCEMENT" == "1" ]] && link_args+=(--allow-inactive-enforcement)
# stdout is suppressed as before, but stderr is left connected: the
# install-ordering guard's FAIL LOUD message (#869 Point-1 C2) must reach
# the operator, not be swallowed silently.
if "$SCRIPTS/mosaic-link-runtime-assets" "${link_args[@]}" >/dev/null; then
ok "Runtime assets linked"
else
warn "Runtime asset linking failed (non-fatal)"
warn "Runtime asset linking failed (non-fatal) — see message above for details."
fi
fi
@@ -1,7 +1,48 @@
{
"model": "opus",
"hooks": {
"PreCompact": [
{
"matcher": ".*",
"hooks": [
{
"type": "command",
"command": "python3 \"$HOME/.config/mosaic/tools/lease-broker/revoke-lease.py\" --runtime claude --reason pre-compact"
}
]
}
],
"SessionStart": [
{
"matcher": "compact",
"hooks": [
{
"type": "command",
"command": "python3 \"$HOME/.config/mosaic/tools/lease-broker/revoke-lease.py\" --runtime claude --reason session-start-compact"
}
]
},
{
"matcher": "resume|clear",
"hooks": [
{
"type": "command",
"command": "python3 \"$HOME/.config/mosaic/tools/lease-broker/revoke-lease.py\" --runtime claude --reason session-start-rollover --bump-generation"
}
]
}
],
"PreToolUse": [
{
"matcher": ".*",
"hooks": [
{
"type": "command",
"command": "python3 ~/.config/mosaic/tools/lease-broker/mutator-gate.py --runtime claude --recovery-command ~/.config/mosaic/tools/lease-broker/recover-context.py",
"timeout": 3
}
]
},
{
"matcher": "Write|Edit|MultiEdit",
"hooks": [
@@ -38,6 +79,11 @@
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "python3 ~/.config/mosaic/tools/lease-broker/receipt-observer-client.py --runtime claude --latest-entry",
"timeout": 3
},
{
"type": "command",
"command": "~/.config/mosaic/tools/qa/reflect-stop-hook.sh",
@@ -0,0 +1,93 @@
export type LeaseLifecycleRunner = (args: string[]) => boolean;
type LifecycleEvent = {
reason?: unknown;
toolName?: unknown;
};
type LifecycleHandler = (
event: LifecycleEvent,
context: Record<string, unknown>,
) => unknown | Promise<unknown>;
export interface LeaseLifecyclePiApi {
on(event: string, handler: LifecycleHandler): void;
}
const ROLLOVER_REASONS = new Set(['reload', 'new', 'resume', 'fork']);
function eventReason(event: LifecycleEvent): string {
return typeof event.reason === 'string' && event.reason.length > 0 ? event.reason : 'unknown';
}
/**
* Register redundant Pi compaction observers and same-PID generation rollover.
*
* A failed pre-compaction observer cancels compaction. A failed post-compaction
* observer or generation rollover locally blocks later tools in addition to the
* broker-backed all-tools gate.
*/
export function registerLeaseLifecycleHooks(
pi: LeaseLifecyclePiApi,
runRevoker: LeaseLifecycleRunner,
): void {
let postCompactReason: string | null = null;
let postCompactFailure = false;
let rolloverFailure = false;
pi.on('session_before_compact', async (event) => {
const reason = eventReason(event);
const revoked = runRevoker([
'--runtime',
'pi',
'--reason',
`pi-session-before-compact:${reason}`,
]);
if (!revoked) return { cancel: true };
return undefined;
});
pi.on('session_compact', async (event) => {
postCompactReason = eventReason(event);
});
pi.on('context', async () => {
if (postCompactReason === null) return undefined;
const reason = postCompactReason;
const revoked = runRevoker([
'--runtime',
'pi',
'--reason',
`pi-context-after-compact:${reason}`,
]);
if (revoked) {
postCompactReason = null;
postCompactFailure = false;
} else {
postCompactFailure = true;
}
return undefined;
});
pi.on('session_start', async (event) => {
const reason = eventReason(event);
if (!ROLLOVER_REASONS.has(reason)) return undefined;
const revoked = runRevoker([
'--runtime',
'pi',
'--reason',
`pi-session-start:${reason}`,
'--bump-generation',
]);
rolloverFailure = !revoked;
return undefined;
});
pi.on('tool_call', async () => {
if (!postCompactFailure && !rolloverFailure) return undefined;
return {
block: true,
reason: 'BLOCKED: Mosaic lease lifecycle revoke failed; runtime remains UNVERIFIED.',
};
});
}
@@ -22,12 +22,23 @@ import {
import { join, basename } from 'node:path';
import { homedir } from 'node:os';
import { execSync, spawnSync } from 'node:child_process';
import { registerLeaseLifecycleHooks, type LeaseLifecyclePiApi } from './lease-lifecycle.js';
// ---------------------------------------------------------------------------
// Config
// ---------------------------------------------------------------------------
const MOSAIC_HOME = process.env['MOSAIC_HOME'] ?? join(homedir(), '.config', 'mosaic');
const MUTATOR_GATE = join(MOSAIC_HOME, 'tools', 'lease-broker', 'mutator-gate.py');
const LEASE_REVOKER = join(MOSAIC_HOME, 'tools', 'lease-broker', 'revoke-lease.py');
const RECOVERY_COMMAND = join(MOSAIC_HOME, 'tools', 'lease-broker', 'recover-context.py');
const RECEIPT_OBSERVER_CLIENT = join(
MOSAIC_HOME,
'tools',
'lease-broker',
'receipt-observer-client.py',
);
const RECOVERY_TOOL = 'mosaic_context_recover';
// ---------------------------------------------------------------------------
// Helpers
@@ -106,6 +117,104 @@ function nowIso(): string {
return new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
}
function runPiLeaseRevoker(args: string[]): boolean {
const result = spawnSync('python3', [LEASE_REVOKER, ...args], {
encoding: 'utf8',
timeout: 2_000,
env: process.env,
});
return result.status === 0;
}
function checkPiMutatorGate(toolName: string): { block: true; reason: string } | undefined {
const result = spawnSync('python3', [MUTATOR_GATE, '--runtime', 'pi'], {
input: `${JSON.stringify({ tool_name: toolName })}\n`,
encoding: 'utf8',
timeout: 2_000,
env: process.env,
});
if (result.status === 0) return undefined;
const detail = String(result.stderr ?? '')
.trim()
.split('\n')[0];
return {
block: true,
reason: detail || 'BLOCKED: Mosaic mutator gate is unavailable or the lease is UNVERIFIED.',
};
}
function checkPiRecoveryGate(): { block: true; reason: string } | undefined {
return checkPiMutatorGate(RECOVERY_TOOL);
}
function assistantMessageText(message: unknown): string | undefined {
if (typeof message !== 'object' || message === null) return undefined;
const value = message as { role?: unknown; content?: unknown };
if (value.role !== 'assistant') return undefined;
if (typeof value.content === 'string') return value.content;
if (!Array.isArray(value.content)) return undefined;
const text: string[] = [];
for (const part of value.content) {
if (typeof part !== 'object' || part === null) return undefined;
const typed = part as { type?: unknown; text?: unknown };
if (typed.type !== 'text' || typeof typed.text !== 'string') return undefined;
text.push(typed.text);
}
return text.join('');
}
function recordPiMessageEnd(message: unknown): void {
const latestAssistantMessage = assistantMessageText(message);
if (latestAssistantMessage === undefined) return;
// This sends finalized Pi message_end content only to the daemon-owned
// authenticated observer transport, never to the public broker request API.
spawnSync('python3', [RECEIPT_OBSERVER_CLIENT, '--runtime', 'pi'], {
input: `${JSON.stringify({ latest_assistant_message: latestAssistantMessage })}\n`,
encoding: 'utf8',
timeout: 2_000,
env: process.env,
});
}
function runPiRecoveryCommand(params: {
phase: 'begin' | 'complete';
construction?: string;
compactionEpoch?: number;
requestEpoch?: number;
}): { content: Array<{ type: 'text'; text: string }> } {
const args = [RECOVERY_COMMAND, params.phase];
if (params.phase === 'begin') {
if (
typeof params.construction !== 'string' ||
!Number.isInteger(params.compactionEpoch) ||
!Number.isInteger(params.requestEpoch) ||
params.compactionEpoch < 0 ||
params.requestEpoch < 0
) {
return {
content: [
{ type: 'text', text: 'Recovery begin requires construction and non-negative epochs.' },
],
};
}
args.push(
'--construction',
params.construction,
'--compaction-epoch',
String(params.compactionEpoch),
'--request-epoch',
String(params.requestEpoch),
);
}
const result = spawnSync('python3', args, {
encoding: 'utf8',
timeout: 3_000,
env: process.env,
});
const output = result.status === 0 ? String(result.stdout ?? '') : String(result.stderr ?? '');
return { content: [{ type: 'text', text: output || 'Constrained recovery refused.' }] };
}
// ---------------------------------------------------------------------------
// Mission detection
// ---------------------------------------------------------------------------
@@ -250,6 +359,40 @@ export default function register(pi: ExtensionAPI) {
let hbModel: string | null = null;
let hbTimer: ReturnType<typeof setInterval> | null = null;
// ── Compaction observers and same-PID generation rollover ─────────────
registerLeaseLifecycleHooks(pi as unknown as LeaseLifecyclePiApi, runPiLeaseRevoker);
// ── Whole mutator-class authorization gate ────────────────────────────
// Every Pi tool, including unknown/custom tools, reaches the broker-backed
// class gate before execution. Broker/script failure blocks fail-closed.
pi.on('tool_call', async (event) => checkPiMutatorGate(event.toolName));
// Pi records only a finalized assistant entry at message_end. It never uses
// after_provider_response, which occurs before stream consumption.
pi.on('message_end', async (event) => {
recordPiMessageEnd((event as unknown as { message?: unknown }).message);
});
// The recovery custom tool is the only Pi invocation that maps to the
// broker's exempt RECOVERY_TOOL identity. It is not a Bash exception.
pi.registerTool({
name: RECOVERY_TOOL,
label: 'Mosaic Context Recovery',
description:
'Run the constrained broker-backed context recovery flow. This is the sole ungated mutator.',
parameters: Type.Object({
phase: Type.Union([Type.Literal('begin'), Type.Literal('complete')]),
construction: Type.Optional(Type.String()),
compactionEpoch: Type.Optional(Type.Integer({ minimum: 0 })),
requestEpoch: Type.Optional(Type.Integer({ minimum: 0 })),
}),
async execute(_toolCallId, params) {
const blocked = checkPiRecoveryGate();
if (blocked !== undefined) return { content: [{ type: 'text', text: blocked.reason }] };
return runPiRecoveryCommand(params);
},
});
// ── Session Start ─────────────────────────────────────────────────────
pi.on('session_start', async (_event, ctx) => {
sessionCwd = process.cwd();
@@ -0,0 +1,65 @@
---
name: mosaic-context-refresh
description: Run the constrained Mosaic context-recovery flow after compaction or directive-loss. This is a thin wrapper over the broker-backed recovery command; it never treats a receipt as a safety or residency proof.
---
# mosaic-context-refresh
Use this only after compaction, session resume, or confirmed directive drift. It invokes the
**single ungated mutator**, `tools/lease-broker/recover-context.py`; every other consequential
mutator remains behind the verified lease gate.
## Wrapper procedure
1. The runtime supplies the exact validated normative-fragment construction and the current
compaction/request epochs.
- **Claude:** invoke only this direct command shape (no shell composition):
```bash
python3 /absolute/path/to/mosaic/tools/lease-broker/recover-context.py begin --construction /absolute/path/to/mosaic-context-refresh-construction.json --compaction-epoch 0 --request-epoch 0
```
This is a literal argv template: replace the recover-context.py path and construction JSON path
with the literal absolute paths for your install, then replace each epoch with literal decimal
digits. Do not use variables, quoting, globs, redirects,
shell operators, substitutions, or line continuations. Claude's all-tools gate maps only this
fully literal recovery shape to `mosaic_context_recover`; ordinary `Bash` remains gated.
- **Pi:** call the registered `mosaic_context_recover` tool with `phase: "begin"`,
`construction`, `compactionEpoch`, and `requestEpoch`. It is the exact broker-exempt tool name;
Pi `bash` and every other tool remain gated.
Both forms delegate to the shipped WI-5 broker transition: revoke first, build the canonical
`B_payload`/`H_payload`, enter `PENDING_DELIVERY`, and mint a fresh one-time challenge. They print
the terminal receipt envelope to deliver exactly as returned.
2. The current assistant message copies that one terminal receipt verbatim. It does not compute a
hash, add prose, quote a prior receipt, or present a caller-supplied receipt/challenge.
3. The production trusted-observer transport records that finalized assistant entry before completion:
- **Claude** selects the latest assistant entry at its `Stop` hook.
- **Pi** records only finalized assistant content at `message_end` (never
`after_provider_response`).
Then invoke completion with the same adapter form: Claude runs
`python3 /absolute/path/to/mosaic/tools/lease-broker/recover-context.py complete`; Pi calls
`mosaic_context_recover` with `phase: "complete"`. Completion supplies no receipt or challenge
argument. The broker observes the exact latest assistant entry, commits evidence, consumes its own
fresh challenge, and promotes VERIFIED last. If observation is absent, malformed, stale, or
duplicated, recovery remains UNVERIFIED and a retry begins a new cycle.
## Scope and honesty
- A receipt from the normal verification path cannot be replayed through recovery: recovery mints a
distinct current challenge and does not accept caller-provided receipt text as evidence.
- Observable absent, malformed, prefix-truncated, and adapter-mutated terminal receipts do not
promote. “Tail-only” is non-promoting only when the delivered terminal bytes are concretely
malformed or incomplete.
- **Negative capability:** a tail-preserving middle drop is not represented as receipt-detectable.
It is a T-C injection-contract residual deferred to WI-7 server-side evidence; do not claim this
skill or receipt catches it.
- The receipt is a T-A delivery/liveness prerequisite only. It never proves obedience, comprehension,
durable residency, or safety; the whole mutator-class gate and server-side branch protection retain
those roles.
This source-resident skill is projected by the Mosaic skill bridge after framework install/upgrade.
Do not create a live symlink manually.
@@ -12,6 +12,8 @@ exact-match session.
- `mosaic-tmux-holder.service` — user-mode holder that owns the named tmux server.
- `[email protected]` — user-mode template for one reusable agent session.
- `[email protected]` — generic Pi operator-interaction template
that fails fast when its pinned runtime policy is incomplete or changed.
- `test-fleet-units.sh` — validates unit syntax and required relationships.
The agent template calls:
@@ -22,36 +24,57 @@ The agent template calls:
which starts or reuses a tmux session on `MOSAIC_TMUX_SOCKET`.
## Local customization
## Generated environment and local data
Per-agent overrides live outside the package in:
The roster-derived projection is written outside the package at:
```text
~/.config/mosaic/fleet/agents/<agent>.env
~/.config/mosaic/fleet/agents/<agent>.env.generated
```
Example:
Systemd does not read either environment file. It starts the launcher with a fixed cleared bootstrap
environment; before it creates, queries, or stops an exact agent tmux session, `start-agent-session.sh`
strictly parses the generated projection and the optional local data file:
```dotenv
MOSAIC_TMUX_SOCKET=mosaic-fleet
MOSAIC_AGENT_RUNTIME=claude
MOSAIC_AGENT_WORKDIR=$HOME/src/your-project
# Optional escape hatch for PoC/canary agents:
# MOSAIC_AGENT_COMMAND=mosaic yolo claude
```text
~/.config/mosaic/fleet/agents/<agent>.env.local
```
The local file may contain only safe machine-specific data (`MOSAIC_RUNTIME_BIN`, heartbeat paths or
interval, and Claude configuration paths). It cannot override roster-derived keys, carry a command,
or contain secret-like/unknown keys. Both files must be private regular files. Do not hand-edit the
generated projection; update the roster and regenerate it instead. A legacy `<agent>.env` is
consumed only for regeneration, strict relocation, or private quarantine and is never launch input.
See `docs/fleet/reference/generated-env-boundary.md` for the full contract.
## Manual canary sequence
Use the roster and the supported installer; do not pre-create the agent environment directory or
edit a generated projection. `mosaic fleet install` validates the roster, installs the units and
helpers, and writes private roster-derived projections before any service is started.
```bash
mkdir -p ~/.config/systemd/user ~/.config/mosaic/tools/fleet ~/.config/mosaic/fleet/agents
cp packages/mosaic/framework/systemd/user/mosaic-*.service ~/.config/systemd/user/
cp packages/mosaic/framework/tools/fleet/start-agent-session.sh ~/.config/mosaic/tools/fleet/
chmod +x ~/.config/mosaic/tools/fleet/start-agent-session.sh
# Create a site-owned canary roster. Inspect an existing roster before using --force.
mosaic fleet init --profile minimal --write
mosaic fleet install
systemctl --user daemon-reload
systemctl --user start mosaic-tmux-holder.service
systemctl --user start mosaic-agent@canary.service
mosaic fleet start canary-pi
tmux -L mosaic-fleet ls
```
For an operator-interaction service, first put `<agent-name>` in the roster with the pinned Pi
runtime, model, reasoning, and `operator-interaction` tool policy. Re-run `mosaic fleet install` after
that roster change so it writes `<agent-name>.env.generated`; ambient `MOSAIC_AGENT_*` values are not
launch authority. The generic unit instance uses that generated identity, and no service source is
renamed for an instance:
```bash
mosaic fleet install
systemctl --user daemon-reload
systemctl --user start mosaic-interaction-agent@<agent-name>.service
~/.config/mosaic/tools/fleet/print-interaction-effective-policy.sh <agent-name>
```
Do not use `tmux kill-server` without `-L mosaic-fleet`; this pattern is meant
to avoid disturbing the user's default tmux server.
@@ -7,16 +7,13 @@ PartOf=mosaic-tmux-holder.service
[Service]
Type=oneshot
# Remove loader and noninteractive-shell controls before ExecStart loads env.
UnsetEnvironment=LD_PRELOAD BASH_ENV ENV
RemainAfterExit=yes
# No default MOSAIC_TMUX_SOCKET: an absent roster socket means the literal
# default tmux socket (no -L). The per-agent .env sets it when the roster names
# one; otherwise it stays unset and start-agent-session.sh uses the default socket.
Environment=MOSAIC_AGENT_NAME=%i
Environment=MOSAIC_AGENT_RUNTIME=pi
Environment=MOSAIC_AGENT_WORKDIR=%h
EnvironmentFile=-%h/.config/mosaic/fleet/agents/%i.env
ExecStart=/bin/bash %h/.config/mosaic/tools/fleet/start-agent-session.sh %i
ExecStop=-/bin/bash -lc 'if [ -n "${MOSAIC_TMUX_SOCKET:-}" ]; then tmux -L "$MOSAIC_TMUX_SOCKET" kill-session -t "=%i"; else tmux kill-session -t "=%i"; fi'
# Never preload the projection. The launcher starts from a fixed minimal
# environment and strictly validates generated/local data before tmux effects.
ExecStart=/usr/bin/env -i HOME=%h MOSAIC_AGENT_NAME=%i PATH=/usr/bin:/bin /bin/bash --noprofile --norc %h/.config/mosaic/tools/fleet/start-agent-session.sh %i
ExecStop=-/usr/bin/env -i HOME=%h MOSAIC_AGENT_NAME=%i PATH=/usr/bin:/bin /bin/bash --noprofile --norc %h/.config/mosaic/tools/fleet/start-agent-session.sh --stop %i
[Install]
WantedBy=default.target
@@ -0,0 +1,19 @@
[Unit]
Description=Mosaic operator interaction agent %i
Documentation=https://git.mosaicstack.dev/mosaicstack/stack
Requires=mosaic-tmux-holder.service
After=mosaic-tmux-holder.service
PartOf=mosaic-tmux-holder.service
[Service]
Type=oneshot
# Remove loader and noninteractive-shell controls before ExecStart loads env.
UnsetEnvironment=LD_PRELOAD BASH_ENV ENV
RemainAfterExit=yes
# The interaction wrapper delegates to the shared strict parser before pinned
# profile checks; no projection data reaches Bash through systemd.
ExecStart=/usr/bin/env -i HOME=%h MOSAIC_AGENT_NAME=%i PATH=/usr/bin:/bin /bin/bash --noprofile --norc %h/.config/mosaic/tools/fleet/start-interaction-service.sh %i
ExecStop=-/usr/bin/env -i HOME=%h MOSAIC_AGENT_NAME=%i PATH=/usr/bin:/bin /bin/bash --noprofile --norc %h/.config/mosaic/tools/fleet/start-agent-session.sh --stop %i
[Install]
WantedBy=default.target
@@ -0,0 +1,22 @@
[Unit]
Description=Mosaic lease broker daemon (framework tools/lease-broker/daemon.py)
Documentation=https://git.mosaicstack.dev/mosaicstack/stack
After=default.target
[Service]
Type=simple
# The broker socket lives under the runtime directory so it disappears with
# the user session instead of surviving as stale state across logins.
# daemon.py's secure_parent() fails closed unless this directory is exactly
# 0700, so RuntimeDirectoryMode is not cosmetic.
RuntimeDirectory=mosaic-lease
RuntimeDirectoryMode=0700
# Remove loader and noninteractive-shell controls before ExecStart loads env,
# matching the tmux fleet units in this same directory.
UnsetEnvironment=LD_PRELOAD BASH_ENV ENV
ExecStart=/usr/bin/env -i HOME=%h PATH=/usr/bin:/bin XDG_RUNTIME_DIR=%t /bin/bash --noprofile --norc %h/.config/mosaic/tools/lease-broker/start-lease-broker.sh
Restart=on-failure
RestartSec=1
[Install]
WantedBy=default.target
@@ -6,10 +6,11 @@ After=default.target
[Service]
Type=oneshot
RemainAfterExit=yes
Environment=MOSAIC_TMUX_SOCKET=mosaic-fleet
Environment=MOSAIC_TMUX_HOLDER=_holder
ExecStart=/bin/bash -lc 'tmux -L "$MOSAIC_TMUX_SOCKET" has-session -t "=${MOSAIC_TMUX_HOLDER}:0.0" 2>/dev/null || tmux -L "$MOSAIC_TMUX_SOCKET" new-session -d -s "$MOSAIC_TMUX_HOLDER" "while true; do sleep 3600; done"'
ExecStop=-/bin/bash -lc 'tmux -L "$MOSAIC_TMUX_SOCKET" kill-server'
# The holder owns the tmux server, so clear loader, shell-control, and stale
# manager/session variables before the server process starts.
UnsetEnvironment=LD_PRELOAD BASH_ENV ENV
ExecStart=/usr/bin/env -i HOME=%h PATH=/usr/bin:/bin MOSAIC_TMUX_SOCKET=mosaic-fleet MOSAIC_TMUX_HOLDER=_holder /bin/bash --noprofile --norc %h/.config/mosaic/tools/fleet/start-tmux-holder.sh
ExecStop=-/usr/bin/env -i HOME=%h PATH=/usr/bin:/bin MOSAIC_TMUX_SOCKET=mosaic-fleet /bin/bash --noprofile --norc -c 'tmux -L "$MOSAIC_TMUX_SOCKET" kill-server'
[Install]
WantedBy=default.target
@@ -0,0 +1,41 @@
[Unit]
# Mosaic wake FALLBACK safety drain (F7 replacement-before-retirement, EPIC #892,
# W7). This is the framework-shipped canon-side FALLBACK WAKE: a LOW-FREQUENCY
# SAFETY drain that fires the canon drain (digest.sh render --from-store) on a
# per-class cadence bound, INDEPENDENT of the event-driven detector daemon
# (mosaic-wake.service). Its whole reason to exist is that a stalled/dead detector
# or daemon can never SILENTLY STARVE delivery: even with nothing pushing, this
# oneshot periodically drains the durable pending-inbox so the cumulative unacked
# set still reaches the consumer. It is the §5 retirement precondition (F7) — it
# must be live + proven-firing BEFORE the legacy mosaic-heartbeat@ timer is reaped,
# so there is never a coverage gap. Fixed-interval heartbeats are forbidden as the
# PRIMARY wake mechanism (WAKE-DOCTRINE); they survive ONLY as this per-class
# fallback cadence, bounded by urgency SLO, never as the steady state.
#
# This is a oneshot SERVICE activated by mosaic-wake-fallback.timer; the cadence
# lives on the TIMER (OnUnitActiveSec), set per-class by the A10 installer via the
# blank-reset drop-in — never here. The service therefore carries NO [Install]
# section (the TIMER is what is enabled/wanted); it is triggered, not wanted.
Description=Mosaic wake fallback safety drain (canon drain: digest.sh render --from-store)
After=default.target
[Service]
Type=oneshot
# Strip loader / noninteractive-shell controls before ExecStart, matching the
# detector, lease-broker and tmux fleet units in this same directory (defense-in-
# depth against an injected BASH_ENV/ENV/LD_PRELOAD in the user manager environment).
UnsetEnvironment=LD_PRELOAD BASH_ENV ENV
# Operator-owned runtime configuration. This EnvironmentFile carries only WAKE_*
# NAMES (the per-agent namespace WAKE_AGENT, the lane WAKE_LANE, and — reused from
# the detector — the pluggable adapter COMMANDS resolved BY NAME at runtime). It
# carries NEVER any secret and NEVER any endpoint value. The '-' prefix keeps a
# missing file from masking the installer's dedicated fail-closed install-validate.
EnvironmentFile=-%h/.config/mosaic/wake/fallback.env
# THE CANON DRAIN. digest.sh render --from-store drains the durable pending-inbox
# (store.sh drain) and renders the cumulative-state digest. Running it here, on the
# timer cadence, is the safety net: it is the SAME drain the delivery path uses, so
# a stalled detector cannot starve it. Delivery/paste of the rendered digest is the
# same operator-wired send seam the detector path uses (out of framework scope);
# this unit guarantees the DRAIN fires on a bounded cadence regardless of detector
# health. digest render exits 0 on an empty inbox, so a quiet cycle is a clean no-op.
ExecStart=/bin/bash --noprofile --norc %h/.config/mosaic/tools/wake/digest.sh render --from-store
@@ -0,0 +1,30 @@
[Unit]
# Cadence timer for the Mosaic wake FALLBACK safety drain (F7, EPIC #892, W7).
# Drives mosaic-wake-fallback.service on a LOW-FREQUENCY per-class cadence bound,
# INDEPENDENT of the event-driven detector daemon, so a stalled detector can never
# silently starve delivery. This is the framework-shipped canon-side FALLBACK WAKE:
# a heartbeat-shaped timer that survives ONLY as the per-class fallback cadence
# (WAKE-DOCTRINE) bounded by urgency SLO — never the steady-state wake mechanism.
Description=Mosaic wake fallback cadence timer (per-class safety wake)
After=default.target
[Timer]
# BASE cadence placeholder. The A10 installer OVERRIDES this per-class from the
# watch-list schema's per-class `fallback_cadence` bound, via a BLANK-RESET drop-in
# (an empty OnUnitActiveSec= reset line, then the new value) written under
# mosaic-wake-fallback.timer.d/. systemd merges base + drop-ins so exactly ONE
# effective OnUnitActiveUSec results (wake-install.sh verify-single). The base value
# here is a conservative safety floor for a host installed before any per-class
# drop-in is written — it is deliberately low-frequency (never the primary wake).
OnUnitActiveSec=1h
# Also fire shortly after boot so a freshly-booted host does not wait a full cadence
# for its first safety drain. OnBootSec is a distinct key from OnUnitActiveSec and
# does NOT count toward the exactly-one-OnUnitActiveUSec blank-reset invariant.
OnBootSec=15min
# Catch up a missed elapse (host asleep/off) rather than silently skipping it — a
# fallback that silently skips is exactly the starvation this unit exists to prevent.
Persistent=true
Unit=mosaic-wake-fallback.service
[Install]
WantedBy=timers.target
@@ -0,0 +1,31 @@
[Unit]
# Mosaic wake DETECTOR daemon (A1/W7 of the wake canon, EPIC #892). A LONG-LIVED
# single-instance detector: tools/wake/detector.sh run. This is a SERVICE, not a
# timer — the per-class SLO lives INSIDE the daemon's run-loop (WAKE_DETECTOR_INTERVAL
# poll cadence + the per-cycle off-host beacon emit), never as a systemd
# OnUnitActiveSec interval. The blank-reset cadence idiom therefore does NOT apply
# to this unit; it applies only to the legacy mosaic-heartbeat@ timer during retire.
Description=Mosaic wake detector daemon (framework tools/wake/detector.sh run)
After=default.target
[Service]
Type=simple
# Strip loader / noninteractive-shell controls before ExecStart, matching the
# lease-broker and tmux fleet units in this same directory (defense-in-depth
# against an injected BASH_ENV/ENV/LD_PRELOAD in the user manager environment).
UnsetEnvironment=LD_PRELOAD BASH_ENV ENV
# Operator-owned runtime configuration. This EnvironmentFile carries only the
# WAKE_* NAMES and the pluggable adapter COMMANDS (the off-host beacon/alarm sink
# and the HMAC key NAME) — NEVER the HMAC key material and NEVER the alarm
# endpoint value. Both are resolved BY NAME at runtime via load_credentials, so
# no secret and no endpoint is ever written into this unit. The installer's
# fail-closed install-validate (wake-install.sh validate-targets) is what proves
# the required names are configured + reachable BEFORE this unit is enabled; the
# '-' prefix keeps a missing file from masking that dedicated validation.
EnvironmentFile=-%h/.config/mosaic/wake/detector.env
ExecStart=/bin/bash --noprofile --norc %h/.config/mosaic/tools/wake/detector.sh run
Restart=on-failure
RestartSec=5
[Install]
WantedBy=default.target
@@ -4,6 +4,9 @@ set -euo pipefail
SCRIPT_DIR=$(cd -- "$(dirname -- "$0")" && pwd)
HOLDER="$SCRIPT_DIR/mosaic-tmux-holder.service"
AGENT="$SCRIPT_DIR/[email protected]"
INTERACTION="$SCRIPT_DIR/[email protected]"
HOLDER_START="$SCRIPT_DIR/../../tools/fleet/start-tmux-holder.sh"
START_AGENT="$SCRIPT_DIR/../../tools/fleet/start-agent-session.sh"
fail() {
echo "FAIL: $*" >&2
@@ -12,19 +15,145 @@ fail() {
[ -f "$HOLDER" ] || fail "missing mosaic-tmux-holder.service"
[ -f "$AGENT" ] || fail "missing [email protected]"
[ -f "$INTERACTION" ] || fail "missing [email protected]"
[ -x "$HOLDER_START" ] || fail "missing executable start-tmux-holder.sh"
[ -x "$START_AGENT" ] || fail "missing executable start-agent-session.sh"
grep -qF 'ExecStart=' "$HOLDER" || fail "holder has no ExecStart"
grep -qF 'tmux -L' "$HOLDER" || fail "holder does not use named tmux socket"
grep -qF '_holder' "$HOLDER" || fail "holder session is not explicit"
grep -qF 'UnsetEnvironment=LD_PRELOAD BASH_ENV ENV' "$HOLDER" || \
fail "holder does not remove loader and shell-control variables"
grep -qF 'ExecStart=/usr/bin/env -i HOME=%h PATH=/usr/bin:/bin MOSAIC_TMUX_SOCKET=mosaic-fleet MOSAIC_TMUX_HOLDER=_holder /bin/bash --noprofile --norc %h/.config/mosaic/tools/fleet/start-tmux-holder.sh' "$HOLDER" || \
fail "holder does not clear manager environment before starting tmux"
grep -qF 'ExecStop=-/usr/bin/env -i HOME=%h PATH=/usr/bin:/bin MOSAIC_TMUX_SOCKET=mosaic-fleet /bin/bash --noprofile --norc -c' "$HOLDER" || \
fail "holder stop does not clear manager environment"
if grep -qF -- '/bin/bash -lc' "$HOLDER"; then
fail "holder must not start tmux through a login shell"
fi
grep -qF 'Requires=mosaic-tmux-holder.service' "$AGENT" || fail "agent does not require holder"
grep -qF 'start-agent-session.sh' "$AGENT" || fail "agent unit does not call start-agent-session.sh"
grep -qF 'kill-session -t "=%i"' "$AGENT" || fail "agent stop does not exact-match its session"
if grep -qE '^Environment(File)?=' "$AGENT" "$INTERACTION"; then
fail "agent units must not accept ambient or projection environment before strict parsing"
fi
grep -qF 'UnsetEnvironment=LD_PRELOAD BASH_ENV ENV' "$AGENT" || \
fail "agent unit does not remove loader and shell-control variables"
grep -qF 'UnsetEnvironment=LD_PRELOAD BASH_ENV ENV' "$INTERACTION" || \
fail "interaction unit does not remove loader and shell-control variables"
grep -qF 'ExecStart=/usr/bin/env -i HOME=%h MOSAIC_AGENT_NAME=%i PATH=/usr/bin:/bin /bin/bash --noprofile --norc' "$AGENT" || \
fail "agent unit does not clear bootstrap environment before strict parsing"
grep -qF 'start-agent-session.sh --stop %i' "$AGENT" || \
fail "agent stop does not use the validated exact-stop path"
grep -qF 'Requires=mosaic-tmux-holder.service' "$INTERACTION" || fail "interaction service does not require holder"
grep -qF 'ExecStart=/usr/bin/env -i HOME=%h MOSAIC_AGENT_NAME=%i PATH=/usr/bin:/bin /bin/bash --noprofile --norc' "$INTERACTION" || \
fail "interaction unit does not clear bootstrap environment before strict parsing"
grep -qF 'start-interaction-service.sh %i' "$INTERACTION" || fail "interaction service does not use shared strict parsing"
grep -qF 'start-agent-session.sh --stop %i' "$INTERACTION" || \
fail "interaction stop does not use the validated exact-stop path"
if command -v systemd-analyze >/dev/null 2>&1; then
systemd-analyze verify --user "$HOLDER" "$AGENT" >/tmp/mosaic-fleet-systemd-verify.log 2>&1 || {
systemd-analyze verify --user "$HOLDER" "$AGENT" "$INTERACTION" >/tmp/mosaic-fleet-systemd-verify.log 2>&1 || {
cat /tmp/mosaic-fleet-systemd-verify.log >&2
fail "systemd-analyze verify failed"
}
fi
# Real isolated socket regression: a preexisting server with an LD_PRELOAD
# constructor marker must fail closed, while a fresh named server is created.
if command -v tmux >/dev/null 2>&1 && command -v cc >/dev/null 2>&1; then
TEST_ROOT=$(mktemp -d)
TEST_SOCKET="mosaic-holder-test-$$"
trap 'tmux -L "$TEST_SOCKET" kill-server >/dev/null 2>&1 || true; rm -rf "$TEST_ROOT"' EXIT
MARKER="$TEST_ROOT/loader-marker"
LIBRARY="$TEST_ROOT/marker.so"
HOLDER_HOME="$TEST_ROOT/holder-home"
mkdir -p "$HOLDER_HOME/.config/mosaic/fleet/run"
chmod 700 "$HOLDER_HOME/.config" "$HOLDER_HOME/.config/mosaic" \
"$HOLDER_HOME/.config/mosaic/fleet" "$HOLDER_HOME/.config/mosaic/fleet/run"
printf '123e4567-e89b-12d3-a456-426614174000\n' > \
"$HOLDER_HOME/.config/mosaic/fleet/run/holder-owner"
chmod 600 "$HOLDER_HOME/.config/mosaic/fleet/run/holder-owner"
cat > "$TEST_ROOT/marker.c" <<'EOF'
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
__attribute__((constructor)) static void mark_loader(void) {
const char *path = getenv("MOSAIC_LOADER_MARKER");
if (path != NULL) {
int fd = open(path, O_WRONLY | O_CREAT | O_APPEND, 0600);
if (fd >= 0) { write(fd, "loaded\\n", 7); close(fd); }
}
}
EOF
cc -shared -fPIC -o "$LIBRARY" "$TEST_ROOT/marker.c"
MOSAIC_LOADER_MARKER="$MARKER" LD_PRELOAD="$LIBRARY" \
tmux -L "$TEST_SOCKET" new-session -d -s _holder 'sleep 60'
[ -s "$MARKER" ] || fail "contaminated fixture did not execute loader constructor"
server_pid=$(tmux -L "$TEST_SOCKET" display-message -p '#{pid}')
: > "$MARKER"
if /usr/bin/env -i HOME="$HOLDER_HOME" PATH=/usr/bin:/bin \
MOSAIC_TMUX_SOCKET="$TEST_SOCKET" MOSAIC_TMUX_HOLDER=_holder "$HOLDER_START" \
>"$TEST_ROOT/holder.out" 2>&1; then
fail "holder adopted contaminated named server"
fi
grep -qF 'global environment does not match the owned-server contract' "$TEST_ROOT/holder.out" || \
fail "holder did not report contaminated server environment"
[ "$(tmux -L "$TEST_SOCKET" display-message -p '#{pid}')" = "$server_pid" ] || \
fail "holder replaced a contaminated server instead of failing closed"
[ ! -s "$MARKER" ] || fail "holder execution triggered a contaminated loader"
# Agent validation must reject the same unmanaged server without cleaning its
# global environment or adding a managed session.
AGENT_HOME="$HOLDER_HOME/.config/mosaic"
AGENT_NAME=loader-safe
AGENT_WORKDIR="$AGENT_HOME/work"
AGENT_BIN="$TEST_ROOT/agent-bin"
mkdir -p "$AGENT_HOME/fleet/agents" "$AGENT_WORKDIR" "$AGENT_BIN"
chmod 700 "$AGENT_HOME/fleet/agents"
cat > "$AGENT_HOME/fleet/agents/$AGENT_NAME.env.generated" <<EOF
MOSAIC_AGENT_NAME=$AGENT_NAME
MOSAIC_AGENT_CLASS=code
MOSAIC_AGENT_RUNTIME=pi
MOSAIC_AGENT_MODEL=
MOSAIC_AGENT_REASONING=
MOSAIC_AGENT_TOOL_POLICY=code
MOSAIC_AGENT_WORKDIR=$AGENT_WORKDIR
MOSAIC_TMUX_SOCKET=$TEST_SOCKET
EOF
printf 'MOSAIC_RUNTIME_BIN=%s\n' "$AGENT_BIN" > "$AGENT_HOME/fleet/agents/$AGENT_NAME.env.local"
chmod 600 "$AGENT_HOME/fleet/agents/$AGENT_NAME.env.generated" \
"$AGENT_HOME/fleet/agents/$AGENT_NAME.env.local"
cat > "$AGENT_BIN/mosaic" <<'EOF'
#!/bin/sh
sleep 30
EOF
chmod 700 "$AGENT_BIN/mosaic"
server_environment_before=$(tmux -L "$TEST_SOCKET" show-environment -g | sort)
server_sessions_before=$(tmux -L "$TEST_SOCKET" list-sessions | sort)
if /usr/bin/env -i HOME="$HOLDER_HOME" PATH=/usr/bin:/bin MOSAIC_HOME="$AGENT_HOME" \
"$START_AGENT" "$AGENT_NAME" >"$TEST_ROOT/agent.out" 2>&1; then
fail "agent launcher adopted contaminated named server"
fi
[ "$(tmux -L "$TEST_SOCKET" display-message -p '#{pid}')" = "$server_pid" ] || \
fail "agent launcher changed unmanaged server PID"
[ "$(tmux -L "$TEST_SOCKET" show-environment -g | sort)" = "$server_environment_before" ] || \
fail "agent launcher changed unmanaged global environment"
[ "$(tmux -L "$TEST_SOCKET" list-sessions | sort)" = "$server_sessions_before" ] || \
fail "agent launcher changed unmanaged sessions"
tmux -L "$TEST_SOCKET" kill-server
/usr/bin/env -i HOME="$HOLDER_HOME" PATH=/usr/bin:/bin \
MOSAIC_TMUX_SOCKET="$TEST_SOCKET" MOSAIC_TMUX_HOLDER=_holder "$HOLDER_START"
tmux -L "$TEST_SOCKET" has-session -t '=_holder:0.0' || fail "fresh holder was not created"
if tmux -L "$TEST_SOCKET" show-environment -g LD_PRELOAD 2>/dev/null | grep -q '^LD_PRELOAD='; then
fail "fresh holder retained LD_PRELOAD"
fi
/usr/bin/env -i HOME="$HOLDER_HOME" PATH=/usr/bin:/bin MOSAIC_HOME="$AGENT_HOME" \
"$START_AGENT" "$AGENT_NAME"
tmux -L "$TEST_SOCKET" has-session -t "=$AGENT_NAME:0.0" || \
fail "agent did not launch on a valid owned server"
tmux -L "$TEST_SOCKET" kill-server
trap - EXIT
rm -rf "$TEST_ROOT"
fi
echo "ok - fleet systemd unit templates"
@@ -9,7 +9,7 @@
2. Do NOT ask for routine confirmation before required push/merge/issue-close/release/tag actions.
3. Completion is forbidden at PR-open stage.
4. Completion requires merged PR to `main` + terminal green CI + linked issue/internal task closed.
5. Before push or merge, run queue guard: `~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose push|merge -B main`.
5. Before push or merge, run the queue guard against the push branch or the merge PR's exact head repository/SHA (`ci-queue-wait.sh --help`); `pr-merge.sh` supplies exact merge metadata automatically.
6. For issue/PR/milestone operations, use Mosaic wrappers first (`~/.config/mosaic/tools/git/*.sh`).
7. If any required wrapper command fails: report `blocked` with the exact failed wrapper command and stop.
8. Do NOT stop at "PR created" and do NOT ask "should I merge?" for routine flow.
@@ -88,7 +88,7 @@ Reference:
5. Do not mark implementation complete until PR is merged.
6. Do not mark implementation complete until CI/pipeline status is terminal green.
7. Close linked issues/tasks only after merge + green CI.
8. Before push or merge, run CI queue guard: `~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose push|merge -B main`.
8. Before push or merge, run the CI queue guard against the push branch or the merge PR's exact head repository/SHA (`ci-queue-wait.sh --help`); `pr-merge.sh` supplies exact merge metadata automatically.
## Container Release Strategy (When Applicable)
@@ -147,9 +147,9 @@ Do NOT stop at "PR created" and do NOT ask "should I merge?" or "should I close
5. Ensure `docs/PRD.md` or `docs/PRD.json` exists and is current before coding.
6. Create scratchpad: `docs/scratchpads/{task-id}-{short-name}.md` and include issue/internal ref.
7. Update `docs/TASKS.md` status + issue/internal ref before coding.
8. Before push, run CI queue guard: `~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose push -B main`.
8. Before push, run CI queue guard: `~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose push`.
9. Open PR to `main` for delivery changes (no direct push to `main`).
10. Before merge, run CI queue guard: `~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose merge -B main`.
10. Before merge, run CI queue guard: `~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose merge -B <PR_HEAD_BRANCH> -R <PR_HEAD_OWNER/REPO> --sha <PR_HEAD_FULL_SHA>`.
11. Merge PRs that pass required checks and review gates with squash strategy only.
12. Reference issues/internal refs in commits (`Fixes #123`, `Refs #123`, or `Refs TASKS:T1`).
13. Close issue/internal task only after testing and documentation gates pass, PR merge is complete, and CI/pipeline status is terminal green.
@@ -9,7 +9,7 @@
2. Do NOT ask for routine confirmation before required push/merge/issue-close/release/tag actions.
3. Completion is forbidden at PR-open stage.
4. Completion requires merged PR to `main` + terminal green CI + linked issue/internal task closed.
5. Before push or merge, run queue guard: `~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose push|merge -B main`.
5. Before push or merge, run the queue guard against the push branch or the merge PR's exact head repository/SHA (`ci-queue-wait.sh --help`); `pr-merge.sh` supplies exact merge metadata automatically.
6. For issue/PR/milestone operations, use Mosaic wrappers first (`~/.config/mosaic/tools/git/*.sh`).
7. If any required wrapper command fails: report `blocked` with the exact failed wrapper command and stop.
8. Do NOT stop at "PR created" and do NOT ask "should I merge?" for routine flow.
@@ -97,7 +97,7 @@ Reference:
5. Do not mark implementation complete until PR is merged.
6. Do not mark implementation complete until CI/pipeline status is terminal green.
7. Close linked issues/tasks only after merge + green CI.
8. Before push or merge, run CI queue guard: `~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose push|merge -B main`.
8. Before push or merge, run the CI queue guard against the push branch or the merge PR's exact head repository/SHA (`ci-queue-wait.sh --help`); `pr-merge.sh` supplies exact merge metadata automatically.
## Container Release Strategy (When Applicable)
@@ -198,9 +198,9 @@ Do NOT stop at "PR created" and do NOT ask "should I merge?" or "should I close
5. Ensure `docs/PRD.md` or `docs/PRD.json` exists and is current before coding.
6. Create scratchpad: `docs/scratchpads/{task-id}-{short-name}.md` and include issue/internal ref.
7. Update `docs/TASKS.md` status + issue/internal ref before coding.
8. Before push, run CI queue guard: `~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose push -B main`.
8. Before push, run CI queue guard: `~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose push`.
9. Open PR to `main` for delivery changes (no direct push to `main`).
10. Before merge, run CI queue guard: `~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose merge -B main`.
10. Before merge, run CI queue guard: `~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose merge -B <PR_HEAD_BRANCH> -R <PR_HEAD_OWNER/REPO> --sha <PR_HEAD_FULL_SHA>`.
11. Merge PRs that pass required checks and review gates with squash strategy only.
12. Reference issues/internal refs in commits (`Fixes #123`, `Refs #123`, or `Refs TASKS:T1`).
13. Close issue/internal task only after testing and documentation gates pass, PR merge is complete, and CI/pipeline status is terminal green.
@@ -9,7 +9,7 @@
2. Do NOT ask for routine confirmation before required push/merge/issue-close/release/tag actions.
3. Completion is forbidden at PR-open stage.
4. Completion requires merged PR to `main` + terminal green CI + linked issue/internal task closed.
5. Before push or merge, run queue guard: `~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose push|merge -B main`.
5. Before push or merge, run the queue guard against the push branch or the merge PR's exact head repository/SHA (`ci-queue-wait.sh --help`); `pr-merge.sh` supplies exact merge metadata automatically.
6. For issue/PR/milestone operations, use Mosaic wrappers first (`~/.config/mosaic/tools/git/*.sh`).
7. If any required wrapper command fails: report `blocked` with the exact failed wrapper command and stop.
8. Do NOT stop at "PR created" and do NOT ask "should I merge?" for routine flow.
@@ -101,7 +101,7 @@ Reference:
5. Do not mark implementation complete until PR is merged.
6. Do not mark implementation complete until CI/pipeline status is terminal green.
7. Close linked issues/tasks only after merge + green CI.
8. Before push or merge, run CI queue guard: `~/.config/mosaic/tools/git/ci-queue-wait.sh --purpose push|merge -B main`.
8. Before push or merge, run the CI queue guard against the push branch or the merge PR's exact head repository/SHA (`ci-queue-wait.sh --help`); `pr-merge.sh` supplies exact merge metadata automatically.
## Container Release Strategy (When Applicable)

Some files were not shown because too many files have changed in this diff Show More