feat(tess): add Mos coordination boundary (#735)
All checks were successful
ci/woodpecker/push/ci Pipeline was successful
ci/woodpecker/push/publish Pipeline was successful

This commit was merged in pull request #735.
This commit is contained in:
2026-07-13 11:59:16 +00:00
parent 9e5b9188ce
commit 76325ca3f2
12 changed files with 1307 additions and 15 deletions

View File

@@ -0,0 +1,154 @@
import { describe, expect, it, vi } from 'vitest';
import {
InMemoryMosCoordinationPort,
MosCoordinationClient,
type CoordinationScope,
type MosCoordinationAuthorityError,
type MosCoordinationPort,
} from '../index.js';
const scope: CoordinationScope = {
actorId: 'operator-1',
tenantId: 'tenant-a',
correlationId: 'corr-1',
requesterAgentId: 'Nova',
};
function client(
port: MosCoordinationPort,
handoffIdFactory: () => string = (): string => 'handoff-1',
): MosCoordinationClient {
return new MosCoordinationClient(
{ interactionAgentId: 'Nova', orchestrationAgentId: 'Conductor' },
port,
handoffIdFactory,
);
}
describe('MosCoordinationClient', (): void => {
it('round-trips handoff, observation, and result through the native port with identities as data', async (): Promise<void> => {
const adapter = new InMemoryMosCoordinationPort();
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', 'Mos accepted the request');
adapter.recordResult('handoff-1', 'completed', 'Merged by Mos');
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 Mos',
});
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 Mos work', async (): Promise<void> => {
const adapter = new InMemoryMosCoordinationPort();
await expect(
client(adapter).handoff(
{ idempotencyKey: 'handoff-request-1', summary: 'Implement the requested feature' },
{ ...scope, requesterAgentId: 'Untrusted' },
),
).rejects.toMatchObject({
code: 'requester_forbidden',
} satisfies Partial<MosCoordinationAuthorityError>);
});
it('rejects self-delegation configuration before constructing a client', (): void => {
expect(
(): MosCoordinationClient =>
new MosCoordinationClient(
{ interactionAgentId: 'Nova', orchestrationAgentId: 'Nova' },
new InMemoryMosCoordinationPort(),
),
).toThrow('Interaction and orchestration identities must differ');
});
it('rejects whitespace-equivalent self-delegation identities', (): void => {
expect(
(): MosCoordinationClient =>
new MosCoordinationClient(
{ interactionAgentId: 'Nova ', orchestrationAgentId: 'Nova' },
new InMemoryMosCoordinationPort(),
),
).toThrow('Interaction and orchestration identities must differ');
});
it('does not expose another tenant handoff to observe or result', async (): Promise<void> => {
const adapter = new InMemoryMosCoordinationPort();
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 InMemoryMosCoordinationPort({ 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: MosCoordinationPort = {
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<MosCoordinationAuthorityError>);
});
});

View File

@@ -0,0 +1,208 @@
import {
type CoordinationObservation,
type CoordinationResult,
type CoordinationScope,
type MosCoordinationActivity,
type MosCoordinationPort,
type MosHandoff,
type MosHandoffReceipt,
type MosHandoffStatus,
} from './mos-coordination.js';
const DEFAULT_HANDOFF_TTL_MS = 60 * 60 * 1_000;
const DEFAULT_MAX_HANDOFFS = 1_000;
interface StoredHandoff {
readonly handoff: MosHandoff;
status: MosHandoffStatus;
readonly activity: MosCoordinationActivity[];
readonly expiresAt: number;
result?: CoordinationResult;
}
export interface InMemoryMosCoordinationPortOptions {
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 MosCoordinationPort without changing interaction-plane callers.
*/
export class InMemoryMosCoordinationPort implements MosCoordinationPort {
private readonly handoffs = new Map<string, StoredHandoff>();
private readonly now: () => Date;
private readonly handoffTtlMs: number;
private readonly maxHandoffs: number;
constructor(options: InMemoryMosCoordinationPortOptions = {}) {
this.now = options.now ?? (() => new Date());
this.handoffTtlMs = options.handoffTtlMs ?? DEFAULT_HANDOFF_TTL_MS;
this.maxHandoffs = options.maxHandoffs ?? DEFAULT_MAX_HANDOFFS;
}
async handoff(handoff: MosHandoff): Promise<MosHandoffReceipt> {
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: MosHandoffStatus, 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 a Mos 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: MosHandoff, status: MosHandoffStatus): MosHandoffReceipt {
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 InMemoryMosCoordinationError('forbidden', 'Handoff scope does not match');
}
return stored;
}
private requireHandoff(handoffId: string): StoredHandoff {
const stored = this.handoffs.get(handoffId);
if (stored === undefined) {
throw new InMemoryMosCoordinationError('not_found', 'Handoff was not found');
}
return stored;
}
private assertSameHandoff(existing: MosHandoff, incoming: MosHandoff): 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 InMemoryMosCoordinationError(
'conflict',
'Handoff ID is already bound to different immutable input',
);
}
}
}
export type InMemoryMosCoordinationErrorCode = 'conflict' | 'forbidden' | 'not_found';
export class InMemoryMosCoordinationError extends Error {
constructor(
readonly code: InMemoryMosCoordinationErrorCode,
message: string,
) {
super(message);
this.name = InMemoryMosCoordinationError.name;
}
}
function activity(
status: MosHandoffStatus,
summary: string,
now: () => Date,
): MosCoordinationActivity {
return { occurredAt: now().toISOString(), status, summary };
}
function copyActivity(entry: MosCoordinationActivity): MosCoordinationActivity {
return { ...entry };
}
function snapshotHandoff(handoff: MosHandoff): MosHandoff {
return Object.freeze({
handoffId: handoff.handoffId,
targetAgentId: handoff.targetAgentId,
request: Object.freeze({ ...handoff.request }),
scope: Object.freeze({ ...handoff.scope }),
});
}

View File

@@ -2,6 +2,23 @@ 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 {
InMemoryMosCoordinationError,
InMemoryMosCoordinationPort,
} from './in-memory-mos-coordination-port.js';
export { MosCoordinationAuthorityError, MosCoordinationClient } from './mos-coordination.js';
export type {
CoordinationObservation,
CoordinationResult,
CoordinationScope,
MosCoordinationActivity,
MosCoordinationIdentity,
MosCoordinationPort,
MosHandoff,
MosHandoffReceipt,
MosHandoffRequest,
MosHandoffStatus,
} from './mos-coordination.js';
export type {
CreateMissionOptions,
Mission,

View File

@@ -0,0 +1,207 @@
export type MosHandoffStatus = '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 MosCoordinationIdentity {
readonly interactionAgentId: string;
readonly orchestrationAgentId: string;
}
export interface MosHandoffRequest {
readonly idempotencyKey: string;
readonly summary: string;
readonly context?: string;
readonly missionId?: string;
}
export interface MosHandoff {
readonly handoffId: string;
readonly targetAgentId: string;
readonly request: MosHandoffRequest;
readonly scope: CoordinationScope;
}
export interface MosHandoffReceipt {
readonly handoffId: string;
readonly targetAgentId: string;
readonly status: 'queued' | 'accepted';
readonly correlationId: string;
}
export interface MosCoordinationActivity {
readonly occurredAt: string;
readonly status: MosHandoffStatus;
readonly summary: string;
}
export interface CoordinationObservation {
readonly handoffId: string;
readonly targetAgentId: string;
readonly status: MosHandoffStatus;
readonly correlationId: string;
readonly activity: readonly MosCoordinationActivity[];
}
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 MosCoordinationPort {
handoff(handoff: MosHandoff): Promise<MosHandoffReceipt>;
observe(handoffId: string, scope: CoordinationScope): Promise<CoordinationObservation>;
result(handoffId: string, scope: CoordinationScope): Promise<CoordinationResult>;
}
export type MosCoordinationAuthorityErrorCode =
| 'invalid_identity'
| 'requester_forbidden'
| 'target_drift'
| 'correlation_drift';
export class MosCoordinationAuthorityError extends Error {
constructor(
readonly code: MosCoordinationAuthorityErrorCode,
message: string,
) {
super(message);
this.name = MosCoordinationAuthorityError.name;
}
}
/**
* Enforces the interaction-to-orchestration authority boundary before a
* transport is reached. Identity names remain configuration data.
*/
export class MosCoordinationClient {
private readonly identity: MosCoordinationIdentity;
constructor(
identity: MosCoordinationIdentity,
private readonly port: MosCoordinationPort,
private readonly handoffIdFactory: () => string = (): string => crypto.randomUUID(),
) {
this.identity = normalizeIdentity(identity);
}
async handoff(request: MosHandoffRequest, scope: CoordinationScope): Promise<MosHandoffReceipt> {
this.assertRequester(scope);
const handoff: MosHandoff = {
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 MosCoordinationAuthorityError(
'target_drift',
'Mos coordination transport returned a mismatched handoff target',
);
}
if (receipt.correlationId !== handoff.scope.correlationId) {
throw new MosCoordinationAuthorityError(
'correlation_drift',
'Mos 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 MosCoordinationAuthorityError(
'requester_forbidden',
'Requester is not the configured interaction agent',
);
}
}
private assertObservation(
observation: CoordinationObservation,
scope: CoordinationScope,
): CoordinationObservation {
if (observation.targetAgentId !== this.identity.orchestrationAgentId) {
throw new MosCoordinationAuthorityError(
'target_drift',
'Mos coordination transport returned an unexpected observation target',
);
}
if (observation.correlationId !== scope.correlationId) {
throw new MosCoordinationAuthorityError(
'correlation_drift',
'Mos 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 MosCoordinationAuthorityError(
'target_drift',
'Mos coordination transport returned an unexpected result target',
);
}
if (result.correlationId !== scope.correlationId) {
throw new MosCoordinationAuthorityError(
'correlation_drift',
'Mos coordination transport returned a mismatched result correlation ID',
);
}
return result;
}
}
function normalizeIdentity(identity: MosCoordinationIdentity): MosCoordinationIdentity {
const interactionAgentId = identity.interactionAgentId.trim();
const orchestrationAgentId = identity.orchestrationAgentId.trim();
if (interactionAgentId.length === 0 || orchestrationAgentId.length === 0) {
throw new MosCoordinationAuthorityError(
'invalid_identity',
'Interaction and orchestration identities are required',
);
}
if (interactionAgentId === orchestrationAgentId) {
throw new MosCoordinationAuthorityError(
'invalid_identity',
'Interaction and orchestration identities must differ',
);
}
return Object.freeze({ interactionAgentId, orchestrationAgentId });
}
function snapshotRequest(request: MosHandoffRequest): MosHandoffRequest {
return Object.freeze({ ...request });
}
function snapshotScope(scope: CoordinationScope): CoordinationScope {
return Object.freeze({ ...scope });
}