Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions pm-stack/aggregator/src/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,17 @@ export const EVENT_CHAIN_GENESIS = "0".repeat(64);

const FIELD = /^[\w ./#:@-]+$/;

// Boundary guard (#7740): a writer that raw-sliced actor/summary at the
// 200/500 caps can hand validateStreamEvent a value whose last code unit
// is a lone high surrogate (the astral pair was split at the cap and the
// low half is already gone). Never persist that: drop the dangling half
// so the stored, hash-chained record round-trips through UTF-8 cleanly.
function dropLoneTrailingSurrogate(t: string): string {
if (t.length === 0) return t;
const c = t.charCodeAt(t.length - 1);
return c >= 0xd800 && c <= 0xdbff ? t.slice(0, -1) : t;
}

export function validateStreamEvent(e: unknown): { ok: true; value: StreamEvent } | { ok: false; error: string } {
if (typeof e !== "object" || e === null) return { ok: false, error: "event must be an object" };
const v = e as Record<string, unknown>;
Expand Down Expand Up @@ -194,10 +205,10 @@ export function validateStreamEvent(e: unknown): { ok: true; value: StreamEvent
ok: true,
value: {
at: v.at,
actor: (v.actor as string).trim(),
actor: dropLoneTrailingSurrogate((v.actor as string).trim()),
kind: (v.kind as string).trim(),
ref: (v.ref as string).trim(),
summary: v.summary.trim(),
summary: dropLoneTrailingSurrogate(v.summary.trim()),
},
};
}
Expand Down
23 changes: 19 additions & 4 deletions pm-stack/aggregator/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,20 @@ import {
type ForecastContract,
} from "./forecast-contract.ts";


// Cap `t` at `max` UTF-16 code units, but never leave half of a surrogate
// pair at the cut (#7740, mirroring the #7694-family capUnits guard): an
// astral character straddling the cap is dropped whole, so a persisted
// event field can never end in a lone high surrogate.
function capUnits(t: string, max: number): string {
if (t.length <= max) return t;
let end = max;
const before = t.charCodeAt(end - 1);
const after = t.charCodeAt(end);
if (before >= 0xd800 && before <= 0xdbff && after >= 0xdc00 && after <= 0xdfff) end--;
return t.slice(0, end);
}

const cfg = loadConfig();
const commentsStore = new CommentsStore(cfg.commentsFile);
const roadmapAnnotationsStore = new RoadmapAnnotationsStore(cfg.roadmapAnnotationsFile);
Expand Down Expand Up @@ -1319,13 +1333,14 @@ async function handler(req: Request): Promise<Response> {
// Fire-and-forget: the response never waits on, and is never
// failed by, the event append.
recordStreamEvent({
actor: updated.appliedByRun ?? body.byRun.slice(0, 200),
actor: updated.appliedByRun ?? capUnits(body.byRun, 200),
kind: body.outcome === "applied" ? "action-applied" : "action-rejected",
ref: updated.objectRef,
summary: (
summary: capUnits(
`${updated.kind}/${updated.verb} ${body.outcome} by ${body.byRun}` +
(typeof body.note === "string" && body.note ? ` — ${body.note}` : "")
).slice(0, 500),
(typeof body.note === "string" && body.note ? ` — ${body.note}` : ""),
500,
),
});
}
const updated = result?.action;
Expand Down
20 changes: 17 additions & 3 deletions pm-stack/aggregator/src/sources/live.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,20 @@ import { overlayQuotaCurrent, overlayTursoUsage, parseQuotaCurrent } from "../qu
import { SnapshotStore } from "../snapshots.ts";
import { gristDocUrl, kaneoTaskUrl } from "../service-links.ts";
import { fixtureSource } from "./fixtures.ts";

// Cap `t` at `max` UTF-16 code units, but never leave half of a surrogate
// pair at the cut (#7740, mirroring the #7694-family capUnits guard): an
// astral character straddling the cap is dropped whole, so a persisted
// event field can never end in a lone high surrogate.
function capUnits(t: string, max: number): string {
if (t.length <= max) return t;
let end = max;
const before = t.charCodeAt(end - 1);
const after = t.charCodeAt(end);
if (before >= 0xd800 && before <= 0xdbff && after >= 0xdc00 && after <= 0xdfff) end--;
return t.slice(0, end);
}

import { mapServerSessions, type MappedSessions } from "./opencode.ts";
import {
type AaFeedSection,
Expand Down Expand Up @@ -1069,7 +1083,7 @@ export function liveSource(
actor: "aggregator",
kind: "session-outcome",
ref: `session:${r.source}:${r.id}`,
summary: `session ${r.label} (${r.agentLabel}) merged into the registry`.slice(0, 500),
summary: capUnits(`session ${r.label} (${r.agentLabel}) merged into the registry`, 500),
});
} catch (err) {
console.error(
Expand Down Expand Up @@ -1634,7 +1648,7 @@ export function liveSource(
actor: "orchestrator",
kind: action.kind,
ref: orchestrationActionRef(action.target),
summary: action.summary.slice(0, 500),
summary: capUnits(action.summary, 500),
});
}
if (lastOrchEventRunId !== null) {
Expand All @@ -1647,7 +1661,7 @@ export function liveSource(
actor: "orchestrator",
kind: "tier-change",
ref: id,
summary: `tier ${prev ?? "—"} → ${tier ?? "—"} (run ${section.runId})`.slice(0, 500),
summary: capUnits(`tier ${prev ?? "—"} → ${tier ?? "—"} (run ${section.runId})`, 500),
});
}
}
Expand Down
90 changes: 90 additions & 0 deletions pm-stack/aggregator/test/events-surrogate-7740.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
// #7740: the event log's writers capped actor/summary with raw UTF-16
// slices at exactly the lengths validateStreamEvent enforces (200/500).
// An astral character straddling a writer's cap was split, the validator
// (length-only) passed it, and a lone high surrogate was persisted into
// the append-only, hash-chained event log. The five writer sites now use
// pair-safe capUnits (live.ts, server.ts), and validateStreamEvent drops
// a lone trailing surrogate at the boundary so no present or future
// writer can persist one. Oracle: the stored value never ends in a lone
// high surrogate and always round-trips through UTF-8 unchanged.
import { describe, expect, test } from "bun:test";
import { mkdtempSync, readFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { EventsStore, validateStreamEvent } from "../src/events.ts";

const EMOJI = "\u{1F600}"; // 😀 — one astral character, two UTF-16 units
const loneHighAtEnd = (s: string) => {
const c = s.charCodeAt(s.length - 1);
return c >= 0xd800 && c <= 0xdbff;
};
const roundTrips = (s: string) => Buffer.from(s, "utf8").toString("utf8") === s;
const at = new Date().toISOString();
const base = { at, actor: "drew", kind: "action-applied", ref: "gh:developing-today/code#7740", summary: "did a thing" };
// The writer shapes from the issue: raw slice at the cap, pair straddling.
const writerSummary = ("x".repeat(499) + EMOJI + "y".repeat(50)).slice(0, 500);
const writerActor = ("r".repeat(199) + EMOJI + "z".repeat(10)).slice(0, 200);

describe("#7740 validateStreamEvent boundary guard is surrogate-pair-safe", () => {
test("precondition: the writer shapes really do end in a lone high surrogate", () => {
expect(writerSummary.length).toBe(500);
expect(loneHighAtEnd(writerSummary)).toBe(true);
expect(writerActor.length).toBe(200);
expect(loneHighAtEnd(writerActor)).toBe(true);
});

test("summary straddling the 500 cap: dangling half dropped, value validates", () => {
const r = validateStreamEvent({ ...base, summary: writerSummary });
expect(r.ok).toBe(true);
if (!r.ok) return;
expect(r.value.summary.length).toBe(499);
expect(loneHighAtEnd(r.value.summary)).toBe(false);
expect(roundTrips(r.value.summary)).toBe(true);
});

test("actor straddling the 200 cap: dangling half dropped, value validates", () => {
const r = validateStreamEvent({ ...base, actor: writerActor });
expect(r.ok).toBe(true);
if (!r.ok) return;
expect(r.value.actor.length).toBe(199);
expect(loneHighAtEnd(r.value.actor)).toBe(false);
expect(roundTrips(r.value.actor)).toBe(true);
});

test("pair fully inside each cap stays intact (exact-fit controls)", () => {
const summary = "x".repeat(498) + EMOJI;
const actor = "r".repeat(198) + EMOJI;
const r = validateStreamEvent({ ...base, summary, actor });
expect(r.ok).toBe(true);
if (!r.ok) return;
expect(r.value.summary).toBe(summary);
expect(r.value.summary.length).toBe(500);
expect(r.value.actor).toBe(actor);
expect(r.value.actor.length).toBe(200);
});

test("under-cap values are unchanged", () => {
const r = validateStreamEvent({ ...base, summary: "plain summary 😀 ok", actor: "run-😀" });
expect(r.ok).toBe(true);
if (!r.ok) return;
expect(r.value.summary).toBe("plain summary 😀 ok");
expect(r.value.actor).toBe("run-😀");
});
});

describe("#7740 EventsStore never persists a lone surrogate", () => {
test("recording writer-shaped events persists clean values and a verifiable chain", async () => {
const dir = mkdtempSync(join(tmpdir(), "agg-events-surrogate-7740-"));
const file = join(dir, "events.json");
const store = new EventsStore(file);
const rec = await store.record({ ...base, actor: writerActor, summary: writerSummary });
expect(loneHighAtEnd(rec.summary)).toBe(false);
expect(loneHighAtEnd(rec.actor)).toBe(false);
expect(roundTrips(rec.summary)).toBe(true);
expect(roundTrips(rec.actor)).toBe(true);
const raw = readFileSync(file, "utf8");
expect(raw.includes("\\ud83d")).toBe(false);
const health = await store.health();
expect(health.integrity.ok).toBe(true);
});
});
Loading