librebot-tools 0.0.0-stage → 0.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,82 @@
1
+ // Binary knowledge assets and skill supporting files: bytes travel beside
2
+ // the draft with hashes, never silently dropped or double-prefixed.
3
+
4
+ import { describe, it } from "node:test";
5
+ import assert from "node:assert/strict";
6
+ import {
7
+ exportBotFiles,
8
+ parseBotFiles,
9
+ sanitizeAssetRel,
10
+ sha256Hex,
11
+ validateFiles,
12
+ } from "../src/index.js";
13
+
14
+ const base = (extra = {}) => ({
15
+ "bot.yaml":
16
+ "formatVersion: 1\nname: T\ndescription: D\nmodelRoles:\n - role: default\n label: Main\n",
17
+ "instructions.md": "Be helpful.",
18
+ "README.md": "# T",
19
+ ...extra,
20
+ });
21
+
22
+ describe("binary assets", () => {
23
+ it("emits binary knowledge as hashed assets without inline content", async () => {
24
+ const bytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x00, 0xff]);
25
+ const result = await validateFiles(base({ "knowledge/image.png": bytes }));
26
+ assert.equal(result.ok, true);
27
+ assert.equal(result.draft.knowledge.length, 1);
28
+ assert.equal(result.draft.knowledge[0].content, undefined);
29
+ assert.equal(result.assets.length, 1);
30
+ const [asset] = result.assets;
31
+ assert.equal(asset.path, "image.png");
32
+ assert.equal(asset.mime, "image/png");
33
+ assert.equal(asset.sha256, sha256Hex(bytes));
34
+ assert.deepEqual(asset.bytes, bytes);
35
+ });
36
+
37
+ it("inlines UTF-8 knowledge and preserves skill supporting files", async () => {
38
+ const result = await validateFiles(
39
+ base({
40
+ "knowledge/guide.md": "# Guide\n",
41
+ "skills/review/SKILL.md": "---\nname: Review\ndescription: Reviews code.\n---\n\nDo reviews.\n",
42
+ "skills/review/reference.md": "reference material",
43
+ }),
44
+ );
45
+ assert.equal(result.ok, true);
46
+ assert.equal(result.draft.knowledge[0].content, "# Guide\n");
47
+ assert.equal(result.draft.skills[0].name, "Review");
48
+ assert.equal(result.draft.skills[0].description, "Reviews code.");
49
+ assert.equal(result.skillFiles.length, 1);
50
+ assert.equal(result.skillFiles[0].path, "reference.md");
51
+ assert.equal(result.skillFiles[0].skillId, "review");
52
+ });
53
+
54
+ it("round-trips export back through the parser byte-identically", async () => {
55
+ const parsed = await parseBotFiles(
56
+ base({
57
+ "knowledge/guide.md": "# Guide\n",
58
+ "knowledge/image.png": new Uint8Array([0x89, 0x50, 0x00]),
59
+ "skills/review/SKILL.md": "# Review\n\nDo reviews.\n",
60
+ "skills/review/reference.md": "reference",
61
+ }),
62
+ );
63
+ const exported = exportBotFiles(parsed.draft, {
64
+ assets: parsed.assets,
65
+ skillFiles: parsed.skillFiles,
66
+ });
67
+ assert.ok(!Object.keys(exported).some((k) => k.includes("knowledge/knowledge/")));
68
+ const reparsed = await parseBotFiles(exported);
69
+ assert.equal(reparsed.draft.knowledge.length, 2);
70
+ assert.equal(reparsed.draft.skills.length, 1);
71
+ assert.equal(reparsed.draft.skills[0].name, "Review");
72
+ assert.equal(reparsed.skillFiles.length, 1);
73
+ assert.equal(reparsed.assets.length, 1);
74
+ assert.equal(reparsed.assets[0].sha256, parsed.assets[0].sha256);
75
+ });
76
+
77
+ it("strips a redundant knowledge/ asset prefix instead of doubling it", () => {
78
+ assert.equal(sanitizeAssetRel("knowledge/img/a.png"), "img/a.png");
79
+ assert.equal(sanitizeAssetRel("img/a.png"), "img/a.png");
80
+ assert.equal(sanitizeAssetRel("../../etc/passwd"), "file_../file_../etc/passwd");
81
+ });
82
+ });
@@ -0,0 +1,155 @@
1
+ // Export fidelity: external references, hostile legacy names, and
2
+ // frontmatter-less skill content all survive an export->parse round-trip.
3
+
4
+ import { describe, it } from "node:test";
5
+ import assert from "node:assert/strict";
6
+ import {
7
+ exportBotFiles,
8
+ parseBotFiles,
9
+ withSkillFrontmatter,
10
+ scaffoldBotFiles,
11
+ } from "../src/index.js";
12
+
13
+ describe("export fidelity", () => {
14
+ it("scaffolds a valid source that round-trips its draft", async () => {
15
+ const initial = await parseBotFiles(scaffoldBotFiles({ name: "Smoke" }));
16
+ const roundtrip = await parseBotFiles(exportBotFiles(initial.draft, { icon: initial.icon }));
17
+ assert.deepEqual(roundtrip.draft, initial.draft);
18
+ });
19
+
20
+ it("round-trips portable action groups independently of checkout declarations", async () => {
21
+ const initial = await parseBotFiles({
22
+ ...scaffoldBotFiles({ name: "GitLab" }),
23
+ "bot.yaml": "formatVersion: 1\nname: GitLab\ndescription: D\nmodelRoles:\n - {role: default, label: Main}\nworkspace:\n - {key: source, path: ./code}\nactions:\n - {key: repo, kind: gitrepo, capabilities: [propose_change, read_change_request, update_issue_title]}\n",
24
+ });
25
+ const exported = exportBotFiles(initial.draft);
26
+ const roundtrip = await parseBotFiles(exported);
27
+ assert.deepEqual(roundtrip.draft.actions, [{ key: "repo", kind: "gitrepo", capabilities: ["propose_change", "read_change_request", "update_issue_title"] }]);
28
+ assert.deepEqual(roundtrip.draft, initial.draft);
29
+ assert.deepEqual(roundtrip.draft.triggers, []);
30
+ });
31
+
32
+ it("omits platform metadata while retaining semantic identifiers", async () => {
33
+ const files = exportBotFiles({
34
+ name: "T",
35
+ description: "D",
36
+ visibility: "public",
37
+ botPrompt: "Hi.",
38
+ readme: "# T",
39
+ workspace: [{ key: "source", label: "Source", path: "./code" }],
40
+ triggers: [{ key: "issues", label: "Issues", kind: "gitrepo", eventTypes: ["issue.opened"], deciderInstructions: "Decide" }],
41
+ connectors: [{ id: "platform-connector", label: "Connector", tools: ["search"], resources: [{ key: "scope", label: "Scope", tools: ["search"] }] }],
42
+ knowledge: [{ id: "docs", name: "Docs", kind: "resource", url: "https://example.com/docs" }],
43
+ });
44
+ assert.doesNotMatch(files["bot.yaml"], /visibility|platform-connector/);
45
+ const parsed = await parseBotFiles(files);
46
+ assert.equal(parsed.draft.connectors[0].label, "Connector");
47
+ assert.equal(parsed.draft.connectors[0].resources[0].key, "scope");
48
+ assert.equal(parsed.draft.knowledge[0].id, "docs");
49
+ assert.equal(parsed.draft.workspace[0].path, "./code");
50
+ assert.equal(parsed.draft.workspace[0].key, "source");
51
+ assert.equal(parsed.draft.triggers[0].key, "issues");
52
+ assert.equal(parsed.draft.triggers[0].label, "Issues");
53
+ assert.equal("visibility" in parsed.draft, false);
54
+ const again = await parseBotFiles(exportBotFiles(parsed.draft));
55
+ assert.deepEqual(again.draft, parsed.draft);
56
+ const edited = structuredClone(parsed.draft);
57
+ edited.workspace[0].label = "Renamed source";
58
+ edited.workspace[0].path = "./renamed";
59
+ edited.triggers[0].label = "Renamed trigger";
60
+ const renamed = await parseBotFiles(exportBotFiles(edited));
61
+ assert.equal(renamed.draft.workspace[0].key, "source");
62
+ assert.equal(renamed.draft.workspace[0].path, "./renamed");
63
+ assert.equal(renamed.draft.triggers[0].key, "issues");
64
+ assert.equal(renamed.draft.triggers[0].label, "Renamed trigger");
65
+ });
66
+
67
+ it("round-trips resource/repo knowledge through knowledgeSources", async () => {
68
+ const draft = {
69
+ name: "T",
70
+ description: "D",
71
+ visibility: "private",
72
+ botPrompt: "Hi.",
73
+ readme: "# T",
74
+ modelRoles: [{ role: "default", label: "Main", requirements: {} }],
75
+ knowledge: [
76
+ { id: "docs", name: "Docs", kind: "resource", url: "https://example.com/d" },
77
+ {
78
+ id: "code",
79
+ name: "Code",
80
+ kind: "repo",
81
+ url: "https://github.com/o/r",
82
+ ref: "main",
83
+ },
84
+ ],
85
+ skills: [],
86
+ connectors: [],
87
+ triggers: [],
88
+ workspace: [],
89
+ actions: [],
90
+ };
91
+ const exported = exportBotFiles(draft);
92
+ assert.ok(!Object.keys(exported).some((k) => k.startsWith("knowledge/") && k !== "knowledge/README.md"));
93
+ const reparsed = await parseBotFiles(exported);
94
+ assert.deepEqual(reparsed.draft.knowledge, draft.knowledge);
95
+ });
96
+
97
+ it("throws when file knowledge has neither content nor asset bytes", () => {
98
+ assert.throws(
99
+ () =>
100
+ exportBotFiles({
101
+ name: "T",
102
+ botPrompt: "Hi.",
103
+ readme: "# T",
104
+ knowledge: [{ id: "x", name: "X", kind: "file" }],
105
+ }),
106
+ /no content and no asset/,
107
+ );
108
+ });
109
+
110
+ it("sanitizes hostile legacy names into stable id-based filenames", async () => {
111
+ const exported = exportBotFiles({
112
+ name: "T",
113
+ description: "D",
114
+ botPrompt: "Hi.",
115
+ readme: "# T",
116
+ knowledge: [
117
+ { id: "evil", name: "../../etc/passwd", kind: "file", content: "x" },
118
+ { id: "evil2", name: "a/b", kind: "file", content: "y" },
119
+ ],
120
+ });
121
+ const paths = Object.keys(exported).filter((k) => k.startsWith("knowledge/"));
122
+ assert.ok(paths.every((p) => !p.includes("..") && p.split("/").length === 2));
123
+ assert.equal(new Set(paths).size, paths.length);
124
+ const reparsed = await parseBotFiles(exported);
125
+ assert.equal(reparsed.draft.knowledge.length, 2);
126
+ });
127
+
128
+ it("injects frontmatter for legacy skill content so names survive", async () => {
129
+ const injected = withSkillFrontmatter({
130
+ id: "legacy",
131
+ name: "Legacy",
132
+ description: "Old skill.",
133
+ content: "Just instructions.\n",
134
+ });
135
+ assert.match(injected, /^---\nname: "Legacy"\ndescription: "Old skill."\n---\n/);
136
+ const exported = exportBotFiles({
137
+ name: "T",
138
+ description: "D",
139
+ botPrompt: "Hi.",
140
+ readme: "# T",
141
+ skills: [{ id: "legacy", name: "Legacy", description: "Old skill.", content: "Just instructions.\n" }],
142
+ });
143
+ const reparsed = await parseBotFiles(exported);
144
+ assert.equal(reparsed.draft.skills[0].name, "Legacy");
145
+ assert.equal(reparsed.draft.skills[0].description, "Old skill.");
146
+ });
147
+
148
+ it("leaves existing frontmatter untouched", () => {
149
+ const content = '---\nname: Keep\ndescription: As-is.\n---\n\nBody.\n';
150
+ assert.equal(
151
+ withSkillFrontmatter({ id: "k", name: "Other", description: "X", content }),
152
+ content,
153
+ );
154
+ });
155
+ });
@@ -0,0 +1,23 @@
1
+ import { it } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { mkdtemp, writeFile, rm } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { execFileSync } from "node:child_process";
8
+
9
+ it("previews portable repository capabilities in human and JSON output", async () => {
10
+ const dir = await mkdtemp(join(tmpdir(), "librebot-gitlab-preview-"));
11
+ try {
12
+ await writeFile(join(dir, "bot.yaml"), "formatVersion: 1\nname: Repository\ndescription: D\nmodelRoles:\n - {role: default, label: Main}\nworkspace:\n - {key: source, path: ./code}\nactions:\n - {key: repo, kind: gitrepo, capabilities: [propose_change, read_change_request]}\n");
13
+ await writeFile(join(dir, "instructions.md"), "Be helpful.");
14
+ await writeFile(join(dir, "README.md"), "# Repository");
15
+ const cli = fileURLToPath(new URL("../bin/librebot.js", import.meta.url));
16
+ const text = execFileSync(process.execPath, [cli, "preview", dir], { encoding: "utf8" });
17
+ assert.ok(text.length > 0);
18
+ const json = JSON.parse(execFileSync(process.execPath, [cli, "preview", dir, "--json"], { encoding: "utf8" }));
19
+ assert.deepEqual(json.draft.actions, [{ key: "repo", kind: "gitrepo", capabilities: ["propose_change", "read_change_request"] }]);
20
+ } finally {
21
+ await rm(dir, { recursive: true, force: true });
22
+ }
23
+ });
@@ -0,0 +1,53 @@
1
+ import { describe, it } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { mkdtemp, writeFile, rm } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { promisify } from "node:util";
7
+ import { execFile } from "node:child_process";
8
+ import { parseBotFiles, scaffoldBotFiles, exportBotFiles } from "../src/index.js";
9
+ import { GITREPO_TRIGGER_EVENT_TYPES } from "../src/validate.js";
10
+
11
+ const trigger = (overrides = {}) => ({ key: "project-events", label: "Project events", kind: "gitrepo", eventTypes: ["change_request.opened"], deciderInstructions: "Decide whether to act", ...overrides });
12
+ const source = (triggers) => ({ ...scaffoldBotFiles({ name: "Triggers" }), "bot.yaml": `formatVersion: 1\nname: Triggers\ndescription: D\nmodelRoles: [{role: default, label: Main}]\ntriggers: ${JSON.stringify(triggers)}\n` });
13
+
14
+ describe("Portable repository trigger authoring", () => {
15
+ it("round-trips every semantic event and preserves explicit keys across label edits", async () => {
16
+ const initial = await parseBotFiles(source([trigger({ eventTypes: GITREPO_TRIGGER_EVENT_TYPES })]));
17
+ assert.equal(initial.draft.triggers[0].kind, "gitrepo");
18
+ const roundtrip = await parseBotFiles(exportBotFiles(initial.draft));
19
+ assert.deepEqual(roundtrip.draft.triggers, initial.draft.triggers);
20
+ const renamed = await parseBotFiles(source([trigger({ label: "Renamed events" })]));
21
+ assert.equal(renamed.draft.triggers[0].key, initial.draft.triggers[0].key);
22
+ });
23
+
24
+ it("rejects native kinds, native events, duplicate events and pinned targets", async () => {
25
+ const invalid = [
26
+ trigger({ kind: "gitlab" }), trigger({ kind: "github" }),
27
+ trigger({ eventTypes: ["issues.opened"] }),
28
+ trigger({ eventTypes: ["merge_request.open"] }), trigger({ eventTypes: ["unknown"] }),
29
+ trigger({ eventTypes: ["repository.pushed", "repository.pushed"] }),
30
+ trigger({ repository: { mode: "pinned", fullName: "group/subgroup/project" } }),
31
+ trigger({ key: "" }),
32
+ ];
33
+ for (const entry of invalid) {
34
+ await assert.rejects(parseBotFiles(source([entry])), undefined, JSON.stringify(entry));
35
+ }
36
+ });
37
+
38
+ it("previews the parsed semantic trigger and stable key", async () => {
39
+ const dir = await mkdtemp(join(tmpdir(), "librebot-gitlab-triggers-"));
40
+ try {
41
+ const files = source([trigger()]);
42
+ for (const [path, contents] of Object.entries(files)) {
43
+ if (!path.includes("/")) await writeFile(join(dir, path), contents);
44
+ }
45
+ const run = promisify(execFile);
46
+ const { stdout } = await run(process.execPath, [new URL("../bin/librebot.js", import.meta.url).pathname, "preview", dir, "--json"]);
47
+ const preview = JSON.parse(stdout);
48
+ assert.equal(preview.draft.triggers[0].kind, "gitrepo");
49
+ assert.deepEqual(preview.draft.triggers[0].eventTypes, ["change_request.opened"]);
50
+ assert.equal(preview.draft.triggers[0].key, "project-events");
51
+ } finally { await rm(dir, { recursive: true, force: true }); }
52
+ });
53
+ });
@@ -0,0 +1,137 @@
1
+ import { describe, it } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { mkdtemp, rm, symlink, mkdir } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { parseBotFiles, validateFiles, scaffoldBotFiles, scaffoldBot, validateSource, exportBotFiles } from "../src/index.js";
7
+ import { DEFAULT_ICON } from "../src/icon.js";
8
+
9
+ const svg = (body = '<rect width="24" height="24" fill="#e23"/>', viewBox = '0 0 24 24') => `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${viewBox}">${body}</svg>`;
10
+ function files(bytes = svg(), path = "assets/icon.svg") {
11
+ const source = scaffoldBotFiles({ name: "Icon" });
12
+ source["bot.yaml"] = source["bot.yaml"].replace("./assets/icon.svg", `./${path}`);
13
+ delete source["assets/icon.svg"];
14
+ if (bytes !== undefined) source[path] = bytes;
15
+ return source;
16
+ }
17
+ const png = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=", "base64");
18
+ const webp = Buffer.from("UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA", "base64");
19
+
20
+ describe("repository icons", () => {
21
+ it("provisions the exact default glyph and validates a new repository", async () => {
22
+ const source = scaffoldBotFiles({ name: "Provisioned" });
23
+ assert.equal(source["assets/icon.svg"], DEFAULT_ICON);
24
+ const dir = await mkdtemp(join(tmpdir(), "librebot-icon-"));
25
+ try {
26
+ await scaffoldBot(dir, { name: "Provisioned" });
27
+ const result = await validateSource(dir);
28
+ assert.equal(result.ok, true);
29
+ assert.equal(result.draft.icon, "./assets/icon.svg");
30
+ assert.equal(result.icon.width, 24);
31
+ assert.equal(result.icon.mime, "image/svg+xml");
32
+ } finally { await rm(dir, { recursive: true, force: true }); }
33
+ });
34
+ it("round-trips original asset bytes separately from knowledge", async () => {
35
+ const initial = await parseBotFiles(files(svg(), "knowledge/icon.svg"));
36
+ assert.equal(initial.assets.length, 0);
37
+ assert.equal(initial.draft.knowledge.some((entry) => entry.name === "icon.svg"), false);
38
+ assert.throws(() => exportBotFiles(initial.draft), /missing/);
39
+ const exported = exportBotFiles(initial.draft, { icon: initial.icon });
40
+ assert.deepEqual(exported["knowledge/icon.svg"], initial.icon.bytes);
41
+ const again = await parseBotFiles(exported);
42
+ assert.deepEqual(again.icon, initial.icon);
43
+ assert.equal(again.draft.icon, "./knowledge/icon.svg");
44
+ });
45
+ it("accepts ordinary colored gradients and local references", async () => {
46
+ const result = await validateFiles(files(svg('<defs><linearGradient id="paint"><stop offset="0" stop-color="#ff0000"/><stop offset="1" stop-color="#00ff00"/></linearGradient><path id="shape" d="M0 0h24v24z"/></defs><g transform="translate(1 1)" opacity=".8"><use href="#shape" fill="url(#paint)"/></g>')));
47
+ assert.equal(result.ok, true, JSON.stringify(result.errors));
48
+ });
49
+ for (const [extension, bytes] of [["png", png], ["webp", webp]]) {
50
+ it(`accepts actual square ${extension} bytes and preserves them`, async () => {
51
+ const parsed = await parseBotFiles(files(bytes, `assets/icon.${extension}`));
52
+ assert.equal(parsed.icon.width, 1);
53
+ assert.equal(parsed.icon.height, 1);
54
+ assert.equal(parsed.icon.mime, `image/${extension}`);
55
+ assert.deepEqual(exportBotFiles(parsed.draft, { icon: parsed.icon })[`assets/icon.${extension}`], bytes);
56
+ });
57
+ }
58
+ it("accepts safe inline presentation styles and square rendered viewport", async () => {
59
+ const source = svg('<path style="fill:#e23;stroke:rgb(0,0,0);opacity:.8" d="M0 0h24v24z"/>').replace('viewBox=', 'width="512px" height="512px" viewBox=');
60
+ assert.equal((await validateFiles(files(source))).ok, true);
61
+ assert.equal((await validateFiles(files(svg().replace('viewBox=', 'width="100%" height="100%" viewBox=')))).ok, true);
62
+ });
63
+ for (const edge of [1, 256, 512, 4096]) {
64
+ it(`accepts square viewBox edge ${edge}`, async () => {
65
+ assert.equal((await validateFiles(files(svg("", `0 0 ${edge} ${edge}`)))).ok, true);
66
+ });
67
+ }
68
+ it("rejects truncated raster containers despite valid dimensions", async () => {
69
+ assert.equal((await validateFiles(files(png.subarray(0, 24), "assets/icon.png"))).ok, false);
70
+ assert.equal((await validateFiles(files(webp.subarray(0, 30), "assets/icon.webp"))).ok, false);
71
+ });
72
+ it("accounts for the derived icon data URL in the total draft cap", async () => {
73
+ const source = files(svg(" ".repeat(200000)));
74
+ for (let i = 0; i < 6; i++) source[`knowledge/part${i}.txt`] = "x".repeat(90000);
75
+ assert.equal((await validateFiles(source)).ok, false);
76
+ });
77
+ it("rejects URL-like, whitespace, hidden, and overlong paths", async () => {
78
+ for (const path of ["assets/a:b.svg", "assets/a b.svg", ".hidden/icon.svg", `assets/${"a".repeat(510)}.svg`]) {
79
+ assert.equal((await validateFiles(files(svg(), path))).ok, false);
80
+ }
81
+ });
82
+ const invalid = [
83
+ ["non-square viewport", svg().replace('viewBox=', 'width="20" height="24" viewBox=')],
84
+ ["style external reference", svg('<path style="fill:url(&#104;ttps://example.org/a)"/>')],
85
+ ["style custom property", svg('<path style="--fill:red;fill:var(--fill)"/>')],
86
+ ["style escaped property", svg('<path style="f\\\\69ll:red"/>')],
87
+ ["style import", svg('<path style="@import:https://example.org/a"/>')],
88
+ ["non-square", svg("", "0 0 24 23")],
89
+ ["zero", svg("", "0 0 0 0")],
90
+ ["oversize dimensions", svg("", "0 0 4097 4097")],
91
+ ["missing viewBox", '<svg xmlns="http://www.w3.org/2000/svg"/>'],
92
+ ["malformed XML", svg("<g>")],
93
+ ["script", svg("<script>alert(1)</script>")],
94
+ ["foreignObject", svg("<foreignObject/>")],
95
+ ["animation", svg('<animate attributeName="fill"/>')],
96
+ ["event", svg('<path onload="alert(1)"/>')],
97
+ ["encoded external href", svg('<use href="&#104;ttps://example.org/a.svg#x"/>')],
98
+ ["encoded external paint", svg('<path fill="url(&#104;ttps://example.org/a)"/>')],
99
+ ["external image", svg('<image href="https://example.org/a.png"/>')],
100
+ ["CSS font", svg('<style>@font-face {src:url(https://example.org/a)}</style>')],
101
+ ["escaped CSS", svg('<path fill="u\\72l(https://example.org/a)"/>')],
102
+ ["DOCTYPE", '<!DOCTYPE svg [<!ENTITY x "test">]>' + svg("&x;")],
103
+ ["oversize bytes", svg(" ".repeat(256 * 1024))],
104
+ ["format mismatch", png],
105
+ ];
106
+ for (const [name, bytes] of invalid) {
107
+ it(`rejects ${name}`, async () => {
108
+ const result = await validateFiles(files(bytes));
109
+ assert.equal(result.ok, false);
110
+ assert.ok(result.errors.some((error) => error.field === "icon"));
111
+ });
112
+ }
113
+ it("rejects non-square raster dimensions and mismatched raster types", async () => {
114
+ const rectangle = Buffer.from(png);
115
+ rectangle.writeUInt32BE(2, 16);
116
+ assert.equal((await validateFiles(files(rectangle, "assets/icon.png"))).ok, false);
117
+ assert.equal((await validateFiles(files(png, "assets/icon.webp"))).ok, false);
118
+ });
119
+ it("rejects missing and traversing icon paths", async () => {
120
+ const missing = files();
121
+ delete missing["assets/icon.svg"];
122
+ assert.equal((await validateFiles(missing)).ok, false);
123
+ for (const path of ["../icon.svg", "/icon.svg", "assets/../icon.svg", "https://example.org/icon.svg"]) {
124
+ const source = files();
125
+ source["bot.yaml"] = source["bot.yaml"].replace("./assets/icon.svg", path);
126
+ assert.equal((await validateFiles(source)).ok, false);
127
+ }
128
+ });
129
+ it("rejects filesystem symlink assets", async () => {
130
+ const dir = await mkdtemp(join(tmpdir(), "librebot-icon-link-"));
131
+ try {
132
+ await mkdir(join(dir, "assets"));
133
+ await symlink("../outside.svg", join(dir, "assets/icon.svg"));
134
+ await assert.rejects(validateSource(dir), /symlinks/);
135
+ } finally { await rm(dir, { recursive: true, force: true }); }
136
+ });
137
+ });
@@ -0,0 +1,92 @@
1
+ // Skill lock reproducibility: identical declarations always hash and lock
2
+ // identically; stale or mismatched locks fail closed; offline SHA pins
3
+ // need no network while branch refs refuse to resolve without it.
4
+
5
+ import { describe, it } from "node:test";
6
+ import assert from "node:assert/strict";
7
+ import {
8
+ checkSourcesLock,
9
+ parseSourcesText,
10
+ parseSourcesYaml,
11
+ resolveSkillsLock,
12
+ serializeLock,
13
+ sourcesHash,
14
+ } from "../src/index.js";
15
+
16
+ const SHA = "a".repeat(40);
17
+ const OTHER_SHA = "b".repeat(40);
18
+
19
+ function sink() {
20
+ return { errors: [], warnings: [] };
21
+ }
22
+
23
+ const sourcesDoc = () => ({
24
+ version: 1,
25
+ sources: [{ name: "lib", source: "octo/skills", ref: SHA, skills: ["review"] }],
26
+ });
27
+
28
+ describe("skill lock reproducibility", () => {
29
+ it("hashes declarations deterministically regardless of key order", () => {
30
+ const parsed = parseSourcesYaml(sourcesDoc(), sink());
31
+ assert.ok(parsed);
32
+ const reordered = {
33
+ version: 1,
34
+ sources: [{ skills: ["review"], ref: SHA, source: "octo/skills", name: "lib" }],
35
+ };
36
+ assert.equal(sourcesHash(parseSourcesYaml(reordered, sink()).sources), sourcesHash(parsed.sources));
37
+ });
38
+
39
+ it("resolves SHA pins offline with byte-identical locks", async () => {
40
+ const parsed = parseSourcesYaml(sourcesDoc(), sink());
41
+ const first = await resolveSkillsLock({ sources: parsed });
42
+ const second = await resolveSkillsLock({ sources: parsed });
43
+ assert.deepEqual(first.errors, []);
44
+ assert.equal(first.lock.resolved[0].resolvedSha, SHA);
45
+ assert.equal(serializeLock(first.lock), serializeLock(second.lock));
46
+ });
47
+
48
+ it("refuses branch refs without network and resolves them with a fetcher", async () => {
49
+ const parsed = parseSourcesYaml(
50
+ { version: 1, sources: [{ name: "lib", source: "octo/skills", ref: "main" }] },
51
+ sink(),
52
+ );
53
+ const offline = await resolveSkillsLock({ sources: parsed });
54
+ assert.ok(offline.errors.length > 0);
55
+
56
+ const fetchImpl = async (url) => {
57
+ assert.match(url, /api\.github\.com/);
58
+ return { ok: true, json: async () => ({ sha: OTHER_SHA }) };
59
+ };
60
+ const online = await resolveSkillsLock({ sources: parsed, network: true, fetchImpl });
61
+ assert.deepEqual(online.errors, []);
62
+ assert.equal(online.lock.resolved[0].resolvedSha, OTHER_SHA);
63
+ });
64
+
65
+ it("round-trips lock serialization and rejects stale hashes", async () => {
66
+ const parsed = parseSourcesYaml(sourcesDoc(), sink());
67
+ const { lock } = await resolveSkillsLock({ sources: parsed });
68
+ const checked = checkSourcesLock(parsed, parseSourcesText(serializeLock(lock)), sink());
69
+ assert.ok(checked);
70
+ assert.equal(checked.resolved[0].resolvedSha, SHA);
71
+
72
+ const stale = checkSourcesLock(parsed, { ...JSON.parse(JSON.stringify(lock)), sourcesHash: "0".repeat(64) }, sink());
73
+ assert.equal(stale, null);
74
+ });
75
+
76
+ it("rejects locks that disagree with declarations", () => {
77
+ const parsed = parseSourcesYaml(sourcesDoc(), sink());
78
+ const tampered = {
79
+ version: 1,
80
+ sourcesHash: sourcesHash(parsed.sources),
81
+ resolved: [
82
+ { name: "lib", repo: "octo/skills", resolvedSha: OTHER_SHA, skills: ["review"] },
83
+ ],
84
+ };
85
+ // SHA-declared ref must match the resolution.
86
+ assert.equal(checkSourcesLock(parsed, tampered, sink()), null);
87
+ });
88
+
89
+ it("rejects malformed source specs", () => {
90
+ assert.equal(parseSourcesYaml({ version: 99, sources: [] }, sink()), null);
91
+ });
92
+ });
@@ -0,0 +1,79 @@
1
+ // Malformed source trees: structural failures carry file/field/message and
2
+ // never throw from validateFiles (parseBotFiles throws BotSourceError).
3
+
4
+ import { describe, it } from "node:test";
5
+ import assert from "node:assert/strict";
6
+ import { BotSourceError, parseBotFiles, validateFiles } from "../src/index.js";
7
+
8
+ const base = (yaml = "") =>
9
+ ({
10
+ "bot.yaml":
11
+ "formatVersion: 1\nname: T\ndescription: D\nmodelRoles:\n - role: default\n label: Main\n" +
12
+ yaml,
13
+ "instructions.md": "Be helpful.",
14
+ "README.md": "# T",
15
+ });
16
+
17
+ const fieldsOf = (result) => result.errors.map((e) => `${e.file}:${e.field}`);
18
+
19
+ describe("malformed source", () => {
20
+ it("requires bot.yaml, instructions.md, and README.md", async () => {
21
+ const missing = await validateFiles({});
22
+ assert.equal(missing.ok, false);
23
+ assert.ok(missing.errors.some((e) => e.file === "bot.yaml"));
24
+ assert.ok(missing.errors.some((e) => e.file === "instructions.md"));
25
+ assert.ok(missing.errors.some((e) => e.file === "README.md"));
26
+ });
27
+
28
+ it("rejects invalid YAML with the file blamed", async () => {
29
+ const result = await validateFiles({
30
+ ...base(),
31
+ "bot.yaml": "formatVersion: [unclosed\n",
32
+ });
33
+ assert.equal(result.ok, false);
34
+ assert.ok(result.errors.some((e) => e.file === "bot.yaml"));
35
+ });
36
+
37
+ it("rejects unknown top-level keys and the removed tools field", async () => {
38
+ const result = await validateFiles(base("frobnicate: 1\ntools: read\n"));
39
+ assert.equal(result.ok, false);
40
+ const fields = fieldsOf(result);
41
+ assert.ok(fields.includes("bot.yaml:frobnicate"));
42
+ const tools = result.errors.find((e) => e.field === "tools");
43
+ assert.match(tools.message, /removed/);
44
+ });
45
+
46
+ it("rejects wrong format versions", async () => {
47
+ const result = await validateFiles({
48
+ ...base(),
49
+ "bot.yaml": "formatVersion: 2\nname: T\ndescription: D\nmodelRoles:\n - role: default\n label: Main\n",
50
+ });
51
+ assert.equal(result.ok, false);
52
+ assert.ok(fieldsOf(result).includes("bot.yaml:formatVersion"));
53
+ });
54
+
55
+ it("rejects non-UTF8 instructions", async () => {
56
+ const result = await validateFiles({
57
+ ...base(),
58
+ "instructions.md": new Uint8Array([0xff, 0xfe, 0x00]),
59
+ });
60
+ assert.equal(result.ok, false);
61
+ assert.ok(result.errors.some((e) => e.file === "instructions.md"));
62
+ });
63
+
64
+ it("parseBotFiles throws BotSourceError carrying every issue", async () => {
65
+ const error = await parseBotFiles({}).catch((e) => e);
66
+ assert.ok(error instanceof BotSourceError);
67
+ assert.ok(error.errors.length >= 2);
68
+ assert.ok(Array.isArray(error.warnings));
69
+ });
70
+
71
+ it("accepts a minimal valid tree", async () => {
72
+ const result = await validateFiles(base());
73
+ assert.equal(result.ok, true);
74
+ assert.deepEqual(result.errors, []);
75
+ assert.equal(result.draft.name, "T");
76
+ assert.equal(result.draft.botPrompt, "Be helpful.");
77
+ assert.ok(!("tools" in result.draft));
78
+ });
79
+ });