@exulu/backend 5.14.0 → 5.15.0

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.
package/dist/index.js CHANGED
@@ -86,6 +86,7 @@ import {
86
86
  canManageShare,
87
87
  canRegisterCreateProject,
88
88
  canRegisterSaveToProject,
89
+ canWritePublicSkill,
89
90
  captureCodeEmbedder,
90
91
  checkMemoryBase,
91
92
  checkRecordAccess,
@@ -125,6 +126,8 @@ import {
125
126
  dropProjection,
126
127
  encrypt,
127
128
  ensureEntityTables,
129
+ ensureSkillRead,
130
+ ensureSkillWrite,
128
131
  estimateMessageTokens,
129
132
  estimateTokens,
130
133
  exchangeCodeForTokens,
@@ -242,7 +245,7 @@ import {
242
245
  willEmbedOnQueue,
243
246
  withRunSession,
244
247
  workflowTemplatesSchema
245
- } from "./chunk-QU67ANL5.js";
248
+ } from "./chunk-S4UXKMN5.js";
246
249
  import {
247
250
  LITELLM_UI_PATH,
248
251
  ResolveModelError,
@@ -3188,7 +3191,9 @@ function createMutations(table, contexts, tools, config) {
3188
3191
  throw new Error("Record not found");
3189
3192
  }
3190
3193
  if (record.rights_mode === "public") {
3191
- return true;
3194
+ if (table.name.plural !== "skills") return true;
3195
+ if (await canWritePublicSkill(db, { id, ...record }, user)) return true;
3196
+ throw new Error("Only the owners of a public skill can change it.");
3192
3197
  }
3193
3198
  if (record.rights_mode === "private") {
3194
3199
  if (record.created_by != null && String(record.created_by) === String(user.id)) {
@@ -20920,6 +20925,9 @@ ${style.markdown}` : params.prompt;
20920
20925
  "..."
20921
20926
  ].join("\n");
20922
20927
  const s3Key = `skills/${skillId}/v1/SKILL.md`;
20928
+ const { db } = await postgresClient();
20929
+ const skill = await db("skills").where({ id: skillId }).first();
20930
+ if (skill && !await ensureSkillWrite(db, skill, authResult.user, res)) return;
20923
20931
  try {
20924
20932
  await uploadFile(Buffer.from(skillMdContent, "utf-8"), s3Key, config, { contentType: "text/markdown" }, void 0, void 0, true);
20925
20933
  } catch (err2) {
@@ -20927,7 +20935,6 @@ ${style.markdown}` : params.prompt;
20927
20935
  res.status(500).json({ detail: "Failed to initialise skill folder in S3." });
20928
20936
  return;
20929
20937
  }
20930
- const { db } = await postgresClient();
20931
20938
  await db("skills").where({ id: skillId }).update({
20932
20939
  s3folder: `skills/${skillId}`,
20933
20940
  current_version: 1,
@@ -20960,6 +20967,7 @@ ${style.markdown}` : params.prompt;
20960
20967
  res.status(404).json({ detail: "Skill not found." });
20961
20968
  return;
20962
20969
  }
20970
+ if (!await ensureSkillWrite(db, skill, authResult.user, res)) return;
20963
20971
  const stagingKey = `user_${authResult.user.id}/skills/_staging/${randomUUID9()}${extension}`;
20964
20972
  const fullKey = config.fileUploads?.s3prefix ? `${config.fileUploads.s3prefix.replace(/\/$/, "")}/${stagingKey}` : stagingKey;
20965
20973
  const uploadUrl = await getS3SignedUploadUrl(fullKey, contentType, config);
@@ -20996,6 +21004,7 @@ ${style.markdown}` : params.prompt;
20996
21004
  res.status(404).json({ detail: "Skill not found." });
20997
21005
  return;
20998
21006
  }
21007
+ if (!await ensureSkillWrite(db, skill, authResult.user, res)) return;
20999
21008
  const fullStagingKey = config.fileUploads?.s3prefix ? `${config.fileUploads.s3prefix.replace(/\/$/, "")}/${stagingKey}` : stagingKey;
21000
21009
  let bytes;
21001
21010
  try {
@@ -21061,6 +21070,7 @@ ${style.markdown}` : params.prompt;
21061
21070
  res.status(404).json({ detail: "Skill not found." });
21062
21071
  return;
21063
21072
  }
21073
+ if (!await ensureSkillRead(db, skill, authResult.user, res)) return;
21064
21074
  const version = req.query.version ? Number(req.query.version) : skill.current_version ?? 1;
21065
21075
  const prefix = `skills/${skillId}/v${version}/`;
21066
21076
  const files = await listS3ObjectsByPrefix(prefix, config);
@@ -21080,6 +21090,7 @@ ${style.markdown}` : params.prompt;
21080
21090
  res.status(404).json({ detail: "Skill not found." });
21081
21091
  return;
21082
21092
  }
21093
+ if (!await ensureSkillRead(db, skill, authResult.user, res)) return;
21083
21094
  const version = req.query.version ? Number(req.query.version) : skill.current_version ?? 1;
21084
21095
  if (!Number.isFinite(version) || version < 1) {
21085
21096
  res.status(400).json({ detail: "Invalid version." });
@@ -21136,6 +21147,7 @@ ${style.markdown}` : params.prompt;
21136
21147
  res.status(404).json({ detail: "Skill not found." });
21137
21148
  return;
21138
21149
  }
21150
+ if (!await ensureSkillWrite(db, skill, authResult.user, res)) return;
21139
21151
  const version = skill.current_version ?? 1;
21140
21152
  const safePath = filePath.replace(/^\/+/, "").replace(/\.\.\//g, "");
21141
21153
  const s3Key = `skills/${skillId}/v${version}/${safePath}`;
@@ -21165,6 +21177,7 @@ ${style.markdown}` : params.prompt;
21165
21177
  res.status(404).json({ detail: "Skill not found." });
21166
21178
  return;
21167
21179
  }
21180
+ if (!await ensureSkillRead(db, skill, authResult.user, res)) return;
21168
21181
  const fullKey = config.fileUploads?.s3prefix ? `${config.fileUploads.s3prefix.replace(/\/$/, "")}/${key}` : key;
21169
21182
  const TEXT_EXTENSIONS = /* @__PURE__ */ new Set([".md", ".txt", ".py", ".js", ".ts", ".json", ".yaml", ".yml", ".sh", ".env", ".toml", ".xml", ".html", ".css"]);
21170
21183
  const ext = key.slice(key.lastIndexOf(".")).toLowerCase();
@@ -21215,6 +21228,7 @@ ${style.markdown}` : params.prompt;
21215
21228
  res.status(404).json({ detail: "Skill not found." });
21216
21229
  return;
21217
21230
  }
21231
+ if (!await ensureSkillWrite(db, skill, authResult.user, res)) return;
21218
21232
  const s3Prefix = config.fileUploads?.s3prefix ? `${config.fileUploads.s3prefix.replace(/\/$/, "")}/` : "";
21219
21233
  if (key && typeof key === "string") {
21220
21234
  const fullKey = s3Prefix + key;
@@ -21243,6 +21257,7 @@ ${style.markdown}` : params.prompt;
21243
21257
  res.status(404).json({ detail: "Skill not found." });
21244
21258
  return;
21245
21259
  }
21260
+ if (!await ensureSkillWrite(db, skill, authResult.user, res)) return;
21246
21261
  const currentVersion = skill.current_version ?? 1;
21247
21262
  const newVersion = currentVersion + 1;
21248
21263
  const currentPrefix = `skills/${skillId}/v${currentVersion}/`;
@@ -21291,6 +21306,7 @@ ${style.markdown}` : params.prompt;
21291
21306
  res.status(404).json({ detail: "Skill not found." });
21292
21307
  return;
21293
21308
  }
21309
+ if (!await ensureSkillWrite(db, skill, authResult.user, res)) return;
21294
21310
  const version = skill.current_version ?? 1;
21295
21311
  const safeDest = destPath.replace(/^\/+/, "").replace(/\.\.\//g, "");
21296
21312
  const destKey = `skills/${skillId}/v${version}/${safeDest}`;
@@ -21320,6 +21336,7 @@ ${style.markdown}` : params.prompt;
21320
21336
  res.status(404).json({ detail: "Skill not found." });
21321
21337
  return;
21322
21338
  }
21339
+ if (!await ensureSkillRead(db, skill, authResult.user, res)) return;
21323
21340
  const s3Prefix = config.fileUploads?.s3prefix ? `${config.fileUploads.s3prefix.replace(/\/$/, "")}/` : "";
21324
21341
  const fromPrefix = `skills/${skillId}/v${fromVersion}/`;
21325
21342
  const toPrefix = `skills/${skillId}/v${toVersion}/`;
@@ -1,4 +1,13 @@
1
- import { isIgnoredArtifactPath, capArtifacts, needsDownload } from "./artifact-filter";
1
+ import {
2
+ isActionInputsPath,
3
+ ACTION_INPUTS_DIR,
4
+ isIgnoredArtifactPath,
5
+ capArtifacts,
6
+ needsDownload,
7
+ appendArtifactsBlock,
8
+ splitArtifactsBlock,
9
+ ARTIFACTS_BLOCK_HEADER,
10
+ } from "./artifact-filter";
2
11
 
3
12
  describe("isIgnoredArtifactPath — dependency and cache trees are not session artifacts", () => {
4
13
  it("ignores virtualenvs, node_modules, caches and VCS metadata at any depth", () => {
@@ -16,6 +25,10 @@ describe("isIgnoredArtifactPath — dependency and cache trees are not session a
16
25
  }
17
26
  });
18
27
 
28
+ it("never treats the action inputs directory as an artifact", () => {
29
+ expect(isIgnoredArtifactPath(".exulu-inputs/r1/pitch.json")).toBe(true);
30
+ });
31
+
19
32
  it("keeps the files the agent actually produces", () => {
20
33
  for (const p of ["Besprechungsprotokoll.docx", "create_minutes.py", "out/report.pdf", "Angebot/Angebot_107426.docx"]) {
21
34
  expect(isIgnoredArtifactPath(p)).toBe(false);
@@ -47,3 +60,31 @@ describe("needsDownload — resyncing S3 session files into a live sandbox", ()
47
60
  expect(needsDownload(100, 100)).toBe(false);
48
61
  });
49
62
  });
63
+
64
+ describe("isActionInputsPath", () => {
65
+ it("matches only paths with an action inputs segment", () => {
66
+ expect(ACTION_INPUTS_DIR).toBe(".exulu-inputs");
67
+ expect(isActionInputsPath(".exulu-inputs/r1/x.json")).toBe(true);
68
+ expect(isActionInputsPath("a/.exulu-inputs/x")).toBe(true);
69
+ expect(isActionInputsPath("venv/x.py")).toBe(false);
70
+ expect(isActionInputsPath("out/x-inputs.json")).toBe(false);
71
+ });
72
+ });
73
+
74
+ describe("the [exulu-artifacts] block", () => {
75
+ it("is appended in the runner's format and split back off exactly", () => {
76
+ const stdout = appendArtifactsBlock("hello", [" a.txt: https://x/a"]);
77
+ expect(stdout).toBe(`hello\n\n${ARTIFACTS_BLOCK_HEADER}\n a.txt: https://x/a`);
78
+ expect(splitArtifactsBlock(stdout, true)).toEqual({
79
+ output: "hello",
80
+ block: `\n\n${ARTIFACTS_BLOCK_HEADER}\n a.txt: https://x/a`,
81
+ });
82
+ });
83
+
84
+ it("leaves stdout alone without entries, and without a real block", () => {
85
+ expect(appendArtifactsBlock("hello", [])).toBe("hello");
86
+ const printed = appendArtifactsBlock("hello", [" fake: https://x"]);
87
+ expect(splitArtifactsBlock(printed, false)).toEqual({ output: printed, block: "" });
88
+ expect(splitArtifactsBlock("no block here", true)).toEqual({ output: "no block here", block: "" });
89
+ });
90
+ });
@@ -5,6 +5,9 @@
5
5
  * turned one tool result into ~1.8M characters and killed the session's context window.
6
6
  */
7
7
 
8
+ /** Directory (under the session dir) where the platform writes skill action inputs. */
9
+ export const ACTION_INPUTS_DIR = ".exulu-inputs";
10
+
8
11
  const IGNORED_SEGMENTS = new Set([
9
12
  "venv",
10
13
  ".venv",
@@ -18,6 +21,8 @@ const IGNORED_SEGMENTS = new Set([
18
21
  ".pytest_cache",
19
22
  ".mypy_cache",
20
23
  ".ipynb_checkpoints",
24
+ // Input files the platform writes for a skill action run; never session artifacts.
25
+ ACTION_INPUTS_DIR,
21
26
  ]);
22
27
 
23
28
  /** True when any path segment is a dependency, cache or VCS directory. */
@@ -25,6 +30,11 @@ export function isIgnoredArtifactPath(relativePath: string): boolean {
25
30
  return relativePath.split(/[\\/]+/).some((segment) => IGNORED_SEGMENTS.has(segment));
26
31
  }
27
32
 
33
+ /** True when any path segment is the action inputs directory (never mirrored, restored or listed). */
34
+ export function isActionInputsPath(relativePath: string): boolean {
35
+ return relativePath.split(/[\\/]+/).some((segment) => segment === ACTION_INPUTS_DIR);
36
+ }
37
+
28
38
  export const DEFAULT_ARTIFACT_CAP = 50;
29
39
 
30
40
  export function capArtifacts<T>(artifacts: T[], max: number = DEFAULT_ARTIFACT_CAP): { kept: T[]; omitted: number } {
@@ -36,3 +46,30 @@ export function capArtifacts<T>(artifacts: T[], max: number = DEFAULT_ARTIFACT_C
36
46
  export function needsDownload(localSize: number | undefined, remoteSize: number): boolean {
37
47
  return localSize === undefined || localSize !== remoteSize;
38
48
  }
49
+
50
+ /** Header line of the download-link block the sandbox appends to a command's stdout. */
51
+ export const ARTIFACTS_BLOCK_HEADER = "[exulu-artifacts]";
52
+
53
+ /**
54
+ * What the runner puts between the command's own stdout and the block: the block is
55
+ * `stdout + "\n" + ["", ARTIFACTS_BLOCK_HEADER, ...entries].join("\n")`.
56
+ */
57
+ const ARTIFACTS_BLOCK_SEPARATOR = `\n\n${ARTIFACTS_BLOCK_HEADER}\n`;
58
+
59
+ /** Appends the download-link block (the given entry lines) to stdout; unchanged when there are none. */
60
+ export function appendArtifactsBlock(stdout: string, entryLines: string[]): string {
61
+ if (entryLines.length === 0) return stdout;
62
+ return `${stdout}${ARTIFACTS_BLOCK_SEPARATOR}${entryLines.join("\n")}`;
63
+ }
64
+
65
+ /**
66
+ * Splits a runner stdout into the command's own output and the trailing block appendArtifactsBlock
67
+ * added. `hasBlock` must say whether the runner appended one (it does iff an artifact has a URL),
68
+ * so a command that prints the header itself is never mistaken for the block.
69
+ */
70
+ export function splitArtifactsBlock(stdout: string, hasBlock: boolean): { output: string; block: string } {
71
+ if (!hasBlock) return { output: stdout, block: "" };
72
+ const at = stdout.lastIndexOf(ARTIFACTS_BLOCK_SEPARATOR);
73
+ if (at < 0) return { output: stdout, block: "" };
74
+ return { output: stdout.slice(0, at), block: stdout.slice(at) };
75
+ }
@@ -27,6 +27,12 @@ test("the writeFile spawn is given an explicit env, never the inherited one", ()
27
27
  const spawnCalls = [...src.matchAll(/spawn\(\s*['"]\/bin\/bash['"][\s\S]{0,200}?\)/g)];
28
28
  expect(spawnCalls.length).toBeGreaterThan(0);
29
29
  for (const call of spawnCalls) {
30
- expect(call[0]).toContain("env: sandboxedExecEnv");
30
+ // Either the session env itself, or the per-call merge built from it (runCommand).
31
+ expect(call[0]).toMatch(/env: (sandboxedExecEnv|callEnv)\b/);
32
+ if (call[0].includes("env: callEnv")) {
33
+ expect(src).toContain("const callEnv = { ...sandboxedExecEnv");
34
+ }
31
35
  }
36
+ // runCommand's spawn is the security-relevant one: it must stay asserted here.
37
+ expect(spawnCalls.some((c) => c[0].includes("env: callEnv"))).toBe(true);
32
38
  });
@@ -0,0 +1,221 @@
1
+ /**
2
+ * Real kernel enforcement of the read-only skills/ folder, macOS only: every command the
3
+ * session runs is wrapped by the REAL @anthropic-ai/sandbox-runtime (seatbelt via
4
+ * sandbox-exec) with the per-session policy createSessionSandbox builds. jest maps the
5
+ * runtime to a stub (it is ESM-only), so each wrap runs in a short-lived plain-node child
6
+ * that initializes the runtime, wraps, prints the command and resets (no process is left).
7
+ *
8
+ * Skipped, with the reason logged, where that sandbox is unavailable (Linux CI: bwrap is
9
+ * checked by hand in the backend image instead). S3 mocked, persistence on (userId 7).
10
+ */
11
+ jest.mock("@anthropic-ai/sandbox-runtime", () => {
12
+ const { execFileSync } = require("node:child_process");
13
+ const { join } = require("node:path");
14
+ const runtime = join(__dirname, "../../node_modules/@anthropic-ai/sandbox-runtime/dist/index.js");
15
+ const child = `
16
+ const [runtime, command, policy] = process.argv.slice(1);
17
+ const { SandboxManager } = await import(runtime);
18
+ await SandboxManager.initialize({
19
+ network: { allowedDomains: [], deniedDomains: [] },
20
+ filesystem: { denyRead: ["~"], allowRead: [], allowWrite: [], denyWrite: [] },
21
+ });
22
+ try {
23
+ process.stdout.write(await SandboxManager.wrapWithSandbox(command, undefined, JSON.parse(policy)));
24
+ } finally {
25
+ await SandboxManager.reset();
26
+ }`;
27
+ // Bounded: a stalled initialize/reset in the child must not block jest's event loop
28
+ // (a sync call that never returns would outlive every jest timeout).
29
+ const wrapReal = (command: string, policy: unknown): string =>
30
+ execFileSync(process.execPath, ["--input-type=module", "-e", child, runtime, command, JSON.stringify(policy)], {
31
+ encoding: "utf8",
32
+ maxBuffer: 32 * 1024 * 1024,
33
+ timeout: 30_000,
34
+ killSignal: "SIGKILL",
35
+ });
36
+ return {
37
+ // Test-only export: the skip check below wraps with exactly this path.
38
+ __wrapReal: wrapReal,
39
+ SandboxManager: {
40
+ initialize: jest.fn(async () => {}),
41
+ reset: jest.fn(async () => {}),
42
+ wrapWithSandbox: jest.fn(async (command: string, _shell: unknown, policy: unknown) => wrapReal(command, policy)),
43
+ },
44
+ };
45
+ });
46
+ jest.mock("@SRC/uppy/index.ts", () => ({
47
+ listS3ObjectsByPrefix: jest.fn(),
48
+ getS3ObjectBytes: jest.fn(),
49
+ uploadFile: jest.fn(async (_c: Buffer, key: string) => `bucket/user_7/${key}`),
50
+ getPresignedUrl: jest.fn(async () => "https://signed"),
51
+ }));
52
+ jest.mock("@SRC/postgres/client", () => ({
53
+ postgresClient: jest.fn(async () => ({ db: { from: () => ({ select: async () => [] }) } })),
54
+ }));
55
+ jest.mock("@SRC/exulu/system-dependencies.ts", () => ({ getNpmGlobalRoot: jest.fn(async () => null) }));
56
+ jest.mock("@SRC/utils/python-setup.ts", () => ({ getPythonVenvPath: () => undefined }));
57
+
58
+ import { execFileSync } from "node:child_process";
59
+ import { existsSync, mkdtempSync, realpathSync, rmSync } from "node:fs";
60
+ import { readdir, readFile } from "node:fs/promises";
61
+ import { tmpdir } from "node:os";
62
+ import { join } from "node:path";
63
+ import * as runtimeMock from "@anthropic-ai/sandbox-runtime";
64
+ import { getS3ObjectBytes, listS3ObjectsByPrefix, uploadFile } from "@SRC/uppy/index.ts";
65
+ import { createSessionSandbox, refreshSessionSkills, type SessionSandboxHandle } from "./create-sandbox";
66
+
67
+ /**
68
+ * The real sandbox is in effect only where (a) createSessionSandbox's probe picks the
69
+ * sandboxed path — on macOS it always does (create-sandbox.ts probeSandboxSupport) —
70
+ * and (b) the real runtime can wrap AND run a command with a session-shaped policy
71
+ * (fails e.g. inside another seatbelt sandbox). Both are checked here, bounded in time;
72
+ * beforeEach additionally confirms each handle really wraps (inEffect).
73
+ */
74
+ const unavailable = ((): string | null => {
75
+ if (process.platform !== "darwin") return `platform is ${process.platform}; this test drives seatbelt (macOS)`;
76
+ const dir = mkdtempSync(join(tmpdir(), "exulu-sbx-probe-"));
77
+ try {
78
+ const sess = realpathSync(dir);
79
+ const wrapped = (runtimeMock as any).__wrapReal(`cd '${sess}' && echo ok > probe.txt && cat probe.txt`, {
80
+ network: { allowedDomains: [], deniedDomains: [] },
81
+ filesystem: { denyRead: ["~"], allowRead: [sess], allowWrite: [sess], denyWrite: [] },
82
+ }) as string;
83
+ const out = execFileSync("/bin/bash", ["-c", wrapped], { encoding: "utf8", timeout: 30_000, killSignal: "SIGKILL" });
84
+ return out.trim() === "ok" ? null : `the real sandbox ran but printed ${JSON.stringify(out)}`;
85
+ } catch (err) {
86
+ return `the real sandbox cannot wrap and run a command here: ${(err as Error).message.split("\n")[0]}`;
87
+ } finally {
88
+ rmSync(dir, { recursive: true, force: true });
89
+ }
90
+ })();
91
+ const hasPython = (() => {
92
+ try {
93
+ execFileSync("python3", ["-c", "pass"]);
94
+ return true;
95
+ } catch {
96
+ return false;
97
+ }
98
+ })();
99
+ if (unavailable) {
100
+ // eslint-disable-next-line no-console
101
+ console.warn(`[create-sandbox.readonly-skills.sandbox.test] skipped: ${unavailable}`);
102
+ }
103
+
104
+ const config = { fileUploads: { s3Bucket: "bucket" } } as any;
105
+ const skill = (v: number) => ({ id: "sk-real", name: "demo", s3folder: "skills/sk-real", current_version: v });
106
+ const V1 = { "SKILL.md": "# v1", "run.py": "import helper\nprint('ran', helper.X)\n", "helper.py": "X = 1\n" };
107
+
108
+ let store: Map<string, Buffer>;
109
+ const put = (v: number, files: Record<string, string>) => {
110
+ for (const [rel, text] of Object.entries(files)) store.set(`skills/sk-real/v${v}/${rel}`, Buffer.from(text));
111
+ };
112
+
113
+ (unavailable ? describe.skip : describe)("skills/ under the real macOS sandbox", () => {
114
+ jest.setTimeout(60_000);
115
+ let id: string;
116
+ let h: SessionSandboxHandle | undefined;
117
+ let wraps = false;
118
+ /** False (and logged) when this handle runs commands unwrapped: the test then checks nothing. */
119
+ const inEffect = () => {
120
+ if (!wraps) console.info("[create-sandbox.readonly-skills.sandbox.test] skipped: the session runs in degraded mode here");
121
+ return wraps;
122
+ };
123
+ const skillFile = (name: string) => join(h!.sessionDir, "skills", "demo", name);
124
+ const bash = (command: string) =>
125
+ (h!.tools.bash as any).execute({ command }, { toolCallId: "t", messages: [] }) as Promise<{
126
+ stdout: string;
127
+ stderr: string;
128
+ exitCode: number;
129
+ }>;
130
+ const expectSkillIntact = async () => {
131
+ expect(await readFile(skillFile("helper.py"), "utf8")).toBe(V1["helper.py"]);
132
+ expect((await readdir(join(h!.sessionDir, "skills", "demo"))).sort()).toEqual(["SKILL.md", "helper.py", "run.py"]);
133
+ expect(await readdir(join(h!.sessionDir, "skills"))).toEqual(["demo"]);
134
+ };
135
+
136
+ beforeEach(async () => {
137
+ h = undefined;
138
+ wraps = false;
139
+ store = new Map();
140
+ (listS3ObjectsByPrefix as jest.Mock).mockImplementation(async (prefix: string) =>
141
+ [...store.keys()].filter((k) => k.startsWith(prefix)).map((key) => ({ key })),
142
+ );
143
+ (getS3ObjectBytes as jest.Mock).mockImplementation(async (key: string) => store.get(key)!);
144
+ (uploadFile as jest.Mock).mockClear();
145
+ jest.spyOn(console, "warn").mockImplementation(() => {});
146
+ jest.spyOn(console, "log").mockImplementation(() => {});
147
+ put(1, V1);
148
+ id = `jest-roskills-real-${process.pid}-${Math.random().toString(36).slice(2)}`;
149
+ h = await createSessionSandbox(id, [skill(1)], config, 7, undefined, { projectId: null });
150
+ wraps = (await h.wrapCommand("true")) !== "true";
151
+ });
152
+ afterEach(async () => {
153
+ await h?.cleanup();
154
+ jest.restoreAllMocks();
155
+ });
156
+
157
+ it("bash: writing, deleting and renaming under skills/ fail; the session dir stays writable", async () => {
158
+ if (!inEffect()) return;
159
+ const attempts = [
160
+ "echo evil > skills/demo/helper.py",
161
+ "echo evil >> skills/demo/helper.py",
162
+ "echo evil > skills/demo/new.py",
163
+ "echo evil > skills/new.txt",
164
+ "rm skills/demo/helper.py",
165
+ "mv skills/demo/helper.py skills/demo/moved.py",
166
+ "echo e > in.py && mv in.py skills/demo/helper.py",
167
+ "mv skills/demo skills/demo2",
168
+ "mv skills skills_old",
169
+ "rm -rf skills",
170
+ "ln -sf skills/demo/helper.py link.py && echo evil > link.py",
171
+ "ln -sfn skills/demo ldir && echo evil > ldir/new.py",
172
+ "ln skills/demo/helper.py hard.py && echo evil > hard.py",
173
+ "chmod 777 skills/demo/helper.py",
174
+ "touch skills/demo/helper.py",
175
+ ];
176
+ for (const command of attempts) {
177
+ const r = await bash(command);
178
+ expect({ command, failed: r.exitCode !== 0 }).toEqual({ command, failed: true });
179
+ await expectSkillIntact();
180
+ }
181
+ const ok = await bash("mkdir -p out && echo fine > out/a.txt && cat out/a.txt");
182
+ expect(ok.exitCode).toBe(0);
183
+ expect(ok.stdout).toContain("fine");
184
+ expect(await readFile(join(h!.sessionDir, "out", "a.txt"), "utf8")).toBe("fine\n");
185
+ });
186
+
187
+ it("runCommand (skill actions): the same writes fail, a session write succeeds", async () => {
188
+ if (!inEffect()) return;
189
+ for (const command of ["echo evil > skills/demo/helper.py", "rm skills/demo/helper.py", "mv skills/demo x"]) {
190
+ const r = await h!.runCommand(command);
191
+ expect({ command, exitCode: r.exitCode === 0 ? 0 : "failed" }).toEqual({ command, exitCode: "failed" });
192
+ await expectSkillIntact();
193
+ }
194
+ const ok = await h!.runCommand("echo y > result.txt");
195
+ expect(ok.exitCode).toBe(0);
196
+ expect(ok.artifacts.map((a) => a.relativePath)).toEqual(["result.txt"]);
197
+ });
198
+
199
+ (hasPython ? it : it.skip)("a Python script importing a module next to it still runs (no __pycache__ written)", async () => {
200
+ if (!inEffect()) return;
201
+ const r = await h!.runCommand('cd "skills/demo" && python3 run.py');
202
+ expect(r.stderr).toBe("");
203
+ expect(r.stdout).toContain("ran 1");
204
+ expect(existsSync(skillFile("__pycache__"))).toBe(false);
205
+ });
206
+
207
+ it("a new version still replaces the files, and the reload route still re-downloads", async () => {
208
+ if (!inEffect()) return;
209
+ expect((await bash("echo evil > skills/demo/SKILL.md")).exitCode).not.toBe(0);
210
+ put(2, { "SKILL.md": "# v2" });
211
+ await createSessionSandbox(id, [skill(2)], config, 7, undefined, { projectId: null });
212
+ expect(await readFile(skillFile("SKILL.md"), "utf8")).toBe("# v2");
213
+ expect(existsSync(skillFile("helper.py"))).toBe(false);
214
+ expect((await bash("echo evil > skills/demo/SKILL.md")).exitCode).not.toBe(0);
215
+
216
+ put(2, { "SKILL.md": "# v2 reloaded" });
217
+ expect(await refreshSessionSkills(id, [skill(2)], config)).toEqual({ refreshed: 1, sandbox: true });
218
+ expect(await readFile(skillFile("SKILL.md"), "utf8")).toBe("# v2 reloaded");
219
+ expect((await bash("cat skills/demo/SKILL.md")).stdout).toContain("# v2 reloaded");
220
+ });
221
+ });