Merge branch 'main' into feat/agent-send-digest-class
All checks were successful
ci/woodpecker/pr/ci Pipeline was successful
All checks were successful
ci/woodpecker/pr/ci Pipeline was successful
This commit is contained in:
41
packages/comms/README.md
Normal file
41
packages/comms/README.md
Normal 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
packages/comms/package.json
Normal file
37
packages/comms/package.json
Normal 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"
|
||||
]
|
||||
}
|
||||
90
packages/comms/src/__tests__/heartbeat.test.ts
Normal file
90
packages/comms/src/__tests__/heartbeat.test.ts
Normal file
@@ -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();
|
||||
});
|
||||
});
|
||||
89
packages/comms/src/__tests__/liveness.test.ts
Normal file
89
packages/comms/src/__tests__/liveness.test.ts
Normal file
@@ -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',
|
||||
});
|
||||
});
|
||||
});
|
||||
131
packages/comms/src/__tests__/matrix-client.test.ts
Normal file
131
packages/comms/src/__tests__/matrix-client.test.ts
Normal file
@@ -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');
|
||||
});
|
||||
});
|
||||
151
packages/comms/src/__tests__/presence-flow.test.ts
Normal file
151
packages/comms/src/__tests__/presence-flow.test.ts
Normal file
@@ -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
packages/comms/src/heartbeat.ts
Normal file
124
packages/comms/src/heartbeat.ts
Normal 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
packages/comms/src/index.ts
Normal file
42
packages/comms/src/index.ts
Normal 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
packages/comms/src/liveness-reader.ts
Normal file
58
packages/comms/src/liveness-reader.ts
Normal 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
packages/comms/src/liveness.ts
Normal file
63
packages/comms/src/liveness.ts
Normal 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
packages/comms/src/matrix-client.ts
Normal file
204
packages/comms/src/matrix-client.ts
Normal 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
packages/comms/src/presence-agent.ts
Normal file
92
packages/comms/src/presence-agent.ts
Normal file
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* High-level presence agent (RFC-001 §4.1 steps 10–11, §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
packages/comms/src/types.ts
Normal file
99
packages/comms/src/types.ts
Normal 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
packages/comms/tsconfig.json
Normal file
9
packages/comms/tsconfig.json
Normal file
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "dist",
|
||||
"rootDir": "src"
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
13
packages/comms/vitest.config.ts
Normal file
13
packages/comms/vitest.config.ts
Normal 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'],
|
||||
},
|
||||
},
|
||||
});
|
||||
31
packages/mosaic/framework/guides/WAKE-DOCTRINE.md
Normal file
31
packages/mosaic/framework/guides/WAKE-DOCTRINE.md
Normal file
@@ -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.
|
||||
@@ -1,6 +1,6 @@
|
||||
#!/bin/bash
|
||||
# pr-review.sh - Review a pull request on GitHub or Gitea
|
||||
# Usage: pr-review.sh -n <pr_number> -a <action> [-c <comment>] [--login <name>]
|
||||
# Usage: pr-review.sh -n <pr_number> -a <action> [-c <comment>] [--login <name>] [-r owner/repo] [-H host]
|
||||
#
|
||||
# Gitea reviews and comments are written through the supported REST API, not
|
||||
# `tea`: tea 0.11.1 cannot emit the id of a record it creates and can silently
|
||||
@@ -16,6 +16,18 @@
|
||||
# override it for this invocation only. The REST write, the /user identity read,
|
||||
# and every read-back are ALL performed with the token of the EFFECTIVE login,
|
||||
# so the write and its verification bind to the same identity.
|
||||
#
|
||||
# -r/--repo override: explicit owner/repo slug, skipping git-remote slug
|
||||
# inference — mirrors the -r convention of the sibling wrappers (pr-view.sh,
|
||||
# pr-diff.sh, pr-ci-wait.sh; mosaicstack/stack #867) for reviewer worktrees
|
||||
# whose origin is nonstandard or missing. -H/--host makes the target Gitea
|
||||
# instance explicit too (skips remote-host inference), so ambient CWD/remote
|
||||
# state can no longer cross-wire the review to the wrong instance. With -r, the
|
||||
# resolved repo is preflighted (GET .../repos/<slug>) BEFORE any write so a
|
||||
# wrong-host cross-wire surfaces as a clear preflight error instead of an opaque
|
||||
# write-404. Every Gitea curl (write, read-back, preflight) carries a
|
||||
# `User-Agent: mosaic-pr-review` header, since some Cloudflare-fronted Gitea
|
||||
# hosts intermittently reject curl's default User-Agent.
|
||||
|
||||
set -e
|
||||
|
||||
@@ -28,6 +40,8 @@ PR_NUMBER=""
|
||||
ACTION=""
|
||||
COMMENT=""
|
||||
LOGIN_OVERRIDE=""
|
||||
REPO_OVERRIDE=""
|
||||
HOST_OVERRIDE=""
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case $1 in
|
||||
@@ -47,14 +61,24 @@ while [[ $# -gt 0 ]]; do
|
||||
LOGIN_OVERRIDE="$2"
|
||||
shift 2
|
||||
;;
|
||||
-r|--repo)
|
||||
REPO_OVERRIDE="$2"
|
||||
shift 2
|
||||
;;
|
||||
-H|--host)
|
||||
HOST_OVERRIDE="$2"
|
||||
shift 2
|
||||
;;
|
||||
-h|--help)
|
||||
echo "Usage: pr-review.sh -n <pr_number> -a <action> [-c <comment>] [--login <name>]"
|
||||
echo "Usage: pr-review.sh -n <pr_number> -a <action> [-c <comment>] [--login <name>] [-r owner/repo] [-H host]"
|
||||
echo ""
|
||||
echo "Options:"
|
||||
echo " -n, --number PR number (required)"
|
||||
echo " -a, --action Review action: approve, request-changes, comment (required)"
|
||||
echo " -c, --comment Review comment (required for request-changes)"
|
||||
echo " -l, --login Override the detected Gitea tea login (approve/request-changes only)"
|
||||
echo " -r, --repo Explicit owner/repo slug (skips git-remote slug inference)"
|
||||
echo " -H, --host Explicit Gitea host (skips remote-host inference)"
|
||||
echo " -h, --help Show this help"
|
||||
exit 0
|
||||
;;
|
||||
@@ -75,7 +99,15 @@ if [[ -z "$ACTION" ]]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
detect_platform >/dev/null
|
||||
if [[ -n "$REPO_OVERRIDE" ]]; then
|
||||
# An explicit --repo is the whole point of a reviewer worktree whose origin
|
||||
# is nonstandard or missing (#867 convention, mirrored from pr-view.sh /
|
||||
# pr-diff.sh): do not hard-fail platform detection on a missing/foreign
|
||||
# origin — assume gitea, the only platform --repo/--host target.
|
||||
detect_platform >/dev/null 2>&1 || PLATFORM="gitea"
|
||||
else
|
||||
detect_platform >/dev/null
|
||||
fi
|
||||
|
||||
# Post a comment to a Gitea PR (PR comments ARE issue comments) via the
|
||||
# supported REST API and verify it against a PROVIDER-RETURNED created id. The
|
||||
@@ -110,6 +142,7 @@ print(json.dumps({"body": os.environ["COMMENT_BODY"]}))
|
||||
if ! write_status=$(curl -sS -o "$write_file" -w '%{http_code}' \
|
||||
-X POST \
|
||||
--config "$auth_config" \
|
||||
-H 'User-Agent: mosaic-pr-review' \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d "$payload" \
|
||||
"$GITEA_API_BASE/issues/$pr_number/comments"); then
|
||||
@@ -140,6 +173,7 @@ PY
|
||||
|
||||
if ! readback_status=$(curl -sS -o "$readback_file" -w '%{http_code}' \
|
||||
--config "$auth_config" \
|
||||
-H 'User-Agent: mosaic-pr-review' \
|
||||
"$GITEA_API_BASE/issues/comments/$created_id"); then
|
||||
echo "Error: Gitea comment read-back transport failed" >&2
|
||||
return 1
|
||||
@@ -245,10 +279,24 @@ PY
|
||||
# caller-supplied --login: that exact login's token MUST resolve, and we FAIL
|
||||
# CLOSED rather than silently downgrading the review/comment to the host default
|
||||
# identity. Returns non-zero (clear stderr) on any resolution failure.
|
||||
#
|
||||
# Honors the module-level REPO_OVERRIDE / HOST_OVERRIDE (-r/--repo, -H/--host):
|
||||
# when set, they skip git-remote slug/host inference entirely — for reviewer
|
||||
# worktrees whose origin is nonstandard or missing, and to make the target
|
||||
# instance fully deterministic (an ambient CWD/remote can otherwise cross-wire
|
||||
# a review to the wrong Gitea host). When -r/--repo is used, the resolved repo
|
||||
# is preflighted (GET .../repos/<slug>) BEFORE any write: a wrong-host
|
||||
# cross-wire would otherwise surface only as an opaque write-404 with zero
|
||||
# residue.
|
||||
gitea_resolve_api_for_login() {
|
||||
local effective_login="$1" override_explicit="${2:-}" host configured_url repo
|
||||
local preflight_auth_config preflight_status
|
||||
|
||||
host=$(get_remote_host)
|
||||
if [[ -n "$HOST_OVERRIDE" ]]; then
|
||||
host="$HOST_OVERRIDE"
|
||||
else
|
||||
host=$(get_remote_host)
|
||||
fi
|
||||
if [[ -n "$override_explicit" ]]; then
|
||||
GITEA_API_TOKEN=$(get_gitea_token_for_login "$effective_login" "$host") || {
|
||||
echo "Error: could not resolve a host-matched Gitea token for --login '$effective_login' on host '$host'; refusing to fall back to the host default identity or a cross-host credential (review write/read-back)" >&2
|
||||
@@ -265,10 +313,14 @@ gitea_resolve_api_for_login() {
|
||||
echo "Error: Configured Gitea URL not found for review read-back verification" >&2
|
||||
return 1
|
||||
}
|
||||
repo=$(get_gitea_repo_slug_for_url "$configured_url") || {
|
||||
echo "Error: Could not resolve Gitea owner/repository relative to configured URL" >&2
|
||||
return 1
|
||||
}
|
||||
if [[ -n "$REPO_OVERRIDE" ]]; then
|
||||
repo="$REPO_OVERRIDE"
|
||||
else
|
||||
repo=$(get_gitea_repo_slug_for_url "$configured_url") || {
|
||||
echo "Error: Could not resolve Gitea owner/repository relative to configured URL" >&2
|
||||
return 1
|
||||
}
|
||||
fi
|
||||
GITEA_API_ROOT="${configured_url%/}/api/v1"
|
||||
GITEA_API_BASE="$GITEA_API_ROOT/repos/$repo"
|
||||
# The provider WEB base (scheme + host + effective port + any deployment path
|
||||
@@ -276,6 +328,22 @@ gitea_resolve_api_for_login() {
|
||||
# Read-back verification pins the returned URL's origin + path prefix to THIS,
|
||||
# not just a repo/PR suffix.
|
||||
GITEA_WEB_BASE="${configured_url%/}"
|
||||
|
||||
if [[ -n "$REPO_OVERRIDE" ]]; then
|
||||
preflight_auth_config=$(gitea_write_auth_config "$GITEA_API_TOKEN") || {
|
||||
echo "Error: could not stage Gitea credential for --repo preflight" >&2
|
||||
return 1
|
||||
}
|
||||
preflight_status=$(curl -sS -o /dev/null -w '%{http_code}' \
|
||||
--config "$preflight_auth_config" \
|
||||
-H 'User-Agent: mosaic-pr-review' \
|
||||
"$GITEA_API_BASE") || preflight_status="000"
|
||||
rm -f "$preflight_auth_config"
|
||||
if [[ "$preflight_status" != "200" ]]; then
|
||||
echo "Error: repo '$repo' not reachable at $configured_url (HTTP $preflight_status) — wrong host? pass -H/--host <gitea-host> or cd into the target checkout" >&2
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
@@ -296,6 +364,7 @@ gitea_authenticated_login() {
|
||||
|
||||
if ! status=$(curl -sS -o "$response_file" -w '%{http_code}' \
|
||||
--config "$auth_config" \
|
||||
-H 'User-Agent: mosaic-pr-review' \
|
||||
"$GITEA_API_ROOT/user"); then
|
||||
echo "Error: Gitea authenticated-identity read transport failed" >&2
|
||||
return 1
|
||||
@@ -332,6 +401,7 @@ gitea_read_pr_head_into() {
|
||||
|
||||
if ! status=$(curl -sS -o "$pr_file" -w '%{http_code}' \
|
||||
--config "$auth_config" \
|
||||
-H 'User-Agent: mosaic-pr-review' \
|
||||
"$GITEA_API_BASE/pulls/$pr_number"); then
|
||||
echo "Error: Gitea PR head read transport failed" >&2
|
||||
return 1
|
||||
@@ -418,6 +488,7 @@ print(json.dumps({
|
||||
if ! write_status=$(curl -sS -o "$write_file" -w '%{http_code}' \
|
||||
-X POST \
|
||||
--config "$auth_config" \
|
||||
-H 'User-Agent: mosaic-pr-review' \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d "$payload" \
|
||||
"$GITEA_API_BASE/pulls/$pr_number/reviews"); then
|
||||
@@ -449,6 +520,7 @@ PY
|
||||
|
||||
if ! readback_status=$(curl -sS -o "$readback_file" -w '%{http_code}' \
|
||||
--config "$auth_config" \
|
||||
-H 'User-Agent: mosaic-pr-review' \
|
||||
"$GITEA_API_BASE/pulls/$pr_number/reviews/$created_id"); then
|
||||
echo "Error: Gitea review read-back transport failed" >&2
|
||||
return 1
|
||||
@@ -557,7 +629,14 @@ if [[ "$PLATFORM" == "github" ]]; then
|
||||
elif [[ "$PLATFORM" == "gitea" ]]; then
|
||||
case $ACTION in
|
||||
approve)
|
||||
host=$(get_remote_host)
|
||||
# Best-effort host for the tea-login GUESS only (gitea_resolve_api_for_login
|
||||
# below re-derives the real host from HOST_OVERRIDE/remote independently and
|
||||
# is authoritative). Prefer an explicit -H/--host; otherwise best-effort
|
||||
# git-remote inference, tolerating its ABSENCE (a bare `get_remote_host` here
|
||||
# under `set -e`, with no origin and no -H, previously killed the script
|
||||
# SILENTLY — exit 1, zero output — even though -r/-H are exactly the flags
|
||||
# that support running with no usable origin at all).
|
||||
host="${HOST_OVERRIDE:-$(get_remote_host 2>/dev/null || true)}"
|
||||
# A --login override always wins. Otherwise name this host's login
|
||||
# only as a best effort: the login name merely selects a per-login
|
||||
# token, and gitea_resolve_api_for_login falls back to the host
|
||||
@@ -587,7 +666,14 @@ elif [[ "$PLATFORM" == "gitea" ]]; then
|
||||
echo "Error: Comment required for request-changes"
|
||||
exit 1
|
||||
fi
|
||||
host=$(get_remote_host)
|
||||
# Best-effort host for the tea-login GUESS only (gitea_resolve_api_for_login
|
||||
# below re-derives the real host from HOST_OVERRIDE/remote independently and
|
||||
# is authoritative). Prefer an explicit -H/--host; otherwise best-effort
|
||||
# git-remote inference, tolerating its ABSENCE (a bare `get_remote_host` here
|
||||
# under `set -e`, with no origin and no -H, previously killed the script
|
||||
# SILENTLY — exit 1, zero output — even though -r/-H are exactly the flags
|
||||
# that support running with no usable origin at all).
|
||||
host="${HOST_OVERRIDE:-$(get_remote_host 2>/dev/null || true)}"
|
||||
# A --login override always wins. Otherwise name this host's login
|
||||
# only as a best effort: the login name merely selects a per-login
|
||||
# token, and gitea_resolve_api_for_login falls back to the host
|
||||
@@ -611,7 +697,14 @@ elif [[ "$PLATFORM" == "gitea" ]]; then
|
||||
echo "Error: Comment required"
|
||||
exit 1
|
||||
fi
|
||||
host=$(get_remote_host)
|
||||
# Best-effort host for the tea-login GUESS only (gitea_resolve_api_for_login
|
||||
# below re-derives the real host from HOST_OVERRIDE/remote independently and
|
||||
# is authoritative). Prefer an explicit -H/--host; otherwise best-effort
|
||||
# git-remote inference, tolerating its ABSENCE (a bare `get_remote_host` here
|
||||
# under `set -e`, with no origin and no -H, previously killed the script
|
||||
# SILENTLY — exit 1, zero output — even though -r/-H are exactly the flags
|
||||
# that support running with no usable origin at all).
|
||||
host="${HOST_OVERRIDE:-$(get_remote_host 2>/dev/null || true)}"
|
||||
# A --login override always wins. Otherwise name this host's login
|
||||
# only as a best effort: the login name merely selects a per-login
|
||||
# token, and gitea_resolve_api_for_login falls back to the host
|
||||
|
||||
323
packages/mosaic/framework/tools/git/test-pr-review-repo-host-override.sh
Executable file
323
packages/mosaic/framework/tools/git/test-pr-review-repo-host-override.sh
Executable file
@@ -0,0 +1,323 @@
|
||||
#!/usr/bin/env bash
|
||||
# Regression harness for pr-review.sh's -r/--repo and -H/--host overrides,
|
||||
# the -r repo-exists preflight, and the mosaic-pr-review User-Agent header
|
||||
# (patch family 5/5c, part of #891).
|
||||
#
|
||||
# -r/--repo and -H/--host skip git-remote slug/host inference entirely, for
|
||||
# reviewer worktrees whose origin is nonstandard, wrong, or missing (mirrors
|
||||
# the -r convention of the sibling wrappers pr-view.sh/pr-diff.sh/pr-ci-wait.sh,
|
||||
# #867). When -r is given, the resolved repo is preflighted (GET
|
||||
# .../repos/<slug>) BEFORE any write, so a wrong-host cross-wire surfaces as a
|
||||
# clear preflight error instead of an opaque write-404. Every Gitea curl call
|
||||
# (preflight, write, read-back, /user, PR-head) must carry a
|
||||
# `User-Agent: mosaic-pr-review` header, since some Cloudflare-fronted Gitea
|
||||
# hosts intermittently reject curl's default User-Agent.
|
||||
#
|
||||
# Round 2 (post-review): the approve/request-changes/comment dispatch bodies
|
||||
# each independently called a BARE `host=$(get_remote_host)` (only for a
|
||||
# best-effort tea-login guess) that ignored -H/--host entirely and, under
|
||||
# `set -e`, DIED SILENTLY (exit 1, zero stdout/stderr) whenever no git origin
|
||||
# existed — exactly the case -r/-H exist to support. The "no git origin at
|
||||
# all" fixture below must be a directory TRULY outside any .git ancestry (a
|
||||
# subdirectory with no .git of its own still resolves `git remote get-url
|
||||
# origin` UPWARD to an enclosing repo's origin — a real flaw in the first
|
||||
# version of this fixture, since the test tree itself sits inside the
|
||||
# mosaicstack/stack checkout). It is created via `mktemp -d` under the SYSTEM
|
||||
# /tmp and additionally bounded with GIT_CEILING_DIRECTORIES, so `git rev-parse
|
||||
# --show-toplevel`/`git remote get-url origin` cannot walk past it under any
|
||||
# circumstance.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
WORK_DIR="${MOSAIC_TEST_WORK_DIR:-$PWD/.mosaic-test-work/pr-review-repo-host-override}"
|
||||
BIN_DIR="$WORK_DIR/bin"
|
||||
STATE_DIR="$WORK_DIR/state"
|
||||
CURL_LOG="$WORK_DIR/curl.log"
|
||||
UA_LOG="$WORK_DIR/ua.log"
|
||||
OUTPUT_FILE="$WORK_DIR/output.log"
|
||||
TMP_SCRATCH="$WORK_DIR/scratch"
|
||||
CREDENTIALS_FILE="$WORK_DIR/credentials.json"
|
||||
# A TRUE no-git-origin fixture: created under the system /tmp (NOT under
|
||||
# $WORK_DIR, which sits inside this very checkout's .git ancestry), so that
|
||||
# `git remote get-url origin` run from inside it cannot resolve upward to the
|
||||
# mosaicstack/stack checkout's own real origin.
|
||||
NO_GIT_DIR="$(mktemp -d "${TMPDIR:-/tmp}/pr-review-no-origin.XXXXXX")"
|
||||
|
||||
cleanup() {
|
||||
rm -rf "$WORK_DIR" "$NO_GIT_DIR"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
HOST_OVERRIDE_VAL="pr-review-override.test"
|
||||
REPO_OVERRIDE_VAL="acme/widgets"
|
||||
TOKEN_VAL="override-token-xyz"
|
||||
ACTING_LOGIN="override-bot"
|
||||
HEAD_SHA_VAL="feedfacecafebabe0000000000000000000000"
|
||||
|
||||
mkdir -p "$BIN_DIR" "$STATE_DIR" "$TMP_SCRATCH"
|
||||
|
||||
# tea stub: deterministic tea-absent behavior regardless of whether the host
|
||||
# actually has a real `tea` binary on PATH. -r/--repo + -H/--host must not
|
||||
# NEED a resolvable tea login to work — the wrapper falls back to the
|
||||
# host-scoped GITEA_TOKEN credential when no tea login resolves.
|
||||
cat > "$BIN_DIR/tea" <<'SH'
|
||||
#!/usr/bin/env bash
|
||||
exit 1
|
||||
SH
|
||||
chmod +x "$BIN_DIR/tea"
|
||||
|
||||
# curl stub: models the target Gitea instance for the OVERRIDDEN host/repo
|
||||
# only. Any request to a DIFFERENT host/repo (i.e. one derived from git-remote
|
||||
# inference instead of the override) is unexpected and fails the run.
|
||||
cat > "$BIN_DIR/curl" <<SH
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
output_file=""
|
||||
method="GET"
|
||||
payload=""
|
||||
url=""
|
||||
config_file=""
|
||||
ua_seen="0"
|
||||
while [[ \$# -gt 0 ]]; do
|
||||
case "\$1" in
|
||||
-o) output_file="\$2"; shift 2 ;;
|
||||
-H)
|
||||
[[ "\$2" == "User-Agent: mosaic-pr-review" ]] && ua_seen="1"
|
||||
shift 2 ;;
|
||||
-K|--config) config_file="\$2"; shift 2 ;;
|
||||
-w) shift 2 ;;
|
||||
-X) shift 2 ;;
|
||||
-d|--data) payload="\$2"; shift 2 ;;
|
||||
-s|-S|-sS) shift ;;
|
||||
http://*|https://*) url="\$1"; shift ;;
|
||||
*) shift ;;
|
||||
esac
|
||||
done
|
||||
|
||||
printf '%s %s\n' "\$method" "\$url" >> "$CURL_LOG"
|
||||
printf '%s %s\n' "\$ua_seen" "\$url" >> "$UA_LOG"
|
||||
|
||||
write_response() {
|
||||
local status="\$1" body="\$2"
|
||||
[[ -n "\$output_file" ]] || exit 96
|
||||
printf '%s' "\$body" > "\$output_file"
|
||||
printf '%s' "\$status"
|
||||
}
|
||||
|
||||
mode="\$(cat "$STATE_DIR/mode" 2>/dev/null || true)"
|
||||
web_base="https://$HOST_OVERRIDE_VAL"
|
||||
repo="$REPO_OVERRIDE_VAL"
|
||||
|
||||
case "\$url" in
|
||||
"https://$HOST_OVERRIDE_VAL/api/v1/repos/$REPO_OVERRIDE_VAL")
|
||||
if [[ "\$mode" == "repo-missing" ]]; then
|
||||
write_response 404 '{"message":"not found"}'
|
||||
else
|
||||
write_response 200 "{\\"full_name\\":\\"$REPO_OVERRIDE_VAL\\"}"
|
||||
fi
|
||||
;;
|
||||
"https://$HOST_OVERRIDE_VAL/api/v1/user")
|
||||
write_response 200 "{\\"login\\":\\"$ACTING_LOGIN\\"}"
|
||||
;;
|
||||
"https://$HOST_OVERRIDE_VAL/api/v1/repos/$REPO_OVERRIDE_VAL/pulls/123")
|
||||
write_response 200 "{\\"head\\":{\\"sha\\":\\"$HEAD_SHA_VAL\\"}}"
|
||||
;;
|
||||
"https://$HOST_OVERRIDE_VAL/api/v1/repos/$REPO_OVERRIDE_VAL/pulls/123/reviews")
|
||||
PR_REVIEW_PAYLOAD="\$payload" PR_REVIEW_ACTING="$ACTING_LOGIN" \
|
||||
python3 -c '
|
||||
import json, os
|
||||
p = json.loads(os.environ["PR_REVIEW_PAYLOAD"])
|
||||
record = {
|
||||
"id": 501,
|
||||
"state": p.get("event"),
|
||||
"commit_id": p.get("commit_id"),
|
||||
"body": p.get("body"),
|
||||
"user": {"login": os.environ["PR_REVIEW_ACTING"]},
|
||||
}
|
||||
with open("$STATE_DIR/review.json", "w", encoding="utf-8") as fh:
|
||||
json.dump(record, fh)
|
||||
'
|
||||
write_response 201 "\$(cat "$STATE_DIR/review.json")"
|
||||
;;
|
||||
"https://$HOST_OVERRIDE_VAL/api/v1/repos/$REPO_OVERRIDE_VAL/pulls/123/reviews/501")
|
||||
write_response 200 "\$(cat "$STATE_DIR/review.json")"
|
||||
;;
|
||||
"https://$HOST_OVERRIDE_VAL/api/v1/repos/$REPO_OVERRIDE_VAL/issues/123/comments")
|
||||
write_response 201 "{\\"id\\":456,\\"body\\":\\"durable-body\\",\\"user\\":{\\"login\\":\\"$ACTING_LOGIN\\"},\\"issue_url\\":\\"\\",\\"pull_request_url\\":\\"\${web_base}/\${repo}/pulls/123\\"}"
|
||||
;;
|
||||
"https://$HOST_OVERRIDE_VAL/api/v1/repos/$REPO_OVERRIDE_VAL/issues/comments/456")
|
||||
write_response 200 "{\\"id\\":456,\\"body\\":\\"durable-body\\",\\"user\\":{\\"login\\":\\"$ACTING_LOGIN\\"},\\"issue_url\\":\\"\\",\\"pull_request_url\\":\\"\${web_base}/\${repo}/pulls/123\\"}"
|
||||
;;
|
||||
*)
|
||||
echo "Unexpected curl request (host/repo not from the override — inference leaked through?): \$method \$url" >&2
|
||||
exit 97
|
||||
;;
|
||||
esac
|
||||
SH
|
||||
chmod +x "$BIN_DIR/curl"
|
||||
|
||||
run() {
|
||||
local repo_dir="$1"; shift
|
||||
: > "$CURL_LOG"
|
||||
: > "$UA_LOG"
|
||||
: > "$OUTPUT_FILE"
|
||||
(
|
||||
cd "$repo_dir"
|
||||
PATH="$BIN_DIR:$PATH" \
|
||||
TMPDIR="$TMP_SCRATCH" \
|
||||
MOSAIC_CREDENTIALS_FILE="$CREDENTIALS_FILE" \
|
||||
GITEA_TOKEN="$TOKEN_VAL" \
|
||||
GITEA_URL="https://$HOST_OVERRIDE_VAL" \
|
||||
GIT_CEILING_DIRECTORIES="$(dirname "$NO_GIT_DIR")" \
|
||||
"$SCRIPT_DIR/pr-review.sh" "$@"
|
||||
) > "$OUTPUT_FILE" 2>&1
|
||||
}
|
||||
|
||||
set_mode() {
|
||||
printf '%s' "$1" > "$STATE_DIR/mode"
|
||||
}
|
||||
|
||||
# A run must not silently die: exit 1 with a COMPLETELY EMPTY combined
|
||||
# stdout+stderr is precisely the pre-fix signature of the dispatch-level bare
|
||||
# `host=$(get_remote_host)` call dying under `set -e` when there was no git
|
||||
# origin at all. Whatever the outcome, the wrapper must always emit SOME
|
||||
# diagnostic (success line, or an "Error: ..." line).
|
||||
assert_not_silently_dead() {
|
||||
local context="$1" exit_code="$2"
|
||||
if [[ "$exit_code" -ne 0 && ! -s "$OUTPUT_FILE" ]]; then
|
||||
echo "FAIL: pr-review.sh died SILENTLY (exit $exit_code, zero output) in a true no-origin dir ($context)" >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Sanity-check the fixture itself BEFORE relying on it: from inside NO_GIT_DIR,
|
||||
# `git remote get-url origin` must fail outright — proving this directory is
|
||||
# truly outside any .git ancestry (the flaw this harness had before: a bare
|
||||
# subdirectory of the checkout resolves `origin` UPWARD to the checkout's own
|
||||
# real remote instead of failing).
|
||||
if (cd "$NO_GIT_DIR" && GIT_CEILING_DIRECTORIES="$(dirname "$NO_GIT_DIR")" git remote get-url origin) 2>/dev/null; then
|
||||
echo "FAIL: NO_GIT_DIR fixture is not actually outside any git ancestry — 'git remote get-url origin' resolved upward" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# --- Case 1: -r/--repo and -H/--host are recognized flags (regression lock on
|
||||
# the previous "Unknown option: -r" / "Unknown option: -H" failure). Use a
|
||||
# bogus ACTION so the run fails cheaply, WITHOUT any network I/O, at the
|
||||
# platform-dispatch unknown-action branch rather than at argument parsing —
|
||||
# proving both flags were consumed as options, not rejected.
|
||||
set_mode "repo-ok"
|
||||
if run "$NO_GIT_DIR" -n 123 -a bogus-action -r "$REPO_OVERRIDE_VAL" -H "$HOST_OVERRIDE_VAL"; then
|
||||
echo "FAIL: bogus action unexpectedly succeeded" >&2
|
||||
cat "$OUTPUT_FILE" >&2
|
||||
exit 1
|
||||
fi
|
||||
if grep -q 'Unknown option' "$OUTPUT_FILE"; then
|
||||
echo "FAIL: -r/--repo or -H/--host was not recognized as a valid flag" >&2
|
||||
cat "$OUTPUT_FILE" >&2
|
||||
exit 1
|
||||
fi
|
||||
grep -q 'Unknown action: bogus-action' "$OUTPUT_FILE"
|
||||
|
||||
# --- Case 2: -h/--help documents both overrides.
|
||||
HELP_TEXT="$("$SCRIPT_DIR/pr-review.sh" -h)"
|
||||
echo "$HELP_TEXT" | grep -q -- '-r, --repo'
|
||||
echo "$HELP_TEXT" | grep -q -- '-H, --host'
|
||||
|
||||
# --- Case 3 (comment): a TRUE no-git-origin dir + -r/-H must not silently die
|
||||
# and must not fail with "not a git repository or no origin remote" either.
|
||||
set_mode "repo-ok"
|
||||
comment_rc=0
|
||||
run "$NO_GIT_DIR" -n 123 -a comment -c durable-body -r "$REPO_OVERRIDE_VAL" -H "$HOST_OVERRIDE_VAL" || comment_rc=$?
|
||||
assert_not_silently_dead "comment" "$comment_rc"
|
||||
if grep -qi 'not a git repository or no origin remote' "$OUTPUT_FILE"; then
|
||||
echo "FAIL: -r/--repo did not tolerate a missing git origin" >&2
|
||||
cat "$OUTPUT_FILE" >&2
|
||||
exit 1
|
||||
fi
|
||||
grep -q 'Added and verified comment on Gitea PR #123' "$OUTPUT_FILE"
|
||||
|
||||
# --- Case 3b (approve): same true no-origin dir, the `approve` dispatch body
|
||||
# (its OWN, previously-unguarded `host=$(get_remote_host)` call) must not
|
||||
# silently die either.
|
||||
set_mode "repo-ok"
|
||||
approve_rc=0
|
||||
run "$NO_GIT_DIR" -n 123 -a approve -r "$REPO_OVERRIDE_VAL" -H "$HOST_OVERRIDE_VAL" || approve_rc=$?
|
||||
assert_not_silently_dead "approve" "$approve_rc"
|
||||
if grep -qi 'not a git repository or no origin remote' "$OUTPUT_FILE"; then
|
||||
echo "FAIL: approve's -r/--repo did not tolerate a missing git origin" >&2
|
||||
cat "$OUTPUT_FILE" >&2
|
||||
exit 1
|
||||
fi
|
||||
grep -q 'Approved and verified Gitea PR #123 (review ID 501)' "$OUTPUT_FILE"
|
||||
|
||||
# --- Case 3c (request-changes): same true no-origin dir, the
|
||||
# `request-changes` dispatch body's OWN previously-unguarded
|
||||
# `host=$(get_remote_host)` call must not silently die either.
|
||||
set_mode "repo-ok"
|
||||
request_changes_rc=0
|
||||
run "$NO_GIT_DIR" -n 123 -a request-changes -c please-fix -r "$REPO_OVERRIDE_VAL" -H "$HOST_OVERRIDE_VAL" || request_changes_rc=$?
|
||||
assert_not_silently_dead "request-changes" "$request_changes_rc"
|
||||
if grep -qi 'not a git repository or no origin remote' "$OUTPUT_FILE"; then
|
||||
echo "FAIL: request-changes's -r/--repo did not tolerate a missing git origin" >&2
|
||||
cat "$OUTPUT_FILE" >&2
|
||||
exit 1
|
||||
fi
|
||||
grep -q 'Requested changes and verified on Gitea PR #123 (review ID 501)' "$OUTPUT_FILE"
|
||||
|
||||
# --- Case 4: -r/--repo and -H/--host WIN over git-remote inference, not just
|
||||
# tolerate its absence — set up a real git repo whose origin points at a
|
||||
# COMPLETELY DIFFERENT host/repo and confirm the override, not the remote, is
|
||||
# what gets used (the curl stub only answers for the override host/repo; any
|
||||
# request derived from the wrong remote is an unexpected request and fails
|
||||
# the stub with exit 97).
|
||||
WRONG_REMOTE_DIR="$WORK_DIR/wrong-remote-repo"
|
||||
mkdir -p "$WRONG_REMOTE_DIR"
|
||||
git -C "$WRONG_REMOTE_DIR" init -q
|
||||
git -C "$WRONG_REMOTE_DIR" remote add origin https://git.wrong-inferred-host.example/wrong/repo.git
|
||||
set_mode "repo-ok"
|
||||
run "$WRONG_REMOTE_DIR" -n 123 -a comment -c durable-body -r "$REPO_OVERRIDE_VAL" -H "$HOST_OVERRIDE_VAL"
|
||||
grep -q 'Added and verified comment on Gitea PR #123' "$OUTPUT_FILE"
|
||||
if grep -q 'wrong-inferred-host' "$CURL_LOG"; then
|
||||
echo "FAIL: -r/--repo + -H/--host did not override git-remote inference" >&2
|
||||
cat "$CURL_LOG" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# --- Case 5 (5c): the repo-exists preflight runs BEFORE any write and fails
|
||||
# closed with a clear diagnostic when the resolved repo is unreachable at the
|
||||
# resolved host — proving a wrong-host cross-wire surfaces here, not as an
|
||||
# opaque write-404.
|
||||
set_mode "repo-missing"
|
||||
if run "$NO_GIT_DIR" -n 123 -a comment -c durable-body -r "$REPO_OVERRIDE_VAL" -H "$HOST_OVERRIDE_VAL"; then
|
||||
echo "FAIL: preflight did not fail closed on a missing repo" >&2
|
||||
cat "$OUTPUT_FILE" >&2
|
||||
exit 1
|
||||
fi
|
||||
grep -q "repo '$REPO_OVERRIDE_VAL' not reachable" "$OUTPUT_FILE"
|
||||
if grep -q '/issues/123/comments' "$CURL_LOG"; then
|
||||
echo "FAIL: wrapper posted a comment despite a failed repo preflight" >&2
|
||||
cat "$CURL_LOG" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# --- Case 6 (5): every Gitea curl call (preflight, /user, comment write,
|
||||
# comment read-back) carries the User-Agent: mosaic-pr-review header.
|
||||
set_mode "repo-ok"
|
||||
run "$NO_GIT_DIR" -n 123 -a comment -c durable-body -r "$REPO_OVERRIDE_VAL" -H "$HOST_OVERRIDE_VAL"
|
||||
grep -q 'Added and verified comment on Gitea PR #123' "$OUTPUT_FILE"
|
||||
call_count="$(wc -l < "$CURL_LOG" | tr -d ' ')"
|
||||
ua_count="$(awk '$1 == "1"' "$UA_LOG" | wc -l | tr -d ' ')"
|
||||
if [[ "$call_count" -lt 4 ]]; then
|
||||
echo "FAIL: expected at least 4 curl calls (preflight, /user, write, read-back), got $call_count" >&2
|
||||
cat "$CURL_LOG" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ "$ua_count" != "$call_count" ]]; then
|
||||
echo "FAIL: not every curl call carried User-Agent: mosaic-pr-review ($ua_count/$call_count)" >&2
|
||||
cat "$UA_LOG" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "pr-review.sh -r/--repo + -H/--host override + preflight + User-Agent regression passed"
|
||||
@@ -25,7 +25,7 @@
|
||||
"lint": "eslint src",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run --passWithNoTests && pnpm run test:framework-shell",
|
||||
"test:framework-shell": "python3 src/lease-broker/daemon_deadline_unittest.py && python3 src/lease-broker/normative_fragments_unittest.py && python3 src/lease-broker/receipt_challenge_unittest.py && python3 src/lease-broker/context_recovery_unittest.py && python3 src/lease-broker/recovery_runtime_unittest.py && python3 src/lease-broker/recovery_b1_adversarial_unittest.py && python3 src/lease-broker/framework_skill_portability_unittest.py && python3 src/mutator-gate/runtime_tools_unittest.py && python3 src/mutator-gate/runtime_launch_guard_unittest.py && python3 src/mutator-gate/version_coupling_unittest.py && python3 framework/tools/lease-broker/check-runtime-launches.py --root ../.. && bash framework/tools/codex/test-pr-diff-context.sh && bash framework/tools/qa/test-deps-preflight.sh && bash framework/tools/git/test-pr-review-gitea-comment.sh && bash framework/tools/git/test-ci-queue-wait-branch-absent.sh && bash framework/tools/git/test-git-credential-mosaic.sh && bash framework/tools/git/test-gitea-token-identity.sh && bash framework/tools/_scripts/test-install-ordering-guard.sh"
|
||||
"test:framework-shell": "python3 src/lease-broker/daemon_deadline_unittest.py && python3 src/lease-broker/normative_fragments_unittest.py && python3 src/lease-broker/receipt_challenge_unittest.py && python3 src/lease-broker/context_recovery_unittest.py && python3 src/lease-broker/recovery_runtime_unittest.py && python3 src/lease-broker/recovery_b1_adversarial_unittest.py && python3 src/lease-broker/framework_skill_portability_unittest.py && python3 src/mutator-gate/runtime_tools_unittest.py && python3 src/mutator-gate/runtime_launch_guard_unittest.py && python3 src/mutator-gate/version_coupling_unittest.py && python3 framework/tools/lease-broker/check-runtime-launches.py --root ../.. && bash framework/tools/codex/test-pr-diff-context.sh && bash framework/tools/qa/test-deps-preflight.sh && bash framework/tools/git/test-pr-review-gitea-comment.sh && bash framework/tools/git/test-pr-review-repo-host-override.sh && bash framework/tools/git/test-ci-queue-wait-branch-absent.sh && bash framework/tools/git/test-git-credential-mosaic.sh && bash framework/tools/git/test-gitea-token-identity.sh && bash framework/tools/_scripts/test-install-ordering-guard.sh"
|
||||
},
|
||||
"dependencies": {
|
||||
"@mosaicstack/brain": "workspace:*",
|
||||
|
||||
@@ -51,8 +51,13 @@ def request(socket_path: Path, value: dict[str, object]) -> dict[str, object]:
|
||||
def wait_ready(process: subprocess.Popen[str], socket_path: Path) -> None:
|
||||
deadline = time.monotonic() + 5.0
|
||||
while time.monotonic() < deadline:
|
||||
if socket_path.exists():
|
||||
try:
|
||||
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as probe:
|
||||
probe.settimeout(0.25)
|
||||
probe.connect(str(socket_path))
|
||||
return
|
||||
except (ConnectionRefusedError, FileNotFoundError):
|
||||
pass
|
||||
if process.poll() is not None:
|
||||
output = process.stdout.read() if process.stdout is not None else ""
|
||||
raise RuntimeError(f"daemon exited before READY: {output}")
|
||||
|
||||
@@ -62,8 +62,13 @@ def request(socket_path: Path, value: dict[str, object]) -> dict[str, object]:
|
||||
def wait_ready(process: subprocess.Popen[str], socket_path: Path) -> None:
|
||||
deadline = time.monotonic() + 5.0
|
||||
while time.monotonic() < deadline:
|
||||
if socket_path.exists():
|
||||
try:
|
||||
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as probe:
|
||||
probe.settimeout(0.25)
|
||||
probe.connect(str(socket_path))
|
||||
return
|
||||
except (ConnectionRefusedError, FileNotFoundError):
|
||||
pass
|
||||
if process.poll() is not None:
|
||||
output = process.stdout.read() if process.stdout is not None else ""
|
||||
raise RuntimeError(f"daemon exited before READY: {output}")
|
||||
|
||||
Reference in New Issue
Block a user