Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

6.6 KB
Raw Blame
/**
 * POST /api/projects/:projectId/agents/:agentId/config/kernel-update — the smart merge of
 * system_config.yaml up to the current defaults generation.
 *
 * - A fresh Agent reports stamped and current, in the config DTO and on the Agent list.
 * - A pre-stamp config is flagged outdated; the update advances untouched old defaults, keeps
 *   and reports the customizations, and stamps the config.
 * - A nonexistent Agent is a 404 with no initialization side effect; a non-member gets 404 and
 *   the config is not touched.
 */
import fs from "node:fs/promises";
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
import {
  KERNEL_VERSION,
  LEGACY_SKILLS_SECTION,
  LEGACY_VAULT_SECTION,
  SCHEDULES_PLACEHOLDER,
  SKILLS_PLACEHOLDER,
  VAULT_PLACEHOLDER,
  defaultSystemConfig,
  systemConfigPath,
} from "@adelie/core";
import type {
  AgentConfigResponse,
  AgentKernelUpdateResponse,
  AgentsResponse,
  ProjectCreateResponse,
} from "../src/api/types.js";
import { apiClient, createTestApp, provisionUser } from "./helpers.js";
import type { TestApp } from "./helpers.js";

describe("POST agent config kernel-update", () => {
  let t: TestApp;
  let alice: ReturnType<typeof apiClient>;
  let projectId: string;
  const configUrl = () => `/api/projects/${projectId}/agents/default_agent/config`;

  beforeAll(async () => {
    t = await createTestApp();
    const a = await provisionUser(t.app, "alice");
    alice = apiClient(t.app, a.cookie);
  });
  afterAll(async () => {
    await t.cleanup();
  });

  // Every case works in a Project of its own.
  let projects = 0;
  beforeEach(async () => {
    projects += 1;
    const created = (await (
      await alice.post("/api/projects", {
        projectId: `alice-kernel_${projects}`,
        name: "Kernel project",
      })
    ).json()) as ProjectCreateResponse;
    projectId = created.project.projectId;
  });

  /**
   * Rewrites default_agent's config on disk into a pre-toggles-era shape with one user
   * customization: no kernel stamp, the legacy default template (LEGACY_* sections instead
   * of the section placeholders, no {{SCHEDULES}}), no vault/skills/schedules sections, and
   * a customized memory.prompt.
   *
   * The template is the one the toggles generation shipped, frozen byte-exact in core's test
   * fixture — not the live default, which has moved on since. The prompt tab reads as an
   * untouched old default (and advances) only while its hash is a recorded superseded one, and
   * the live template with the legacy sections swapped in stopped hashing to one the first
   * time the prompt changed after that generation.
   */
  async function agePersistedConfig(): Promise<void> {
    const configPath = systemConfigPath(t.root, projectId, "default_agent");
    const config = parseYaml(await fs.readFile(configPath, "utf8")) as Record<string, unknown>;
    delete config.kernel_version;
    delete config.vault;
    delete config.skills;
    delete config.schedules;
    const togglesGenerationTemplate = await fs.readFile(
      new URL("../../core/test/fixtures/toggles-generation-system-prompt.txt", import.meta.url),
      "utf8",
    );
    config.system_prompt = togglesGenerationTemplate
      .split(VAULT_PLACEHOLDER)
      .join(LEGACY_VAULT_SECTION)
      .split(SKILLS_PLACEHOLDER)
      .join(LEGACY_SKILLS_SECTION)
      .split(`${SCHEDULES_PLACEHOLDER}\n\n`)
      .join("");
    config.memory = { ...(config.memory as object), prompt: "my memory prompt" };
    await fs.writeFile(configPath, stringifyYaml(config), "utf8");
  }

  it("reports a fresh agent as stamped and current (config DTO + agents list)", async () => {
    const got = (await (await alice.get(configUrl())).json()) as AgentConfigResponse;
    expect(got.config.kernelVersion).toBe(KERNEL_VERSION);
    expect(got.config.kernelLatest).toBe(KERNEL_VERSION);
    expect(got.config.kernelOutdated).toBe(false);
    const list = (await (
      await alice.get(`/api/projects/${projectId}/agents`)
    ).json()) as AgentsResponse;
    expect(list.agents.find((a) => a.agentId === "default_agent")?.kernelOutdated).toBe(false);
  });

  it("flags a pre-stamp config as outdated, then advances it while keeping the customization", async () => {
    await agePersistedConfig();

    const before = (await (await alice.get(configUrl())).json()) as AgentConfigResponse;
    expect(before.config.kernelVersion).toBeNull();
    expect(before.config.kernelOutdated).toBe(true);
    const listBefore = (await (
      await alice.get(`/api/projects/${projectId}/agents`)
    ).json()) as AgentsResponse;
    expect(listBefore.agents.find((a) => a.agentId === "default_agent")?.kernelOutdated).toBe(true);

    const res = await alice.post(`${configUrl()}/kernel-update`);
    expect(res.status).toBe(200);
    const body = (await res.json()) as AgentKernelUpdateResponse;
    expect(body.kernelVersion).toBe(KERNEL_VERSION);
    // Tab-wise: the prompt tab hash-matches the pre-toggles default and advances, the three
    // missing sections are materialized, and the edited memory tab is kept whole.
    expect(body.advanced).toEqual(["prompt", "skills", "vault", "schedules"]);
    expect(body.kept).toEqual(["memory"]);

    // Persisted: the template advanced, the customization survived, the stamp is current.
    const after = (await (await alice.get(configUrl())).json()) as AgentConfigResponse;
    expect(after.config.systemPrompt).toBe(defaultSystemConfig().system_prompt);
    expect(after.config.memory.prompt).toBe("my memory prompt");
    expect(after.config.kernelVersion).toBe(KERNEL_VERSION);
    expect(after.config.kernelOutdated).toBe(false);
    const listAfter = (await (
      await alice.get(`/api/projects/${projectId}/agents`)
    ).json()) as AgentsResponse;
    expect(listAfter.agents.find((a) => a.agentId === "default_agent")?.kernelOutdated).toBe(false);
  });

  it("404 for a nonexistent agent (no initialization side effect)", async () => {
    const res = await alice.post(`/api/projects/${projectId}/agents/ghost/config/kernel-update`);
    expect(res.status).toBe(404);
  });

  it("404 for a non-member; the config is not modified", async () => {
    await agePersistedConfig();
    const before = (await (await alice.get(configUrl())).json()) as AgentConfigResponse;
    const m = await provisionUser(t.app, "mallory");
    const mallory = apiClient(t.app, m.cookie);
    const res = await mallory.post(`${configUrl()}/kernel-update`);
    expect(res.status).toBe(404);
    const after = (await (await alice.get(configUrl())).json()) as AgentConfigResponse;
    expect(after.systemConfigYaml).toBe(before.systemConfigYaml);
  });
});