Files
PaperClipAI/server/src/__tests__/skill-package-store.test.ts
T
Nicky LeachandClaude Opus 5.5 11ac90e31f fix(build): typecheck server/src/__tests__ and fix every type error (#18739)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The server has about 1,100 test and helper files in
`server/src/__tests__`
> - `server/tsconfig.json` excludes that directory, Vitest does not
check types, and no script runs the tsconfig in that directory
> - So a test can call a function with the wrong arguments and still
pass, and no tool reports it
> - This gap hid 2,168 real type errors, and some of them hid tests that
did not test what they claim
> - This pull request fixes all of these errors and adds the directory
to the server layers from paperclipai/paperclip#18737
> - The benefit is that a type error in a server test now fails the
typecheck, with no baseline and no backlog

## Linked Issues or Issue Description

Refs paperclipai/paperclip#18737, which is merged and added the server
layers. Refs paperclipai/paperclip#18738, which is merged and checks the
test projects outside `pnpm -r`, so it is not a duplicate. Refs
paperclipai/paperclip#18137, which records that this directory has no
check.

**What happened?**

No tool checked the types of 1,074 of the 1,101 files in
`server/src/__tests__`. I searched `package.json`, the workflows, and
all tsconfig files. 27 files are in the program of another tsconfig, and
these 27 have 0 errors. 11 of the 27 are in
`helpers/maintenance/tsconfig.json`. No script ran that project when I
measured this. paperclipai/paperclip#18738 now runs it.

**Expected behavior**

The server typecheck checks these files, and a type error fails the
check.

**Steps to reproduce**

1. On the base commit, run `tsc -p server/src/__tests__/tsconfig.json
--noEmit`. It reports 6,536 errors and needs 12.3 GiB.
2. Add a type error to any file in `server/src/__tests__`.
3. Run `pnpm --filter @paperclipai/server typecheck`. It passes.

**Paperclip version or commit**

I measured the error breakdown below on commit `8dfd632452`, with
TypeScript 7.0.2. The branch now includes master up to
paperclipai/paperclip#18865.

**Deployment mode**

Not applicable. This issue applies to development and CI. No production
source file in the server changes.

### Error breakdown

Each row adds one change to the row above.

| Step | Total errors | Change | Cause |
| --- | --- | --- | --- |
| Config as committed | 6,536 | | |
| Add `src/types/*.d.ts` | 4,447 | -2,089 | Config. The Express request
types were missing. |
| Set `rootDir` to the repository root | 2,436 | -2,011 | Config. |
| Set `allowImportingTsExtensions` | 2,181 | -255 | Config. Vitest
accepts `.ts` imports. |
| Add `ES2024.Promise` to `lib` | 2,138 | -43 | Config. Node 24 has
`Promise.withResolvers`. |
| Set `allowJs` for `.mjs` imports | 2,148 | +10 | Config. It removes 8
`TS7016` errors and shows new real errors. |
| Set `declaration` to false | 2,142 | -6 | Config. Tests emit nothing.
|
| Count only files in `server/src` | 2,058 | -84 | Other packages: 53
Daytona, 29 Runner test, 2 UI. |

So 4,478 of the 6,536 errors (69%) came from config or scope, and 2,058
are real type errors in 314 files. The 29 Runner test errors are also
real, which gives 2,087 errors. Tests that master added after this
measurement had 81 more errors, so this pull request fixes 2,168 errors.

This table classifies the first 2,058 errors.

| Kind of real error | Errors |
| --- | --- |
| Wrong argument or assignment type | 1,023 |
| Stale or partial fixture objects | 525 |
| Property that the type does not have | 317 |
| Missing narrowing of null or unknown | 101 |
| Implicit any | 60 |
| Missing name or module | 16 |
| Other | 16 |

### What the type errors hid

Most errors were stale fixtures and loose mocks. These errors hid real
test problems, and this pull request fixes them:

- **A test that never ran.** `instrumentation.test.ts` required
`sdk-trace-base`, which is not installed. So 3 span tests were skipped.
They now run and pass.
- **Assertions that could not fail.**
- `issue-thread-interactions-service` used a company ID as an issue ID.
- `status-card-evaluation-work` compared `[]` with `[]` in a rollback
check.
- `slack-conversation-lifecycle` read `item.issueId`, which does not
exist.
  - `email-channels` used a permission key that does not exist.
- `heartbeat-project-env` imported `LOW_TRUST_REVIEW_PRESET`, which is
not exported. The value was undefined.
- **Postgres processes that did not stop.** 11 test files called `stop`
on the test database helper. That method does not exist, and the helper
method is `cleanup`.
- **Arguments that the service ignored.**
- `methodKey` is now `connectionMethodKey` in the Daytona, Unikraft,
1Password, and Railway tests.
- 108 calls passed `"owner-user"` to a parameter that expects an options
object.
- 9 chat wizard fixtures passed `managementContext` as `source`, so they
ran `existing_app` and not `manifest`.
  - 2 tests passed a `{ userId }` actor that the function ignores.
- Inserts into `environments` passed a `companyId` column that the table
does not have.
- **Problems in tests that master added during this work.**
- `sandbox-creation-operations` read `database.connectionString` when an
external test database was set. In that mode `database` is undefined, so
the fixture would stop with a TypeError. It now uses the external URL.
- `idle-completed-history` set a Dot operation to `dispatched`. That is
a Muse status, and the Dot type does not have it. The fixture now uses
`admitted`, which is a real in-flight Dot status.

### Possible product problems, not changed

These may be real problems in production code or types. I did not change
them, because this pull request does not change production behavior:

- `decisions-service` `service.create` does not validate the lenient
`cancel_issue_tree` input.
- `createConnection` ignores `input.connectionPurpose`.
- The `createConnection` route schema default stores `{}` for
`transportConfig`.
- `prepareManagedAiRuntime` accepted the invalid value `mode:
"connection"`.
- `createBinding` accepts invalid `projectionClass` strings outside
class 3.
- `ensureManagedProjectWorkspace` forwards an untyped `repoRef` by
spread.
- `routineVariableSchema.label` is optional, but `RoutineVariable.label`
is required.
- `ToolRunContext.projectId` may be too strict.
- `withdrawInteraction` reads `issue.status`, which its type omits.
- `issueService.list` and `reconcileNativeFinalizations` omit fields
that they return at runtime.
- `createGitHubExternalObjectProvider` handles `tokenProvider: null`,
but its type forbids this value.

## What Changed

- Fixed the 2,168 type errors. The diff changes 322 test and helper
files.
- Corrected `server/src/__tests__/tsconfig.json`. Editors and the
typecheck now read the same options and report the same errors.
- Added three `test-tree` layers to
`server/scripts/typecheck-layers.mjs`. They read the server layers as
declarations, and any error fails them. A hash of the path selects the
shard, so a new file does not move other files.
- Added `server/scripts/typecheck-stubs/daytona-sdk.d.ts`. Server tests
reach Daytona plugin source, and the root install does not have
`@daytonaio/sdk`.
- Changed two imports in `ui/src/lib/issue-execution-policy.ts` to use
`.js` extensions, because server tests import this file.
- Made `declarationsConfig` and `--declarations-only` skip the
`test-tree` layers, because these layers emit nothing. Other projects
read only the source layers. Added a test for this.
- Updated `doc/DEVELOPING.md`.

## Verification

Run these commands:

```sh
pnpm --filter @paperclipai/server typecheck
pnpm exec vitest run server/scripts/typecheck-layers.test.mjs
```

Results on macOS (arm64), Node 24, 16 cores. Each check ran after the
merge of paperclipai/paperclip#18738 unless the row says otherwise:

| Check | Commit | Result |
| --- | --- | --- |
| Server typecheck, `PAPERCLIP_TYPECHECK_LOW_MEMORY=1`, all 7 layers |
`6e45a08573` | Exit 0, 0 errors, 62 seconds, peak 3.52 GiB |
| `node scripts/typecheck-test-projects.mjs --low-memory` | `a3306bd13e`
| Exit 0, 0 errors, 42 seconds, peak 3.25 GiB |
| The same script with `--reuse-declarations` | `1b878aabc0` | Exit 0, 0
errors |
| `typecheck-layers.test.mjs` and `live-recovery-work.test.ts` |
`01db5634e4` | 90 passed. These include real compiler runs for a pass, a
type error, and an invalid tsconfig. |
| `tsconfig.declarations.json` after a full server typecheck |
`0fb1e4fb0a` | It references only `below`, `cycle`, and `above`. No
generated config names a `tsconfig.layers.json` file. |
| Owned runtime test in `idle-completed-history` | `e8f2f448ac` |
Passed, with the fix that master later replaced |
| `idle-incoming-wake`, `plugin-idle-manager`, and the changed
`chat-channels` test | `6e45a08573` | 30 passed |
| Runner `native-execution.test.ts` | `eab4dcc1f4` | 114 passed |
| The 19 server test files that changed since `eab4dcc1f4`, and
`typecheck-layers.test.mjs` | `259737b700` | 4,275 of 4,277 passed. The
2 failures are in `chat-channels` and are in the list of 7 below. |

The peak is the largest single process, from `/usr/bin/time -l`. Peaks
for the server typecheck were between 3.42 GiB and 3.56 GiB across 8
runs. Peaks for the test projects were 3.25 GiB and 3.37 GiB across 2
runs. I did not measure a cgroup.

**Runtime check of the fixes.** Types do not prove that a test still
works. So I ran all 309 changed server test files, 11,929 tests, before
the rebase onto paperclipai/paperclip#18737:

| Result | Tests | Detail |
| --- | --- | --- |
| Passed | 11,913 | Includes the 2 tests and the 54 `dot-runner` tests
that passed in a later run, as described below. |
| Failed | 7 | The same 7 tests also fail on the commit before the
fixes. |
| Skipped | 9 | These tests have their own skip conditions: `sentry` 5,
and 1 each in `bundled-plugin-registration`, `customer-success-cloud`,
`onepassword-connection`, and `workspace-runtime-https-live-exercise`. |

The 7 tests that fail with and without this change, on my machine:

- 3 tests in `chat-channels` and `email-channels` stop with `ENOENT` on
a `SKILL.md` file. The path is in the parent checkout, above the git
worktree that I used, so I expect that the worktree is the cause. I did
not prove this.
- `workspace-instance-cleanup` compares `/private/var/...` with
`/var/...`. This is a macOS symlink difference.
- 2 tests in `git-reproducible-managed-checkouts` get
`unknown_base_git_files` and expect `unpushed_managed_checkout`. I did
not find the cause.
- 1 more test in `chat-channels`, `materializes direct external-chat
finals once`, gets `undefined`. I did not find the cause.

CI is the check for these 7 tests. `ci / verify` passed on `eab4dcc1f4`.

Failures during this work:

- My fix to `agent-runtime-connector-access` changed an invalid
permission key in the setup, but not in the assertion. The runtime check
found this. I corrected the assertion, and the file passes.
- `heartbeat-plugin-environment` failed one wait in the full run. It
passed three times alone, so I think that load caused the failure. It
can fail again under load.
- `dot-runner` skipped all 54 tests in the full run because `cargo` was
not on my `PATH`. It then passed 54 of 54 with the toolchain on the
`PATH`.
- My first `lib` value removed the default DOM types, and the error
count went up by 375. I added the DOM libraries.
- My Daytona stub with bare `any` left 48 errors, because generic
helpers then inferred `unknown`. I added shapes that return promises.
- One fix to `agent-secrets-routes` used `class_3_static_lease`, and the
test failed. That class allows only specific paths. I reverted to
`unclassified`.
- `ci / General tests (server (8/12))` failed on `259737b700` because of
the flaky port in `idle-completed-history`. paperclipai/paperclip#18853
fixed this test on master, so this pull request keeps that fix.

**Audit of the diff.** I counted these patterns in added and removed
lines, to find fixes that only hide an error:

| Pattern | Added | Removed |
| --- | --- | --- |
| `@ts-ignore` | 0 | 0 |
| `@ts-expect-error` | 0 | 1 |
| `.skip` | 0 | 0 |
| `as any` | 9 | 9 |
| `: any` | 11 | 2 |
| `as never` | 8 | 2 |
| `as unknown as` | 35 | 4 |
| `Promise<unknown>` | 16 | 5 |
| `expect(` | 128 | 113 |

No hunk removes more `expect(` calls than it adds. Three removals of
test content were intentional, and I checked each one:

- `muse-control` removed `signalToken`. Line 1012 already asserts that
it is absent.
- `merged-pr-confirmation-sweep` removed legacy aliases. Other tests
cover them.
- `heartbeat-workspace-branch-containment` removed a `finalize` branch
that no test row can reach.

Some partial fixtures stay unchecked through `as unknown as` and
`Promise<unknown>`, mostly in `issue-agent-mutation-ownership-routes`
and `issue-comment-reopen-routes`.

**Accuracy of the check.** One program over the tree and the three
shards reported the same errors at the same positions. Memory, as the
peak of the largest process on one thread, was 3.93 GiB for one program
and 2.43 GiB for the largest shard. I measured these two values before
the fixes.

Not run or not proven:

- I did not run the full `pnpm test:run`, or a root `pnpm build`. I
expect CI to run the full suites.
- I did not run the 4 GiB container check, or the full
`scripts/typecheck-low-memory.mjs`. The peaks above come from macOS, so
they are not a Linux cgroup measurement.
- I did not run the UI typecheck after the merges.
- `workspace-runtime-https-live-exercise` is skipped, so its `cleanup`
fix did not run.

## Risks

- **A large diff in test files.** 328 files change. A pull request that
edits the same tests can get merge conflicts. New tests on master can
also add type errors before this merges. Any such error fails this check
and needs a fix here.
- **A higher cost for changes to source types.** A change to a type can
add errors in test files that the author did not touch. The author must
then fix them. This is the purpose of the check, but it is new work.
- **Changed test behavior.** Some tests now run paths that they did not
run before, such as the 9 chat wizard fixtures and the 3 span tests.
They pass here, but they can be more sensitive to timing or to the
environment.
- **The Daytona stub can go stale.** The stub is written by hand. If the
plugin uses a new SDK member, the typecheck reports an error until
someone updates the stub.
- **The release path.** `release-verify.yml` and `scripts/release.sh`
run `pnpm -r typecheck`, so they now run this check.
- **The tsconfig change.** The test transform reads
`server/src/__tests__/tsconfig.json`. The options that I changed are for
type checks, and the runs above passed.
- **A gap that remains.** Tsconfigs in `packages/paperclip-runner` and
in most sandbox provider plugins exclude `*.test.ts`. This check does
not read most of those test files, so they can still drift. That work is
separate from this pull request.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

Anthropic Claude Opus 5.5 (`claude-opus-5-5`) through Claude Code, with
reasoning, tool use, code execution, and subagents. The runtime does not
show the context window size.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [ ] I have run tests locally and they pass (7 tests fail locally, with
and without this change. See Verification.)
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 15:27:38 -08:00

1041 lines
66 KiB
TypeScript

import { skillPackageWork } from "../services/skill-package-work.js";
import * as packageCache from "../services/skill-package-cache.js";
import * as recovery from "../services/skill-package-recovery.js";
import type { GitHubRead } from "../services/github-skill-source.js";
import { randomUUID } from "node:crypto";
import { promises as fs } from "node:fs";
import os from "node:os";
import path from "node:path";
import { and, eq, sql } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { agents, companies, companySkills, companySkillVersions, companySkillRepositorySnapshots as snapshots,
skillPackageDeletions, createDb, withDedicatedDbConnection } from "@paperclipai/db";
import * as dbModule from "@paperclipai/db";
import type { CompanySkill, CompanySkillVersionFileInventoryEntry } from "@paperclipai/shared";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import * as storageModule from "../storage/index.js";
import { createStorageService } from "../storage/service.js";
import { createLocalDiskStorageProvider } from "../storage/local-disk-provider.js";
import { companySkillService } from "../services/company-skills.js";
import { skillPackageStore, skillPackagePaths, withSkillPackageReadScope } from "../services/skill-package-store.js";
import { skillPackageMaintenance } from "../services/skill-package-maintenance.js";
import { skillPackageManifest, validateSkillPackageManifest, writeSkillPackageArchive, extractSkillPackageArchive,
verifySkillPackageDirectory } from "../services/skill-package-files.js";
import { skillFileBytes, skillSnapshotHash } from "../services/skill-snapshot.js";
import { readCustomerSuccessResource } from "../services/customer-success-inspection.js";
import { repositorySkillProjection } from "../services/skill-repository-package.js";
import { hasRestorableSnapshot } from "../services/skill-version-cache.js";
function toSkill(row: typeof companySkills.$inferSelect): CompanySkill {
return { ...row, sourceType: row.sourceType as CompanySkill["sourceType"], trustLevel: row.trustLevel as CompanySkill["trustLevel"],
compatibility: row.compatibility as CompanySkill["compatibility"], fileInventory: row.fileInventory.map(entry => ({ path: String(entry.path), kind: entry.kind as CompanySkill["fileInventory"][number]["kind"] })) };
}
const support = await getEmbeddedPostgresTestSupport();
describe.skipIf(!support.supported)("external skill packages", () => {
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: ReturnType<typeof createDb>;
let home: string;
let storage: storageModule.StorageService;
const previousHome = process.env.PAPERCLIP_HOME;
const files: CompanySkillVersionFileInventoryEntry[] = [
{ path: "skills/one/SKILL.md", kind: "skill", content: "---\nname: one\ndescription: Test one\n---\nUse ../../shared/run.sh\n" },
{ path: "skills/two/SKILL.md", kind: "skill", content: "---\nname: two\ndescription: Test two\n---\nUse ../../shared/run.sh\n" },
{ path: "shared/run.sh", kind: "script", content: "#!/bin/sh\necho original\n", executable: true },
{ path: "assets/binary", kind: "reference", content: Buffer.from([0, 255, 7]).toString("base64"), encoding: "base64" },
{ path: "assets/base64-text", kind: "reference", content: Buffer.from("text encoded explicitly").toString("base64"), encoding: "base64" },
];
beforeAll(async () => {
database = await startEmbeddedPostgresTestDatabase("skill-packages-");
db = createDb(database.connectionString, { maxConnections: 1 });
home = await fs.mkdtemp(path.join(os.tmpdir(), "skill-packages-"));
process.env.PAPERCLIP_HOME = home;
storage = createStorageService(createLocalDiskStorageProvider(path.join(home, "objects")));
});
afterEach(() => vi.restoreAllMocks());
afterAll(async () => {
if (previousHome === undefined) delete process.env.PAPERCLIP_HOME;
else process.env.PAPERCLIP_HOME = previousHome;
await db?.$client.end({ timeout: 1 });
await database?.cleanup();
if (home) await fs.rm(home, { recursive: true, force: true });
});
async function company() {
const id = randomUUID();
await db.insert(companies).values({ id, name: "Package test", issuePrefix: `P${id.slice(0, 6)}` });
return id;
}
async function fixture(recoverable = false) {
const companyId = await company();
vi.spyOn(storageModule, "getStorageService").mockReturnValue(storage);
const store = skillPackageStore(db, storage);
const recipe = recoverable ? { version: 1 as const, sourceId: randomUUID(), repositoryId: "123", repositoryUrl: "https://github.com/acme/skills",
commitSha: "a".repeat(40), skillPath: null, manifest: skillPackageManifest(files) } : undefined;
const id = await store.prepare(companyId, files, false, undefined, recipe);
const skills: { skill: CompanySkill; version: typeof companySkillVersions.$inferSelect }[] = [];
for (const name of ["one", "two"]) {
const [skill] = await db.insert(companySkills).values({ companyId, key: `company/${companyId}/${name}`, slug: name,
name, markdown: files.find(file => file.path === `skills/${name}/SKILL.md`)!.content, sourceType: "github",
metadata: { skillSourceId: randomUUID(), snapshotHash: "saved" } }).returning();
const [version] = await db.insert(companySkillVersions).values({ companyId, companySkillId: skill!.id, revisionNumber: 1,
repositorySnapshotId: id, repositorySkillPath: `skills/${name}/SKILL.md`, packageSnapshotId: id, migrationAt: null,
packageFileMap: [{ path: "SKILL.md", kind: "skill", sourcePath: `skills/${name}/SKILL.md` }] }).returning();
await db.update(companySkills).set({ currentVersionId: version!.id }).where(eq(companySkills.id, skill!.id));
skills.push({ skill: toSkill(skill!), version: version! });
}
const service = companySkillService(db);
const resolve = () => service.listRuntimeSkillEntries(companyId, { onlyKeys: new Set(skills.map(({ skill }) => skill.key)), snapshotLatest: true });
return { companyId, id, store, skills, service, resolve };
}
it("keeps unchanged linked-local execution on the verified manifest path with complete metadata indexes", async () => {
const companyId = await company();
vi.spyOn(storageModule, "getStorageService").mockReturnValue(storage);
const directory = path.join(home, `linked-${companyId}`);
await fs.mkdir(directory);
await fs.writeFile(path.join(directory, "SKILL.md"), "# Linked");
await fs.writeFile(path.join(directory, "support.txt"), "unchanged support");
const [skill] = await db.insert(companySkills).values({ companyId, key: "linked", slug: "linked", name: "Linked",
markdown: "# Linked", sourceType: "local_path", sourceLocator: directory,
fileInventory: [{ path: "SKILL.md", kind: "skill" }, { path: "support.txt", kind: "other" }] }).returning();
const service = companySkillService(db);
const version = await service.createVersion(companyId, skill!.id);
const resolve = () => service.listRuntimeSkillEntries(companyId, { onlyKeys: new Set([skill!.key]), snapshotLatest: true });
await resolve();
const read = vi.spyOn(fs, "readFile");
const [runtime] = await resolve();
expect(runtime?.versionId).toBe(version.id);
expect(read.mock.calls.filter(([file]) => String(file).endsWith("support.txt"))).toHaveLength(0);
});
it("orders skill and package locks consistently with an edit's dedicated upload connection", async () => {
const f = await fixture();
const skill = f.skills[0]!.skill;
const options = { skill, skipInventoryRefresh: true, fileInventory: files, packageSnapshotId: f.id };
let waitingOnSkill!: () => void;
const waiting = new Promise<void>(resolve => { waitingOnSkill = resolve; });
const debug = db.$client.options.debug;
db.$client.options.debug = (_connection, query) => {
if (query.includes('from "company_skills"') && query.includes('for update')) waitingOnSkill();
};
let saving: Promise<unknown> | undefined;
try {
await withDedicatedDbConnection(db, connection => connection.transaction(async tx => {
// updateFile owns this lock before its package is prepared separately.
await tx.select({ id: companySkills.id }).from(companySkills).where(eq(companySkills.id, skill.id)).for("update");
saving = f.service.createVersion(f.companyId, skill.id, {}, null, options);
await waiting;
await withDedicatedDbConnection(db, async upload => {
// A regression fails promptly and releases the outer lock instead of
// leaving a hidden cross-connection wait cycle hanging the suite.
await upload.execute(sql`set statement_timeout = '3s'`);
expect(await skillPackageStore(upload, storage).prepare(f.companyId, files)).toBe(f.id);
});
await f.service.createVersion(f.companyId, skill.id, {}, null, { ...options, database: tx });
}));
await saving;
expect(await f.service.listVersions(f.companyId, skill.id)).toHaveLength(3);
} finally { db.$client.options.debug = debug; await saving; }
}, 15_000);
it("follows a package published between version metadata and summary reads", async () => {
const companyId = await company();
const [skill] = await db.insert(companySkills).values({ companyId, key: "summary", slug: "summary", name: "Summary", markdown: files[0]!.content }).returning();
const [stale] = await db.insert(companySkillVersions).values({ companyId, companySkillId: skill!.id, revisionNumber: 1, fileInventory: files }).returning();
await skillPackageMaintenance(db, storage).migrateVersions({ id: stale!.id, apply: true, clearLegacy: true });
expect(await skillPackageStore(db, storage).versionInventory(stale!)).toEqual(files.map(({ path, kind }) => ({ path, kind })));
});
it("prepares a repository fork before its publication transaction with a one-connection pool", async () => {
const f = await fixture();
let publishing = false;
const read = storage.getObject.bind(storage);
vi.spyOn(storage, "getObject").mockImplementation((...args) => {
expect(publishing, "Package acquisition must finish before publication takes database locks").toBe(false);
return read(...args);
});
const fork = await f.service.createLocalSkill(f.companyId,
{ name: "Idempotent fork", slug: "idempotent-fork", forkedFromSkillId: f.skills[0]!.skill.id }, null, {
beforeLock: async () => { publishing = true; },
afterPublish: async (tx, skill, version) => {
expect((await tx.select().from(companySkillVersions).where(eq(companySkillVersions.id, version.id)))[0])
.toMatchObject({ companySkillId: skill.id });
},
});
publishing = false;
const saved = await f.service.getVersion(f.companyId, fork.id, fork.currentVersionId!);
expect(saved!.fileInventory).toEqual(expect.arrayContaining([
expect.objectContaining({ path: ".paperclip-repository/shared/run.sh", content: files[2]!.content }),
]));
}, 15_000);
it("publishes a fork and agent reassignment atomically with a one-connection pool", async () => {
const f = await fixture();
const original = f.skills[0]!.skill;
const [agent] = await db.insert(agents).values({ companyId: f.companyId, name: "Fork user", adapterType: "codex_local",
adapterConfig: { paperclipSkillSync: { desiredSkills: [{ key: original.key }] } } }).returning();
await expect(f.service.forkSkill(f.companyId, original.id, { slug: "atomic-fork", reassignAgentIds: [agent!.id] }, null,
{ afterPublish: async () => { throw new Error("audit rollback"); } })).rejects.toThrow("audit rollback");
expect(await f.service.getByKey(f.companyId, `company/${f.companyId}/atomic-fork`)).toBeNull();
expect((await db.select().from(agents).where(eq(agents.id, agent!.id)))[0]!.adapterConfig).toEqual(agent!.adapterConfig);
const fork = await f.service.forkSkill(f.companyId, original.id, { slug: "atomic-fork", reassignAgentIds: [agent!.id] });
expect(fork.reassignments).toEqual([{ agentId: agent!.id, previousSkillKey: original.key, nextSkillKey: fork.skill.key }]);
});
it("lists version metadata without reading archives, while inspection reads the requested historical bytes", async () => {
const f = await fixture();
const { skill, version } = f.skills[0]!;
await db.update(companySkills).set({ markdown: "New current markdown" }).where(eq(companySkills.id, skill.id));
const read = vi.spyOn(storage, "getObject");
const history = await f.service.listVersions(f.companyId, skill.id);
expect(history[0]!.fileInventory).toEqual([{ path: "SKILL.md", kind: "skill" }]);
expect(read.mock.calls.filter(call => call[1].endsWith("files.tar.gz"))).toHaveLength(0);
await db.update(companySkillVersions).set({ packageFileMap: [
...version.packageFileMap!, { path: "run.sh", kind: "script", sourcePath: "shared/run.sh" },
] }).where(eq(companySkillVersions.id, version.id));
const script = await readCustomerSuccessResource(db, storage, {
operation: "skills.file", companyId: f.companyId, resourceId: skill.id, versionId: version.id, path: "run.sh",
}) as { content: string };
expect(Buffer.from(script.content, "base64").toString()).toBe(files[2]!.content);
const result = await readCustomerSuccessResource(db, storage, {
operation: "skills.file", companyId: f.companyId, resourceId: skill.id, versionId: version.id, path: "SKILL.md",
}) as { content: string };
expect(Buffer.from(result.content, "base64").toString()).toBe(files[0]!.content);
const missing = await readCustomerSuccessResource(db, storage, {
operation: "skills.file", companyId: f.companyId, resourceId: skill.id, versionId: version.id, path: "not-saved.md",
});
expect(missing).toEqual({ available: false, reason: "skill_file_not_snapshotted" });
});
it("does not block a warm turn behind a paused archive read for retention", async () => {
const f = await fixture();
await f.resolve();
await fs.rm(skillPackagePaths(f.companyId, f.id).directory, { recursive: true, force: true });
let release!: () => void;
let entered!: () => void;
const blocked = new Promise<void>(resolve => { release = resolve; });
const reading = new Promise<void>(resolve => { entered = resolve; });
const original = storage.getObject.bind(storage);
vi.spyOn(storage, "getObject").mockImplementation(async (companyId, key, options) => {
if (key.endsWith("files.tar.gz")) { entered(); await blocked; }
return original(companyId, key, options);
});
const cleanup = hasRestorableSnapshot(db, f.companyId, f.skills[0]!.version.id);
try {
await reading;
const warm = await f.resolve();
expect(warm.map(entry => entry.sourceStatus)).toEqual(["available", "available"]);
} finally { release(); await cleanup; }
expect(await fs.stat(skillPackagePaths(f.companyId, f.id).directory).catch(() => null)).toBeNull();
}, 15_000);
it("skips an in-flight publication without waiting on its row or the warm preparation lock", async () => {
const f = await fixture(true);
await db.update(companySkills).set({ currentVersionId: null }).where(eq(companySkills.companyId, f.companyId));
await db.update(snapshots).set({ createdAt: new Date(0), maintenanceAt: new Date(0) }).where(eq(snapshots.id, f.id));
let retirementStarted!: () => void;
const waiting = new Promise<void>(resolve => { retirementStarted = resolve; });
const debug = db.$client.options.debug;
db.$client.options.debug = (_connection, query) => {
if (query.includes('company_skill_repository_snapshots') && query.includes('for update')) retirementStarted();
};
let sweep: Promise<void> | undefined;
try {
await withDedicatedDbConnection(db, connection => connection.transaction(async tx => {
await tx.select({ id: snapshots.id }).from(snapshots).where(eq(snapshots.id, f.id)).for("update");
await tx.update(companySkills).set({ currentVersionId: f.skills[0]!.version.id }).where(eq(companySkills.id, f.skills[0]!.skill.id));
sweep = skillPackageWork(db, storage).tick(new AbortController().signal);
await waiting;
await sweep;
}));
await sweep;
expect((await f.store.descriptor(f.companyId, f.id)).storage).not.toBeNull();
} finally { db.$client.options.debug = debug; await sweep; }
}, 15_000);
it("refuses to publish a package retired before the publication row lock", async () => {
const f = await fixture(true);
await db.update(companySkills).set({ currentVersionId: null }).where(eq(companySkills.companyId, f.companyId));
await db.update(snapshots).set({ storage: null }).where(eq(snapshots.id, f.id));
await expect(f.service.createVersion(f.companyId, f.skills[0]!.skill.id, {}, null, {
skill: f.skills[0]!.skill, skipInventoryRefresh: true, fileInventory: files,
packageSnapshotId: f.id, repositorySnapshotId: f.id, repositorySkillPath: files[0]!.path,
})).rejects.toThrow(/changed during publication/);
const [skill] = await db.select().from(companySkills).where(eq(companySkills.id, f.skills[0]!.skill.id));
expect(skill!.currentVersionId).toBeNull();
});
it("converts a legacy fork with the scanner's deepest accepted repository path", async () => {
const companyId = await company();
const deep = [...Array(63).fill("d"), "SKILL.md"].join("/");
const projected = repositorySkillProjection([{ ...files[0]!, path: deep }], deep);
const [skill] = await db.insert(companySkills).values({ companyId, key: "deep", slug: "deep", name: "Deep", markdown: projected[0]!.content }).returning();
const [version] = await db.insert(companySkillVersions).values({ companyId, companySkillId: skill!.id, revisionNumber: 1, fileInventory: projected }).returning();
await skillPackageMaintenance(db, storage).migrateVersions({ id: version!.id, apply: true, clearLegacy: true });
const [saved] = await db.select().from(companySkillVersions).where(eq(companySkillVersions.id, version!.id));
expect(saved!.migrationAt).toBeNull();
expect(await skillPackageStore(db, storage).versionFiles(saved!)).toEqual(projected);
});
it("automatically converts legacy rows, clears verified payloads and preserves version identities", async () => {
const companyId = await company();
const [snapshot] = await db.insert(snapshots).values({ companyId, contentHash: skillSnapshotHash(files), fileInventory: files }).returning();
const [skill] = await db.insert(companySkills).values({ companyId, key: "legacy", slug: "legacy", name: "Legacy", markdown: files[0]!.content }).returning();
const [version] = await db.insert(companySkillVersions).values({ companyId, companySkillId: skill!.id, revisionNumber: 7,
repositorySnapshotId: snapshot!.id, repositorySkillPath: files[0]!.path,
fileInventory: [{ ...files[0]!, path: "SKILL.md" }] }).returning();
const work = skillPackageWork(db, storage);
await work.tick(new AbortController().signal);
const [saved] = await db.select().from(snapshots).where(eq(snapshots.id, snapshot!.id));
const [converted] = await db.select().from(companySkillVersions).where(eq(companySkillVersions.id, version!.id));
expect(saved!.fileInventory).toEqual([]);
expect(saved!.migrationAt).toBeNull();
expect(saved!.storage).not.toBeNull();
expect(converted!.fileInventory).toEqual([]);
expect(converted!.migrationAt).toBeNull();
expect(converted!.packageSnapshotId).toBe(snapshot!.id);
expect(converted!.revisionNumber).toBe(7);
expect(await skillPackageStore(db, storage).versionFiles(converted!)).toEqual([{ ...files[0]!, path: "SKILL.md" }]);
});
it.each(["file", "folder"] as const)("keeps committed %s contents when the replacement package upload fails", async target => {
const companyId = await company();
vi.spyOn(storageModule, "getStorageService").mockReturnValue(storage);
const service = companySkillService(db);
const skill = await service.createLocalSkill(companyId, { name: "Delete rollback", slug: "delete-rollback", markdown: "# Keep the skill\n" });
const binary = Buffer.from([0, 255, 7, 128]);
await service.updateFile(companyId, skill.id, "bundle/probe.sh", "#!/bin/sh\nprintf kept\n", null, { executable: true });
await service.updateFile(companyId, skill.id, "bundle/nested/data.bin", binary.toString("base64"), null, { encoding: "base64" });
await service.updateFile(companyId, skill.id, "keep.txt", "Unrelated file\n");
const [before] = await db.select().from(companySkills).where(eq(companySkills.id, skill.id));
const versionsBefore = await db.select({ id: companySkillVersions.id }).from(companySkillVersions)
.where(eq(companySkillVersions.companySkillId, skill.id));
const input = { path: target === "file" ? "bundle/probe.sh" : "bundle", target };
const upload = vi.spyOn(storage, "putFile").mockRejectedValue(new Error("Object storage unavailable"));
try {
await expect(service.deleteFile(companyId, skill.id, input)).rejects.toThrow("Object storage unavailable");
expect(upload).toHaveBeenCalled();
} finally { upload.mockRestore(); }
expect(await service.readFile(companyId, skill.id, "bundle/probe.sh"))
.toMatchObject({ content: "#!/bin/sh\nprintf kept\n", executable: true });
expect(await service.readFile(companyId, skill.id, "bundle/nested/data.bin"))
.toMatchObject({ content: binary.toString("base64"), encoding: "base64" });
const [after] = await db.select().from(companySkills).where(eq(companySkills.id, skill.id));
expect(after).toEqual(before);
expect(await db.select({ id: companySkillVersions.id }).from(companySkillVersions)
.where(eq(companySkillVersions.companySkillId, skill.id))).toEqual(versionsBefore);
// Failed uploads keep a durable claim for reconciliation. Simulate its
// expiry before retrying the same package with recovered storage.
await db.update(snapshots).set({ upload: sql`jsonb_set(${snapshots.upload}, '{expiresAt}', to_jsonb(${new Date(0).toISOString()}::text))` })
.where(and(eq(snapshots.companyId, companyId), sql`${snapshots.upload} is not null`));
const deleted = await service.deleteFile(companyId, skill.id, input);
expect(deleted.deletedPaths).toContain("bundle/probe.sh");
await expect(service.readFile(companyId, skill.id, "bundle/probe.sh")).rejects.toMatchObject({ status: 404 });
if (target === "folder") await expect(service.readFile(companyId, skill.id, "bundle/nested/data.bin")).rejects.toMatchObject({ status: 404 });
expect(await service.readFile(companyId, skill.id, "keep.txt")).toMatchObject({ content: "Unrelated file\n" });
expect((await service.getVersion(companyId, skill.id, before!.currentVersionId!))!.fileInventory)
.toEqual(expect.arrayContaining([expect.objectContaining({ path: "bundle/probe.sh", executable: true })]));
});
it.each(["committed", "rolled_back", "newer_edit", "unavailable"] as const)("reconciles a lost deletion commit reply when %s", async outcome => {
const companyId = await company();
vi.spyOn(storageModule, "getStorageService").mockReturnValue(storage);
const service = companySkillService(db);
const skill = await service.createLocalSkill(companyId, { name: "Commit reply", slug: "commit-reply", markdown: "# Keep\n" });
await service.updateFile(companyId, skill.id, "notes.txt", "Original notes\n");
await service.updateFile(companyId, skill.id, "keep.txt", "Keep\n");
const before = (await service.getById(companyId, skill.id))!;
let deletionFinished = false;
const ambiguousDb = new Proxy(db, {
get(target, property, receiver) {
if (property === "transaction") return async (callback: (tx: any) => Promise<any>, ...options: any[]) => {
if (deletionFinished && outcome === "unavailable") throw new Error("Database unavailable");
const result = await target.transaction(async tx => {
const value = await callback(tx);
if (value?.skill?.id === skill.id && value?.version) {
deletionFinished = true;
if (outcome === "rolled_back") throw new Error("Lost commit reply");
}
return value;
}, ...options);
if (result?.skill?.id !== skill.id || !result?.version) return result;
if (outcome === "newer_edit") await service.updateFile(companyId, skill.id, "notes.txt", "Newer edit\n");
throw new Error("Lost commit reply");
};
return Reflect.get(target, property, receiver);
},
});
await expect(companySkillService(ambiguousDb, { packageDb: db }).deleteFile(companyId, skill.id,
{ path: "notes.txt", target: "file", expectedVersionId: before.currentVersionId })).rejects.toThrow("Lost commit reply");
expect(deletionFinished).toBe(true);
const [saved] = await db.select().from(companySkills).where(eq(companySkills.id, skill.id));
if (outcome === "rolled_back") {
expect(saved!.currentVersionId).toBe(before.currentVersionId);
expect(await service.readFile(companyId, skill.id, "notes.txt")).toMatchObject({ content: "Original notes\n" });
await expect(service.deleteFile(companyId, skill.id, { path: "notes.txt", target: "file", expectedVersionId: before.currentVersionId }))
.resolves.toMatchObject({ deletedPaths: ["notes.txt"] });
} else {
expect(saved!.currentVersionId).not.toBe(before.currentVersionId);
if (outcome === "newer_edit") expect(await service.readFile(companyId, skill.id, "notes.txt"))
.toMatchObject({ content: "Newer edit\n" });
else await expect(service.readFile(companyId, skill.id, "notes.txt")).rejects.toMatchObject({ status: 404 });
await expect(service.deleteFile(companyId, skill.id, { path: "notes.txt", target: "file", expectedVersionId: before.currentVersionId }))
.rejects.toMatchObject({ status: 409 });
}
expect((await service.getVersion(companyId, skill.id, before.currentVersionId!))!.fileInventory)
.toEqual(expect.arrayContaining([expect.objectContaining({ path: "notes.txt", content: "Original notes\n" })]));
});
it("expires an unused Git package and reacquires its exact bytes without a migration command", async () => {
const f = await fixture(true);
const recipe = { version: 1 as const, sourceId: randomUUID(), repositoryId: "123", repositoryUrl: "https://github.com/acme/skills",
commitSha: "a".repeat(40), skillPath: null, manifest: skillPackageManifest(files) };
await f.store.prepare(f.companyId, files, true, undefined, recipe);
await f.store.files(f.companyId, f.id);
await db.update(snapshots).set({ createdAt: new Date(Date.now() - 40 * 86_400_000), maintenanceAt: new Date(0), migrationAt: null }).where(eq(snapshots.id, f.id));
// Current versions stay pinned even after their cache age expires.
await skillPackageWork(db, storage).tick(new AbortController().signal);
expect((await f.store.descriptor(f.companyId, f.id)).storage).not.toBeNull();
for (const { skill } of f.skills) await db.update(companySkills).set({ currentVersionId: null }).where(eq(companySkills.id, skill.id));
await db.update(snapshots).set({ maintenanceAt: new Date(0) }).where(eq(snapshots.id, f.id));
await skillPackageWork(db, storage).tick(new AbortController().signal);
expect((await f.store.descriptor(f.companyId, f.id)).storage).toBeNull();
expect(await fs.stat(skillPackagePaths(f.companyId, f.id).directory).catch(() => null)).toBeNull();
const entries = recipe.manifest.files.map((file, i) => ({ path: file.path, mode: file.executable ? "100755" : "100644", type: "blob", size: file.size, sha: String(i).repeat(40) }));
const read = Object.assign(vi.fn(async () => ({ id: 123 })), { openSnapshot: vi.fn(async () => ({ commitSha: recipe.commitSha, entries,
readBlob: async (entry: typeof entries[number]) => skillFileBytes(files[entries.indexOf(entry)]!), release: async () => {} })) }) as unknown as GitHubRead;
const authorization = vi.spyOn(recovery, "skillPackageRecoveryReader").mockResolvedValue(read);
expect(await f.store.files(f.companyId, f.id)).toEqual(files);
expect(read.openSnapshot).toHaveBeenCalledOnce();
await f.store.files(f.companyId, f.id);
expect(authorization).toHaveBeenCalledOnce();
await fs.rm(skillPackagePaths(f.companyId, f.id).directory, { recursive: true });
authorization.mockRejectedValue(new Error("grant revoked"));
await expect(f.store.files(f.companyId, f.id)).rejects.toThrow("grant revoked");
await expect(f.store.files(f.companyId, f.id)).rejects.toThrow("backoff");
expect(authorization).toHaveBeenCalledTimes(2);
});
it("recovers missing archive and manifest objects while a published receipt still exists", async () => {
const companyId = await company();
const store = skillPackageStore(db, storage);
const recipe = { version: 1 as const, sourceId: randomUUID(), repositoryId: "123", repositoryUrl: "https://github.com/acme/skills",
commitSha: "a".repeat(40), skillPath: null, manifest: skillPackageManifest(files) };
const id = await store.prepare(companyId, files, true, undefined, recipe);
const receipt = (await store.descriptor(companyId, id)).storage!;
await storage.deleteObject(companyId, receipt.archiveKey);
await storage.deleteObject(companyId, receipt.manifestKey);
await expect(recovery.skillPackageRecoveryReader(db, companyId, recipe)).rejects.toThrow("Reconnect its original repository");
const entries = recipe.manifest.files.map((file, i) => ({ path: file.path, mode: file.executable ? "100755" : "100644", type: "blob", size: file.size, sha: String(i).repeat(40) }));
const read = Object.assign(vi.fn(async () => ({ id: 123 })), { openSnapshot: vi.fn(async () => ({ commitSha: recipe.commitSha, entries,
readBlob: async (entry: typeof entries[number]) => skillFileBytes(files[entries.indexOf(entry)]!), release: async () => {} })) }) as unknown as GitHubRead;
vi.spyOn(recovery, "skillPackageRecoveryReader").mockResolvedValue(read);
// PostgreSQL JSONB has reordered recipe object keys; its canonical bytes must
// still agree with the original externally written manifest checksum.
expect(await store.files(companyId, id)).toEqual(files);
expect(read.openSnapshot).toHaveBeenCalledOnce();
});
it("retains referenced historical bytes without an exact Git recipe", async () => {
const f = await fixture();
for (const { skill } of f.skills) await db.update(companySkills).set({ currentVersionId: null }).where(eq(companySkills.id, skill.id));
await db.update(snapshots).set({ createdAt: new Date(0), migrationAt: null, maintenanceAt: new Date(0) }).where(eq(snapshots.id, f.id));
await skillPackageWork(db, storage).tick(new AbortController().signal);
expect((await f.store.descriptor(f.companyId, f.id)).storage).not.toBeNull();
expect(await f.store.files(f.companyId, f.id)).toEqual(files);
});
it("retains authored history when a Git import shares its package and later loses access", async () => {
const f = await fixture();
const [authored] = await db.insert(companySkillVersions).values({ companyId: f.companyId, companySkillId: f.skills[0]!.skill.id,
revisionNumber: 2, packageSnapshotId: f.id, migrationAt: null }).returning();
const recipe = { version: 1 as const, sourceId: randomUUID(), repositoryId: "123", repositoryUrl: "https://github.com/acme/skills",
commitSha: "a".repeat(40), skillPath: null, manifest: skillPackageManifest(files) };
expect(await f.store.prepare(f.companyId, files, true, undefined, recipe)).toBe(f.id);
for (const { skill } of f.skills) await db.update(companySkills).set({ currentVersionId: null }).where(eq(companySkills.id, skill.id));
await db.update(snapshots).set({ createdAt: new Date(0), migrationAt: null, maintenanceAt: new Date(0) }).where(eq(snapshots.id, f.id));
await skillPackageWork(db, storage).tick(new AbortController().signal);
expect((await f.store.descriptor(f.companyId, f.id)).storage).not.toBeNull();
await fs.rm(skillPackagePaths(f.companyId, f.id).directory, { recursive: true, force: true });
const upstream = vi.spyOn(recovery, "skillPackageRecoveryReader").mockRejectedValue(new Error("grant revoked"));
expect(await f.store.versionFiles(authored!)).toEqual(files);
expect(upstream).not.toHaveBeenCalled();
});
it("keeps authored durability when it joins an in-flight Git package upload", async () => {
const companyId = await company();
const store = skillPackageStore(db, storage);
const recipe = { version: 1 as const, sourceId: randomUUID(), repositoryId: "123", repositoryUrl: "https://github.com/acme/skills",
commitSha: "a".repeat(40), skillPath: null, manifest: skillPackageManifest(files) };
let release!: () => void;
let entered!: () => void;
const blocked = new Promise<void>(resolve => { release = resolve; });
const uploading = new Promise<void>(resolve => { entered = resolve; });
const put = storage.putFile.bind(storage);
vi.spyOn(storage, "putFile").mockImplementationOnce(async input => { entered(); await blocked; return put(input); });
const git = store.prepare(companyId, files, true, undefined, recipe);
await uploading;
const authored = store.prepare(companyId, files);
release();
const ids = await Promise.all([git, authored]);
expect(ids[0]).toBe(ids[1]);
expect((await store.descriptor(companyId, ids[0]!)).storage?.durable).toBe(true);
expect(await db.select().from(skillPackageDeletions).where(eq(skillPackageDeletions.companyId, companyId))).toEqual([]);
});
it("preserves version kinds and encodings when identical package bytes are deduplicated", async () => {
const companyId = await company();
const original: CompanySkillVersionFileInventoryEntry[] = [{ path: "SKILL.md", kind: "skill", content: files[0]!.content },
{ path: "helper", kind: "other", content: "#!/bin/sh\necho same\n" }];
const changed: CompanySkillVersionFileInventoryEntry[] = [original[0]!, { ...original[1]!, kind: "script", encoding: "base64",
content: Buffer.from(original[1]!.content).toString("base64") }];
const store = skillPackageStore(db, storage);
const packageId = await store.prepare(companyId, original);
vi.spyOn(storageModule, "getStorageService").mockReturnValue(storage);
const [skill] = await db.insert(companySkills).values({ companyId, key: "metadata", slug: "metadata", name: "Metadata", markdown: original[0]!.content }).returning();
const service = companySkillService(db);
const saved = await service.createVersion(companyId, skill!.id, {}, null, { skill: toSkill(skill!), skipInventoryRefresh: true, fileInventory: changed });
expect((await service.getVersion(companyId, skill!.id, saved.id))!.fileInventory).toEqual(changed);
const [legacy] = await db.insert(companySkillVersions).values({ companyId, companySkillId: skill!.id, revisionNumber: 2, fileInventory: changed }).returning();
await skillPackageMaintenance(db, storage).migrateVersions({ id: legacy!.id, apply: true, clearLegacy: true });
const [converted] = await db.select().from(companySkillVersions).where(eq(companySkillVersions.id, legacy!.id));
expect(converted!.packageSnapshotId).toBe(packageId);
expect(converted!.fileInventory).toEqual([]);
expect(await store.versionFiles(converted!)).toEqual(changed);
});
it("does not delete an orphan whose expired upload was reclaimed after selection", async () => {
const companyId = await company();
const upload = { token: randomUUID(), provider: "local_disk" as const, archiveKey: `${companyId}/old/archive`, manifestKey: `${companyId}/old/manifest`, expiresAt: new Date(0).toISOString() };
const [row] = await db.insert(snapshots).values({ companyId, contentHash: skillSnapshotHash(files), createdAt: new Date(0), upload }).returning();
const renewed = { ...upload, token: randomUUID(), expiresAt: new Date(Date.now() + 600_000).toISOString() };
const racingDb = new Proxy(db, { get(target, key) {
if (key !== "delete") return Reflect.get(target, key);
return (table: typeof snapshots) => ({ where: (predicate: Parameters<ReturnType<typeof db.delete>["where"]>[0]) => ({ returning: async () => {
await db.update(snapshots).set({ upload: renewed }).where(eq(snapshots.id, row!.id));
return db.delete(table).where(predicate).returning({ id: snapshots.id });
} }) });
} });
expect((await skillPackageMaintenance(racingDb, storage).collectOrphans({ companyId, apply: true })).removed).toBe(0);
const [saved] = await db.select().from(snapshots).where(eq(snapshots.id, row!.id));
expect(saved!.upload).toEqual(renewed);
});
it("restores one shared archive, then prepares a warm turn without object reads or SQL file bodies", async () => {
const f = await fixture();
const read = vi.spyOn(storage, "getObject");
const cold = await f.resolve();
expect(cold.map(entry => entry.sourceStatus)).toEqual(["available", "available"]);
expect(read.mock.calls.filter(call => call[1].endsWith("files.tar.gz"))).toHaveLength(1);
expect(read.mock.calls.filter(call => call[1].endsWith("manifest.json"))).toHaveLength(1);
const [row] = await db.select().from(snapshots).where(eq(snapshots.id, f.id));
expect(row!.fileInventory).toEqual([]);
const sql: string[] = [];
const oldDebug = db.$client.options.debug;
db.$client.options.debug = (_connection, query) => { sql.push(query); };
read.mockClear();
try { expect(await f.resolve()).toEqual(cold); }
finally { db.$client.options.debug = oldDebug; }
expect(read).not.toHaveBeenCalled();
expect(sql.length).toBeLessThanOrEqual(6);
for (const query of sql.filter(query => /from "company_skill_(repository_snapshots|versions)"/.test(query))) {
// Bundled release validation returns only a DB-side digest.
if (!query.includes("encode(sha256(")) expect(query).not.toMatch(/"file_inventory"/);
}
expect((await f.service.getVersion(f.companyId, f.skills[0]!.skill.id, f.skills[0]!.version.id))!.fileInventory)
.toEqual([{ path: "SKILL.md", kind: "skill", content: files[0]!.content }]);
const restored = await f.store.files(f.companyId, f.id);
expect(restored.map(skillFileBytes)).toEqual(files.map(skillFileBytes));
await expect(f.store.files(await company(), f.id)).rejects.toThrow("unavailable");
});
it("repairs a same-size cached edit and restores old versions without upstream access", async () => {
const f = await fixture();
const entries = await f.resolve();
const target = path.join(entries[0]!.source, ".paperclip-repository/shared/run.sh");
const stat = await fs.stat(target);
await fs.chmod(target, 0o755);
await fs.writeFile(target, "#!/bin/sh\necho modified\n");
await fs.utimes(target, stat.atime, stat.mtime);
const read = vi.spyOn(storage, "getObject");
await f.resolve();
expect(await fs.readFile(target, "utf8")).toBe(files[2]!.content);
expect(read).not.toHaveBeenCalled();
const upstream = vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("offline"));
for (const entry of entries) await fs.rm(entry.source, { recursive: true });
await fs.rm(skillPackagePaths(f.companyId, f.id).directory, { recursive: true });
expect((await f.resolve()).every(entry => entry.sourceStatus === "available")).toBe(true);
expect(upstream).not.toHaveBeenCalled();
});
it("refuses cache eviction when durable objects are missing, even after an earlier verification", async () => {
const f = await fixture();
await f.resolve();
expect(await hasRestorableSnapshot(db, f.companyId, f.skills[0]!.version.id)).toBe(true);
const receipt = (await f.store.descriptor(f.companyId, f.id)).storage!;
await storage.deleteObject(f.companyId, receipt.archiveKey);
await expect(hasRestorableSnapshot(db, f.companyId, f.skills[0]!.version.id)).rejects.toThrow();
// Existing local verified files remain usable while storage is unavailable.
expect((await f.resolve()).every(entry => entry.sourceStatus === "available")).toBe(true);
});
it("reads verified cached versions offline while independently checking durable bytes and rejecting corrupt files", async () => {
const f = await fixture();
await f.store.files(f.companyId, f.id);
const read = vi.spyOn(storage, "getObject").mockRejectedValue(new Error("storage offline"));
const saved = f.skills[0]!;
expect((await f.service.getVersion(f.companyId, saved.skill.id, saved.version.id))!.fileInventory)
.toEqual([{ path: "SKILL.md", kind: "skill", content: files[0]!.content }]);
expect(await f.store.versionFiles({ ...saved.version, packageFileMap: null })).toEqual(files);
expect(read).not.toHaveBeenCalled();
await expect(f.store.verifyDurable(f.companyId, f.id)).rejects.toThrow("storage offline");
const target = path.join(skillPackagePaths(f.companyId, f.id).directory, files[0]!.path);
await fs.chmod(target, 0o600);
await fs.writeFile(target, "x".repeat(Buffer.byteLength(files[0]!.content)));
await expect(f.store.versionFiles(saved.version)).rejects.toThrow("storage offline");
});
it("coalesces cold version reads and retains the verified package for subsequent reads", async () => {
const f = await fixture();
await f.resolve();
const root = skillPackagePaths(f.companyId, f.id).directory;
await fs.rm(root, { recursive: true });
const read = vi.spyOn(storage, "getObject");
const saved = f.skills[0]!;
const get = () => f.service.getVersion(f.companyId, saved.skill.id, saved.version.id);
const [first, second, third] = await Promise.all([get(), get(), get()]);
expect(first!.fileInventory).toEqual([{ path: "SKILL.md", kind: "skill", content: files[0]!.content }]);
expect(second).toEqual(first);
expect(third).toEqual(first);
expect(await get()).toEqual(first);
expect(await f.store.readVersionFile(saved.version, "SKILL.md")).toMatchObject({ content: files[0]!.content });
expect(read.mock.calls.filter(call => call[1].endsWith("files.tar.gz"))).toHaveLength(1);
expect(await verifySkillPackageDirectory(root, skillPackageManifest(files).files)).toBe(true);
});
it("shares a cold manifest while allowing one caller to cancel without aborting another", async () => {
const f = await fixture();
const get = storage.getObject.bind(storage);
let entered!: () => void;
const started = new Promise<void>(resolve => { entered = resolve; });
let release!: () => void;
const blocked = new Promise<void>(resolve => { release = resolve; });
let storageSignal: AbortSignal | undefined;
const read = vi.spyOn(storage, "getObject").mockImplementation(async (...args) => {
storageSignal = args[2]?.signal;
entered();
await blocked;
return get(...args);
});
const cancellation = new AbortController();
const first = f.store.manifest(f.companyId, f.id, cancellation.signal).catch(error => error);
await started;
const second = f.store.manifest(f.companyId, f.id);
try {
// The shared one-slot pool places this query after the second descriptor.
await db.select({ id: snapshots.id }).from(snapshots).where(eq(snapshots.id, f.id));
cancellation.abort(new Error("Caller stopped"));
expect((await first).message).toBe("Caller stopped");
expect(storageSignal?.aborted).toBe(false);
release();
expect(await second).toEqual(skillPackageManifest(files));
expect(read).toHaveBeenCalledOnce();
} finally { release(); await Promise.allSettled([first, second]); }
});
it("keeps warm preparation responsive while a read-triggered cache trim verifies storage", async () => {
const f = await fixture();
await f.resolve();
const paths = skillPackagePaths(f.companyId, f.id);
// Exceed the directory bound without manufacturing large file payloads.
for (let index = 0; index < 63; index++) {
const orphan = path.join(paths.parent, randomUUID());
await fs.mkdir(orphan);
const later = new Date(Date.now() + 60_000);
await fs.utimes(orphan, later, later);
}
const changed = files.map((file, index) => index ? file : { ...file, content: `${file.content}Updated\n` });
const id = await f.store.prepare(f.companyId, changed);
const [version] = await db.insert(companySkillVersions).values({ companyId: f.companyId,
companySkillId: f.skills[0]!.skill.id, revisionNumber: 2, packageSnapshotId: id, migrationAt: null,
packageFileMap: f.skills[0]!.version.packageFileMap }).returning();
const receipt = (await f.store.descriptor(f.companyId, f.id)).storage!;
const get = storage.getObject.bind(storage);
let entered!: () => void;
const started = new Promise<void>(resolve => { entered = resolve; });
let release!: () => void;
const blocked = new Promise<void>(resolve => { release = resolve; });
vi.spyOn(storage, "getObject").mockImplementation(async (...args) => {
if (args[1] === receipt.manifestKey) { entered(); await blocked; }
return get(...args);
});
const reading = f.store.versionFiles(version!);
let warming: ReturnType<typeof f.resolve> | undefined;
let timeout: ReturnType<typeof setTimeout> | undefined;
try {
await started;
warming = f.resolve();
expect((await Promise.race([warming, new Promise<never>((_resolve, reject) => {
timeout = setTimeout(() => reject(new Error("Warm preparation waited for eviction storage")), 1_000);
})])).every(entry => entry.sourceStatus === "available")).toBe(true);
// Preparation can reuse its separate projection. Also access the shared
// package itself to prove eviction rechecks use after verification.
await f.store.versionFiles(f.skills[0]!.version);
release();
expect((await reading)[0]!.content).toBe(changed[0]!.content);
expect((await fs.stat(paths.directory)).isDirectory()).toBe(true);
} finally { clearTimeout(timeout); release(); await Promise.allSettled([reading, warming]); }
});
it("bounds cold response lifetimes while cleanup is waiting without blocking warm preparation", async () => {
const fixtures = [await fixture(), await fixture(), await fixture()];
let bothEntered!: () => void;
const started = new Promise<void>(resolve => { bothEntered = resolve; });
let release!: () => void;
const blocked = new Promise<void>(resolve => { release = resolve; });
let decoded = 0;
const trim = vi.spyOn(packageCache, "trimSkillPackageCache").mockImplementation(async () => {
if (++decoded === 2) bothEntered();
await blocked;
});
const reads = fixtures.slice(0, 2).map(f => f.store.versionFiles(f.skills[0]!.version));
const storageRead = vi.spyOn(storage, "getObject");
try {
await started;
reads.push(fixtures[2]!.store.versionFiles(fixtures[2]!.skills[0]!.version));
expect((await fixtures[0]!.resolve()).every(entry => entry.sourceStatus === "available")).toBe(true);
// Let the third metadata/manifest read settle. Its archive and response
// must remain queued while two decoded responses are owned by cleanup.
await new Promise(resolve => setTimeout(resolve, 50));
expect(decoded).toBe(2);
const third = (await fixtures[2]!.store.descriptor(fixtures[2]!.companyId, fixtures[2]!.id)).storage!;
expect(storageRead.mock.calls.filter(call => call[1] === third.archiveKey)).toHaveLength(0);
release();
expect((await Promise.all(reads)).every(files => files[0]!.path === "SKILL.md")).toBe(true);
expect(trim).toHaveBeenCalledTimes(3);
} finally { release(); await Promise.allSettled(reads); }
});
it.each(["manifest", "files"] as const)("does not load queued legacy bodies for %s reads", async kind => {
const f = await fixture();
const companyId = await company();
const rows = await db.insert(snapshots).values(Array.from({ length: 33 }, (_, index) => {
const inventory = files.map((file, i) => i ? file : { ...file, content: `${file.content}${index}` });
return { companyId, contentHash: skillSnapshotHash(inventory), fileInventory: inventory };
})).returning({ id: snapshots.id });
const store = skillPackageStore(db, storage);
if (kind === "files") for (const row of rows) await store.manifest(companyId, row.id);
let release!: () => void;
const blocked = new Promise<void>(resolve => { release = resolve; });
let active = 0;
const occupying = Array.from({ length: 2 }, () => f.store.withIsolatedPackage(f.companyId, f.id, async () => {
active++;
await blocked;
}));
await vi.waitFor(() => expect(active).toBe(2));
let bodies = 0;
const observe = (_connection: number, query: string) => {
if (query.includes('"file_inventory"') && query.includes('"company_skill_repository_snapshots"')) bodies++;
};
const debug = db.$client.options.debug;
db.$client.options.debug = observe;
const dedicated = dbModule.withDedicatedDbConnection;
let ready = 0;
vi.spyOn(dbModule, "withDedicatedDbConnection").mockImplementation((owner, action) => dedicated(owner, connection => {
connection.$client.options.debug = observe;
if (kind === "files") ready++;
return action(connection);
}));
if (kind === "manifest") {
const parent = skillPackagePaths(companyId, rows[0]!.id).parent;
const lstat = fs.lstat.bind(fs);
vi.spyOn(fs, "lstat").mockImplementation(async (...args) => {
const result = await lstat(...args);
if (args[0] === parent) ready++;
return result;
});
}
const read = (id: string) => kind === "files" ? store.files(companyId, id, true) : store.manifest(companyId, id);
const queued = rows.slice(0, 32).map(row => read(row.id));
try {
await vi.waitFor(() => expect(ready).toBe(32));
// The final reader observes the full queue only after all earlier readers
// have reached admission. None may preload repository bodies while waiting.
await expect(read(rows[32]!.id)).rejects.toThrow("busy");
expect(bodies).toBe(0);
release();
expect(await Promise.all(queued)).toHaveLength(32);
} finally {
release();
await Promise.allSettled([...occupying, ...queued]);
db.$client.options.debug = debug;
}
}, 15_000);
it("does not deadlock a transaction behind cold reads on a one-connection pool", async () => {
const fixtures = [await fixture(), await fixture(), await fixture()];
const roots = new Map(fixtures.slice(0, 2).map(f => [skillPackagePaths(f.companyId, f.id).directory, 0]));
let release!: () => void;
const blocked = new Promise<void>(resolve => { release = resolve; });
const lstat = fs.lstat.bind(fs);
const stat = vi.spyOn(fs, "lstat").mockImplementation(async (...args) => {
const root = String(args[0]);
if (roots.has(root)) {
roots.set(root, roots.get(root)! + 1);
await blocked;
throw Object.assign(new Error("Cold package"), { code: "ENOENT" });
}
return lstat(...args);
});
const reads = fixtures.slice(0, 2).map(f => f.store.versionFiles(f.skills[0]!.version));
let timeout: ReturnType<typeof setTimeout> | undefined;
try {
// Both callers have loaded metadata but have not entered cold fallback.
await vi.waitFor(() => expect([...roots.values()]).toEqual([1, 1]));
await db.transaction(async tx => {
await tx.execute(sql`select 1`);
release();
// Their second cache misses now queue the cold fallback while this
// transaction owns the only ordinary connection.
await vi.waitFor(() => expect([...roots.values()]).toEqual([2, 2]));
const cancellation = new AbortController();
timeout = setTimeout(() => cancellation.abort(new Error("Cold read deadlocked the pool")), 1_000);
const third = fixtures[2]!;
expect(await skillPackageStore(tx as unknown as typeof db, storage, db)
.versionFiles(third.skills[0]!.version, true, cancellation.signal))
.toEqual([{ path: "SKILL.md", kind: "skill", content: files[0]!.content }]);
});
} finally {
clearTimeout(timeout);
release();
stat.mockRestore();
await Promise.allSettled(reads);
}
expect((await Promise.all(reads)).every(result => result[0]!.content === files[0]!.content)).toBe(true);
});
it("bounds concurrent cached inventories while leaving warm turn preparation responsive", async () => {
const f = await fixture();
await f.resolve();
const target = path.join(skillPackagePaths(f.companyId, f.id).directory, files[0]!.path);
const open = fs.open.bind(fs);
let entered = 0;
let bothEntered!: () => void;
const started = new Promise<void>(resolve => { bothEntered = resolve; });
let release!: () => void;
const blocked = new Promise<void>(resolve => { release = resolve; });
vi.spyOn(fs, "open").mockImplementation(async (...args) => {
if (args[0] === target) {
if (++entered === 2) bothEntered();
await blocked;
}
return open(...args);
});
const version = { ...f.skills[0]!.version, packageFileMap: null };
const storageRead = vi.spyOn(storage, "getObject");
const reads = [f.store.versionFiles(version), f.store.versionFiles(version)];
let preview: ReturnType<typeof f.store.readVersionFile> | undefined;
try {
await started;
reads.push(f.store.versionFiles(version));
preview = f.store.readVersionFile(version, files[0]!.path);
reads.push(...Array.from({ length: 30 }, () => f.store.versionFiles(version)));
// These queries share the one-connection pool, so the third inventory has
// loaded its descriptor by the time preparation finishes. Its byte read
// must still be queued behind the two active readers.
expect((await f.resolve()).every(entry => entry.sourceStatus === "available")).toBe(true);
expect(entered).toBe(2);
await expect(f.store.versionFiles(version)).rejects.toThrow("busy");
expect(storageRead).not.toHaveBeenCalled();
release();
expect(await Promise.all(reads)).toEqual(reads.map(() => files));
expect(await preview).toMatchObject(files[0]!);
} finally { release(); await Promise.allSettled([...reads, preview]); }
});
it("reads cached versions while both storage operations are stalled", async () => {
const f = await fixture();
await f.resolve();
const get = storage.getObject.bind(storage);
let entered = 0;
let bothEntered!: () => void;
const started = new Promise<void>(resolve => { bothEntered = resolve; });
let release!: () => void;
const blocked = new Promise<void>(resolve => { release = resolve; });
vi.spyOn(storage, "getObject").mockImplementation(async (...args) => {
if (++entered === 2) bothEntered();
await blocked;
return get(...args);
});
const pending = [f.store.withIsolatedPackage(f.companyId, f.id, async () => null),
f.store.withIsolatedPackage(f.companyId, f.id, async () => null)];
let timeout: ReturnType<typeof setTimeout> | undefined;
try {
await started;
const reading = db.transaction(tx => skillPackageStore(tx as unknown as typeof db, storage)
.versionFiles({ ...f.skills[0]!.version, packageFileMap: null }));
expect(await Promise.race([reading, new Promise<never>((_resolve, reject) => {
timeout = setTimeout(() => reject(new Error("Cached read waited for storage")), 1_000);
})])).toEqual(files);
} finally { clearTimeout(timeout); release(); await Promise.allSettled(pending); }
});
it("retries expired upload claims with fresh keys and only deletes the abandoned attempt", async () => {
const companyId = await company();
const store = skillPackageStore(db, storage);
const put = vi.spyOn(storage, "putFile").mockRejectedValueOnce(new Error("connection lost"));
await expect(store.prepare(companyId, files)).rejects.toThrow("connection lost");
put.mockRestore();
const [pending] = await db.select().from(snapshots).where(eq(snapshots.companyId, companyId));
expect(pending!.storage).toBeNull();
await expect(store.prepare(companyId, files)).rejects.toThrow("being saved");
await db.update(snapshots).set({ upload: { ...pending!.upload!, expiresAt: new Date(0).toISOString() } }).where(eq(snapshots.id, pending!.id));
const id = await store.prepare(companyId, files);
expect(id).toBe(pending!.id);
const receipt = (await store.descriptor(companyId, id)).storage!;
expect(receipt.archiveKey).not.toBe(pending!.upload!.archiveKey);
const [deletion] = await db.select().from(skillPackageDeletions).where(eq(skillPackageDeletions.companyId, companyId));
expect(deletion!.archiveKey).toBe(pending!.upload!.archiveKey);
await db.update(skillPackageDeletions).set({ deleteAfter: new Date(0) }).where(eq(skillPackageDeletions.id, deletion!.id));
expect((await skillPackageMaintenance(db, storage).deleteObjects({ companyId, apply: true })).removed).toBe(1);
expect(await store.verifyDurable(companyId, id)).toBe(true);
// Company cascades retain a receipt after removing the snapshot's DB row.
await db.delete(companies).where(eq(companies.id, companyId));
expect(await db.select().from(skillPackageDeletions).where(eq(skillPackageDeletions.companyId, companyId)))
.toEqual([expect.objectContaining({ archiveKey: receipt.archiveKey })]);
});
it("cancels queued and active uploads without publishing or leaking I/O capacity", async () => {
const ids = await Promise.all([company(), company(), company()]);
const active = new AbortController();
const queued = new AbortController();
const put = vi.spyOn(storage, "putFile").mockImplementation(async input => {
expect(input.signal).toBeDefined();
await new Promise<void>((_resolve, reject) => {
input.signal!.addEventListener("abort", () => reject(input.signal!.reason), { once: true });
});
throw new Error("Unreachable cancelled upload");
});
const store = skillPackageStore(db, storage);
const running = ids.slice(0, 2).map(id => store.prepare(id!, files, false, active.signal).catch(error => error));
try {
await vi.waitFor(() => expect(put).toHaveBeenCalledTimes(2));
const waiting = store.prepare(ids[2]!, files, false, queued.signal).catch(error => error);
await vi.waitFor(async () => expect(await db.select({ id: snapshots.id }).from(snapshots)
.where(eq(snapshots.companyId, ids[2]!))).toHaveLength(1));
queued.abort(new Error("queued cancellation"));
expect((await waiting).message).toBe("queued cancellation");
expect(put).toHaveBeenCalledTimes(2);
} finally {
active.abort(new Error("active cancellation"));
await Promise.all(running);
put.mockRestore();
}
for (const id of ids) {
const [row] = await db.select().from(snapshots).where(eq(snapshots.companyId, id!));
expect(row!.storage).toBeNull();
expect(row!.upload).not.toBeNull();
}
expect(await store.prepare(await company(), files)).toEqual(expect.any(String));
});
it("migrates both legacy payload locations in bounded resumable pages without changing version IDs", async () => {
const companyId = await company();
const [snapshot] = await db.insert(snapshots).values({ companyId, contentHash: skillSnapshotHash(files), fileInventory: files }).returning();
const [skill] = await db.insert(companySkills).values({ companyId, key: "legacy", slug: "legacy", name: "Legacy", markdown: files[0]!.content }).returning();
const original = { path: "SKILL.md", kind: "skill" as const, content: files[0]!.content };
const [version] = await db.insert(companySkillVersions).values({ companyId, companySkillId: skill!.id, revisionNumber: 7,
repositorySnapshotId: snapshot!.id, repositorySkillPath: files[0]!.path, fileInventory: [original] }).returning();
const maintenance = skillPackageMaintenance(db, storage);
expect((await maintenance.migrateSnapshots({ companyId })).migrated).toBe(0);
const fail = vi.spyOn(storage, "getObject").mockRejectedValueOnce(new Error("verification interrupted"));
await expect(maintenance.migrateSnapshots({ companyId, apply: true })).rejects.toThrow("verification interrupted");
fail.mockRestore();
const [pending] = await db.select().from(snapshots).where(eq(snapshots.id, snapshot!.id));
expect(pending!.fileInventory).toEqual(files);
await db.update(snapshots).set({ upload: { ...pending!.upload!, expiresAt: new Date(0).toISOString() } }).where(eq(snapshots.id, snapshot!.id));
expect((await maintenance.migrateSnapshots({ companyId, limit: 1, apply: true })).migrated).toBe(1);
const [soaked] = await db.select().from(snapshots).where(eq(snapshots.id, snapshot!.id));
expect(soaked!.storage).not.toBeNull();
expect(soaked!.fileInventory).toEqual(files);
expect((await maintenance.migrateSnapshots({ companyId, limit: 1, apply: true, clearLegacy: true })).migrated).toBe(1);
expect((await maintenance.migrateSnapshots({ companyId, apply: true })).inspected).toBe(0);
expect((await maintenance.migrateVersions({ companyId, apply: true, clearLegacy: true })).migrated).toBe(1);
const [saved] = await db.select().from(companySkillVersions).where(and(eq(companySkillVersions.id, version!.id), eq(companySkillVersions.companyId, companyId)));
expect(saved).toMatchObject({ id: version!.id, revisionNumber: 7, fileInventory: [], repositorySnapshotId: snapshot!.id, packageSnapshotId: snapshot!.id });
expect(await skillPackageStore(db, storage).versionFiles(saved!)).toEqual([original]);
});
it("backfills a cleared version's metadata index without changing its identity or bytes", async () => {
const f = await fixture();
const [version] = await db.insert(companySkillVersions).values({ companyId: f.companyId,
companySkillId: f.skills[0]!.skill.id, revisionNumber: 2, packageSnapshotId: f.id,
packageFileMap: null, fileInventory: [], migrationAt: null }).returning();
expect((await skillPackageMaintenance(db, storage).migrateVersions({ id: version!.id, apply: true })).migrated).toBe(1);
const [saved] = await db.select().from(companySkillVersions).where(eq(companySkillVersions.id, version!.id));
expect(saved).toMatchObject({ id: version!.id, revisionNumber: 2, packageSnapshotId: f.id, fileInventory: [] });
expect(await f.store.versionFiles(saved!)).toEqual(expect.arrayContaining(files));
const read = vi.spyOn(storage, "getObject").mockRejectedValue(new Error("Metadata must not fetch objects"));
expect(await f.store.versionInventory(saved!)).toEqual(expect.arrayContaining(files.map(({ path, kind }) => ({ path, kind }))));
expect(read).not.toHaveBeenCalled();
expect((await skillPackageMaintenance(db, storage).migrateVersions({ id: version!.id, apply: true })).inspected).toBe(0);
});
it.each([false, true])("restores across legacy payload clearing with a cached manifest: %s", async cachedManifest => {
const companyId = await company();
const [snapshot] = await db.insert(snapshots).values({ companyId, contentHash: skillSnapshotHash(files), fileInventory: files }).returning();
const store = skillPackageStore(db, storage);
await withSkillPackageReadScope(db, async () => {
expect((await store.descriptor(companyId, snapshot!.id)).storage).toBeNull();
if (cachedManifest) await store.manifest(companyId, snapshot!.id);
await store.prepare(companyId, files, true);
await db.update(snapshots).set({ fileInventory: [] }).where(eq(snapshots.id, snapshot!.id));
expect(skillSnapshotHash(await store.files(companyId, snapshot!.id))).toBe(skillSnapshotHash(files));
expect(await store.verifyDurable(companyId, snapshot!.id)).toBe(true);
});
});
it("bounds and validates archives, binaries, paths, executable modes, and corruption", async () => {
const root = await fs.mkdtemp(path.join(home, "codec-"));
const archive = path.join(root, "files.tar.gz");
const manifest = skillPackageManifest(files);
await writeSkillPackageArchive(archive, files);
const output = path.join(root, "out");
await fs.mkdir(output);
await extractSkillPackageArchive(archive, output, manifest);
expect(await verifySkillPackageDirectory(output, manifest.files)).toBe(true);
expect((await fs.stat(path.join(output, "shared/run.sh"))).mode & 0o111).toBe(0o111);
expect(() => validateSkillPackageManifest({ ...manifest, files: [{ ...manifest.files[0], path: "../escape" }] })).toThrow();
expect(() => validateSkillPackageManifest({ ...manifest, files: [manifest.files[0], manifest.files[0]] })).toThrow();
expect(() => validateSkillPackageManifest({ ...manifest, totalBytes: 1 })).toThrow();
const boundary = { ...manifest, totalBytes: 100 * 1024 * 1024,
files: [{ ...manifest.files[0]!, size: 100 * 1024 * 1024 }] };
expect(validateSkillPackageManifest(boundary).totalBytes).toBe(boundary.totalBytes);
expect(() => validateSkillPackageManifest({ ...boundary, totalBytes: boundary.totalBytes + 1,
files: [{ ...boundary.files[0]!, size: boundary.totalBytes + 1 }] })).toThrow("byte bound");
const bad = path.join(root, "bad");
await fs.mkdir(bad);
await fs.truncate(archive, 20);
await expect(extractSkillPackageArchive(archive, bad, manifest)).rejects.toThrow();
});
it("stores and converts a saved directory package above 64 MiB without losing its history", async () => {
const companyId = await company();
const content = "x".repeat(1024 * 1024);
const large = [{ path: "SKILL.md", kind: "skill" as const, content: "---\nname: large\n---\nlarge skill" },
...Array.from({ length: 65 }, (_, index) => ({ path: `asset-${index}`, kind: "asset" as const, content }))];
const store = skillPackageStore(db, storage);
const id = await store.prepare(companyId, large);
const [skill] = await db.insert(companySkills).values({ companyId, key: "large", slug: "large", name: "Large", markdown: large[0]!.content }).returning();
const [version] = await db.insert(companySkillVersions).values({ companyId, companySkillId: skill!.id,
revisionNumber: 1, fileInventory: large }).returning();
await skillPackageMaintenance(db, storage).migrateVersions({ id: version!.id, apply: true, clearLegacy: true });
const [converted] = await db.select().from(companySkillVersions).where(eq(companySkillVersions.id, version!.id));
expect(converted!.fileInventory).toEqual([]);
expect(converted!.migrationAt).toBeNull();
expect(converted!.packageSnapshotId).toBe(id);
expect(skillSnapshotHash(await store.versionFiles(converted!))).toBe(skillSnapshotHash(large));
}, 90_000);
});