Multiplayer agent harness for work.
Keep admin-archived catalog skills archived across restarts (#2330)
Joshua France5878bc51050a
diff --git a/src/api/app-skills.ts b/src/api/app-skills.tsindex c652ee38a..83136570f 100644--- a/src/api/app-skills.ts+++ b/src/api/app-skills.ts@@ -53,7 +53,9 @@ function requireRegistry(deps: AppDeps): { packs: SkillPackStore; fetcher: Skillasync function nativeNamesFor(deps: AppDeps, packId: string, scope: ScopeId): Promise<Set<string>> {const all = await deps.skills.list();return new Set(- all.filter((s) => s.scopeId === scope && s.createdBy !== `pack:${packId}`).map((s) => s.manifest.name),+ all+ .filter((s) => s.scopeId === scope && s.status !== "archived" && s.createdBy !== `pack:${packId}`)+ .map((s) => s.manifest.name),);}diff --git a/src/skills/seed.ts b/src/skills/seed.tsindex cde91dd76..a57bd49e2 100644--- a/src/skills/seed.ts+++ b/src/skills/seed.ts@@ -87,7 +87,14 @@ const upsertQueue = createKeyedQueue<string>();export function upsertSeedSkill(skills: SkillStore,- input: { scopeId: ScopeId; manifest: SkillManifest; createdBy: string; reviewer: string; pack?: Skill["pack"] },+ input: {+ scopeId: ScopeId;+ manifest: SkillManifest;+ createdBy: string;+ reviewer: string;+ pack?: Skill["pack"];+ respectArchived?: boolean;+ },): Promise<UpsertOutcome> {const run = () => upsertSeedSkillUnsafe(skills, input);return upsertQueue(`${input.scopeId}\0${input.manifest.name}`, () =>@@ -97,7 +104,14 @@ export function upsertSeedSkill(async function upsertSeedSkillUnsafe(skills: SkillStore,- input: { scopeId: ScopeId; manifest: SkillManifest; createdBy: string; reviewer: string; pack?: Skill["pack"] },+ input: {+ scopeId: ScopeId;+ manifest: SkillManifest;+ createdBy: string;+ reviewer: string;+ pack?: Skill["pack"];+ respectArchived?: boolean;+ },): Promise<UpsertOutcome> {const { scopeId, manifest, createdBy, reviewer, pack } = input;const all = await skills.list();@@ -105,6 +119,7 @@ async function upsertSeedSkillUnsafe((s) => s.scopeId === scopeId && s.manifest.name === manifest.name && s.createdBy === createdBy,);if (!existing && foreignSkillCollision(all, scopeId, manifest.name, createdBy)) return "foreign";+ if (existing?.status === "archived" && input.respectArchived) return "skipped";if (existing) {const changed = !sameManifest(existing.manifest, manifest);if (!changed && existing.status === "published") return "skipped";@@ -121,7 +136,7 @@ async function upsertSeedSkillUnsafe(export async function installSeedSkills(skills: SkillStore,- opts: { dir: string; scopeId: ScopeId; createdBy?: string; reviewer?: string },+ opts: { dir: string; scopeId: ScopeId; createdBy?: string; reviewer?: string; respectArchived?: boolean },): Promise<SeedInstallResult> {if (!existsSync(opts.dir)) return { installed: [], updated: [], skipped: [] };const createdBy = opts.createdBy ?? "system:skills-seed";@@ -134,7 +149,13 @@ export async function installSeedSkills(if (!existsSync(skillPath) || !statSync(skillPath).isFile()) continue;const manifest = parseSeedSkill(readFileSync(skillPath, "utf8"));manifest.files = readSkillFiles(skillDir);- const outcome = await upsertSeedSkill(skills, { scopeId: opts.scopeId, manifest, createdBy, reviewer });+ const outcome = await upsertSeedSkill(skills, {+ scopeId: opts.scopeId,+ manifest,+ createdBy,+ reviewer,+ ...(opts.respectArchived ? { respectArchived: true } : {}),+ });result[outcome === "foreign" ? "skipped" : outcome].push(manifest.name);}diff --git a/src/skills/skill-store.ts b/src/skills/skill-store.tsindex 5cba51ed9..975d11d34 100644--- a/src/skills/skill-store.ts+++ b/src/skills/skill-store.ts@@ -4,7 +4,7 @@ import type { ScopeId } from "../types.ts";import { parseScopeId } from "../types.ts";import { createMemoryMap, type DurableMap } from "../persistence/durable-map.ts";import { assertSafeSkillName, isSafeSkillName } from "./skill-name.ts";-import type { AdvisoryLock } from "../persistence/advisory-lock.ts";+import { createMemoryAdvisoryLock, type AdvisoryLock } from "../persistence/advisory-lock.ts";type SkillStatus = "draft" | "reviewed" | "published" | "archived";@@ -170,6 +170,9 @@ export function visibleSkillRows<T extends SkillSummary>(export function createSkillStore(opts: SkillStoreOptions = {}): SkillStore {const skills = opts.backing ?? createMemoryMap<Skill>();const secret = opts.signingSecret ?? randomUUID();+ const advisoryLock = opts.advisoryLock ?? createMemoryAdvisoryLock();+ const withNameLock = <T>(scopeId: ScopeId, name: string, fn: () => Promise<T>) =>+ advisoryLock.withLock(`skill-name:${scopeId}:${name}`, fn);function sign(manifest: SkillManifest): string {const files = canonicalFiles(manifest.files);@@ -184,8 +187,7 @@ export function createSkillStore(opts: SkillStoreOptions = {}): SkillStore {}return {- withNameLock: (scopeId, name, fn) =>- opts.advisoryLock ? opts.advisoryLock.withLock(`skill-name:${scopeId}:${name}`, fn) : fn(),+ withNameLock,async create(input) {assertSafeSkillName(input.manifest.name);const at = Date.now();@@ -254,13 +256,17 @@ export function createSkillStore(opts: SkillStoreOptions = {}): SkillStore {},async archive(id) {- const s = await skills.get(id);- if (!s) throw new Error(`unknown skill: ${id}`);- if (s.status === "archived") return s;- s.status = "archived";- s.updatedAt = Date.now();- await skills.put(s.id, s);- return s;+ const existing = await skills.get(id);+ if (!existing) throw new Error(`unknown skill: ${id}`);+ return withNameLock(existing.scopeId, existing.manifest.name, async () => {+ const s = await skills.get(id);+ if (!s) throw new Error(`unknown skill: ${id}`);+ if (s.status === "archived") return s;+ s.status = "archived";+ s.updatedAt = Date.now();+ await skills.put(s.id, s);+ return s;+ });},async restore(skill) {diff --git a/src/wiring.ts b/src/wiring.tsindex 4e34d7e92..e80ef056c 100644--- a/src/wiring.ts+++ b/src/wiring.ts@@ -769,7 +769,7 @@ export function buildApp(let skillsReady: Promise<void>;if (config.seedSkills) {const installCatalogs = async (): Promise<void> => {- await installSeedSkills(skills, { dir: config.skillsSeedDir, scopeId: orgScope });+ await installSeedSkills(skills, { dir: config.skillsSeedDir, scopeId: orgScope, respectArchived: true });for (const dir of config.pluginSkillDirs) {if (layerSkillsDir && resolve(dir) === layerSkillsDir) continue;await installSeedSkills(skills, {@@ -777,6 +777,7 @@ export function buildApp(scopeId: orgScope,createdBy: "system:plugin-skills",reviewer: "system:plugin-skills-reviewer",+ respectArchived: true,});}};diff --git a/test/skill-packs-routes.test.ts b/test/skill-packs-routes.test.tsindex 75e5d6da3..931590505 100644--- a/test/skill-packs-routes.test.ts+++ b/test/skill-packs-routes.test.ts@@ -688,6 +688,72 @@ test("a single imported skill can be un-indexed (archived) via DELETE /admin/ski}});+test("an admin can replace an archived seeded org skill with a same-named pack skill", async () => {+ const repo = makeFixtureRepo();+ const s = start();+ try {+ const seeded = await s.built.skills.create({+ scopeId: "org:default-org",+ manifest: { name: "reg-alpha", description: "bundled default", requiredCapabilities: [], body: "bundled" },+ createdBy: "system:skills-seed",+ });+ await s.built.skills.review(seeded.id, "system:skills-seed", []);+ await s.built.skills.publish(seeded.id);++ const reg = await json(+ await fetch(`${s.base}/v1/admin/skill-packs`, {+ method: "POST",+ headers: ADMIN,+ body: JSON.stringify({ url: repo.dir, ref: repo.sha, config: { exclude: ["trusted/*"] } }),+ }),+ );+ const id = reg.pack.id as string;+ const before = await json(await fetch(`${s.base}/v1/admin/skill-packs/${id}/catalog`, { headers: ADMIN }));+ const blocked = before.candidates.find((c: any) => c.upstreamName === "reg-alpha");+ assert.equal(blocked?.eligible, false);+ assert.equal(blocked.excludeReason, "collision");+ const blockedImport = await fetch(`${s.base}/v1/admin/skill-packs/${id}/import`, {+ method: "POST",+ headers: ADMIN,+ body: JSON.stringify({ selected: ["reg-alpha"] }),+ });+ assert.equal(blockedImport.status, 200);+ assert.deepEqual((await json(blockedImport)).imported, []);+ assert.equal((await s.built.skills.resolve("reg-alpha", ["org:default-org"])).skill?.id, seeded.id);++ const archived = await fetch(`${s.base}/v1/admin/skills/${seeded.id}?scope=org:default-org`, {+ method: "DELETE",+ headers: ADMIN,+ });+ assert.equal(archived.status, 200);+ assert.equal((await s.built.skills.get(seeded.id))?.status, "archived");++ const after = await json(await fetch(`${s.base}/v1/admin/skill-packs/${id}/catalog`, { headers: ADMIN }));+ assert.equal(+ after.candidates.find((c: any) => c.upstreamName === "reg-alpha")?.eligible,+ true,+ "archiving the bundled default frees its name for a replacement",+ );+ const imported = await fetch(`${s.base}/v1/admin/skill-packs/${id}/import`, {+ method: "POST",+ headers: ADMIN,+ body: JSON.stringify({ selected: ["reg-alpha"] }),+ });+ assert.equal(imported.status, 200);+ assert.deepEqual((await json(imported)).imported, ["reg-alpha"]);+ assert.equal((await s.built.skills.get(seeded.id))?.status, "archived");+ const replacement = (await s.built.skills.resolve("reg-alpha", ["org:default-org"])).skill;+ assert.ok(replacement);+ assert.notEqual(replacement.id, seeded.id);+ assert.equal(replacement.createdBy, `pack:${id}`);+ assert.equal(replacement.scopeId, "org:default-org");+ assert.equal(replacement.manifest.description, "a");+ } finally {+ rmSync(repo.dir, { recursive: true, force: true });+ await s.close();+ }+});+test("remove then re-register the same repo re-imports cleanly (no stuck-archived records)", async () => {const repo = makeFixtureRepo();const s = start();diff --git a/test/skills-seed-cross-server.test.ts b/test/skills-seed-cross-server.test.tsindex f9a846067..fd1c0f997 100644--- a/test/skills-seed-cross-server.test.ts+++ b/test/skills-seed-cross-server.test.ts@@ -1,6 +1,6 @@import { test, after } from "node:test";import assert from "node:assert/strict";-import { mkdtempSync, mkdirSync, writeFileSync } from "node:fs";+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { createSkillStore, type Skill } from "../src/skills/skill-store.ts";@@ -11,9 +11,11 @@ import {type AdvisoryLock,} from "../src/persistence/advisory-lock.ts";import { scopeId } from "../src/types.ts";+import { installSeedSkills } from "../src/skills/seed.ts";const URL = process.env.DATABASE_URL;const factory = URL ? createPostgresMapFactory(URL) : null;+let tableSequence = 0;after(async () => {await factory?.pool.close();});@@ -23,7 +25,7 @@ const shared = async (): Promise<{ backing: DurableMap<Skill>; lock: () => Advisconst lock = createMemoryAdvisoryLock();return { backing: createMemoryMap<Skill>(), lock: () => lock };}- const table = `xsrv_skills_${process.pid}`;+ const table = `xsrv_skills_${process.pid}_${++tableSequence}`;await factory.pool.query(`DROP TABLE IF EXISTS ${table}`);return { backing: factory.map<Skill>(table), lock: () => createPostgresAdvisoryLock(factory.pool) };};@@ -59,3 +61,80 @@ test("two servers seeding the same catalog at boot install each skill once", asyassert.equal(rows.length, 1);assert.equal(rows[0]!.status, "published");});++test("an admin archive racing another server's changed seed update leaves the skill archived", async () => {+ const dir = mkdtempSync(join(tmpdir(), "seed-archive-xsrv-"));+ const { backing, lock } = await shared();+ const copied: DurableMap<Skill> = {+ ...backing,+ get: async (id) => structuredClone(await backing.get(id)),+ all: async () => structuredClone(await backing.all()),+ put: (id, skill) => backing.put(id, structuredClone(skill)),+ };+ const seedWriting = Promise.withResolvers<void>();+ const releaseSeed = Promise.withResolvers<void>();+ const archiveLockEntered = Promise.withResolvers<void>();+ const archiveLock = lock();+ const left = createSkillStore({+ backing: {+ ...copied,+ async put(id, skill) {+ if (skill.status === "draft" && skill.manifest.body === "Updated instructions.\n") {+ seedWriting.resolve();+ await releaseSeed.promise;+ }+ await copied.put(id, skill);+ },+ },+ signingSecret: "s",+ advisoryLock: lock(),+ });+ const right = createSkillStore({+ backing: copied,+ signingSecret: "s",+ advisoryLock: {+ ...archiveLock,+ withLock(key, fn) {+ archiveLockEntered.resolve();+ return archiveLock.withLock(key, fn);+ },+ },+ });+ const org = scopeId("org", "default-org");+ const options = { dir, scopeId: org, respectArchived: true };+ const pending: Promise<unknown>[] = [];+ try {+ mkdirSync(join(dir, "hello"));+ const path = join(dir, "hello", "SKILL.md");+ writeFileSync(path, "---\nname: hello\ndescription: Say hello.\n---\nOriginal instructions.\n");+ await installSeedSkills(left, options);+ const original = (await right.resolve("hello", [org])).skill!;+ assert.ok(original);+ writeFileSync(path, "---\nname: hello\ndescription: Say hello.\n---\nUpdated instructions.\n");++ const seeding = installSeedSkills(left, options);+ pending.push(seeding);+ await Promise.race([+ seedWriting.promise,+ seeding.then(() => assert.fail("the changed seed did not reach the write barrier")),+ ]);+ const archiving = right.archive(original.id);+ pending.push(archiving);+ await Promise.race([archiving, archiveLockEntered.promise]);+ releaseSeed.resolve();+ await Promise.all([seeding, archiving]);++ const rows = await backing.all();+ assert.equal(rows.length, 1);+ assert.equal(rows[0]!.id, original.id);+ assert.equal(rows[0]!.status, "archived");+ assert.equal(rows[0]!.manifest.body, "Updated instructions.\n");+ assert.equal(rows[0]!.version, original.version + 1);+ assert.equal((await left.resolve("hello", [org])).skill, null);+ assert.equal((await right.resolve("hello", [org])).skill, null);+ } finally {+ releaseSeed.resolve();+ await Promise.allSettled(pending);+ rmSync(dir, { recursive: true, force: true });+ }+});diff --git a/test/skills-seed.test.ts b/test/skills-seed.test.tsindex 917624ba5..cdf5325b0 100644--- a/test/skills-seed.test.ts+++ b/test/skills-seed.test.ts@@ -147,6 +147,29 @@ test("installSeedSkills re-seeds a changed manifest over its own prior install,assert.equal((await skills.get(mine.id))!.manifest.description, "user authored");});+test("installSeedSkills leaves an admin-archived catalog skill archived when asked to", async () => {+ const skills = createSkillStore({ signingSecret: "seed-test-secret" });+ const org = scopeId("org", "default-org");+ const dir = mkdtempSync(join(tmpdir(), "seed-archived-"));+ writeSeedSkill(dir, "retired", "old catalog skill", "# Retired v1");+ await installSeedSkills(skills, { dir, scopeId: org, respectArchived: true });+ const installed = (await skills.list()).find((s) => s.manifest.name === "retired")!;+ await skills.archive(installed.id);++ const again = await installSeedSkills(skills, { dir, scopeId: org, respectArchived: true });+ assert.deepEqual(again, { installed: [], updated: [], skipped: ["retired"] });+ writeSeedSkill(dir, "retired", "catalog changed upstream", "# Retired v2");+ const changed = await installSeedSkills(skills, { dir, scopeId: org, respectArchived: true });+ assert.deepEqual(changed, { installed: [], updated: [], skipped: ["retired"] });+ const kept = (await skills.list()).filter((s) => s.manifest.name === "retired");+ assert.equal(kept.length, 1, "no replacement record is created beside the archived one");+ assert.equal(kept[0]!.status, "archived");++ const republished = await installSeedSkills(skills, { dir, scopeId: org });+ assert.deepEqual(republished, { installed: [], updated: ["retired"], skipped: [] });+ assert.equal((await skills.get(installed.id))!.status, "published");+});+test("concurrent upserts of the same scope+name serialize into one record (no duplicate creates)", async () => {const skills = createSkillStore({ signingSecret: "seed-test-secret" });const org = scopeId("org", "default-org");