Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.
JavaScript 3d3d-assets3d-modelingagent-skillsagent-toolsai-agentsasset-pipelinecligame-assetsglbgltfmcpmcp-servermodel-context-protocolprocedural-generationprocedural-modelingtext-to-3dthreejstypescript
feat: publish the skills at a well-known URI (7.13) (#75)
Matthew Kissinger994fb3284bc6
diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.ymlindex f8387050..c67b0e9d 100644--- a/.github/workflows/pages.yml+++ b/.github/workflows/pages.yml@@ -73,9 +73,11 @@ jobs:run: bunx tsc --noEmitworking-directory: site- # `site/scripts` has had tests since posters were attested and no workflow- # ran them, so a change to the provenance verification could ship green.- # They are the only automated check on what a poster receipt asserts.+ # Not closing a gap: `bun run test` is `bun test src scripts`, and bun treats+ # those as SUBSTRING filters on paths, so `site/scripts` already matched and+ # CI already ran these. Kept because that coverage is incidental -- spelling+ # the script `bun test ./src ./scripts` would silently drop it -- and because+ # these are the only automated check on what a poster receipt asserts.- name: Test the site scriptsrun: bun test scriptsworking-directory: site@@ -86,6 +88,12 @@ jobs:run: bun scripts/build-assets.mjsworking-directory: site+ # Derived from `skills/`, and published with a sha256 per artifact, so it has+ # to be generated in the same run that serves it rather than committed.+ - name: Build the well-known skills index+ run: bun scripts/build-skills-discovery.mjs+ working-directory: site+- name: Build the siterun: bunx vite buildworking-directory: sitediff --git a/.gitignore b/.gitignoreindex a2aa2265..959f2c68 100644--- a/.gitignore+++ b/.gitignore@@ -38,6 +38,11 @@ site/public/assets/site/public/thumbs/site/dist/+# Same reason, for the well-known skills index: `site/scripts/build-skills-discovery.mjs`+# derives it from `skills/`, and its published sha256 digests would go stale the+# moment a skill changed if a copy were committed here instead.+site/public/.well-known/+# Local agent config (launch profiles, per-machine settings). The shipped# plugin manifest lives in .claude-plugin/, which is tracked.# .claude/ is local state. The exception is .claude/skills/, which is committed sodiff --git a/CHANGELOG.md b/CHANGELOG.mdindex cd7629b6..0ae6b9a6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,28 @@Changes to `@kiln/engine`. Source and installable packages are distributed throughGitHub. The package is not published on the npm registry.+## Skills are fetchable by URL — 2026-09-11++- The six skills are published at+ `https://kilnstudio.tools/.well-known/agent-skills/index.json`, per+ [Cloudflare's Agent Skills Discovery RFC](https://github.com/cloudflare/agent-skills-discovery-rfc)+ v0.2.0 — which is what OpenCode's `skills.urls` consumes. One `skill-md` entry+ and five archives for the skills carrying `references/`, each with a sha256 of+ the artifact's raw bytes so a client can verify what it fetched.+- The archives are built by hand as POSIX ustar with every non-content field+ pinned — mode 0644, uid/gid 0, mtime 0, sorted entries — because the digest is+ *published*. Neither the system `tar` nor a convenience library gives that by+ default, and an archive whose bytes move on every build publishes a digest that+ is wrong the moment it is written. The test asserts those header fields+ directly rather than only comparing two builds, since two builds agreeing is+ also what a tar with a coarse clock does inside one second.+- Verified end to end: real `tar` extracts the archives with `SKILL.md` at the+ root and contents byte-identical to `skills/`, and Vite copies the+ dot-directory into the published output.+- **This path carries skills and no MCP server**, so a client that loads them has+ the workflows and none of the tools they describe. `docs/install.md` says so+ where it offers the URL.+## Bun-only APIs cannot reach a Node bundle unnoticed — 2026-09-11- Audited the shipped bundles for the defect class behind the MCP server's@@ -70,8 +92,13 @@ GitHub. The package is not published on the npm registry.`site/scripts/verify-assets.mjs` completes — 80 source/GLB pairs, posters, bothedit-demo revisions and the geometry example. Before this it failed on thefirst example.-- `site/scripts` has had tests since posters were attested and no workflow ran- them. `pages.yml` now does.+- `pages.yml` now runs `site/scripts`'s tests explicitly. **Correction:** this+ entry first said those tests had never run in any workflow. They had. `bun run+ test` is `bun test src scripts`, bun treats those as substring filters on+ paths, and `site/scripts` matches `scripts` — so both files were already in the+ suite CI runs. The step stays for a smaller reason: that coverage is+ incidental, and spelling the script `bun test ./src ./scripts` would drop it+ silently.- **The gallery no longer builds on Windows.** `pages.yml` is `ubuntu-latest`,which closes Phase 6.- New `scripts/glb-chunk-hashes.mjs` splits a GLB by chunk, and it answered thediff --git a/docs/install.md b/docs/install.mdindex dbc3cace..53f2a865 100644--- a/docs/install.md+++ b/docs/install.md@@ -174,6 +174,27 @@ OpenCode workspaces register their local `skills/` directory using the supportedinspect native discovery without a model request. Author, refine and QA entriesshould point into that workspace. See the [OpenCode configuration schema](https://opencode.ai/config.json).+### Fetching the skills by URL instead++The same skills are published at a well-known URI, so a client that reads+[Cloudflare's Agent Skills Discovery RFC](https://github.com/cloudflare/agent-skills-discovery-rfc)+can load them with no clone and no workspace. OpenCode's `skills.urls` consumes it:++```+https://kilnstudio.tools/.well-known/agent-skills/index.json+```++Each entry names an artifact and the sha256 of its raw bytes, so a client can+verify what it fetched. The index is generated from `skills/` in the same run that+serves it -- a committed copy would publish digests that go stale the moment a+skill changes.++This path carries the skills and nothing else. It does not configure an MCP server,+so `kiln_workspace` is still absent and no tool call will resolve; the skills will+describe a tool surface that is not there. Use it to read the workflows, or+alongside a server you configured yourself, not as a substitute for+`kiln-setup-workspace`.+Ask the agent to read `AGENTS.md`, discover geometry helpers, render a small draft,read its source, edit it by `programRef`, and export the accepted revision. Check theactual tools and files, not only the agent's final message. CPU rendering needs nodiff --git a/docs/plans/repo-size-and-r2-migration-2026-09-10.md b/docs/plans/repo-size-and-r2-migration-2026-09-10.mdindex 250e94c8..2900cbb9 100644--- a/docs/plans/repo-size-and-r2-migration-2026-09-10.md+++ b/docs/plans/repo-size-and-r2-migration-2026-09-10.md@@ -539,9 +539,18 @@ the index against the files built beside it, the build receipt against the indexand both demo receipts against their own run's GLBs. Those compare artifacts tothemselves within one build and cannot diverge by platform.-`site/scripts` has had tests since posters were attested and **no workflow ran-them**, so a change to this verification could have shipped green. `pages.yml`-now runs them.+`pages.yml` now runs `site/scripts`'s tests explicitly.++**Correction, 2026-09-11.** The commit that added that step said those tests had+never run in any workflow. That is wrong, and measured rather than argued: `bun+run test` is `bun test src scripts`, bun treats positional arguments as substring+filters on paths, and `site/scripts` matches `scripts`. Both files were already in+the 210-file suite -- `bun test provenance.test` from the repository root finds+and runs all four of its tests. CI was covering them.++The step stays for a different and smaller reason than the one first given: that+coverage is incidental, and spelling the script `bun test ./src ./scripts` would+drop it without a word.### Phase 3 rehearsal@@ -990,7 +999,7 @@ clone and no install. It does not depend on SEP-2640.| ID | Task | State || --- | --- | --- || 7.12 | Watch SEP-2640 to ratification, then expose the skills as `skill://` resources and retire the hand-built per-harness registration where clients support the extension | Deferred by decision; not this pass |-| 7.13 | Publish the skills at `/.well-known/agent-skills/index.json` on the existing site per the Cloudflare discovery RFC, giving opencode `skills.urls` users a zero-install path | Pending, and the path above is a correction: the RFC moved to `/.well-known/agent-skills/index.json` at v0.2.0, not the `/.well-known/skills/` this row recorded. Each entry needs `name`, `type`, `description`, `url` and a `sha256:` digest of the artifact's raw bytes. Five of six skills carry `references/`, so they need `type: archive` rather than `skill-md` -- and the archives must be built deterministically (fixed mtime, sorted entries) or the published digest changes on every build |+| 7.13 | Publish the skills at `/.well-known/agent-skills/index.json` on the existing site per the Cloudflare discovery RFC, giving opencode `skills.urls` users a zero-install path | **Done 2026-09-11.** The path is a correction to what this row recorded: the RFC is at `/.well-known/agent-skills/index.json` as of v0.2.0, not `/.well-known/skills/`. `site/scripts/build-skills-discovery.mjs` derives the index from `skills/` -- one `skill-md` entry, five `archive` entries for the skills carrying `references/`, each with a sha256 of the artifact's raw bytes. Verified: the apex is this repo's Pages deployment at an origin root, which a well-known URI requires; Vite copies the dot-directory into `dist/`; real `tar` extracts the archives with `SKILL.md` at the root and the contents byte-identical to `skills/`; and two builds publish identical digests. Gitignored and built in CI, because a committed copy would publish digests that go stale |### 7.1 execution record@@ -1252,7 +1261,7 @@ independently verified; 9.2 is the one that looks like the same bug class as 9.1| 9.5 | `arrayRadial` count semantics are not inferable from the signature plus the example: whether the source mesh survives as the copy at index 0 had to be deduced from a mesh count. **Done 2026-09-11.** Both array helpers now say it outright: `count` is the TOTAL including the source, which survives as copy 0, so the call returns count-1 new instances || 9.6 | CLI `--out` does not create parent directories, failing with a bare `ENOENT` *after* the build succeeded and printed a `programRef`. Invisible from the README, whose example writes into the cwd | Done 2026-09-11 -- `prepareDestination` in `src/cli-output.ts`, applied at every CLI destination: `render --out`, `render --views`, `generate`, `source <ref> --out` and `export --out`. Guarded by `src/__tests__/cli-out-directories.test.ts` || 9.7 | The MCP server resolves the render service once before its first connection, so a service started afterwards is invisible until the session restarts, while the CLI picks it up on the next call. **Done 2026-09-11, and by a wider route than a lazy re-probe: see Phase 11.** Re-probing would have cured the symptom while leaving the user two processes to sequence. The server now starts the service itself, so there is nothing to have started first and nothing to restart |-| 9.8 | Narrow the generated per-harness configuration to suppress user-level skills and MCP servers where each harness supports it. The blind run inherited roughly twenty unrelated skills and four unrelated servers. This is the only option that reduces inherited context rather than reporting it, and it needs vendor documentation per harness first: configuration that validates and silently does nothing is the `${PLUGIN_ROOT}` failure class. Pending |+| 9.8 | Narrow the generated per-harness configuration to suppress user-level skills and MCP servers where each harness supports it | **ANSWERED 2026-09-11: not implementable as written, and the reason is structural rather than effort.** Every documented suppression mechanism across all five harnesses is name-based, and the generator runs before it can know which unrelated skills and servers a given user has installed -- it has no names to write. The two name-agnostic candidates each fail the row's own test. See the section below; the vendor evidence is recorded there so this does not have to be researched again |## Phase 11 -- The renderer moves to where the users are@@ -1374,3 +1383,75 @@ asserts, which is 6.2. The maintainer's call on 6.1/6.3 -- that the gallery imagare display assets -- points at narrowing the receipt to `sourceHash` and`imageHash`, the two claims that are platform-stable and that the galleryactually makes. That remains a decision, not a task.++### 7.13, and why the archive is hand-rolled++The digest is published, so determinism is not a nicety here: an archive whose+bytes move on every build publishes a digest that is wrong the moment it is+written, and a client that verifies would reject every skill. Neither the system+`tar` nor a convenience library gives that by default -- both record real mtimes,+uids and gids. So `build-skills-discovery.mjs` writes POSIX ustar headers itself+with every non-content field pinned: mode 0644, uid and gid 0, mtime 0, empty+uname and gname, entries in sorted order. `node:zlib`'s gzip was measured+deterministic already, writing a zero MTIME and a fixed OS byte.++`skills-discovery.test.ts` asserts the pinned header fields directly rather than+only comparing two builds, and was verified to fail on an injected mtime. Two+builds agreeing proves nothing on its own: it is exactly what a tar with a+coarse-grained clock does when both builds land in the same second.++One limitation worth stating rather than discovering. This path carries skills and+no MCP server, so a client that loads them has the workflows and none of the tools+they describe -- `kiln_workspace` is absent and no call resolves. `docs/install.md`+says so where it offers the URL. SEP-2640 (7.12) is the mechanism that would carry+both, and it is still unratified.++### 9.8, and why a generator cannot narrow a loadout++Researched against vendor documentation on 2026-09-11, which is what the row said+it needed. The answer is that the task is not doable as specified, and the reason+is worth recording precisely so it is not attempted again on a hunch.++| Harness | Suppress user MCP servers from project config | Suppress or bound user skills from project config |+| --- | --- | --- |+| claude | `deniedMcpServers` (by name, URL or command), `disabledMcpjsonServers`, both settable in any settings file | `skillOverrides`, keys are skill NAMES, values `on` / `name-only` / `user-invocable-only` / `off`; any settings file. Plugin skills are explicitly exempt. Name-agnostic: `disableBundledSkills`, `skillListingMaxDescChars`, `skillListingBudgetFraction` |+| codex | project `.codex/config.toml` (trusted projects only), and `codex mcp disable <server> --scope project` | Nothing documented |+| opencode | project config MERGES with global rather than replacing it; nothing documented to suppress | **Nothing.** Global skills load from `~/.config/opencode/skills`, `~/.claude/skills` and `~/.agents/skills` unconditionally. `permission.skill.*` and `tools.skill` exist but govern invocation |+| hermes | `mcp_servers:` in `config.yaml`; skills in `~/.hermes/skills/` plus `external_dirs` | Nothing documented |+| agy | workspace `.agents/mcp_config.json` exists | Nothing documented |++**The structural blocker.** Every mechanism above that actually suppresses is+keyed by NAME. `deniedMcpServers` takes names, `skillOverrides` takes skill names,+`codex mcp disable` takes a server name. `scripts/create-workspace.mjs` runs+before any of that is knowable: it cannot enumerate what a stranger has in+`~/.claude/skills` on a machine it has not seen. There is no documented+"project skills only" or "ignore user scope" flag in any of the five.++**Both name-agnostic candidates fail their own test.** `skillListingMaxDescChars`+and `skillListingBudgetFraction` are real, are settable in a project file, and+would bound the cost of whatever is inherited without naming anyone -- but their+defaults and units are **not documented**. The skills page states only that the+combined description text is truncated at 1,536 characters. Writing a key whose+semantics cannot be verified is exactly the `${PLUGIN_ROOT}` failure class this+row was written to avoid. And OpenCode's `permission.skill.*` deny glob is fully+documented, but it blocks INVOCATION rather than loading, so it does not reduce+inherited context -- which is the entire point of 9.8 -- while it would stop a+user invoking their own skills inside their own workspace.++**One confirmation that the feared class is real, not hypothetical.**+`google-antigravity/antigravity-cli` issue 60: project-local+`.antigravitycli/mcp_config.json` is discovered at startup and its `mcpServers`+field is **silently ignored**, with only the HOME-level config loading servers.+Configuration that validates and does nothing, in the exact shape this row+predicted. CLI toggles landed in v1.1.16, which are again name-based.++**What would unblock it**, in order of how much it would buy: documented defaults+and units for the two Claude listing-budget keys, which would let a generated+workspace bound inherited context without naming anything; or a name-agnostic+project-scope switch in any harness; or SEP-2640 (7.12), under which a host+advertises its own skills as resources and the question of what else is registered+stops mattering as much.++Until one of those exists, reporting the inherited loadout -- which the setup skill+already does, and which the blind run did unprompted -- is the whole of what can+be done. That is a weaker outcome than the row wanted and it is the honest one.diff --git a/package.json b/package.jsonindex 8e81e8f1..c58a6c02 100644--- a/package.json+++ b/package.json@@ -103,6 +103,7 @@"lint": "biome check .","verify:posters": "bun scripts/verify-posters.mjs","site:assets": "cd site && bun scripts/build-assets.mjs",+ "site:skills": "cd site && bun scripts/build-skills-discovery.mjs","site:dev": "bun run --cwd site dev","site:build": "bun run --cwd site build","smoke:harness": "node scripts/harness-smoke.mjs"diff --git a/site/scripts/build-skills-discovery.mjs b/site/scripts/build-skills-discovery.mjsnew file mode 100644index 00000000..81f75a94--- /dev/null+++ b/site/scripts/build-skills-discovery.mjs@@ -0,0 +1,164 @@+/**+ * Publish the engine's skills at the RFC 8615 well-known URI, so a harness can+ * fetch them by URL with no clone and no install.+ *+ * Ledger 7.13. The format is Cloudflare's Agent Skills Discovery RFC, v0.2.0,+ * which is what opencode's `skills.urls` key consumes. It is an index at+ * `/.well-known/agent-skills/index.json` naming each skill's artifact and a+ * sha256 of that artifact's raw bytes.+ *+ * URLs are path-absolute, matching the RFC's own example. That is only correct+ * because this site is served at an origin root: `kilnstudio.tools` is the+ * gallery's Pages domain, verified serving `assets/index.json`. A well-known URI+ * has to sit at an origin root to be one at all, so a subpath deployment would+ * need relative URLs here and would not satisfy RFC 8615 anyway.+ *+ * Five of the six skills carry `references/`, so they ship as archives rather+ * than as a bare `SKILL.md`. That makes determinism load-bearing: the digest is+ * published, so an archive whose bytes move on every build publishes a digest+ * that is wrong the moment it is written. Hence a tar built by hand below with+ * every non-content field fixed, rather than a library's or the system tar's+ * defaults, which carry mtimes and uids.+ */+import { createHash } from 'node:crypto';+import { mkdir, readdir, readFile, rm, writeFile } from 'node:fs/promises';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { gzipSync } from 'node:zlib';++const SITE = resolve(dirname(fileURLToPath(import.meta.url)), '..');+const REPO = resolve(SITE, '..');+const SKILLS = join(REPO, 'skills');+const WELL_KNOWN = join(SITE, 'public', '.well-known', 'agent-skills');+const SCHEMA = 'https://schemas.agentskills.io/discovery/0.2.0/schema.json';+const URL_PREFIX = '/.well-known/agent-skills';++const sha256 = (bytes) => `sha256:${createHash('sha256').update(bytes).digest('hex')}`;++/** Every file under a skill, as sorted paths relative to the skill directory. */+async function tree(directory, prefix = '') {+ const out = [];+ for (const entry of await readdir(directory, { withFileTypes: true })) {+ const relative = prefix ? `${prefix}/${entry.name}` : entry.name;+ if (entry.isDirectory()) out.push(...(await tree(join(directory, entry.name), relative)));+ else out.push(relative);+ }+ return out.sort();+}++/** `name` and `description` from the SKILL.md frontmatter the spec requires. */+function frontmatter(text) {+ const match = /^---\r?\n([\s\S]*?)\r?\n---/u.exec(text);+ if (!match) throw new Error('SKILL.md has no YAML frontmatter');+ const fields = new Map();+ for (const line of match[1].split(/\r?\n/u)) {+ const pair = /^([A-Za-z-]+):\s*(.*)$/u.exec(line);+ if (pair) fields.set(pair[1], pair[2]);+ }+ return fields;+}++const BLOCK = 512;++/**+ * One POSIX ustar header. Every field that is not content is pinned: mode 0644,+ * uid and gid 0, mtime 0, empty uname and gname. A tar that embedded a real+ * mtime would change the published digest on every build without any skill+ * having changed.+ */+function ustarHeader(path, size) {+ const header = Buffer.alloc(BLOCK);+ const octal = (value, width) => value.toString(8).padStart(width - 1, '0') + '\0';+ if (Buffer.byteLength(path) > 100) throw new Error(`path too long for ustar: ${path}`);+ header.write(path, 0, 100, 'utf8');+ header.write(octal(0o644, 8), 100, 8, 'ascii');+ header.write(octal(0, 8), 108, 8, 'ascii');+ header.write(octal(0, 8), 116, 8, 'ascii');+ header.write(octal(size, 12), 124, 12, 'ascii');+ header.write(octal(0, 12), 136, 12, 'ascii');+ // The checksum is defined over the header with its own eight bytes read as+ // spaces, so they are filled before summing and overwritten after.+ header.fill(0x20, 148, 156);+ header.write('0', 156, 1, 'ascii');+ header.write('ustar\0', 257, 6, 'ascii');+ header.write('00', 263, 2, 'ascii');+ let sum = 0;+ for (const byte of header) sum += byte;+ header.write(`${sum.toString(8).padStart(6, '0')}\0 `, 148, 8, 'ascii');+ return header;+}++/** A deterministic tar of `[path, bytes]` entries, in the order given. */+function tar(entries) {+ const parts = [];+ for (const [path, bytes] of entries) {+ parts.push(ustarHeader(path, bytes.byteLength), bytes);+ const remainder = bytes.byteLength % BLOCK;+ if (remainder) parts.push(Buffer.alloc(BLOCK - remainder));+ }+ // Two zero blocks terminate the archive.+ parts.push(Buffer.alloc(BLOCK * 2));+ return Buffer.concat(parts);+}++export async function buildSkillsDiscovery({ out = WELL_KNOWN, skills = SKILLS } = {}) {+ await rm(out, { recursive: true, force: true });+ await mkdir(out, { recursive: true });++ const names = (await readdir(skills, { withFileTypes: true }))+ .filter((entry) => entry.isDirectory())+ .map((entry) => entry.name)+ .sort();++ const published = [];+ for (const name of names) {+ const directory = join(skills, name);+ const files = await tree(directory);+ if (!files.includes('SKILL.md')) throw new Error(`${name}: no SKILL.md`);+ const fields = frontmatter(await readFile(join(directory, 'SKILL.md'), 'utf8'));+ const description = fields.get('description');+ if (fields.get('name') !== name) throw new Error(`${name}: frontmatter name disagrees`);+ if (!description) throw new Error(`${name}: no description`);++ if (files.length === 1) {+ // A lone SKILL.md needs no container, and `skill-md` is one fetch instead+ // of a fetch plus a decompress.+ const bytes = await readFile(join(directory, 'SKILL.md'));+ await mkdir(join(out, name), { recursive: true });+ await writeFile(join(out, name, 'SKILL.md'), bytes);+ published.push({+ name,+ type: 'skill-md',+ description,+ url: `${URL_PREFIX}/${name}/SKILL.md`,+ digest: sha256(bytes),+ });+ continue;+ }++ // "The archive contents represent the skill directory -- files are placed at+ // the archive root, not nested in a wrapper directory."+ const entries = [];+ for (const file of files) entries.push([file, await readFile(join(directory, file))]);+ const archive = gzipSync(tar(entries), { level: 9 });+ await writeFile(join(out, `${name}.tar.gz`), archive);+ published.push({+ name,+ type: 'archive',+ description,+ url: `${URL_PREFIX}/${name}.tar.gz`,+ digest: sha256(archive),+ });+ }++ const index = { $schema: SCHEMA, skills: published };+ await writeFile(join(out, 'index.json'), `${JSON.stringify(index, null, 2)}\n`);+ return index;+}++if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {+ const index = await buildSkillsDiscovery();+ for (const skill of index.skills)+ console.log(` ${skill.name.padEnd(22)} ${skill.type.padEnd(9)} ${skill.digest.slice(0, 23)}`);+ console.log(`${index.skills.length} skills published at ${URL_PREFIX}/index.json`);+}diff --git a/site/scripts/skills-discovery.test.ts b/site/scripts/skills-discovery.test.tsnew file mode 100644index 00000000..aa635740--- /dev/null+++ b/site/scripts/skills-discovery.test.ts@@ -0,0 +1,112 @@+/**+ * The well-known skills index is published with a sha256 per artifact, so the+ * two properties that matter are that the digests describe the bytes actually+ * served, and that they do not move unless a skill does. A tar carrying real+ * mtimes would satisfy the first and quietly break the second on every build.+ */+import { createHash } from 'node:crypto';+import { mkdtemp, readFile, readdir, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { gunzipSync } from 'node:zlib';++import { expect, test } from 'bun:test';++import { buildSkillsDiscovery } from './build-skills-discovery.mjs';++const REPO = resolve(import.meta.dir, '../..');+const SKILLS = join(REPO, 'skills');+const sha256 = (bytes: Uint8Array) =>+ `sha256:${createHash('sha256').update(bytes).digest('hex')}`;++/** Read a ustar archive back as a path -> bytes map, and its pinned header fields. */+function untar(bytes: Buffer) {+ const files = new Map<string, Buffer>();+ const stamps: { mode: string; uid: string; gid: string; mtime: string }[] = [];+ const field = (block: Buffer, start: number, length: number) =>+ block.subarray(start, start + length).toString('ascii').replace(/\0.*$/, '').trim();+ for (let offset = 0; offset + 512 <= bytes.byteLength; ) {+ const header = bytes.subarray(offset, offset + 512);+ const name = field(header, 0, 100);+ if (!name) break;+ expect(field(header, 257, 6)).toBe('ustar');+ const size = Number.parseInt(field(header, 124, 12), 8);+ stamps.push({+ mode: field(header, 100, 8),+ uid: field(header, 108, 8),+ gid: field(header, 116, 8),+ mtime: field(header, 136, 12),+ });+ files.set(name, Buffer.from(bytes.subarray(offset + 512, offset + 512 + size)));+ offset += 512 + Math.ceil(size / 512) * 512;+ }+ return { files, stamps };+}++async function build() {+ const out = await mkdtemp(join(tmpdir(), 'kiln-skills-discovery-'));+ const index = await buildSkillsDiscovery({ out });+ return { out, index };+}++test('every published digest is the sha256 of the bytes actually served', async () => {+ const { out, index } = await build();+ try {+ expect(index.$schema).toBe('https://schemas.agentskills.io/discovery/0.2.0/schema.json');+ // Every skill directory has to appear, or a skill is silently unpublished.+ const directories = (await readdir(SKILLS, { withFileTypes: true }))+ .filter((entry) => entry.isDirectory())+ .map((entry) => entry.name)+ .sort();+ expect(index.skills.map((skill) => skill.name)).toEqual(directories);++ for (const skill of index.skills) {+ expect(['skill-md', 'archive']).toContain(skill.type);+ expect(skill.description.length).toBeGreaterThan(0);+ expect(skill.description.length).toBeLessThanOrEqual(1024);+ expect(skill.url.startsWith('/.well-known/agent-skills/')).toBe(true);+ expect(skill.digest).toMatch(/^sha256:[a-f0-9]{64}$/);+ const served = await readFile(+ join(out, skill.url.replace('/.well-known/agent-skills/', '')),+ );+ expect(skill.digest).toBe(sha256(served));+ }+ } finally {+ await rm(out, { recursive: true, force: true });+ }+});++test('an archive carries SKILL.md at its root and reproduces the skill exactly', async () => {+ const { out, index } = await build();+ try {+ const archives = index.skills.filter((skill) => skill.type === 'archive');+ // A passing loop over an empty list would assert nothing.+ expect(archives.length).toBeGreaterThan(0);+ for (const skill of archives) {+ const { files, stamps } = untar(+ Buffer.from(gunzipSync(await readFile(join(out, `${skill.name}.tar.gz`)))),+ );+ // "files are placed at the archive root, not nested in a wrapper directory"+ expect(files.has('SKILL.md')).toBe(true);+ expect([...files.keys()].some((path) => path.startsWith(`${skill.name}/`))).toBe(false);+ for (const [path, bytes] of files)+ expect(sha256(bytes)).toBe(sha256(await readFile(join(SKILLS, skill.name, path))));+ // The determinism the published digest depends on, asserted at the source+ // rather than only through a repeat build.+ for (const stamp of stamps) expect(stamp).toEqual({ mode: '0000644', uid: '0000000', gid: '0000000', mtime: '00000000000' });+ }+ } finally {+ await rm(out, { recursive: true, force: true });+ }+});++test('two builds of an unchanged tree publish identical digests', async () => {+ const first = await build();+ const second = await build();+ try {+ expect(second.index).toEqual(first.index);+ } finally {+ await rm(first.out, { recursive: true, force: true });+ await rm(second.out, { recursive: true, force: true });+ }+});