From c2e1e9fccb206f6c29ad701f20759c43aa7198c7 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Thu, 20 Aug 2026 16:51:44 -0700 Subject: [PATCH 1/2] Add tests for @corbits/longevity-sim's campaign core --- packages/longevity-sim/src/config.test.ts | 66 +++++++++ packages/longevity-sim/src/metrics.test.ts | 112 ++++++++++++++ packages/longevity-sim/src/personas.test.ts | 59 ++++++++ packages/longevity-sim/src/plan.test.ts | 133 +++++++++++++++++ packages/longevity-sim/src/prng.test.ts | 49 +++++++ packages/longevity-sim/src/probes.test.ts | 69 +++++++++ packages/longevity-sim/src/report.test.ts | 153 ++++++++++++++++++++ 7 files changed, 641 insertions(+) create mode 100644 packages/longevity-sim/src/config.test.ts create mode 100644 packages/longevity-sim/src/metrics.test.ts create mode 100644 packages/longevity-sim/src/personas.test.ts create mode 100644 packages/longevity-sim/src/plan.test.ts create mode 100644 packages/longevity-sim/src/prng.test.ts create mode 100644 packages/longevity-sim/src/probes.test.ts create mode 100644 packages/longevity-sim/src/report.test.ts diff --git a/packages/longevity-sim/src/config.test.ts b/packages/longevity-sim/src/config.test.ts new file mode 100644 index 000000000..6baf3d7d2 --- /dev/null +++ b/packages/longevity-sim/src/config.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, test } from "bun:test"; +import { parseCampaignConfig } from "./config"; + +function validInput() { + return { + seed: 1, + targetMessages: 100, + checkpoints: [0, 50, 100], + threadReplyRate: 0.2, + mentionEvery: 10, + realTurnEvery: 15, + burstEvery: 20, + burstSize: 3, + simDaysPerCheckpointGap: 2, + restartAtMessages: [60], + providerSwitchAtMessages: [70], + skillEditAtMessages: [40], + spawnAgentAtMessages: [30], + }; +} + +describe("parseCampaignConfig", () => { + test("accepts a well-formed config", () => { + const config = parseCampaignConfig(validInput()); + expect(config.targetMessages).toBe(100); + expect(config.checkpoints).toEqual([0, 50, 100]); + }); + + test("rejects a config missing required fields", () => { + const { seed: _seed, ...rest } = validInput(); + expect(() => parseCampaignConfig(rest)).toThrow(); + }); + + test("rejects a threadReplyRate outside [0, 1]", () => { + expect(() => + parseCampaignConfig({ ...validInput(), threadReplyRate: 1.5 }), + ).toThrow(); + }); + + test("rejects a negative targetMessages", () => { + expect(() => + parseCampaignConfig({ ...validInput(), targetMessages: -5 }), + ).toThrow(); + }); + + test("rejects checkpoints that do not start at 0", () => { + expect(() => + parseCampaignConfig({ ...validInput(), checkpoints: [10, 50] }), + ).toThrow(/start at 0/); + }); + + test("rejects checkpoints that are not strictly ascending", () => { + expect(() => + parseCampaignConfig({ ...validInput(), checkpoints: [0, 50, 50] }), + ).toThrow(/ascending/); + }); + + test("error messages are readable, not raw arktype internals", () => { + try { + parseCampaignConfig({ ...validInput(), seed: "not-a-number" }); + throw new Error("expected parseCampaignConfig to throw"); + } catch (error) { + expect(String(error)).toContain("parseCampaignConfig"); + } + }); +}); diff --git a/packages/longevity-sim/src/metrics.test.ts b/packages/longevity-sim/src/metrics.test.ts new file mode 100644 index 000000000..622a0b7c2 --- /dev/null +++ b/packages/longevity-sim/src/metrics.test.ts @@ -0,0 +1,112 @@ +import { describe, expect, test } from "bun:test"; +import { findKnees, percentile, type CheckpointRecord } from "./metrics"; + +function checkpoint(overrides: Partial): CheckpointRecord { + return { + atMessages: 0, + wallClockMs: 0, + sendLatencyP50Ms: 0, + sendLatencyP95Ms: 0, + sendLatencyMaxMs: 0, + turnLatencyP50Ms: 0, + turnLatencyP95Ms: 0, + turnCount: 0, + firstTokenP50Ms: 0, + dbSizeBytes: 0, + messagePageMs: 0, + messagePageDeepMs: 0, + workbenchListMs: 0, + hubRssBytes: 0, + sidecarRssBytes: 0, + collectorFailures: 0, + routineFiresTotal: 0, + routineFiresAccepted: 0, + sendFailures: 0, + turnFailures: 0, + ...overrides, + }; +} + +describe("percentile", () => { + test("returns 0 for an empty array", () => { + expect(percentile([], 50)).toBe(0); + }); + + test("returns the single value for a one-element array", () => { + expect(percentile([42], 50)).toBe(42); + expect(percentile([42], 99)).toBe(42); + }); + + test("p50 of an even-length sorted array picks the lower-middle value", () => { + expect(percentile([10, 20, 30, 40], 50)).toBe(20); + }); + + test("p95 picks a high value near the tail", () => { + const values = Array.from({ length: 100 }, (_, i) => i + 1); + expect(percentile(values, 95)).toBe(95); + }); + + test("is order-independent", () => { + const sorted = [1, 2, 3, 4, 5]; + const shuffled = [3, 1, 5, 2, 4]; + expect(percentile(sorted, 50)).toBe(percentile(shuffled, 50)); + }); +}); + +describe("findKnees", () => { + test("finds no knees on a flat metric", () => { + const checkpoints = [ + checkpoint({ atMessages: 0, sendLatencyP50Ms: 100 }), + checkpoint({ atMessages: 100, sendLatencyP50Ms: 105 }), + checkpoint({ atMessages: 200, sendLatencyP50Ms: 98 }), + ]; + expect(findKnees(checkpoints)).toEqual([]); + }); + + test("finds a knee at the first checkpoint crossing the ratio threshold", () => { + const checkpoints = [ + checkpoint({ atMessages: 0, sendLatencyP50Ms: 50 }), + checkpoint({ atMessages: 100, sendLatencyP50Ms: 80 }), + checkpoint({ atMessages: 200, sendLatencyP50Ms: 200 }), + checkpoint({ atMessages: 300, sendLatencyP50Ms: 400 }), + ]; + const knees = findKnees(checkpoints); + const sendKnee = knees.find((knee) => knee.metric === "sendLatencyP50Ms"); + expect(sendKnee).toBeDefined(); + expect(sendKnee?.atMessages).toBe(200); + expect(sendKnee?.baseline).toBe(50); + }); + + test("uses the first nonzero checkpoint as baseline, skipping leading zeros", () => { + const checkpoints = [ + checkpoint({ atMessages: 0, dbSizeBytes: 0 }), + checkpoint({ atMessages: 100, dbSizeBytes: 1000 }), + checkpoint({ atMessages: 200, dbSizeBytes: 3500 }), + ]; + const knees = findKnees(checkpoints); + const dbKnee = knees.find((knee) => knee.metric === "dbSizeBytes"); + expect(dbKnee).toBeDefined(); + expect(dbKnee?.baseline).toBe(1000); + expect(dbKnee?.atMessages).toBe(200); + }); + + test("respects a custom ratio threshold", () => { + const checkpoints = [ + checkpoint({ atMessages: 0, workbenchListMs: 10 }), + checkpoint({ atMessages: 100, workbenchListMs: 15 }), + ]; + expect(findKnees(checkpoints, { ratioThreshold: 3 })).toEqual([]); + const knees = findKnees(checkpoints, { ratioThreshold: 1.4 }); + expect(knees.some((knee) => knee.metric === "workbenchListMs")).toBe(true); + }); + + test("ignores a metric that never becomes nonzero", () => { + const checkpoints = [ + checkpoint({ atMessages: 0, hubRssBytes: 0 }), + checkpoint({ atMessages: 100, hubRssBytes: 0 }), + ]; + expect( + findKnees(checkpoints).some((knee) => knee.metric === "hubRssBytes"), + ).toBe(false); + }); +}); diff --git a/packages/longevity-sim/src/personas.test.ts b/packages/longevity-sim/src/personas.test.ts new file mode 100644 index 000000000..af2a1edc1 --- /dev/null +++ b/packages/longevity-sim/src/personas.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, test } from "bun:test"; +import { createRng } from "./prng"; +import { SALES_TEAM, utterance } from "./personas"; + +describe("SALES_TEAM", () => { + test("has exactly 10 distinct personas", () => { + expect(SALES_TEAM).toHaveLength(10); + const keys = new Set(SALES_TEAM.map((persona) => persona.key)); + expect(keys.size).toBe(10); + }); + + test("every persona has topics and a positive cadence weight", () => { + for (const persona of SALES_TEAM) { + expect(persona.topics.length).toBeGreaterThan(0); + expect(persona.cadenceWeight).toBeGreaterThan(0); + } + }); + + test("no persona name or topic contains a known real company/person name", () => { + const banned = ["salesforce", "google", "microsoft", "acme corp"]; + for (const persona of SALES_TEAM) { + const haystack = [persona.name, ...persona.topics] + .join(" ") + .toLowerCase(); + for (const term of banned) { + expect(haystack).not.toContain(term); + } + } + }); +}); + +describe("utterance", () => { + test("is deterministic for the same persona, rng seed, and simDay", () => { + const persona = SALES_TEAM[0]; + if (persona === undefined) throw new Error("expected a persona"); + const a = utterance(persona, createRng(11), 3); + const b = utterance(persona, createRng(11), 3); + expect(a).toBe(b); + }); + + test("varies across draws for the same persona", () => { + const persona = SALES_TEAM[0]; + if (persona === undefined) throw new Error("expected a persona"); + const rng = createRng(5); + const draws = new Set( + Array.from({ length: 20 }, () => utterance(persona, rng, 1)), + ); + expect(draws.size).toBeGreaterThan(1); + }); + + test("every persona produces chatter mentioning one of its own topics", () => { + const rng = createRng(17); + for (const persona of SALES_TEAM) { + const text = utterance(persona, rng, 2); + expect(text.length).toBeGreaterThan(0); + expect(persona.topics.some((topic) => text.includes(topic))).toBe(true); + } + }); +}); diff --git a/packages/longevity-sim/src/plan.test.ts b/packages/longevity-sim/src/plan.test.ts new file mode 100644 index 000000000..a41c98992 --- /dev/null +++ b/packages/longevity-sim/src/plan.test.ts @@ -0,0 +1,133 @@ +import { describe, expect, test } from "bun:test"; +import { parseCampaignConfig, type CampaignConfig } from "./config"; +import { buildPlan, summarizePlan, type PlanStep } from "./plan"; + +function baseConfig(overrides: Partial = {}): CampaignConfig { + return parseCampaignConfig({ + seed: 123, + targetMessages: 300, + checkpoints: [0, 100, 200, 300], + threadReplyRate: 0.3, + mentionEvery: 12, + realTurnEvery: 25, + burstEvery: 40, + burstSize: 4, + simDaysPerCheckpointGap: 3, + restartAtMessages: [150], + providerSwitchAtMessages: [180], + skillEditAtMessages: [50, 210], + spawnAgentAtMessages: [90], + ...overrides, + }); +} + +function sayAndBurstSendCount(steps: readonly PlanStep[]): number { + return steps.reduce((count, step) => { + if (step.kind === "say") return count + 1; + if (step.kind === "burst") return count + step.sends.length; + if (step.kind === "realTurn") return count + 1; + return count; + }, 0); +} + +describe("buildPlan", () => { + test("is deterministic for the same seed", () => { + const config = baseConfig(); + expect(buildPlan(config)).toEqual(buildPlan(config)); + }); + + test("say + burst-send + realTurn count equals targetMessages", () => { + const config = baseConfig(); + const steps = buildPlan(config); + expect(sayAndBurstSendCount(steps)).toBe(config.targetMessages); + }); + + test("checkpoints appear exactly at their configured message counts, in order", () => { + const config = baseConfig(); + const steps = buildPlan(config); + const checkpointSteps = steps.filter( + (step): step is Extract => + step.kind === "checkpoint", + ); + expect(checkpointSteps.map((step) => step.atMessages)).toEqual( + config.checkpoints as number[], + ); + }); + + test("every skillEdit is followed later by its skillProbe with the same marker", () => { + const config = baseConfig(); + const steps = buildPlan(config); + const edits = steps + .map((step, index) => ({ step, index })) + .filter(({ step }) => step.kind === "skillEdit"); + expect(edits.length).toBe(config.skillEditAtMessages.length); + for (const { step, index } of edits) { + if (step.kind !== "skillEdit") continue; + const probeIndex = steps.findIndex( + (candidate) => + candidate.kind === "skillProbe" && candidate.marker === step.marker, + ); + expect(probeIndex).toBeGreaterThan(index); + } + }); + + test("refs are unique and every inReplyToRef names an earlier ref", () => { + const config = baseConfig(); + const steps = buildPlan(config); + const seenRefs = new Set(); + for (const step of steps) { + if (step.kind !== "say") continue; + if (step.inReplyToRef !== undefined) { + expect(seenRefs.has(step.inReplyToRef)).toBe(true); + } + if (step.ref !== undefined) { + expect(seenRefs.has(step.ref)).toBe(false); + seenRefs.add(step.ref); + } + } + expect(seenRefs.size).toBeGreaterThan(0); + }); + + test("places an event beyond targetMessages at the end", () => { + const config = baseConfig({ + targetMessages: 50, + checkpoints: [0, 50], + restartAtMessages: [500], + skillEditAtMessages: [], + spawnAgentAtMessages: [], + providerSwitchAtMessages: [], + }); + const steps = buildPlan(config); + const restart = steps.find((step) => step.kind === "restartHub"); + expect(restart).toBeDefined(); + if (restart?.kind === "restartHub") { + expect(restart.atMessages).toBe(50); + } + }); + + test("distributes says across personas rather than always picking one", () => { + const config = baseConfig(); + const steps = buildPlan(config); + const actors = new Set( + steps + .filter( + (step): step is Extract => + step.kind === "say", + ) + .map((step) => step.actor), + ); + expect(actors.size).toBeGreaterThan(1); + }); +}); + +describe("summarizePlan", () => { + test("matches manual counts over a built plan", () => { + const config = baseConfig(); + const steps = buildPlan(config); + const summary = summarizePlan(steps); + expect(summary.says + summary.burstSends).toBeLessThanOrEqual( + config.targetMessages, + ); + expect(summary.checkpoints).toEqual(config.checkpoints as number[]); + }); +}); diff --git a/packages/longevity-sim/src/prng.test.ts b/packages/longevity-sim/src/prng.test.ts new file mode 100644 index 000000000..0612b8d66 --- /dev/null +++ b/packages/longevity-sim/src/prng.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, test } from "bun:test"; +import { createRng, pick } from "./prng"; + +describe("createRng", () => { + test("is deterministic for a given seed", () => { + const a = createRng(42); + const b = createRng(42); + const seqA = Array.from({ length: 10 }, () => a()); + const seqB = Array.from({ length: 10 }, () => b()); + expect(seqA).toEqual(seqB); + }); + + test("differs across seeds", () => { + const a = createRng(1); + const b = createRng(2); + expect(a()).not.toBe(b()); + }); + + test("stays in [0, 1)", () => { + const rng = createRng(7); + for (let i = 0; i < 200; i++) { + const value = rng(); + expect(value).toBeGreaterThanOrEqual(0); + expect(value).toBeLessThan(1); + } + }); +}); + +describe("pick", () => { + test("only returns items from the input", () => { + const rng = createRng(3); + const items = ["a", "b", "c"] as const; + for (let i = 0; i < 50; i++) { + expect(items).toContain(pick(rng, items)); + } + }); + + test("throws on an empty list", () => { + const rng = createRng(3); + expect(() => pick(rng, [])).toThrow(); + }); + + test("is deterministic per rng state", () => { + const items = ["a", "b", "c", "d"] as const; + const first = pick(createRng(9), items); + const second = pick(createRng(9), items); + expect(first).toBe(second); + }); +}); diff --git a/packages/longevity-sim/src/probes.test.ts b/packages/longevity-sim/src/probes.test.ts new file mode 100644 index 000000000..51969f970 --- /dev/null +++ b/packages/longevity-sim/src/probes.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, test } from "bun:test"; + +import { countLogSignatures, parseRssKb } from "./probes"; + +describe("parseRssKb", () => { + test("parses a plain ps -o rss= reading into bytes", () => { + expect(parseRssKb("12345\n")).toBe(12345 * 1024); + }); + + test("trims surrounding whitespace", () => { + expect(parseRssKb(" 4096 \n")).toBe(4096 * 1024); + }); + + test("returns 0 for blank output", () => { + expect(parseRssKb("")).toBe(0); + expect(parseRssKb(" \n")).toBe(0); + }); + + test("returns 0 for unparseable output", () => { + expect(parseRssKb("not-a-number")).toBe(0); + }); +}); + +describe("countLogSignatures", () => { + test("counts every collector-failure signature", () => { + const log = [ + "info: boot ok", + "error: Failed to persist event id=1", + "error: turn_part insert failed id=2", + "error: Failed to persist event id=3", + ].join("\n"); + const counts = countLogSignatures(log); + expect(counts.collectorFailures).toBe(3); + expect(counts.fanoutFailures).toBe(0); + expect(counts.deadLetters).toBe(0); + expect(counts.schedulerFailures).toBe(0); + }); + + test("counts fan-out failures and dead-letters independently", () => { + const log = [ + "error: Routing failed for workbench wb_1", + "warn: message dead-lettered after 5 retries", + "error: Routing failed for workbench wb_2", + ].join("\n"); + const counts = countLogSignatures(log); + expect(counts.fanoutFailures).toBe(2); + expect(counts.deadLetters).toBe(1); + }); + + test("counts a scheduler fire line only when it reads as a failure", () => { + const log = [ + "info: scheduled fire of routine rt_1 succeeded", + "error: scheduled fire of routine rt_2 failed to launch", + "warn: scheduled fire of routine rt_3 rejected: bad definition", + ].join("\n"); + const counts = countLogSignatures(log); + expect(counts.schedulerFailures).toBe(2); + }); + + test("returns all-zero counts for a clean log", () => { + const log = "info: everything is fine\ninfo: still fine\n"; + expect(countLogSignatures(log)).toEqual({ + collectorFailures: 0, + fanoutFailures: 0, + deadLetters: 0, + schedulerFailures: 0, + }); + }); +}); diff --git a/packages/longevity-sim/src/report.test.ts b/packages/longevity-sim/src/report.test.ts new file mode 100644 index 000000000..3fcdd1e05 --- /dev/null +++ b/packages/longevity-sim/src/report.test.ts @@ -0,0 +1,153 @@ +import { describe, expect, test } from "bun:test"; +import { parseCampaignConfig } from "./config"; +import type { CheckpointRecord, Knee } from "./metrics"; +import { + renderCampaignReport, + reportVerdict, + type CampaignReport, + type Defect, +} from "./report"; + +function checkpoint(overrides: Partial): CheckpointRecord { + return { + atMessages: 0, + wallClockMs: 0, + sendLatencyP50Ms: 0, + sendLatencyP95Ms: 0, + sendLatencyMaxMs: 0, + turnLatencyP50Ms: 0, + turnLatencyP95Ms: 0, + turnCount: 0, + firstTokenP50Ms: 0, + dbSizeBytes: 0, + messagePageMs: 0, + messagePageDeepMs: 0, + workbenchListMs: 0, + hubRssBytes: 0, + sidecarRssBytes: 0, + collectorFailures: 0, + routineFiresTotal: 0, + routineFiresAccepted: 0, + sendFailures: 0, + turnFailures: 0, + ...overrides, + }; +} + +function baseReport(overrides: Partial = {}): CampaignReport { + const config = parseCampaignConfig({ + seed: 1, + targetMessages: 200, + checkpoints: [0, 100, 200], + threadReplyRate: 0.2, + mentionEvery: 10, + realTurnEvery: 15, + burstEvery: 20, + burstSize: 3, + simDaysPerCheckpointGap: 1, + restartAtMessages: [], + providerSwitchAtMessages: [], + skillEditAtMessages: [], + spawnAgentAtMessages: [], + }); + return { + name: "nightly-longevity", + startedAt: "2026-08-19T00:00:00.000Z", + config, + checkpoints: [ + checkpoint({ atMessages: 0, sendLatencyP50Ms: 40, dbSizeBytes: 1000 }), + checkpoint({ atMessages: 100, sendLatencyP50Ms: 60, dbSizeBytes: 2000 }), + checkpoint({ atMessages: 200, sendLatencyP50Ms: 200, dbSizeBytes: 4000 }), + ], + defects: [], + knees: [], + selfImprovement: [], + notes: [], + ...overrides, + }; +} + +describe("renderCampaignReport", () => { + test("includes a summary header with the campaign name and seed", () => { + const markdown = renderCampaignReport(baseReport()); + expect(markdown).toContain("nightly-longevity"); + expect(markdown).toContain("Seed: 1"); + }); + + test("renders one checkpoint table row per checkpoint", () => { + const markdown = renderCampaignReport(baseReport()); + expect(markdown).toContain("| 0 |"); + expect(markdown).toContain("| 100 |"); + expect(markdown).toContain("| 200 |"); + }); + + test("renders self-improvement checks", () => { + const markdown = renderCampaignReport( + baseReport({ + selfImprovement: [ + { + name: "skill edit propagates", + pass: true, + detail: "marker seen in reply", + }, + { + name: "provider switch survives restart", + pass: false, + detail: "timed out", + }, + ], + }), + ); + expect(markdown).toContain("skill edit propagates"); + expect(markdown).toContain("PASS"); + expect(markdown).toContain("provider switch survives restart"); + expect(markdown).toContain("FAIL"); + }); + + test("groups the defect log by severity", () => { + const defects: Defect[] = [ + { + severity: "S2", + title: "slow send", + detail: "p95 rose", + atMessages: 150, + }, + { + severity: "S1", + title: "dropped message", + detail: "never persisted", + atMessages: 180, + }, + ]; + const markdown = renderCampaignReport(baseReport({ defects })); + const s1Index = markdown.indexOf("### S1"); + const s2Index = markdown.indexOf("### S2"); + expect(s1Index).toBeGreaterThan(-1); + expect(s2Index).toBeGreaterThan(-1); + expect(s1Index).toBeLessThan(s2Index); + expect(markdown).toContain("dropped message"); + expect(markdown).toContain("slow send"); + }); + + test("renders knees and a verdict paragraph", () => { + const knees: Knee[] = [ + { + metric: "sendLatencyP50Ms", + atMessages: 200, + baseline: 40, + value: 200, + ratio: 5, + }, + ]; + const report = baseReport({ knees }); + const markdown = renderCampaignReport(report); + expect(markdown).toContain("sendLatencyP50Ms"); + expect(markdown).toContain("## Verdict"); + expect(markdown).toContain(reportVerdict(report)); + }); + + test("says no degradation found when there are no knees", () => { + const verdict = reportVerdict(baseReport({ knees: [] })); + expect(verdict).toContain("no metric crossing the"); + }); +}); From 8ab7784e7c189423d752f5d4acaeb4f7048ed4c2 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Thu, 20 Aug 2026 16:51:45 -0700 Subject: [PATCH 2/2] Add @corbits/longevity-sim: real-inference longevity campaign harness Boots a scratch hub+sidecar stack, signs up a simulated sales team, deploys real Ollama-backed agents through the workflow deployment freeze path, and drives a seeded campaign plan against it: paced sends, measured agent turns, time-compressed routines, hub restarts, provider switches, and mid-campaign skill-edit/agent-spawn checks, with degradation metrics checkpointed by message count. --- .prettierignore | 1 + bun.lock | 15 + packages/longevity-sim/.gitignore | 1 + packages/longevity-sim/LICENSE | 176 +++ packages/longevity-sim/README.md | 36 + packages/longevity-sim/package.json | 24 + packages/longevity-sim/src/agent-workflow.ts | 70 ++ packages/longevity-sim/src/cli.ts | 178 +++ packages/longevity-sim/src/config.ts | 69 ++ packages/longevity-sim/src/engine.ts | 691 ++++++++++++ packages/longevity-sim/src/index.ts | 6 + packages/longevity-sim/src/metrics.ts | 82 ++ packages/longevity-sim/src/personas.ts | 220 ++++ packages/longevity-sim/src/plan.ts | 274 +++++ packages/longevity-sim/src/prng.ts | 24 + packages/longevity-sim/src/probes.ts | 231 ++++ packages/longevity-sim/src/report.ts | 164 +++ packages/longevity-sim/src/stack.ts | 1020 ++++++++++++++++++ packages/longevity-sim/tsconfig.json | 7 + 19 files changed, 3289 insertions(+) create mode 100644 packages/longevity-sim/.gitignore create mode 100644 packages/longevity-sim/LICENSE create mode 100644 packages/longevity-sim/README.md create mode 100644 packages/longevity-sim/package.json create mode 100644 packages/longevity-sim/src/agent-workflow.ts create mode 100644 packages/longevity-sim/src/cli.ts create mode 100644 packages/longevity-sim/src/config.ts create mode 100644 packages/longevity-sim/src/engine.ts create mode 100644 packages/longevity-sim/src/index.ts create mode 100644 packages/longevity-sim/src/metrics.ts create mode 100644 packages/longevity-sim/src/personas.ts create mode 100644 packages/longevity-sim/src/plan.ts create mode 100644 packages/longevity-sim/src/prng.ts create mode 100644 packages/longevity-sim/src/probes.ts create mode 100644 packages/longevity-sim/src/report.ts create mode 100644 packages/longevity-sim/src/stack.ts create mode 100644 packages/longevity-sim/tsconfig.json diff --git a/.prettierignore b/.prettierignore index d13627241..7ff65d903 100644 --- a/.prettierignore +++ b/.prettierignore @@ -13,3 +13,4 @@ plans/ tmp/ .mb-scratch/ .corbits/ +packages/longevity-sim/output/ diff --git a/bun.lock b/bun.lock index 315f96366..1f25be0b0 100644 --- a/bun.lock +++ b/bun.lock @@ -855,6 +855,19 @@ "typescript": "catalog:", }, }, + "packages/longevity-sim": { + "name": "@corbits/longevity-sim", + "version": "0.0.1", + "dependencies": { + "@intx/agent": "0.3.0", + "@intx/workflow": "workspace:*", + "arktype": "catalog:", + }, + "devDependencies": { + "@types/bun": "catalog:", + "typescript": "catalog:", + }, + }, "packages/mcp-tools": { "name": "@corbits/mcp-tools", "version": "0.0.7", @@ -1930,6 +1943,8 @@ "@corbits/linear-tools": ["@corbits/linear-tools@workspace:packages/linear-tools"], + "@corbits/longevity-sim": ["@corbits/longevity-sim@workspace:packages/longevity-sim"], + "@corbits/mailbox": ["@corbits/mailbox@github:corbitsdev/corbits-mailbox#caa5214", { "dependencies": { "@hono/standard-validator": "0.2.3", "@standard-community/standard-json": "0.3.5", "@standard-community/standard-openapi": "0.2.9", "arktype": "2.1.29", "hono-openapi": "1.3.1" }, "peerDependencies": { "@intx/log": "^0.2.2", "@intx/mime": "^0.2.2", "@intx/types": "^0.2.2", "drizzle-orm": "^0.45.2", "hono": "^4.12.0", "postgres": "^3.4.0" } }, "corbitsdev-corbits-mailbox-caa5214", "sha512-z8DRBFgA4ukM8p29COeaMjfKZYe5jAUF4OBMiaIQFuW592+DGD/y6Ws6SjGlXmR9azkHNWh8oTzjlWlRP24vsQ=="], "@corbits/mcp-tools": ["@corbits/mcp-tools@workspace:packages/mcp-tools"], diff --git a/packages/longevity-sim/.gitignore b/packages/longevity-sim/.gitignore new file mode 100644 index 000000000..ea1472ec1 --- /dev/null +++ b/packages/longevity-sim/.gitignore @@ -0,0 +1 @@ +output/ diff --git a/packages/longevity-sim/LICENSE b/packages/longevity-sim/LICENSE new file mode 100644 index 000000000..c6487f4fd --- /dev/null +++ b/packages/longevity-sim/LICENSE @@ -0,0 +1,176 @@ +GNU LESSER GENERAL PUBLIC LICENSE + +Version 2.1, February 1999 + +Copyright (C) 1991, 1999 Free Software Foundation, Inc. +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] + +Preamble + +The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. + +This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. + +When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. + +To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. + +For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. + +We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. + +To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. + +Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. + +Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. + +When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. + +We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. + +For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. + +In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. + +Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. + +The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. + +GNU LESSER GENERAL PUBLIC LICENSE +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + +0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". + +A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. + +The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) + +"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. + +Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. + +1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. + +You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. + +2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. + +(For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. + +3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. + +Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. + +This option is useful when you wish to copy part of the code of the Library into a program that is not a library. + +4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. + +If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. + +5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. + +However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. + +When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. + +If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) + +Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. + +6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. + +You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: + + a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. + + e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. + +For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. + +It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. + +7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. + + b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. + +8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. + +9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. + +10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. + +11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. + +This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. + +12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. + +13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. + +14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. + +NO WARRANTY + +15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Libraries + +If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). + +To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. + + one line to give the library's name and an idea of what it does. + Copyright (C) year name of author + + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: + +Yoyodyne, Inc., hereby disclaims all copyright interest in +the library `Frob' (a library for tweaking knobs) written +by James Random Hacker. + +signature of Ty Coon, 1 April 1990 +Ty Coon, President of Vice +That's all there is to it! diff --git a/packages/longevity-sim/README.md b/packages/longevity-sim/README.md new file mode 100644 index 000000000..c625d60c8 --- /dev/null +++ b/packages/longevity-sim/README.md @@ -0,0 +1,36 @@ +# @corbits/longevity-sim + +Longevity simulation harness (CL-6440): drives a real workbench stack +(hub + sidecar + Postgres) through time-compressed team life — ~10 +simulated sales humans, agents, and routines. The humans are scripted +(deterministic posts, replies, mentions), but every agent turn is real +inference against the owner's Ollama fleet, spread across multiple +models and base URLs — there is no stub or noop inference path. +Checkpoints track degradation metrics and self-improvement checks as +the campaign runs. + +## This package's slice: the pure core + +Everything under `src/` here is pure and deterministic given a `seed` — +no network, no process spawning, no filesystem access. It owns: + +- `prng.ts` — seeded RNG (`createRng`, `pick`). +- `personas.ts` — the fictional 10-person sales team and their + deterministic chatter (`SALES_TEAM`, `utterance`). +- `config.ts` — `CampaignConfig`, arktype-validated + (`campaignConfig`, `parseCampaignConfig`). +- `plan.ts` — turns a `CampaignConfig` into an ordered `PlanStep[]` + (`buildPlan`, `summarizePlan`). +- `metrics.ts` — percentile math and knee detection over + `CheckpointRecord`s (`percentile`, `findKnees`). +- `report.ts` — renders a `CampaignReport` to markdown + (`renderCampaignReport`, `reportVerdict`). + +A separate stack layer (`stack.ts`, `engine.ts`, `probes.ts`, `cli.ts`) +drives the actual HTTP stack and boot glue against this plan; it is out +of scope for this slice and not exported from `src/index.ts` yet. + +## Scripts + +- `bun run typecheck` +- `bun test` diff --git a/packages/longevity-sim/package.json b/packages/longevity-sim/package.json new file mode 100644 index 000000000..1c9a9b68f --- /dev/null +++ b/packages/longevity-sim/package.json @@ -0,0 +1,24 @@ +{ + "name": "@corbits/longevity-sim", + "private": true, + "description": "Longevity simulation harness (CL-6440): drives a real workbench stack through time-compressed team life, checkpointing degradation metrics and self-improvement checks against a deterministic simulated sales campaign.", + "version": "0.0.1", + "license": "LGPL-2.1-or-later", + "type": "module", + "exports": { + ".": "./src/index.ts" + }, + "scripts": { + "typecheck": "tsc --noEmit", + "test": "bun test" + }, + "dependencies": { + "@intx/agent": "0.3.0", + "@intx/workflow": "workspace:*", + "arktype": "catalog:" + }, + "devDependencies": { + "@types/bun": "catalog:", + "typescript": "catalog:" + } +} diff --git a/packages/longevity-sim/src/agent-workflow.ts b/packages/longevity-sim/src/agent-workflow.ts new file mode 100644 index 000000000..32abaaaad --- /dev/null +++ b/packages/longevity-sim/src/agent-workflow.ts @@ -0,0 +1,70 @@ +// The campaign's own conversational agent definition: a mail-triggered +// single-step agent with a per-agent system prompt, shaped exactly like +// the seeded `workflows/assistant` definition (single step, unbounded +// triggers, explicit timeout) but with the prompt as input — the seeded +// builder hardcodes its prompt, and the campaign needs distinct +// personas plus mid-campaign prompt changes (skill-marker redeploys). +// +// The declared `inference.sources` MUST equal the deploy body's +// `(provider, model)` pair: the deploy gate approves exactly the pairs +// the agent declares (vendor/intx/workflow-deploy orchestrator), and +// the sidecar rejects sources whose provider is not a registered +// adapter — so a `catalog:`-style placeholder cannot deploy through +// the public deployments route. + +import { defineAgent } from "@intx/agent"; +import type { InferencePreference } from "@intx/agent"; +import { defineWorkflow, step } from "@intx/workflow"; +import type { WorkflowDefinition } from "@intx/workflow"; + +export interface CampaignAgentWorkflowInput { + readonly handle: string; + readonly tenantDomain: string; + readonly description: string; + readonly systemPrompt: string; + readonly inferencePreferences: readonly InferencePreference[]; + readonly turnTimeoutMs: number; +} + +export function buildCampaignAgentWorkflow( + input: CampaignAgentWorkflowInput, +): WorkflowDefinition { + if (input.handle === "") { + throw new Error("buildCampaignAgentWorkflow requires a non-empty handle"); + } + if (input.systemPrompt === "") { + throw new Error( + "buildCampaignAgentWorkflow requires a non-empty systemPrompt", + ); + } + if (!Number.isInteger(input.turnTimeoutMs) || input.turnTimeoutMs <= 0) { + throw new Error( + "buildCampaignAgentWorkflow requires turnTimeoutMs to be a positive integer", + ); + } + const stepId = "agent"; + return defineWorkflow({ + id: `wf_agent_${input.handle}`, + trigger: { type: "mail", to: `${input.handle}@${input.tenantDomain}` }, + steps: { + [stepId]: step({ + agent: defineAgent({ + id: stepId, + description: input.description, + systemPrompt: input.systemPrompt, + tools: [], + capabilities: [], + inference: { sources: input.inferencePreferences }, + }), + timeout: input.turnTimeoutMs, + triggers: "unbounded", + }), + }, + }); +} + +export function serializeCampaignAgentWorkflow( + definition: WorkflowDefinition, +): string { + return JSON.stringify(definition); +} diff --git a/packages/longevity-sim/src/cli.ts b/packages/longevity-sim/src/cli.ts new file mode 100644 index 000000000..c1cb34565 --- /dev/null +++ b/packages/longevity-sim/src/cli.ts @@ -0,0 +1,178 @@ +// `bun src/cli.ts --config `: reads DATABASE_URL and a +// REQUIRED REAL_TARGETS env (JSON array of `InferenceTarget` — each a +// real Ollama origin dialed through the `openai-compatible` adapter, +// e.g. `baseURL: "https:///v1"`), boots the stack, +// builds and executes the plan, writes the markdown report, prints its +// path and verdict, and exits 1 on any S1 defect. There is no +// noop/Anthropic fallback mode: every agent this CLI creates is a real +// agent pinned at one of REAL_TARGETS' catalog models. + +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { type } from "arktype"; + +import { parseCampaignConfig } from "./config"; +import { buildPlan, MENTION_AGENT_KEY, REAL_AGENT_KEY } from "./plan"; +import { renderCampaignReport, reportVerdict } from "./report"; +import { SALES_TEAM } from "./personas"; +import { + bootLongevityStack, + type AgentDefinitionSpec, + type InferenceTarget, + type RoutineSpec, + type SkillSpec, +} from "./stack"; +import { executeCampaign } from "./engine"; + +const inferenceTarget = type({ + label: "string", + provider: "string", + model: "string", + baseURL: "string", + apiKey: "string", +}); +const realTargetsSchema = inferenceTarget.array(); + +/** REAL_TARGETS is required: this CLI seeds no noop/Anthropic fallback + * catalog chain, so a campaign with no real target has no model any + * agent could ever be pinned at. */ +function parseRealTargets(raw: string | undefined): readonly InferenceTarget[] { + if (raw === undefined || raw.trim() === "") { + throw new Error( + "REAL_TARGETS is required (JSON array of InferenceTarget) — this " + + "campaign has no noop/Anthropic fallback; every agent needs a " + + "real Ollama target to pin its model at", + ); + } + const parsed = realTargetsSchema(JSON.parse(raw)); + if (parsed instanceof type.errors) { + throw new Error(`REAL_TARGETS: ${parsed.summary}`); + } + if (parsed.length === 0) { + throw new Error("REAL_TARGETS must name at least one InferenceTarget"); + } + return parsed; +} + +const SKILL_MARKER_NAME = "campaign-self-improvement"; + +/** One real agent definition per `realTargets` entry (cycling if the + * roster below outgrows the fleet) — every agent is real inference, + * pinned at that target's own catalog model. The fleet is expected to + * grow by adding more `realTargets` entries, never by this function + * inventing a stub/noop path. */ +function buildAgentSpecs( + realTargets: readonly InferenceTarget[], +): AgentDefinitionSpec[] { + // Order matters twice: index 0 (the plan's measured-turn target) owns + // the marker skill, and the round-robin below maps roster order onto + // `realTargets` order — so the lead agent lands on the first target. + const roster = [ + { key: REAL_AGENT_KEY, handle: REAL_AGENT_KEY, name: "Sales Analyst" }, + { key: "deal-desk", handle: "deal-desk", name: "Deal Desk" }, + { key: "ops-analyst", handle: "ops-analyst", name: "Ops Analyst" }, + { + key: MENTION_AGENT_KEY, + handle: MENTION_AGENT_KEY, + name: "Support Copilot", + }, + ]; + return roster.map((entry, index) => { + const target = realTargets[index % realTargets.length]; + if (target === undefined) { + throw new Error( + "unreachable: realTargets is non-empty by parseRealTargets", + ); + } + return { + key: entry.key, + handle: entry.handle, + name: entry.name, + systemPrompt: + "You are a real-model assistant helping a sales team. Keep replies short and concrete.", + real: true, + targetLabel: target.label, + skills: index === 0 ? [SKILL_MARKER_NAME] : [], + }; + }); +} + +const ROUTINE_SPECS: RoutineSpec[] = [ + { key: "heartbeat-1", name: "Daily heartbeat" }, +]; + +function skillSpecs(): SkillSpec[] { + return [ + { + name: SKILL_MARKER_NAME, + description: "Longevity campaign self-improvement marker skill.", + body: "Reply normally; this skill's instructions are updated during the campaign.", + }, + ]; +} + +function parseArgs(argv: readonly string[]): { configPath: string } { + const flagIndex = argv.indexOf("--config"); + const configPath = flagIndex >= 0 ? argv[flagIndex + 1] : undefined; + if (configPath === undefined) { + throw new Error("usage: bun src/cli.ts --config "); + } + return { configPath }; +} + +async function main(): Promise { + const { configPath } = parseArgs(process.argv.slice(2)); + const configRaw = JSON.parse(await readFile(configPath, "utf8")); + const config = parseCampaignConfig(configRaw); + + const databaseUrl = process.env["DATABASE_URL"]; + if (databaseUrl === undefined || databaseUrl === "") { + throw new Error( + "DATABASE_URL is not set; the campaign needs a reachable Postgres", + ); + } + const realTargets = parseRealTargets(process.env["REAL_TARGETS"]); + + const stack = await bootLongevityStack( + SALES_TEAM, + buildAgentSpecs(realTargets), + ROUTINE_SPECS, + { databaseUrl, realTargets, skills: skillSpecs() }, + ); + + try { + const steps = buildPlan(config); + const report = await executeCampaign(stack, steps, config, { + onProgress: (info) => { + process.stdout.write(`[${info.atMessages}] ${info.kind}\n`); + }, + }); + + const outputDir = path.join(import.meta.dir, "..", "output"); + await mkdir(outputDir, { recursive: true }); + const outputPath = path.join(outputDir, `${report.name}.md`); + await writeFile(outputPath, renderCampaignReport(report), "utf8"); + + process.stdout.write(`report written to ${outputPath}\n`); + process.stdout.write(`${reportVerdict(report)}\n`); + + const hasS1Defect = report.defects.some( + (defect) => defect.severity === "S1", + ); + return hasS1Defect ? 1 : 0; + } finally { + await stack.close(); + } +} + +// Top-level await (not a floating `main().then(...)` chain) is load-bearing: +// a detached promise does not keep Bun's event loop alive, and the boot +// sequence has handle-free moments where a drained loop exits 0 mid-campaign. +try { + process.exit(await main()); +} catch (error) { + const detail = + error instanceof Error ? (error.stack ?? error.message) : String(error); + process.stderr.write(`${detail}\n`); + process.exit(1); +} diff --git a/packages/longevity-sim/src/config.ts b/packages/longevity-sim/src/config.ts new file mode 100644 index 000000000..5fb111b07 --- /dev/null +++ b/packages/longevity-sim/src/config.ts @@ -0,0 +1,69 @@ +import { type } from "arktype"; + +export interface CampaignConfig { + seed: number; + targetMessages: number; + checkpoints: readonly number[]; + threadReplyRate: number; + /** Every Nth say @mentions an agent fire-and-forget: the mention is sent + * and the campaign moves on without waiting — the agent's turn still + * runs as real inference server-side, just unmeasured. */ + mentionEvery: number; + /** Every Nth say becomes a measured turn: a mention is sent to a real + * agent (real Ollama inference, no stub/noop path) and the campaign + * waits for that turn to complete, recording its latency. */ + realTurnEvery: number; + burstEvery: number; + burstSize: number; + simDaysPerCheckpointGap: number; + restartAtMessages: readonly number[]; + providerSwitchAtMessages: readonly number[]; + skillEditAtMessages: readonly number[]; + spawnAgentAtMessages: readonly number[]; +} + +export const campaignConfig = type({ + seed: "number.integer", + targetMessages: "number.integer > 0", + checkpoints: "number.integer[]", + threadReplyRate: "0 <= number <= 1", + mentionEvery: "number.integer >= 0", + realTurnEvery: "number.integer >= 0", + burstEvery: "number.integer >= 0", + burstSize: "number.integer >= 0", + simDaysPerCheckpointGap: "number.integer >= 0", + restartAtMessages: "number.integer[]", + providerSwitchAtMessages: "number.integer[]", + skillEditAtMessages: "number.integer[]", + spawnAgentAtMessages: "number.integer[]", +}); + +function assertAscendingFromZero(checkpoints: readonly number[]): void { + if (checkpoints.length === 0 || checkpoints[0] !== 0) { + throw new Error( + "parseCampaignConfig: checkpoints must be non-empty and start at 0", + ); + } + for (let i = 1; i < checkpoints.length; i++) { + const previous = checkpoints[i - 1]; + const current = checkpoints[i]; + if ( + previous === undefined || + current === undefined || + current <= previous + ) { + throw new Error( + `parseCampaignConfig: checkpoints must be strictly ascending, got ${checkpoints.join(", ")}`, + ); + } + } +} + +export function parseCampaignConfig(input: unknown): CampaignConfig { + const result = campaignConfig(input); + if (result instanceof type.errors) { + throw new Error(`parseCampaignConfig: ${result.summary}`); + } + assertAscendingFromZero(result.checkpoints); + return result; +} diff --git a/packages/longevity-sim/src/engine.ts b/packages/longevity-sim/src/engine.ts new file mode 100644 index 000000000..e32c242f0 --- /dev/null +++ b/packages/longevity-sim/src/engine.ts @@ -0,0 +1,691 @@ +// Drives a built `PlanStep[]` against a booted `LongevityStack`, +// recording latencies, failures, and self-improvement checks into a +// `CampaignReport`. HTTP + SQL only — no plan construction, no +// metrics math (that's `./plan.ts` and `./metrics.ts`, owned by the +// pure-core agent). + +import { api, expectStatus } from "../../../scripts/e2e/harness.ts"; +import { + arrayField, + stringField, + type LongevityStack, + type StackAgent, +} from "./stack"; +import { + collectCheckpoint, + newCheckpointWindow, + type CheckpointWindow, +} from "./probes"; +import type { CampaignConfig } from "./config"; +import type { PlanStep } from "./plan"; +import { findKnees, type CheckpointRecord } from "./metrics"; +import type { Defect, CampaignReport } from "./report"; + +export interface CampaignHooks { + onProgress?: (info: { atMessages: number; kind: string }) => void; +} + +const CONSECUTIVE_SEND_FAILURE_ABORT = 50; +const MENTION_TURN_POLL_TIMEOUT_MS = 120_000; +const REAL_TURN_POLL_TIMEOUT_MS = 240_000; +const ROUTINE_SCHEDULER_WAIT_MS = 45_000; +const RESTART_RECOVERY_WINDOW_MS = 30_000; +const RESTART_RECOVERY_DEFECT_THRESHOLD_MS = 15_000; + +// Every agent is real inference now (no zero-cost noop stub left), so +// the campaign paces itself rather than firing sends as fast as the +// HTTP layer allows: an overall send-rate cap (every send, mention or +// not) and a pending-turn budget gate applied before any send that +// mentions an agent — these models can think for a while before +// replying, so a burst of mentions with nothing pacing them would pile +// up an unbounded number of concurrent turns against a handful of +// local Ollama hosts. +const MIN_SEND_INTERVAL_MS = 200; // caps the overall send rate at ~5/s +const MAX_PENDING_TURNS = 8; +const PENDING_GATE_MAX_WAIT_MS = 180_000; + +interface AgentTurnRow { + id: string; + workbenchId: string; + agentAddress: string; + status: "running" | "completed" | "failed"; + requestMessageIds: readonly string[]; + replyMessageId: string | null; + startedAt: string; + endedAt: string | null; +} + +interface MutableCounters { + collectorFailures: number; + sendFailures: number; + turnFailures: number; + routineFiresTotal: number; + routineFiresAccepted: number; +} + +async function postMessage( + stack: LongevityStack, + cookies: string[], + text: string, + inReplyToMessageId?: string, +): Promise<{ id: string; latencyMs: number } | { error: string }> { + const start = performance.now(); + const res = await api( + stack.baseUrl, + "POST", + `/api/tenants/${stack.tenantId}/chat/workbenches/${stack.workbenchId}/messages`, + inReplyToMessageId === undefined + ? { parts: [{ kind: "text", text }] } + : { parts: [{ kind: "text", text }], inReplyToMessageId }, + cookies, + ); + const latencyMs = performance.now() - start; + if (res.status !== 201) { + return { + error: `expected 201, got ${res.status}: ${JSON.stringify(res.data)}`, + }; + } + return { id: stringField(res.data, "id", "post message"), latencyMs }; +} + +async function listTurns(stack: LongevityStack): Promise { + const res = await api( + stack.baseUrl, + "GET", + `/api/tenants/${stack.tenantId}/chat/workbenches/${stack.workbenchId}/turns`, + undefined, + stack.ownerCookies, + ); + expectStatus("list turns", res, 200); + return arrayField( + res.data, + "items", + "list turns", + ) as unknown as AgentTurnRow[]; +} + +/** Polls turns until one whose `requestMessageIds` contains `messageId` + * settles (status !== "running"), bounded by `timeoutMs`. Returns + * `undefined` on timeout — the caller decides whether that is a + * recorded turn failure. */ +async function waitForTurnSettled( + stack: LongevityStack, + messageId: string, + timeoutMs: number, +): Promise { + const deadline = Date.now() + timeoutMs; + for (;;) { + const turns = await listTurns(stack); + const turn = turns.find((t) => t.requestMessageIds.includes(messageId)); + if (turn !== undefined && turn.status !== "running") return turn; + if (Date.now() > deadline) return undefined; + await Bun.sleep(1000); + } +} + +function turnLatencyMs(turn: AgentTurnRow): number { + if (turn.endedAt === null) return 0; + return new Date(turn.endedAt).getTime() - new Date(turn.startedAt).getTime(); +} + +async function fetchMessageText( + stack: LongevityStack, + messageId: string, +): Promise { + const res = await api( + stack.baseUrl, + "GET", + `/api/tenants/${stack.tenantId}/chat/workbenches/${stack.workbenchId}/messages`, + undefined, + stack.ownerCookies, + ); + expectStatus("read messages for reply text", res, 200); + const items = arrayField( + res.data, + "items", + "read messages for reply text", + ) as { + id: string; + parts: { kind: string; text?: string }[]; + }[]; + const message = items.find((item) => item.id === messageId); + if (message === undefined) return undefined; + const textPart = message.parts.find((p) => p.kind === "text"); + return textPart?.text; +} + +export async function executeCampaign( + stack: LongevityStack, + steps: readonly PlanStep[], + config: CampaignConfig, + hooks?: CampaignHooks, +): Promise { + const startedAt = new Date(); + const startedAtMs = Date.now(); + const agents = new Map(stack.agents); + const refs = new Map(); + const defects: Defect[] = []; + const selfImprovement: { name: string; pass: boolean; detail: string }[] = []; + const checkpoints: CheckpointRecord[] = []; + const notes: string[] = []; + + const counters: MutableCounters = { + collectorFailures: 0, + sendFailures: 0, + turnFailures: 0, + routineFiresTotal: 0, + routineFiresAccepted: 0, + }; + + let messagesSent = 0; + let mentionsSeen = 0; + let consecutiveSendFailures = 0; + let window: CheckpointWindow = newCheckpointWindow(0, startedAtMs); + let providerSwitchIndex = 0; + let nextSendAllowedAt = Date.now(); + + /** Enforces the overall send-rate cap ahead of every send, mention or + * not — a single gate every send path routes through rather than + * each caller tracking its own timer. */ + async function paceSend(): Promise { + const now = Date.now(); + if (now < nextSendAllowedAt) await Bun.sleep(nextSendAllowedAt - now); + nextSendAllowedAt = + Math.max(Date.now(), nextSendAllowedAt) + MIN_SEND_INTERVAL_MS; + } + + async function countRunningTurns(): Promise { + const turns = await listTurns(stack); + return turns.filter((t) => t.status === "running").length; + } + + /** Backpressure gate a mention-bearing send waits on: holds while + * more than `MAX_PENDING_TURNS` turns are in flight, bounded so a + * wedged inference host can never stall the campaign forever — past + * the bound it proceeds anyway and leaves a note rather than hanging. */ + async function waitForPendingBudget(): Promise { + const deadline = Date.now() + PENDING_GATE_MAX_WAIT_MS; + for (;;) { + const pending = await countRunningTurns(); + if (pending <= MAX_PENDING_TURNS) return; + if (Date.now() > deadline) { + notes.push( + `pending-turn backpressure gate saturated (>${MAX_PENDING_TURNS} running turns) ` + + `after ${PENDING_GATE_MAX_WAIT_MS}ms; proceeded anyway at ${messagesSent} messages`, + ); + return; + } + await Bun.sleep(2000); + } + } + + function actorCookies(actorKey: string): string[] { + const actor = stack.actors.get(actorKey); + if (actor === undefined) { + throw new Error(`plan names unknown actor "${actorKey}"`); + } + return actor.cookies; + } + + function agentHandle(agentKey: string): string { + const agent = agents.get(agentKey); + if (agent === undefined) + throw new Error(`plan names unknown agent "${agentKey}"`); + return agent.handle; + } + + /** Sends one `say`/`burst` line and folds latency/failure bookkeeping. + * Returns the sent message id, or `undefined` on a recorded failure — + * the caller decides whether that failure is fatal (see the + * consecutive-failure abort below, applied only for `say`/`burst`). */ + async function recordSend( + actorKey: string, + text: string, + ref?: string, + inReplyToRef?: string, + ): Promise { + const inReplyToMessageId = + inReplyToRef === undefined ? undefined : refs.get(inReplyToRef); + await paceSend(); + const result = await postMessage( + stack, + actorCookies(actorKey), + text, + inReplyToMessageId, + ); + if ("error" in result) { + counters.sendFailures += 1; + consecutiveSendFailures += 1; + if (consecutiveSendFailures >= CONSECUTIVE_SEND_FAILURE_ABORT) { + throw new Error( + `aborting: ${consecutiveSendFailures} consecutive send failures, latest: ${result.error}`, + ); + } + return undefined; + } + consecutiveSendFailures = 0; + messagesSent += 1; + window.sendLatenciesMs.push(result.latencyMs); + if (ref !== undefined) refs.set(ref, result.id); + return result.id; + } + + /** A `say`'s mention fan-out: fires the mention and, on every 10th + * mention seen this campaign, polls the mentioned agent's turn to + * completion and samples its latency. Never blocks the ordinary + * conversational pace on the other 9 — every mentioned agent is a + * real model now, so waiting on every single one would defeat the + * campaign's own send-rate pacing; this samples degradation instead + * of measuring every reply. */ + async function sampleMentionTurn(messageId: string): Promise { + mentionsSeen += 1; + if (mentionsSeen % 10 !== 0) return; + const turn = await waitForTurnSettled( + stack, + messageId, + MENTION_TURN_POLL_TIMEOUT_MS, + ); + if (turn === undefined) { + counters.turnFailures += 1; + defects.push({ + severity: "S2", + title: "sampled mention turn timed out", + detail: `no settled turn within ${MENTION_TURN_POLL_TIMEOUT_MS}ms`, + atMessages: messagesSent, + }); + return; + } + if (turn.status === "failed") counters.turnFailures += 1; + window.turnLatenciesMs.push(turnLatencyMs(turn)); + } + + async function realTurn( + actorKey: string, + agentKey: string, + text: string, + verb: string, + ): Promise { + const handle = agentHandle(agentKey); + const mentionText = `@${handle} ${text}`; + await waitForPendingBudget(); + await paceSend(); + const result = await postMessage( + stack, + actorCookies(actorKey), + mentionText, + ); + if ("error" in result) { + counters.sendFailures += 1; + defects.push({ + severity: "S1", + title: `${verb} send failed for @${handle}`, + detail: result.error, + atMessages: messagesSent, + }); + return undefined; + } + messagesSent += 1; + window.sendLatenciesMs.push(result.latencyMs); + + const turn = await waitForTurnSettled( + stack, + result.id, + REAL_TURN_POLL_TIMEOUT_MS, + ); + if (turn === undefined) { + counters.turnFailures += 1; + defects.push({ + severity: "S1", + title: `${verb} turn timed out for @${handle}`, + detail: `no settled turn within ${REAL_TURN_POLL_TIMEOUT_MS}ms`, + atMessages: messagesSent, + }); + return undefined; + } + if (turn.status === "failed") { + counters.turnFailures += 1; + defects.push({ + severity: "S2", + title: `${verb} turn failed for @${handle}`, + detail: turn.id, + atMessages: messagesSent, + }); + } else { + window.turnLatenciesMs.push(turnLatencyMs(turn)); + } + return turn; + } + + const firstActorKey = [...stack.actors.keys()][0]; + if (firstActorKey === undefined) { + throw new Error("executeCampaign: stack has no actors"); + } + const ownerActorKey: string = firstActorKey; + + async function runStep(step: PlanStep): Promise { + hooks?.onProgress?.({ atMessages: messagesSent, kind: step.kind }); + switch (step.kind) { + case "say": { + const mentionKeys = step.mentions ?? []; + const text = + mentionKeys.length === 0 + ? step.text + : `${mentionKeys.map((key) => `@${agentHandle(key)}`).join(" ")} ${step.text}`; + if (mentionKeys.length > 0) await waitForPendingBudget(); + const messageId = await recordSend( + step.actor, + text, + step.ref, + step.inReplyToRef, + ); + if (messageId !== undefined && mentionKeys.length > 0) { + await sampleMentionTurn(messageId); + } + return; + } + case "burst": { + await Promise.all( + step.sends.map((send) => recordSend(send.actor, send.text)), + ); + return; + } + case "realTurn": { + await realTurn(step.actor, step.agent, step.text, "realTurn"); + return; + } + case "routineAdvance": { + const entries = [...stack.routines.values()]; + if (entries.length === 0) return; + const advanceIndex = step.simDay % entries.length; + for (let i = 0; i < entries.length; i++) { + const routine = entries[i]; + if (routine === undefined) continue; + if (i === advanceIndex) { + const before = await api( + stack.baseUrl, + "GET", + `/api/tenants/${stack.tenantId}/routines/${routine.id}/runs`, + undefined, + stack.ownerCookies, + ); + expectStatus("routineAdvance: baseline runs", before, 200); + const beforeIds = new Set( + ( + arrayField(before.data, "items", "baseline runs") as { + runId: string; + }[] + ).map((r) => r.runId), + ); + await stack.sql.unsafe( + `UPDATE routines.routine SET next_fire_at = now() - interval '1 second' WHERE id = $1`, + [routine.id], + ); + counters.routineFiresTotal += 1; + const deadline = Date.now() + ROUTINE_SCHEDULER_WAIT_MS; + let accepted = false; + while (Date.now() < deadline) { + const after = await api( + stack.baseUrl, + "GET", + `/api/tenants/${stack.tenantId}/routines/${routine.id}/runs`, + undefined, + stack.ownerCookies, + ); + expectStatus("routineAdvance: polled runs", after, 200); + const items = arrayField(after.data, "items", "polled runs") as { + runId: string; + }[]; + if (items.some((r) => !beforeIds.has(r.runId))) { + accepted = true; + break; + } + await Bun.sleep(1000); + } + if (accepted) counters.routineFiresAccepted += 1; + } else { + counters.routineFiresTotal += 1; + const res = await api( + stack.baseUrl, + "POST", + `/api/tenants/${stack.tenantId}/routines/${routine.id}/run`, + {}, + stack.ownerCookies, + ); + if (res.status === 201) counters.routineFiresAccepted += 1; + } + } + return; + } + case "checkpoint": { + // The record is labeled with the count this checkpoint fires + // AT, not the count the window opened at — the window opened + // at the previous checkpoint. + window.atMessages = step.atMessages; + const record = await collectCheckpoint(stack, window, counters); + checkpoints.push(record); + window = newCheckpointWindow(step.atMessages, startedAtMs); + return; + } + case "restartHub": { + await stack.restartHub(); + const recoveryStart = Date.now(); + let recovered = false; + while (Date.now() - recoveryStart < RESTART_RECOVERY_WINDOW_MS) { + await paceSend(); + const result = await postMessage( + stack, + stack.ownerCookies, + `post-restart check ${crypto.randomUUID()}`, + ); + if (!("error" in result)) { + messagesSent += 1; + window.sendLatenciesMs.push(result.latencyMs); + recovered = true; + break; + } + await Bun.sleep(1000); + } + const recoveryMs = Date.now() - recoveryStart; + if (!recovered) { + defects.push({ + severity: "S1", + title: "hub restart recovery failed", + detail: `no accepted send within ${RESTART_RECOVERY_WINDOW_MS}ms`, + atMessages: messagesSent, + }); + } else if (recoveryMs > RESTART_RECOVERY_DEFECT_THRESHOLD_MS) { + defects.push({ + severity: "S2", + title: "hub restart recovery slow", + detail: `recovered after ${recoveryMs}ms`, + atMessages: messagesSent, + }); + } + return; + } + case "providerSwitch": { + if (stack.realTargets.length === 0) return; + const realAgent = [...agents.values()].find((a) => a.real); + if (realAgent === undefined) return; + const nextTarget = + stack.realTargets[providerSwitchIndex % stack.realTargets.length]; + providerSwitchIndex += 1; + if (nextTarget === undefined) return; + try { + const redeployed = await stack.redeployAgent(realAgent.key, { + targetLabel: nextTarget.label, + }); + agents.set(realAgent.key, redeployed); + } catch (error) { + defects.push({ + severity: "S2", + title: `providerSwitch failed for @${realAgent.handle}`, + detail: error instanceof Error ? error.message : String(error), + atMessages: messagesSent, + }); + return; + } + const turn = await realTurn( + ownerActorKey, + realAgent.key, + "confirm you're still online", + "providerSwitch verify", + ); + selfImprovement.push({ + name: `providerSwitch to ${nextTarget.label}`, + pass: turn !== undefined && turn.status === "completed", + detail: `model=${nextTarget.model}`, + }); + return; + } + case "spawnAgent": { + const spawnTarget = stack.realTargets[0]; + if (spawnTarget === undefined) { + throw new Error( + "spawnAgent: stack has no realTargets to pin the new agent at", + ); + } + let spawned: StackAgent; + try { + spawned = await stack.deployAgent({ + key: step.agentKey, + handle: step.agentKey, + name: `Spawned ${step.agentKey}`, + systemPrompt: + "You are a newly onboarded team member. Reply briefly and helpfully.", + targetLabel: spawnTarget.label, + skills: [], + }); + } catch (error) { + defects.push({ + severity: "S2", + title: `spawnAgent deploy failed for ${step.agentKey}`, + detail: error instanceof Error ? error.message : String(error), + atMessages: messagesSent, + }); + return; + } + const handle = spawned.handle; + agents.set(step.agentKey, spawned); + + const turn = await realTurn( + ownerActorKey, + step.agentKey, + "welcome aboard, please confirm you're online", + "spawnAgent verify", + ); + selfImprovement.push({ + name: `spawnAgent ${step.agentKey}`, + pass: turn !== undefined && turn.status === "completed", + detail: `handle=${handle}`, + }); + return; + } + case "skillEdit": { + const entry = [...stack.skillOwners.entries()][0]; + if (entry === undefined) { + notes.push("skillEdit: no seeded skill to edit; step skipped"); + return; + } + const [skillName, owningAgentKey] = entry; + const markerBody = `Always end every reply with the exact word ${step.marker}.`; + const updated = await api( + stack.baseUrl, + "PUT", + `/api/tenants/${stack.tenantId}/skills/${skillName}`, + { + description: "Longevity campaign self-improvement marker skill", + body: markerBody, + }, + stack.ownerCookies, + ); + if (updated.status !== 200) { + defects.push({ + severity: "S2", + title: `skillEdit failed for ${skillName}`, + detail: `expected 200, got ${updated.status}: ${JSON.stringify(updated.data)}`, + atMessages: messagesSent, + }); + return; + } + // The tenant skill row alone never reaches a turn (known + // blocker D2/D3 drops tools/history on the openai-compatible + // path), so the edit only lands once the owning agent's asset + // is redeployed with the new body inlined — the same freeze + // path a real re-publish takes. + try { + const redeployed = await stack.redeployAgent(owningAgentKey, { + skillBody: { name: skillName, body: markerBody }, + }); + agents.set(owningAgentKey, redeployed); + } catch (error) { + defects.push({ + severity: "S2", + title: `skillEdit redeploy failed for ${skillName}`, + detail: error instanceof Error ? error.message : String(error), + atMessages: messagesSent, + }); + } + return; + } + case "skillProbe": { + const entry = [...stack.skillOwners.entries()][0]; + if (entry === undefined) { + notes.push("skillProbe: no seeded skill owner; step skipped"); + return; + } + const [, agentKey] = entry; + const turn = await realTurn( + ownerActorKey, + agentKey, + "please respond so I can confirm your latest instructions", + "skillProbe", + ); + const knownBlockerNote = + " (known blocker D2/D3: tools/history dropped on the " + + "openai-compatible path — rule this out before treating a " + + "failed probe as a new defect)"; + if (turn === undefined || turn.replyMessageId === null) { + selfImprovement.push({ + name: `skillProbe ${step.marker}`, + pass: false, + detail: `no settled turn or reply message${knownBlockerNote}`, + }); + return; + } + const replyText = await fetchMessageText(stack, turn.replyMessageId); + const pass = replyText !== undefined && replyText.includes(step.marker); + selfImprovement.push({ + name: `skillProbe ${step.marker}`, + pass, + detail: pass + ? (replyText ?? "(no reply text found)") + : `${replyText ?? "(no reply text found)"}${knownBlockerNote}`, + }); + return; + } + } + } + + for (const step of steps) { + await runStep(step); + } + + const wallHours = (Date.now() - startedAtMs) / 3_600_000; + const messagesPerHour = wallHours > 0 ? messagesSent / wallHours : 0; + notes.push( + `sustained throughput: ${messagesPerHour.toFixed(2)} messages/hour ` + + `(${messagesSent} persisted sends over ${wallHours.toFixed(2)}h)`, + ); + + return { + name: `longevity-${startedAt.toISOString()}`, + startedAt: startedAt.toISOString(), + config, + checkpoints, + defects, + knees: findKnees(checkpoints), + selfImprovement, + notes, + }; +} diff --git a/packages/longevity-sim/src/index.ts b/packages/longevity-sim/src/index.ts new file mode 100644 index 000000000..2065b6c1f --- /dev/null +++ b/packages/longevity-sim/src/index.ts @@ -0,0 +1,6 @@ +export * from "./prng"; +export * from "./personas"; +export * from "./config"; +export * from "./plan"; +export * from "./metrics"; +export * from "./report"; diff --git a/packages/longevity-sim/src/metrics.ts b/packages/longevity-sim/src/metrics.ts new file mode 100644 index 000000000..194090d21 --- /dev/null +++ b/packages/longevity-sim/src/metrics.ts @@ -0,0 +1,82 @@ +export interface CheckpointRecord { + atMessages: number; + wallClockMs: number; + sendLatencyP50Ms: number; + sendLatencyP95Ms: number; + sendLatencyMaxMs: number; + turnLatencyP50Ms: number; + turnLatencyP95Ms: number; + turnCount: number; + firstTokenP50Ms: number; + dbSizeBytes: number; + messagePageMs: number; + messagePageDeepMs: number; + workbenchListMs: number; + hubRssBytes: number; + sidecarRssBytes: number; + collectorFailures: number; + routineFiresTotal: number; + routineFiresAccepted: number; + sendFailures: number; + turnFailures: number; +} + +export function percentile(values: readonly number[], p: number): number { + if (values.length === 0) return 0; + const sorted = [...values].sort((a, b) => a - b); + const index = Math.min( + sorted.length - 1, + Math.ceil((p / 100) * sorted.length) - 1, + ); + return sorted[Math.max(0, index)] ?? 0; +} + +export interface Knee { + metric: string; + atMessages: number; + baseline: number; + value: number; + ratio: number; +} + +const KNEE_METRICS = [ + "sendLatencyP50Ms", + "sendLatencyP95Ms", + "turnLatencyP50Ms", + "messagePageMs", + "messagePageDeepMs", + "workbenchListMs", + "hubRssBytes", + "dbSizeBytes", +] as const satisfies readonly (keyof CheckpointRecord)[]; + +export function findKnees( + checkpoints: readonly CheckpointRecord[], + opts?: { ratioThreshold?: number }, +): Knee[] { + const ratioThreshold = opts?.ratioThreshold ?? 3; + const knees: Knee[] = []; + for (const metric of KNEE_METRICS) { + const baselineCheckpoint = checkpoints.find( + (checkpoint) => checkpoint[metric] !== 0, + ); + if (baselineCheckpoint === undefined) continue; + const baseline = baselineCheckpoint[metric]; + for (const checkpoint of checkpoints) { + if (checkpoint.atMessages <= baselineCheckpoint.atMessages) continue; + const value = checkpoint[metric]; + const ratio = value / baseline; + if (ratio >= ratioThreshold) { + knees.push({ + metric, + atMessages: checkpoint.atMessages, + baseline, + value, + ratio, + }); + break; + } + } + } + return knees; +} diff --git a/packages/longevity-sim/src/personas.ts b/packages/longevity-sim/src/personas.ts new file mode 100644 index 000000000..04c6d8765 --- /dev/null +++ b/packages/longevity-sim/src/personas.ts @@ -0,0 +1,220 @@ +import { pick } from "./prng"; + +export interface Persona { + key: string; + name: string; + role: string; + topics: readonly string[]; + cadenceWeight: number; +} + +type Shape = (topic: string, simDay: number, name: string) => string; + +const AE_SHAPES: readonly Shape[] = [ + (topic) => `Pipeline update: ${topic} moved to verbal — paperwork this week.`, + (topic) => + `Blocker on ${topic}: procurement wants a redline before signature.`, + (topic) => + `Just got off the call with ${topic}, they want a second demo for their VP.`, + (topic) => + `Anyone have bandwidth to help me prep the ${topic} proposal tonight?`, + (topic, simDay) => + `Day ${simDay}: ${topic} still stuck in security review, chasing them again.`, +]; + +const SDR_SHAPES: readonly Shape[] = [ + (topic) => `Booked a discovery call with ${topic} for Thursday.`, + (topic) => `${topic} went cold after three touches, moving to nurture.`, + (topic) => + `Handing ${topic} off to an AE now that they replied to the sequence.`, + (topic) => + `Quick question — does ${topic} already have an open opportunity in the pipeline?`, + (topic, simDay) => + `Day ${simDay} outreach recap: ${topic} opened the email twice, no reply yet.`, +]; + +const SALES_OPS_SHAPES: readonly Shape[] = [ + (topic) => + `Pulled the ${topic} report — conversion rate is down from last cycle.`, + (topic) => + `Blocker: ${topic} field is missing on half the records after the CRM sync.`, + (topic) => + `Handing the ${topic} dashboard back to the team, refresh is live.`, + (topic) => + `Question — should ${topic} count toward this quarter's attainment or next?`, + (topic, simDay) => + `Day ${simDay} data check: ${topic} numbers reconciled against finance.`, +]; + +const MANAGER_SHAPES: readonly Shape[] = [ + (topic) => + `Forecast call: ${topic} is the deal that decides if we hit this month.`, + (topic) => + `Blocker on ${topic} — need to loop in leadership before we discount further.`, + (topic) => `Handing coaching notes on ${topic} over to the rep now.`, + (topic) => `Question for the team — who else is touching ${topic} this week?`, + (topic, simDay) => + `Day ${simDay} standup: ${topic} is the one to watch this sprint.`, +]; + +const CS_SHAPES: readonly Shape[] = [ + (topic) => `Renewal update: ${topic} confirmed budget for another year.`, + (topic) => `Blocker on ${topic} — usage dropped and champion went quiet.`, + (topic) => + `Handing the ${topic} QBR deck to sales, expansion opportunity there.`, + (topic) => + `Question — has anyone heard from ${topic} since the outage ticket?`, + (topic, simDay) => + `Day ${simDay} health check: ${topic} score moved back to green.`, +]; + +const SE_SHAPES: readonly Shape[] = [ + (topic) => + `Ran the technical deep dive for ${topic}, integration questions all answered.`, + (topic) => + `Blocker on ${topic}: their security team wants a pen test summary first.`, + (topic) => + `Handing the ${topic} POC environment over, credentials are in the thread.`, + (topic) => + `Question — does ${topic} need the SSO walkthrough again for the new stakeholder?`, + (topic, simDay) => + `Day ${simDay}: ${topic} POC is passing every test case so far.`, +]; + +const REVOPS_SHAPES: readonly Shape[] = [ + (topic) => + `Territory update: ${topic} is being reassigned after the restructure.`, + (topic) => + `Blocker: ${topic} routing rule is misfiring, leads landing in the wrong queue.`, + (topic) => `Handing the ${topic} comp plan model back for legal sign-off.`, + (topic) => + `Question — is ${topic} in scope for the new territory carving pass?`, + (topic, simDay) => + `Day ${simDay}: ${topic} automation shipped, no more manual routing.`, +]; + +const VP_SHAPES: readonly Shape[] = [ + (topic) => `Board prep note: ${topic} is the headline logo for this quarter.`, + (topic) => + `Blocker on ${topic} — need pricing exception approved by finance today.`, + (topic) => + `Handing the ${topic} exec sponsor intro to the AE, warm and ready.`, + (topic) => + `Question — where do we stand on ${topic} versus the competitive threat?`, + (topic, simDay) => + `Day ${simDay}: ${topic} is the deal I'm walking the board through.`, +]; + +export const SALES_TEAM: readonly Persona[] = [ + { + key: "briar", + name: "Briar Holloway", + role: "Account Executive", + topics: ["Marrowgate Logistics", "Fennwick Retail", "Cobalt Peak Foods"], + cadenceWeight: 3, + }, + { + key: "dax", + name: "Dax Ferreira", + role: "Account Executive", + topics: ["Sablewood Insurance", "Northfell Utilities", "Thistledown Media"], + cadenceWeight: 3, + }, + { + key: "ivy", + name: "Ivy Tanaka-Reyes", + role: "SDR", + topics: [ + "Quillstone Manufacturing", + "Redbrick Analytics", + "Palefire Studios", + ], + cadenceWeight: 4, + }, + { + key: "oren", + name: "Oren Vasquez", + role: "SDR", + topics: ["Amberlight Health", "Driftmark Shipping", "Grovewell Energy"], + cadenceWeight: 4, + }, + { + key: "maple", + name: "Maple Chen-Okafor", + role: "Sales Ops", + topics: [ + "Q3 conversion report", + "lead-routing rules", + "quota attainment sheet", + ], + cadenceWeight: 2, + }, + { + key: "gideon", + name: "Gideon Novak", + role: "Sales Manager", + topics: [ + "Marrowgate Logistics", + "Sablewood Insurance", + "team pipeline review", + ], + cadenceWeight: 2, + }, + { + key: "wren", + name: "Wren Adeyemi", + role: "Customer Success", + topics: [ + "Bellcrest Hospitality", + "Ashgrove Pharma", + "Ironvale Construction", + ], + cadenceWeight: 3, + }, + { + key: "silas", + name: "Silas Petrov", + role: "Solutions Engineer", + topics: ["Fennwick Retail", "Quillstone Manufacturing", "SSO rollout"], + cadenceWeight: 2, + }, + { + key: "farrah", + name: "Farrah Lindqvist", + role: "RevOps", + topics: ["East region territory map", "comp plan v3", "lead scoring model"], + cadenceWeight: 1, + }, + { + key: "toby", + name: "Toby Ekwueme", + role: "VP Sales", + topics: ["Northfell Utilities", "Cobalt Peak Foods", "annual board deck"], + cadenceWeight: 1, + }, +]; + +const SHAPES_BY_ROLE: Record = { + "Account Executive": AE_SHAPES, + SDR: SDR_SHAPES, + "Sales Ops": SALES_OPS_SHAPES, + "Sales Manager": MANAGER_SHAPES, + "Customer Success": CS_SHAPES, + "Solutions Engineer": SE_SHAPES, + RevOps: REVOPS_SHAPES, + "VP Sales": VP_SHAPES, +}; + +export function utterance( + persona: Persona, + rng: () => number, + simDay: number, +): string { + const shapes = SHAPES_BY_ROLE[persona.role]; + if (shapes === undefined) { + throw new Error(`utterance: no message shapes for role "${persona.role}"`); + } + const shape = pick(rng, shapes); + const topic = pick(rng, persona.topics); + return shape(topic, simDay, persona.name); +} diff --git a/packages/longevity-sim/src/plan.ts b/packages/longevity-sim/src/plan.ts new file mode 100644 index 000000000..8978f65d0 --- /dev/null +++ b/packages/longevity-sim/src/plan.ts @@ -0,0 +1,274 @@ +import { createRng, pick } from "./prng"; +import { SALES_TEAM, utterance, type Persona } from "./personas"; +import type { CampaignConfig } from "./config"; + +export type PlanStep = + | { + kind: "say"; + actor: string; + text: string; + ref?: string; + inReplyToRef?: string; + mentions?: readonly string[]; + } + | { kind: "burst"; sends: readonly { actor: string; text: string }[] } + | { kind: "realTurn"; actor: string; text: string; agent: string } + | { kind: "routineAdvance"; simDay: number } + | { kind: "checkpoint"; atMessages: number } + | { kind: "restartHub"; atMessages: number } + | { kind: "providerSwitch"; atMessages: number } + | { kind: "skillEdit"; marker: string; atMessages: number } + | { kind: "skillProbe"; marker: string; atMessages: number } + | { kind: "spawnAgent"; agentKey: string; atMessages: number }; + +/** The agent key every fire-and-forget mention targets; the provisioned + * cast must include an agent under this key. */ +export const MENTION_AGENT_KEY = "support-copilot"; +/** The agent key measured turns (`realTurn`), skill probes, and + * provider switches target; the provisioned cast must include it. */ +export const REAL_AGENT_KEY = "sales-analyst"; +const THREAD_WINDOW_SIZE = 20; +const THREAD_ROOT_EVERY = 4; +const SKILL_PROBE_DELAY_MESSAGES = 20; + +const EVENT_PRIORITY: Record = { + checkpoint: 0, + restartHub: 1, + providerSwitch: 2, + skillEdit: 3, + skillProbe: 4, + spawnAgent: 5, + routineAdvance: 6, + say: 7, + burst: 7, + realTurn: 7, +}; + +function clampToTarget(atMessages: number, targetMessages: number): number { + return Math.min(atMessages, targetMessages); +} + +function buildWeightedPicker( + personas: readonly Persona[], +): (rng: () => number) => Persona { + const totalWeight = personas.reduce( + (sum, persona) => sum + persona.cadenceWeight, + 0, + ); + return (rng: () => number): Persona => { + let remaining = rng() * totalWeight; + for (const persona of personas) { + remaining -= persona.cadenceWeight; + if (remaining <= 0) return persona; + } + const last = personas[personas.length - 1]; + if (last === undefined) { + throw new Error("buildWeightedPicker: personas must be non-empty"); + } + return last; + }; +} + +function routineAdvancePositions(config: CampaignConfig): number[] { + const positions: number[] = []; + if (config.simDaysPerCheckpointGap <= 0) return positions; + for (let i = 0; i < config.checkpoints.length - 1; i++) { + const start = config.checkpoints[i]; + const end = config.checkpoints[i + 1]; + if (start === undefined || end === undefined) continue; + for (let slot = 1; slot <= config.simDaysPerCheckpointGap; slot++) { + const fraction = slot / (config.simDaysPerCheckpointGap + 1); + const position = Math.round(start + (end - start) * fraction); + positions.push(clampToTarget(position, config.targetMessages)); + } + } + return positions; +} + +function collectEvents(config: CampaignConfig): Map { + const events = new Map(); + const addEvent = (atMessages: number, step: PlanStep): void => { + const existing = events.get(atMessages) ?? []; + existing.push(step); + events.set(atMessages, existing); + }; + + for (const atMessages of config.checkpoints) { + addEvent(atMessages, { kind: "checkpoint", atMessages }); + } + for (const raw of config.restartAtMessages) { + const atMessages = clampToTarget(raw, config.targetMessages); + addEvent(atMessages, { kind: "restartHub", atMessages }); + } + for (const raw of config.providerSwitchAtMessages) { + const atMessages = clampToTarget(raw, config.targetMessages); + addEvent(atMessages, { kind: "providerSwitch", atMessages }); + } + config.skillEditAtMessages.forEach((raw, index) => { + const marker = `skill-edit-${index + 1}`; + const editAt = clampToTarget(raw, config.targetMessages); + const probeAt = clampToTarget( + raw + SKILL_PROBE_DELAY_MESSAGES, + config.targetMessages, + ); + addEvent(editAt, { kind: "skillEdit", marker, atMessages: editAt }); + addEvent(probeAt, { kind: "skillProbe", marker, atMessages: probeAt }); + }); + config.spawnAgentAtMessages.forEach((raw, index) => { + const atMessages = clampToTarget(raw, config.targetMessages); + addEvent(atMessages, { + kind: "spawnAgent", + agentKey: `spawned-agent-${index + 1}`, + atMessages, + }); + }); + for (const atMessages of routineAdvancePositions(config)) { + addEvent(atMessages, { kind: "routineAdvance", simDay: 0 }); + } + + for (const [atMessages, steps] of events) { + events.set( + atMessages, + [...steps].sort( + (a, b) => EVENT_PRIORITY[a.kind] - EVENT_PRIORITY[b.kind], + ), + ); + } + return events; +} + +/** + * buildPlan runs one deterministic forward pass over message slots 1..targetMessages. + * A burst never crosses an event boundary, so every scheduled event still lands + * exactly on its configured message count even when bursts jump several + * messages at once. + */ +export function buildPlan(config: CampaignConfig): PlanStep[] { + const rng = createRng(config.seed); + const pickPersona = buildWeightedPicker(SALES_TEAM); + const events = collectEvents(config); + const sortedEventKeys = [...events.keys()].sort((a, b) => a - b); + + const steps: PlanStep[] = []; + const threadWindow: string[] = []; + let simDay = 0; + let refCounter = 0; + let attemptIndex = 0; + + const nextBoundaryAfter = (count: number): number => { + for (const key of sortedEventKeys) { + if (key > count) return key; + } + return config.targetMessages; + }; + + const emitEventsAt = (count: number): void => { + const due = events.get(count); + if (due === undefined) return; + for (const step of due) { + if (step.kind === "routineAdvance") { + simDay += 1; + steps.push({ kind: "routineAdvance", simDay }); + } else { + steps.push(step); + } + } + events.delete(count); + }; + + emitEventsAt(0); + + let messagesSoFar = 0; + while (messagesSoFar < config.targetMessages) { + attemptIndex += 1; + const remaining = config.targetMessages - messagesSoFar; + const boundary = nextBoundaryAfter(messagesSoFar); + const roomBeforeBoundary = boundary - messagesSoFar; + + if ( + config.burstEvery > 0 && + config.burstSize > 0 && + attemptIndex % config.burstEvery === 0 + ) { + const size = Math.max( + 1, + Math.min(config.burstSize, remaining, roomBeforeBoundary), + ); + const sends = Array.from({ length: size }, () => { + const persona = pickPersona(rng); + return { actor: persona.key, text: utterance(persona, rng, simDay) }; + }); + steps.push({ kind: "burst", sends }); + messagesSoFar += size; + } else if ( + config.realTurnEvery > 0 && + attemptIndex % config.realTurnEvery === 0 + ) { + const persona = pickPersona(rng); + steps.push({ + kind: "realTurn", + actor: persona.key, + text: utterance(persona, rng, simDay), + agent: REAL_AGENT_KEY, + }); + messagesSoFar += 1; + } else { + const persona = pickPersona(rng); + const step: PlanStep = { + kind: "say", + actor: persona.key, + text: utterance(persona, rng, simDay), + }; + if (config.mentionEvery > 0 && attemptIndex % config.mentionEvery === 0) { + step.mentions = [MENTION_AGENT_KEY]; + } + if (threadWindow.length > 0 && rng() < config.threadReplyRate) { + step.inReplyToRef = pick(rng, threadWindow); + } + if (attemptIndex % THREAD_ROOT_EVERY === 0) { + refCounter += 1; + const ref = `say-${refCounter}`; + step.ref = ref; + threadWindow.push(ref); + if (threadWindow.length > THREAD_WINDOW_SIZE) threadWindow.shift(); + } + steps.push(step); + messagesSoFar += 1; + } + + emitEventsAt(messagesSoFar); + } + + return steps; +} + +export function summarizePlan(steps: readonly PlanStep[]): { + says: number; + burstSends: number; + realTurns: number; + checkpoints: number[]; +} { + let says = 0; + let burstSends = 0; + let realTurns = 0; + const checkpoints: number[] = []; + for (const step of steps) { + switch (step.kind) { + case "say": + says += 1; + break; + case "burst": + burstSends += step.sends.length; + break; + case "realTurn": + realTurns += 1; + break; + case "checkpoint": + checkpoints.push(step.atMessages); + break; + default: + break; + } + } + return { says, burstSends, realTurns, checkpoints }; +} diff --git a/packages/longevity-sim/src/prng.ts b/packages/longevity-sim/src/prng.ts new file mode 100644 index 000000000..a083a3266 --- /dev/null +++ b/packages/longevity-sim/src/prng.ts @@ -0,0 +1,24 @@ +// mulberry32: small, fast, seeded PRNG — good enough for deterministic +// simulation, not for anything security-sensitive. +export function createRng(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = state; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +export function pick(rng: () => number, items: readonly T[]): T { + if (items.length === 0) { + throw new Error("pick: items must be non-empty"); + } + const index = Math.floor(rng() * items.length); + const item = items[Math.min(index, items.length - 1)]; + if (item === undefined) { + throw new Error("pick: index out of range"); + } + return item; +} diff --git a/packages/longevity-sim/src/probes.ts b/packages/longevity-sim/src/probes.ts new file mode 100644 index 000000000..803b491de --- /dev/null +++ b/packages/longevity-sim/src/probes.ts @@ -0,0 +1,231 @@ +// Pure parsers (unit-tested, no network/DB) plus the network+DB +// collector that turns one checkpoint's live reads into a +// `CheckpointRecord`. The collector talks only to the booted stack's +// public HTTP surface, its scratch Postgres, and `ps` against the two +// pids `stack.ts` resolved at boot. + +import { readFile } from "node:fs/promises"; + +import { percentile, type CheckpointRecord } from "./metrics"; +import { api, expectStatus } from "../../../scripts/e2e/harness.ts"; +import { arrayField, type LongevityStack } from "./stack"; + +/** Parses `ps -o rss= -p ` output (kB on both Linux and macOS) into + * bytes. Returns 0 for blank/unparseable output — a dead or unresolved + * pid, never a thrown error, since a probe must never abort a + * checkpoint over a missing RSS reading. */ +export function parseRssKb(psOutput: string): number { + const trimmed = psOutput.trim(); + if (trimmed === "") return 0; + const kb = Number(trimmed.split(/\s+/)[0]); + if (!Number.isFinite(kb) || kb < 0) return 0; + return kb * 1024; +} + +export interface LogSignatureCounts { + collectorFailures: number; + fanoutFailures: number; + deadLetters: number; + schedulerFailures: number; +} + +const COLLECTOR_FAILURE_SIGNATURES = [ + "Failed to persist event", + "turn_part insert failed", +]; +const FANOUT_FAILURE_SIGNATURE = "Routing failed for workbench"; +const DEAD_LETTER_SIGNATURE = "dead-lettered"; +const SCHEDULER_FAILURE_SIGNATURE = "scheduled fire of routine"; + +function countOccurrences(log: string, needle: string): number { + if (needle === "") return 0; + let count = 0; + let index = log.indexOf(needle); + while (index !== -1) { + count += 1; + index = log.indexOf(needle, index + needle.length); + } + return count; +} + +/** Counts the log-signature families the campaign treats as + * degradation evidence, over the full accumulated hub log (cumulative + * across restarts — see `stack.ts`'s continuous flush to `hubLogPath`). + * "scheduled fire of routine" only counts as a failure when paired with + * a failure-shaped suffix on the same line, never a routine's ordinary + * successful fire log line. */ +export function countLogSignatures(log: string): LogSignatureCounts { + let collectorFailures = 0; + for (const signature of COLLECTOR_FAILURE_SIGNATURES) { + collectorFailures += countOccurrences(log, signature); + } + const fanoutFailures = countOccurrences(log, FANOUT_FAILURE_SIGNATURE); + const deadLetters = countOccurrences(log, DEAD_LETTER_SIGNATURE); + + let schedulerFailures = 0; + for (const line of log.split("\n")) { + if (!line.includes(SCHEDULER_FAILURE_SIGNATURE)) continue; + if (/fail|error|reject/i.test(line)) schedulerFailures += 1; + } + + return { collectorFailures, fanoutFailures, deadLetters, schedulerFailures }; +} + +async function rssBytes(pid: number | undefined): Promise { + if (pid === undefined) return 0; + const proc = Bun.spawn(["ps", "-o", "rss=", "-p", String(pid)], { + stdout: "pipe", + stderr: "pipe", + }); + const output = await new Response(proc.stdout).text(); + await proc.exited; + return parseRssKb(output); +} + +async function timed( + run: () => Promise, +): Promise<{ ms: number; value: T }> { + const start = performance.now(); + const value = await run(); + return { ms: performance.now() - start, value }; +} + +export interface CheckpointWindow { + atMessages: number; + wallClockStartedAtMs: number; + sendLatenciesMs: number[]; + turnLatenciesMs: number[]; + firstTokenLatenciesMs: number[]; + sendFailures: number; + turnFailures: number; + routineFiresTotal: number; + routineFiresAccepted: number; +} + +export function newCheckpointWindow( + atMessages: number, + campaignStartedAtMs: number, +): CheckpointWindow { + return { + atMessages, + wallClockStartedAtMs: campaignStartedAtMs, + sendLatenciesMs: [], + turnLatenciesMs: [], + firstTokenLatenciesMs: [], + sendFailures: 0, + turnFailures: 0, + routineFiresTotal: 0, + routineFiresAccepted: 0, + }; +} + +/** + * Collects one checkpoint's `CheckpointRecord`: db size, newest-page and + * 5-page-deep message read latency, a workbench list read, both + * processes' RSS, cumulative log-signature counts, and the window's own + * latency arrays. `sendFailures`/`turnFailures`/`routineFiresTotal`/ + * `routineFiresAccepted` are cumulative counters the campaign engine + * threads through — this collector only folds them into the record, it + * never resets them (that is `executeCampaign`'s job between + * checkpoints). + */ +export async function collectCheckpoint( + stack: LongevityStack, + window: CheckpointWindow, + cumulative: { + collectorFailures: number; + sendFailures: number; + turnFailures: number; + routineFiresTotal: number; + routineFiresAccepted: number; + }, +): Promise { + const dbSizeRows = await stack.sql.unsafe( + "SELECT pg_database_size(current_database()) AS bytes", + ); + const dbSizeBytes = Number(dbSizeRows[0]?.["bytes"] ?? 0); + + const pageRes = await timed(async () => { + const res = await api( + stack.baseUrl, + "GET", + `/api/tenants/${stack.tenantId}/chat/workbenches/${stack.workbenchId}/messages`, + undefined, + stack.ownerCookies, + ); + expectStatus("checkpoint: newest message page", res, 200); + return res; + }); + + let deepCursor: string | undefined; + let deepMs = 0; + for (let page = 0; page < 5; page++) { + const pageResult = await timed(async () => { + const route = + deepCursor === undefined + ? `/api/tenants/${stack.tenantId}/chat/workbenches/${stack.workbenchId}/messages` + : `/api/tenants/${stack.tenantId}/chat/workbenches/${stack.workbenchId}/messages?cursor=${encodeURIComponent(deepCursor)}`; + const res = await api( + stack.baseUrl, + "GET", + route, + undefined, + stack.ownerCookies, + ); + expectStatus(`checkpoint: message page ${page}`, res, 200); + return res; + }); + deepMs += pageResult.ms; + const data = pageResult.value.data as { nextCursor?: string }; + if (data.nextCursor === undefined) break; + deepCursor = data.nextCursor; + } + + const workbenchListRes = await timed(async () => { + const res = await api( + stack.baseUrl, + "GET", + `/api/tenants/${stack.tenantId}/chat/workbenches`, + undefined, + stack.ownerCookies, + ); + expectStatus("checkpoint: workbench list", res, 200); + arrayField(res.data, "items", "checkpoint: workbench list"); + return res; + }); + + const [hubRssBytes, sidecarRssBytes] = await Promise.all([ + rssBytes(stack.hubPid()), + rssBytes(stack.sidecarPid()), + ]); + + const hubLog = await readFile(stack.hubLogPath, "utf8").catch(() => ""); + const signatures = countLogSignatures(hubLog); + + return { + atMessages: window.atMessages, + wallClockMs: Date.now() - window.wallClockStartedAtMs, + sendLatencyP50Ms: percentile(window.sendLatenciesMs, 50), + sendLatencyP95Ms: percentile(window.sendLatenciesMs, 95), + sendLatencyMaxMs: window.sendLatenciesMs.reduce( + (m, v) => Math.max(m, v), + 0, + ), + turnLatencyP50Ms: percentile(window.turnLatenciesMs, 50), + turnLatencyP95Ms: percentile(window.turnLatenciesMs, 95), + turnCount: window.turnLatenciesMs.length, + firstTokenP50Ms: percentile(window.firstTokenLatenciesMs, 50), + dbSizeBytes, + messagePageMs: pageRes.ms, + messagePageDeepMs: deepMs, + workbenchListMs: workbenchListRes.ms, + hubRssBytes, + sidecarRssBytes, + collectorFailures: + signatures.collectorFailures + cumulative.collectorFailures, + routineFiresTotal: cumulative.routineFiresTotal, + routineFiresAccepted: cumulative.routineFiresAccepted, + sendFailures: cumulative.sendFailures, + turnFailures: cumulative.turnFailures, + }; +} diff --git a/packages/longevity-sim/src/report.ts b/packages/longevity-sim/src/report.ts new file mode 100644 index 000000000..cc5889d5c --- /dev/null +++ b/packages/longevity-sim/src/report.ts @@ -0,0 +1,164 @@ +import type { CampaignConfig } from "./config"; +import type { CheckpointRecord, Knee } from "./metrics"; + +export interface Defect { + severity: "S1" | "S2" | "S3"; + title: string; + detail: string; + atMessages: number; +} + +export interface CampaignReport { + name: string; + startedAt: string; + config: CampaignConfig; + checkpoints: readonly CheckpointRecord[]; + defects: readonly Defect[]; + knees: readonly Knee[]; + selfImprovement: readonly { name: string; pass: boolean; detail: string }[]; + notes: readonly string[]; +} + +const SEVERITY_ORDER: readonly Defect["severity"][] = ["S1", "S2", "S3"]; + +function formatBytes(bytes: number): string { + if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)}MB`; + if (bytes >= 1024) return `${(bytes / 1024).toFixed(1)}KB`; + return `${bytes}B`; +} + +function formatMs(ms: number): string { + if (ms >= 1000) return `${(ms / 1000).toFixed(1)}s`; + return `${Math.round(ms)}ms`; +} + +function renderCheckpointTable( + checkpoints: readonly CheckpointRecord[], +): string[] { + if (checkpoints.length === 0) { + return ["_no checkpoints recorded_", ""]; + } + const lines = [ + "| messages | wall clock | send p50 | send p95 | turn p50 | msg page | msg page (deep) | workbench list | hub RSS | db size |", + "| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |", + ]; + for (const checkpoint of checkpoints) { + lines.push( + `| ${checkpoint.atMessages} | ${formatMs(checkpoint.wallClockMs)} | ` + + `${formatMs(checkpoint.sendLatencyP50Ms)} | ${formatMs(checkpoint.sendLatencyP95Ms)} | ` + + `${formatMs(checkpoint.turnLatencyP50Ms)} | ${formatMs(checkpoint.messagePageMs)} | ` + + `${formatMs(checkpoint.messagePageDeepMs)} | ${formatMs(checkpoint.workbenchListMs)} | ` + + `${formatBytes(checkpoint.hubRssBytes)} | ${formatBytes(checkpoint.dbSizeBytes)} |`, + ); + } + lines.push(""); + return lines; +} + +function renderSelfImprovementTable( + selfImprovement: CampaignReport["selfImprovement"], +): string[] { + if (selfImprovement.length === 0) { + return ["_no self-improvement checks recorded_", ""]; + } + const lines = ["| check | result | detail |", "| --- | --- | --- |"]; + for (const check of selfImprovement) { + lines.push( + `| ${check.name} | ${check.pass ? "PASS" : "FAIL"} | ${check.detail} |`, + ); + } + lines.push(""); + return lines; +} + +function renderDefectLog(defects: readonly Defect[]): string[] { + if (defects.length === 0) { + return ["_no defects recorded_", ""]; + } + const lines: string[] = []; + for (const severity of SEVERITY_ORDER) { + const forSeverity = defects.filter( + (defect) => defect.severity === severity, + ); + if (forSeverity.length === 0) continue; + lines.push(`### ${severity}`, ""); + for (const defect of forSeverity) { + lines.push( + `- **${defect.title}** (at ${defect.atMessages} messages): ${defect.detail}`, + ); + } + lines.push(""); + } + return lines; +} + +function renderKnees(knees: readonly Knee[]): string[] { + if (knees.length === 0) { + return ["_no metric crossed the knee threshold_", ""]; + } + const lines = [ + "| metric | at messages | baseline | value | ratio |", + "| --- | --- | --- | --- | --- |", + ]; + for (const knee of knees) { + lines.push( + `| ${knee.metric} | ${knee.atMessages} | ${knee.baseline.toFixed(1)} | ` + + `${knee.value.toFixed(1)} | ${knee.ratio.toFixed(1)}x |`, + ); + } + lines.push(""); + return lines; +} + +export function reportVerdict(report: CampaignReport): string { + if (report.knees.length === 0) { + return ( + `${report.name} ran ${report.config.targetMessages} messages across ` + + `${report.checkpoints.length} checkpoints with no metric crossing the ` + + `degradation threshold — no first point of failure identified in this run.` + ); + } + const earliest = [...report.knees].sort( + (a, b) => a.atMessages - b.atMessages, + )[0]; + if (earliest === undefined) { + return `${report.name}: no degradation detected.`; + } + return ( + `${report.name} first degrades at ${earliest.atMessages} messages, where ` + + `${earliest.metric} reached ${earliest.ratio.toFixed(1)}x its baseline of ` + + `${earliest.baseline.toFixed(1)} — that is the first point this run's data shows the stack losing headroom.` + ); +} + +export function renderCampaignReport(report: CampaignReport): string { + const lines = [ + `# Longevity report: ${report.name}`, + "", + `Started: ${report.startedAt}`, + `Seed: ${report.config.seed} — target messages: ${report.config.targetMessages}`, + "", + "## Checkpoints", + "", + ...renderCheckpointTable(report.checkpoints), + "## Self-improvement checks", + "", + ...renderSelfImprovementTable(report.selfImprovement), + "## Defects", + "", + ...renderDefectLog(report.defects), + "## Knees", + "", + ...renderKnees(report.knees), + "## Verdict", + "", + reportVerdict(report), + "", + ]; + if (report.notes.length > 0) { + lines.push("## Notes", ""); + for (const note of report.notes) lines.push(`- ${note}`); + lines.push(""); + } + return lines.join("\n"); +} diff --git a/packages/longevity-sim/src/stack.ts b/packages/longevity-sim/src/stack.ts new file mode 100644 index 000000000..8a25269c3 --- /dev/null +++ b/packages/longevity-sim/src/stack.ts @@ -0,0 +1,1020 @@ +// Boots one real workbench stack (hub + sidecar + Postgres) for a +// longevity campaign: ~10 signed-up humans in one tenant, real +// Ollama-backed inference targets only (no Anthropic, no stub/noop +// model), one multi-participant workbench, real agent definitions +// invited into it, one skill, and interval routines bound to a +// deployed heartbeat definition pinned at a real target. Mirrors the +// proven e2e boots (`scripts/e2e/chat.test.ts` for tenancy/workbench +// mechanics, `scripts/e2e/routine-repeat.test.ts` for the catalog-seed +// + heartbeat-deploy shape) without reinventing any of it — only the +// inference source differs: every catalog provider here rides the +// `openai-compatible` adapter against an Ollama origin, matching how +// `packages/hub-client/src/credential-test.ts` documents Ollama's own +// `/v1` wire shape. + +import { mkdtemp, rm, appendFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { resetSchema, setupDatabase } from "../../../scripts/db-setup.ts"; +import { + api, + connectE2eDb, + expectStatus, + freePort, + provisionSidecar, + pushWorkflowSource, + runCleanups, + startHub, + startSidecar, + workflowDeployBody, + type ApiResult, + type HubHandle, + type SpawnedApp, +} from "../../../scripts/e2e/harness.ts"; +import { + buildHeartbeatWorkflow, + serializeHeartbeatWorkflow, +} from "../../../workflows/heartbeat/src/index.ts"; + +import { + buildCampaignAgentWorkflow, + serializeCampaignAgentWorkflow, +} from "./agent-workflow"; +import type { Persona } from "./personas"; + +export function stringField( + data: unknown, + field: string, + what: string, +): string { + if (typeof data === "object" && data !== null && field in data) { + const value = (data as Record)[field]; + if (typeof value === "string" && value !== "") return value; + } + throw new Error( + `${what}: missing string field "${field}": ${JSON.stringify(data)}`, + ); +} + +export function arrayField( + data: unknown, + field: string, + what: string, +): unknown[] { + if (typeof data === "object" && data !== null && field in data) { + const value = (data as Record)[field]; + if (Array.isArray(value)) return value; + } + throw new Error( + `${what}: missing array field "${field}": ${JSON.stringify(data)}`, + ); +} + +export interface SqlClient { + unsafe(query: string, params?: unknown[]): Promise[]>; + end(): Promise; +} + +export type InferenceTarget = { + label: string; + provider: string; + model: string; + baseURL: string; + apiKey: string; +}; + +/** One agent definition to seed. Every agent is real inference now — + * `targetLabel` must name a `realTargets` entry, whose catalog model + * the definition is pinned at. `real` stays on the type (and stays + * `true` for every spec) only so `StackAgent`/`engine.ts` keep one + * shared shape rather than growing a second, noop-only one. */ +export interface AgentDefinitionSpec { + key: string; + handle: string; + name: string; + systemPrompt: string; + real: true; + targetLabel: string; + /** Skill names (already registered via `skillSpecs`) this agent pins + * at creation. */ + skills?: readonly string[]; +} + +/** What one agent deploy (or redeploy) is built from — the workflow + * JSON pushed to the agent's asset is a pure function of this plus the + * current bodies of its pinned skills. */ +export interface AgentDeploySpec { + key: string; + handle: string; + name: string; + systemPrompt: string; + targetLabel: string; + skills?: readonly string[]; +} + +/** One skill to seed into the tenant's registry before agent + * definitions are created, so a `skills` pin above can resolve it. */ +export interface SkillSpec { + name: string; + description: string; + body: string; +} + +export interface RoutineSpec { + key: string; + name: string; +} + +export interface StackOptions { + databaseUrl: string; + realTargets: readonly InferenceTarget[]; + skills?: readonly SkillSpec[]; +} + +export interface StackActor { + key: string; + cookies: string[]; +} + +export interface StackAgent { + key: string; + handle: string; + definitionId: string; + real: boolean; +} + +export interface StackRoutine { + key: string; + id: string; +} + +export interface LongevityStack { + baseUrl: string; + tenantId: string; + workbenchId: string; + actors: ReadonlyMap; + agents: ReadonlyMap; + routines: ReadonlyMap; + ownerCookies: string[]; + hubLogPath: string; + restartHub(): Promise; + sql: SqlClient; + hubPid(): number | undefined; + sidecarPid(): number | undefined; + close(): Promise; + /** Every real inference target this stack seeded into the catalog, + * in the order given — `engine.ts`'s `providerSwitch` step cycles a + * real agent's model through this list. Empty when the campaign ran + * with no `realTargets`. */ + realTargets: readonly InferenceTarget[]; + /** `(skill name) -> (agent key)` for every seeded skill that was + * attached to an agent at creation — `engine.ts`'s `skillEdit`/ + * `skillProbe` steps use this to find the skill and agent a marker + * edit targets. */ + skillOwners: ReadonlyMap; + /** Deploys a fresh agent through the working freeze path (asset -> + * source push -> deployment -> invite) — the only path whose + * definitions are launchable (known blocker D1: bare + * `POST /agent-definitions` rows carry no frozen projection). */ + deployAgent(spec: AgentDeploySpec): Promise; + /** Pushes a new commit to an existing agent's asset and redeploys it + * — how a mid-campaign skill edit or provider switch actually + * reaches later launches. */ + redeployAgent( + agentKey: string, + changes: { + targetLabel?: string; + skillBody?: { name: string; body: string }; + }, + ): Promise; +} + +async function signUp( + baseUrl: string, + name: string, +): Promise<{ userId: string; email: string; cookies: string[] }> { + const email = `longevity-${crypto.randomUUID()}@example.invalid`; + // better-auth rate-limits the sign-up route per IP; ten cast members + // signing up back-to-back trips it, so 429s get a bounded backoff. + const deadline = Date.now() + 180_000; + let res = await api(baseUrl, "POST", "/api/auth/sign-up/email", { + name, + email, + password: `pw-${crypto.randomUUID()}`, + }); + while (res.status === 429 && Date.now() < deadline) { + await Bun.sleep(15_000); + res = await api(baseUrl, "POST", "/api/auth/sign-up/email", { + name, + email, + password: `pw-${crypto.randomUUID()}`, + }); + } + expectStatus(`sign-up for ${name}`, res, 200); + if (res.cookies.length === 0) { + throw new Error(`sign-up for ${name} returned no session cookie`); + } + const userId = stringField( + (res.data as { user: unknown }).user, + "id", + `sign-up user field for ${name}`, + ); + return { userId, email, cookies: res.cookies }; +} + +/** + * Resolves the OS pid of whichever local process holds a socket naming + * `port` — the hub's own listening pid (`LISTEN`) and, once the + * sidecar's WebSocket dial-in has completed, the sidecar's pid too + * (`ESTABLISHED`, its remote port equal to the hub's). Both processes + * are loopback-local, so `lsof -iTCP:` sees both ends of the + * connection without needing either process's own pid handed to us — + * `startHub`/`startSidecar` (scripts/e2e/harness.ts) expose no pid of + * their own, and this package must never fork that shared harness to + * add one. + */ +async function resolvePortPids( + port: number, +): Promise<{ hubPid: number | undefined; sidecarPid: number | undefined }> { + const proc = Bun.spawn(["lsof", "-nP", `-iTCP:${port}`], { + stdout: "pipe", + stderr: "pipe", + }); + const output = await new Response(proc.stdout).text(); + await proc.exited; + + let hubPid: number | undefined; + let sidecarPid: number | undefined; + for (const line of output.split("\n").slice(1)) { + const fields = line.trim().split(/\s+/); + const pidField = fields[1]; + const state = fields[fields.length - 1]; + if (pidField === undefined || state === undefined) continue; + const pid = Number(pidField); + if (!Number.isFinite(pid)) continue; + if (state.includes("LISTEN")) hubPid = pid; + else if (state.includes("ESTABLISHED") && pid !== hubPid) sidecarPid = pid; + } + return { hubPid, sidecarPid }; +} + +export async function bootLongevityStack( + personas: readonly Persona[], + agentSpecs: readonly AgentDefinitionSpec[], + routineSpecs: readonly RoutineSpec[], + options: StackOptions, +): Promise { + const cleanups: (() => Promise | void)[] = []; + const close = () => runCleanups(cleanups); + + try { + await resetSchema(options.databaseUrl); + await setupDatabase(options.databaseUrl); + + const sidecarId = `longevity-${crypto.randomUUID().slice(0, 8)}`; + const sidecarToken = crypto.randomUUID(); + process.stderr.write("boot: sidecar row\n"); + await provisionSidecar(options.databaseUrl, sidecarId, sidecarToken); + process.stderr.write("boot: sidecar row done\n"); + + const hubDataDir = await mkdtemp( + path.join(tmpdir(), "longevity-hub-data-"), + ); + cleanups.push(() => rm(hubDataDir, { recursive: true, force: true })); + const sidecarDataDir = await mkdtemp( + path.join(tmpdir(), "longevity-sidecar-data-"), + ); + cleanups.push(() => rm(sidecarDataDir, { recursive: true, force: true })); + + const hubLogDir = await mkdtemp(path.join(tmpdir(), "longevity-hub-log-")); + cleanups.push(() => rm(hubLogDir, { recursive: true, force: true })); + const hubLogPath = path.join(hubLogDir, "hub.log"); + await Bun.write(hubLogPath, ""); + + const port = freePort(); + const sessionSecret = Buffer.from( + crypto.getRandomValues(new Uint8Array(32)), + ).toString("hex"); + + // No inference API key ever reaches either child process: `startHub`/ + // `startSidecar` (scripts/e2e/harness.ts) build each child's env from + // an explicit whitelist (`osEnv()`: PATH/HOME/TMPDIR/USER) plus this + // call's own `extraEnv`, never a spread of this process's full + // `process.env` — so a shell-inherited ANTHROPIC_API_KEY/ + // OPENAI_API_KEY can never leak in, and this stack passes no + // `extraEnv` of its own that could reintroduce one. Verified by + // reading `spawnApp`/`startHub` directly rather than assumed. + process.stderr.write("boot: starting hub\n"); + let hub: HubHandle = await startHub({ + databaseUrl: options.databaseUrl, + port, + sessionSecret, + dataDir: hubDataDir, + }); + cleanups.push(() => hub.stop()); + + let flushedLength = 0; + async function flushHubLog(): Promise { + const full = hub.output(); + if (full.length > flushedLength) { + await appendFile(hubLogPath, full.slice(flushedLength)); + flushedLength = full.length; + } + } + + const flushTimer = setInterval(() => { + void flushHubLog(); + }, 2000); + cleanups.push(async () => { + clearInterval(flushTimer); + await flushHubLog(); + }); + + process.stderr.write("boot: hub up, starting sidecar\n"); + const sidecar: SpawnedApp = startSidecar({ + hubPort: port, + sidecarId, + token: sidecarToken, + dataDir: sidecarDataDir, + }); + cleanups.push(() => sidecar.stop()); + + let hubPid: number | undefined; + let sidecarPid: number | undefined; + const pidDeadline = Date.now() + 30_000; + while (sidecarPid === undefined && Date.now() < pidDeadline) { + const resolved = await resolvePortPids(port); + hubPid = resolved.hubPid ?? hubPid; + sidecarPid = resolved.sidecarPid ?? sidecarPid; + if (sidecarPid === undefined) await Bun.sleep(500); + } + + const humanEntries = personas; + const first = humanEntries[0]; + if (first === undefined) + throw new Error("bootLongevityStack: no personas given"); + + process.stderr.write("boot: signup owner\n"); + const owner = await signUp(hub.baseUrl, first.name); + const slug = `longevity${crypto.randomUUID().slice(0, 8)}`; + const tenantRes = await api( + hub.baseUrl, + "POST", + "/api/tenants", + { name: `Longevity: ${first.name}'s team`, slug }, + owner.cookies, + ); + expectStatus("create tenant", tenantRes, 201); + const tenantId = stringField(tenantRes.data, "id", "create tenant"); + + const actors = new Map(); + actors.set(first.key, { key: first.key, cookies: owner.cookies }); + + async function plantGrant( + principalId: string, + resource: string, + action: string, + ): Promise { + const res = await api( + hub.baseUrl, + "POST", + `/api/tenants/${tenantId}/grants`, + { principalId, resource, action, effect: "allow", origin: "creator" }, + owner.cookies, + ); + expectStatus(`grant ${resource}/${action} to ${principalId}`, res, 201); + } + + for (const persona of humanEntries.slice(1)) { + const member = await signUp(hub.baseUrl, persona.name); + const invited = await api( + hub.baseUrl, + "POST", + `/api/tenants/${tenantId}/members/invite`, + { email: member.email }, + owner.cookies, + ); + expectStatus(`invite ${persona.name}`, invited, 201); + const principalId = stringField( + invited.data, + "id", + `invite ${persona.name}`, + ); + const activated = await api( + hub.baseUrl, + "PATCH", + `/api/tenants/${tenantId}/principals/${principalId}`, + { status: "active" }, + owner.cookies, + ); + expectStatus(`activate ${persona.name}`, activated, 200); + + for (const [resource, action] of [ + ["workflow-run:*", "read"], + ["workflow-run:*", "write"], + ["workflow-run:*", "create"], + ["room:*", "read"], + ["room:*", "write"], + ] as const) { + await plantGrant(principalId, resource, action); + } + actors.set(persona.key, { key: persona.key, cookies: member.cookies }); + } + + if (options.realTargets.length === 0) { + throw new Error( + "bootLongevityStack: no realTargets given — this stack seeds no " + + "Anthropic/noop fallback catalog chain, so at least one real " + + "(Ollama, openai-compatible) target is required", + ); + } + + // Every catalog provider rides the `openai-compatible` adapter + // against an Ollama origin — never `anthropic`, never the hub's + // noop-inference endpoint. Ollama needs no real secret + // (`credential-test.ts`'s `OLLAMA_PLACEHOLDER_SECRET`), but the + // credential row still requires some string, so each target's own + // `apiKey` (expected to be the same placeholder) is threaded through + // unchanged rather than this package inventing its own convention. + async function seedCatalogChain(target: InferenceTarget): Promise { + const model = await api( + hub.baseUrl, + "POST", + `/api/tenants/${tenantId}/catalog/models`, + { canonicalName: target.model }, + owner.cookies, + ); + expectStatus(`create catalog model ${target.model}`, model, 201); + const modelId = stringField(model.data, "id", "create catalog model"); + + const providerName = `ollama-${target.label}`; + const provider = await api( + hub.baseUrl, + "POST", + `/api/tenants/${tenantId}/providers`, + { name: providerName, plugin: "openai-compatible" }, + owner.cookies, + ); + expectStatus(`create provider ${providerName}`, provider, 201); + const providerId = stringField(provider.data, "id", "create provider"); + + const credential = await api( + hub.baseUrl, + "POST", + `/api/tenants/${tenantId}/credentials`, + { + providerId, + name: `${providerName}-default`, + type: "api_key", + secret: target.apiKey, + }, + owner.cookies, + ); + expectStatus(`create credential ${providerName}`, credential, 201); + const credentialId = stringField( + credential.data, + "id", + "create credential", + ); + + const catalogProvider = await api( + hub.baseUrl, + "POST", + `/api/tenants/${tenantId}/catalog/providers`, + { + name: providerName, + plugin: "openai-compatible", + baseURL: target.baseURL, + credentialId, + }, + owner.cookies, + ); + expectStatus( + `create catalog provider ${providerName}`, + catalogProvider, + 201, + ); + const catalogProviderId = stringField( + catalogProvider.data, + "id", + "create catalog provider", + ); + + const offering = await api( + hub.baseUrl, + "POST", + `/api/tenants/${tenantId}/catalog/offerings`, + { modelId, providerId: catalogProviderId }, + owner.cookies, + ); + expectStatus(`create catalog offering ${target.model}`, offering, 201); + } + + for (const target of options.realTargets) { + await seedCatalogChain(target); + } + + for (const skill of options.skills ?? []) { + const created = await api( + hub.baseUrl, + "POST", + `/api/tenants/${tenantId}/skills`, + { + name: skill.name, + description: skill.description, + body: skill.body, + scope: "tenant", + }, + owner.cookies, + ); + expectStatus(`create skill ${skill.name}`, created, 201); + } + + // The delivery/gathering room: one multi-participant workbench every + // human and every agent below is invited into (`chat.test.ts`'s + // "workbench" kind, not the 1:1 "chat" kind — this stack needs one + // shared room, not a per-agent DM). + let workbenchRes: ApiResult; + const workbenchDeadline = Date.now() + 60_000; + for (;;) { + if (sidecar.exited()) { + throw new Error( + `sidecar exited before workbench creation; output:\n${sidecar.output()}`, + ); + } + workbenchRes = await api( + hub.baseUrl, + "POST", + `/api/tenants/${tenantId}/chat/workbenches`, + { kind: "workbench", name: "Longevity campaign" }, + owner.cookies, + ); + if (workbenchRes.status !== 500) break; + if (Date.now() > workbenchDeadline) { + throw new Error( + `workbench never became launchable: ${JSON.stringify(workbenchRes.data)}\n` + + `sidecar output:\n${sidecar.output()}`, + ); + } + await Bun.sleep(1000); + } + expectStatus("create workbench", workbenchRes, 201); + const workbenchId = stringField( + workbenchRes.data, + "id", + "create workbench", + ); + + const domain = stringField(tenantRes.data, "domain", "create tenant"); + const agents = new Map(); + const skillOwners = new Map(); + const skillBodies = new Map(); + for (const skill of options.skills ?? []) { + skillBodies.set(skill.name, skill.body); + } + // Per-agent deploy state `redeployAgent` rebuilds from: the base + // prompt/target plus the asset the first deploy claimed, so a + // redeploy pushes a new commit to the SAME asset and the launch + // path's newest-projection resolution picks it up. + const agentDeployState = new Map< + string, + { + spec: AgentDeploySpec; + assetId: string; + skills: Map; + } + >(); + + function agentSystemPrompt( + spec: AgentDeploySpec, + skills: ReadonlyMap, + ): string { + // D2/D3 (tools+history dropped on the openai-compatible path) + // means skill delivery via tool/memory machinery never reaches + // the model — inlining the pinned skill bodies into the system + // prompt is the one channel a skill edit can honestly reach a + // turn through, exercised end-to-end by redeploying the asset. + let prompt = spec.systemPrompt; + for (const [name, body] of skills) { + prompt += `\n\nSkill "${name}": ${body}`; + } + return prompt; + } + + async function deployAgentAsset(input: { + spec: AgentDeploySpec; + assetId: string | undefined; + skills: ReadonlyMap; + }): Promise<{ assetId: string; definitionId: string }> { + const { spec } = input; + const target = options.realTargets.find( + (t) => t.label === spec.targetLabel, + ); + if (target === undefined) { + throw new Error( + `agent ${spec.key}: no realTarget labeled "${spec.targetLabel}"`, + ); + } + let assetId = input.assetId; + if (assetId === undefined) { + const assetCreated = await api( + hub.baseUrl, + "POST", + `/api/tenants/${tenantId}/assets`, + { kind: "workflow", name: spec.handle }, + owner.cookies, + ); + expectStatus(`create agent asset ${spec.handle}`, assetCreated, 201); + assetId = stringField( + assetCreated.data, + "id", + `create agent asset ${spec.handle}`, + ); + } + + const minted = await api( + hub.baseUrl, + "POST", + `/api/tenants/${tenantId}/git-tokens`, + { + name: `longevity-agent-push-${spec.handle}-${crypto.randomUUID().slice(0, 8)}`, + resource: "asset:*", + refPattern: "**", + actions: ["can_read", "can_push"], + expiresAt: new Date(Date.now() + 10 * 60_000).toISOString(), + }, + owner.cookies, + ); + expectStatus(`mint git token for agent ${spec.handle}`, minted, 201); + + const workflowJson = serializeCampaignAgentWorkflow( + buildCampaignAgentWorkflow({ + handle: spec.handle, + tenantDomain: domain, + description: spec.name, + systemPrompt: agentSystemPrompt(spec, input.skills), + inferencePreferences: [ + { provider: target.provider, model: target.model }, + ], + turnTimeoutMs: 240_000, + }), + ); + const pushed = await pushWorkflowSource({ + baseUrl: hub.baseUrl, + tenantId, + assetName: spec.handle, + tokenSecret: stringField(minted.data, "secret", "mint git token"), + workflowJson, + }); + + const deployDeadline = Date.now() + 90_000; + for (;;) { + if (sidecar.exited()) { + throw new Error( + `sidecar exited before agent ${spec.handle} deploy; output:\n${sidecar.output()}`, + ); + } + const deployed = await api( + hub.baseUrl, + "POST", + `/api/tenants/${tenantId}/workflows/deployments`, + workflowDeployBody({ + assetId, + commitSha: pushed.commitSha, + sourceId: `src-agent-${spec.handle}`, + provider: target.provider, + baseURL: target.baseURL, + apiKey: target.apiKey, + model: target.model, + }), + owner.cookies, + ); + if (deployed.status !== 502) { + expectStatus(`deploy agent ${spec.handle}`, deployed, 201); + break; + } + if (Date.now() > deployDeadline) { + throw new Error( + `agent ${spec.handle} never became deployable (502): ` + + `last body: ${JSON.stringify(deployed.data)}\n` + + `sidecar output:\n${sidecar.output()}`, + ); + } + await Bun.sleep(1000); + } + + const listed = await api( + hub.baseUrl, + "GET", + `/api/tenants/${tenantId}/workflows/definitions`, + undefined, + owner.cookies, + ); + expectStatus(`list definitions for agent ${spec.handle}`, listed, 200); + const rows = + typeof listed.data === "object" && + listed.data !== null && + "data" in listed.data + ? ((listed.data as { data: unknown[] }).data as { + id: string; + name?: string; + }[]) + : (listed.data as { id: string; name?: string }[]); + const found = rows.find((row) => row.name === spec.handle); + if (found === undefined) { + throw new Error( + `no workflow definition named "${spec.handle}" after deploy`, + ); + } + return { assetId, definitionId: found.id }; + } + + async function deployAgent(spec: AgentDeploySpec): Promise { + const pinned = new Map(); + for (const skillName of spec.skills ?? []) { + const body = skillBodies.get(skillName); + if (body === undefined) { + throw new Error( + `agent ${spec.key} pins unknown skill "${skillName}"`, + ); + } + pinned.set(skillName, body); + skillOwners.set(skillName, spec.key); + } + const { assetId, definitionId } = await deployAgentAsset({ + spec, + assetId: undefined, + skills: pinned, + }); + agentDeployState.set(spec.key, { spec, assetId, skills: pinned }); + + const invited = await api( + hub.baseUrl, + "POST", + `/api/tenants/${tenantId}/chat/workbenches/${workbenchId}/invite`, + { definitionId }, + owner.cookies, + ); + expectStatus(`invite agent ${spec.key}`, invited, 201); + const address = stringField( + invited.data, + "address", + `invite agent ${spec.key}`, + ); + + const settings = await api( + hub.baseUrl, + "GET", + `/api/tenants/${tenantId}/chat/workbenches/${workbenchId}/settings`, + undefined, + owner.cookies, + ); + expectStatus(`read settings after inviting ${spec.key}`, settings, 200); + const participants = arrayField( + settings.data, + "participants", + `settings after inviting ${spec.key}`, + ) as { address: string; handle: string }[]; + const participant = participants.find((p) => p.address === address); + if (participant === undefined) { + throw new Error( + `agent ${spec.key} invited but missing from participants: ` + + JSON.stringify(participants), + ); + } + + const agent: StackAgent = { + key: spec.key, + handle: participant.handle, + definitionId, + real: true, + }; + agents.set(spec.key, agent); + return agent; + } + + async function redeployAgent( + agentKey: string, + changes: { + targetLabel?: string; + skillBody?: { name: string; body: string }; + }, + ): Promise { + const state = agentDeployState.get(agentKey); + const existing = agents.get(agentKey); + if (state === undefined || existing === undefined) { + throw new Error(`redeployAgent: no deployed agent "${agentKey}"`); + } + if (changes.targetLabel !== undefined) { + state.spec.targetLabel = changes.targetLabel; + } + if (changes.skillBody !== undefined) { + state.skills.set(changes.skillBody.name, changes.skillBody.body); + skillBodies.set(changes.skillBody.name, changes.skillBody.body); + } + const { definitionId } = await deployAgentAsset({ + spec: state.spec, + assetId: state.assetId, + skills: state.skills, + }); + const updated: StackAgent = { + key: existing.key, + handle: existing.handle, + definitionId, + real: true, + }; + agents.set(agentKey, updated); + return updated; + } + + for (const spec of agentSpecs) { + await deployAgent({ + key: spec.key, + handle: spec.handle, + name: spec.name, + systemPrompt: spec.systemPrompt, + targetLabel: spec.targetLabel, + skills: spec.skills ?? [], + }); + } + + // Routines: one heartbeat-workflow deployment per campaign, pinned at + // the first real target (never noop/anthropic), reused by every + // routine spec — each routine is its own row, but they all fire the + // same deployed definition. + const routineTarget = options.realTargets[0]; + if (routineTarget === undefined) { + throw new Error("unreachable: realTargets checked non-empty above"); + } + const assetName = "longevity-heartbeat"; + const heartbeatAssetCreated = await api( + hub.baseUrl, + "POST", + `/api/tenants/${tenantId}/assets`, + { kind: "workflow", name: assetName }, + owner.cookies, + ); + expectStatus("create heartbeat asset", heartbeatAssetCreated, 201); + const heartbeatAssetId = stringField( + heartbeatAssetCreated.data, + "id", + "create heartbeat asset", + ); + + const heartbeatGitToken = await api( + hub.baseUrl, + "POST", + `/api/tenants/${tenantId}/git-tokens`, + { + name: "longevity-heartbeat-push", + resource: "asset:*", + refPattern: "**", + actions: ["can_read", "can_push"], + expiresAt: new Date(Date.now() + 10 * 60_000).toISOString(), + }, + owner.cookies, + ); + expectStatus("mint heartbeat git token", heartbeatGitToken, 201); + + const heartbeatPushed = await pushWorkflowSource({ + baseUrl: hub.baseUrl, + tenantId, + assetName, + tokenSecret: stringField( + heartbeatGitToken.data, + "secret", + "mint git token", + ), + workflowJson: serializeHeartbeatWorkflow( + buildHeartbeatWorkflow({ + triggerAddress: `${assetName}@${domain}`, + inferencePreferences: [ + { provider: "openai-compatible", model: routineTarget.model }, + ], + turnTimeoutMs: 240_000, + }), + ), + }); + + const heartbeatDeployDeadline = Date.now() + 60_000; + let heartbeatDeployed: ApiResult; + for (;;) { + if (sidecar.exited()) { + throw new Error( + `sidecar exited before heartbeat deploy; output:\n${sidecar.output()}`, + ); + } + heartbeatDeployed = await api( + hub.baseUrl, + "POST", + `/api/tenants/${tenantId}/workflows/deployments`, + workflowDeployBody({ + assetId: heartbeatAssetId, + commitSha: heartbeatPushed.commitSha, + sourceId: "src-longevity-heartbeat", + provider: "openai-compatible", + baseURL: routineTarget.baseURL, + apiKey: routineTarget.apiKey, + model: routineTarget.model, + }), + owner.cookies, + ); + if (heartbeatDeployed.status !== 502) break; + if (Date.now() > heartbeatDeployDeadline) { + throw new Error( + `heartbeat never became deployable (502): ` + + `${JSON.stringify(heartbeatDeployed.data)}\nsidecar output:\n${sidecar.output()}`, + ); + } + await Bun.sleep(1000); + } + expectStatus("deploy heartbeat workflow", heartbeatDeployed, 201); + + const listedDefinitions = await api( + hub.baseUrl, + "GET", + `/api/tenants/${tenantId}/workflows/definitions`, + undefined, + owner.cookies, + ); + expectStatus("list workflow definitions", listedDefinitions, 200); + const definitionRows = + typeof listedDefinitions.data === "object" && + listedDefinitions.data !== null && + "data" in listedDefinitions.data + ? (listedDefinitions.data as { data: unknown[] }).data + : (listedDefinitions.data as unknown[]); + const heartbeatDefinition = ( + definitionRows as { id: string; name?: string }[] + ).find((row) => row.name === assetName); + if (heartbeatDefinition === undefined) { + throw new Error( + `no workflow definition named "${assetName}": ${JSON.stringify(listedDefinitions.data)}`, + ); + } + const heartbeatDefinitionId = heartbeatDefinition.id; + + const routines = new Map(); + for (const spec of routineSpecs) { + const created = await api( + hub.baseUrl, + "POST", + `/api/tenants/${tenantId}/routines`, + { + name: spec.name, + definitionId: heartbeatDefinitionId, + trigger: { kind: "interval", unit: "hours", every: 1 }, + scope: "bench", + deliveryWorkbenchId: workbenchId, + }, + owner.cookies, + ); + expectStatus(`create routine ${spec.key}`, created, 201); + routines.set(spec.key, { + key: spec.key, + id: stringField(created.data, "id", `create routine ${spec.key}`), + }); + } + + const sql = await connectE2eDb(options.databaseUrl); + cleanups.push(() => sql.end()); + + async function restartHub(): Promise { + await flushHubLog(); + await hub.stop(); + flushedLength = 0; + hub = await startHub({ + databaseUrl: options.databaseUrl, + port, + sessionSecret, + dataDir: hubDataDir, + }); + const resolved = await resolvePortPids(port); + hubPid = resolved.hubPid ?? hubPid; + } + + return { + baseUrl: hub.baseUrl, + tenantId, + workbenchId, + actors, + agents, + routines, + ownerCookies: owner.cookies, + hubLogPath, + restartHub, + sql, + hubPid: () => hubPid, + sidecarPid: () => sidecarPid, + close, + realTargets: options.realTargets, + skillOwners, + deployAgent, + redeployAgent, + }; + } catch (cause) { + await close(); + throw cause; + } +} diff --git a/packages/longevity-sim/tsconfig.json b/packages/longevity-sim/tsconfig.json new file mode 100644 index 000000000..12ec9a862 --- /dev/null +++ b/packages/longevity-sim/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "types": ["bun"] + }, + "include": ["src"] +}