@crewhaus/runtime-core 0.1.4 → 0.1.5

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.
@@ -1,145 +0,0 @@
1
- /**
2
- * Tests for the project-memory auto-loader. Covers:
3
- * - File discovery in cwd (AGENTS.md, CLAUDE.md, CODE-COMPANION.md, AGENT.md)
4
- * - Multi-file concatenation with envelope tags
5
- * - Cap-byte truncation with notice
6
- * - Graceful no-match (empty result; non-erroring)
7
- * - Boundary classification with user origin (smoke — full classifier
8
- * tests live in boundary-classifier package).
9
- */
10
- import { afterAll, beforeAll, describe, expect, test } from "bun:test";
11
- import { mkdirSync, rmSync, writeFileSync } from "node:fs";
12
- import { mkdtempSync } from "node:fs";
13
- import { tmpdir } from "node:os";
14
- import { join } from "node:path";
15
- import {
16
- CANONICAL_MEMORY_FILES,
17
- DEFAULT_PROJECT_MEMORY_CAP_BYTES,
18
- loadProjectMemory,
19
- } from "./project-memory";
20
-
21
- let workdir: string;
22
-
23
- beforeAll(() => {
24
- workdir = mkdtempSync(join(tmpdir(), "crewhaus-project-memory-"));
25
- });
26
-
27
- afterAll(() => {
28
- rmSync(workdir, { recursive: true, force: true });
29
- });
30
-
31
- function setUpWorkdir(files: Record<string, string>): string {
32
- const dir = mkdtempSync(join(workdir, "case-"));
33
- for (const [name, content] of Object.entries(files)) {
34
- writeFileSync(join(dir, name), content);
35
- }
36
- return dir;
37
- }
38
-
39
- describe("loadProjectMemory", () => {
40
- test("returns empty result when no memory files present", async () => {
41
- const dir = setUpWorkdir({ "unrelated.md": "ignored", "package.json": "{}" });
42
- const result = await loadProjectMemory({ cwd: dir });
43
- expect(result.files).toEqual([]);
44
- expect(result.prompt).toBe("");
45
- expect(result.totalBytes).toBe(0);
46
- });
47
-
48
- test("loads AGENTS.md when present", async () => {
49
- const dir = setUpWorkdir({ "AGENTS.md": "# Project Neutral\nHandles the thing." });
50
- const result = await loadProjectMemory({ cwd: dir });
51
- expect(result.files.length).toBe(1);
52
- expect(result.files[0]?.filename).toBe("AGENTS.md");
53
- expect(result.files[0]?.content).toContain("# Project Neutral");
54
- expect(result.files[0]?.truncated).toBe(false);
55
- expect(result.prompt).toContain('<project_memory file="AGENTS.md">');
56
- expect(result.prompt).toContain("</project_memory>");
57
- });
58
-
59
- test("loads CLAUDE.md when present", async () => {
60
- const dir = setUpWorkdir({ "CLAUDE.md": "# Project X\nDoes the thing." });
61
- const result = await loadProjectMemory({ cwd: dir });
62
- expect(result.files.length).toBe(1);
63
- expect(result.files[0]?.filename).toBe("CLAUDE.md");
64
- expect(result.files[0]?.content).toContain("# Project X");
65
- expect(result.files[0]?.truncated).toBe(false);
66
- expect(result.prompt).toContain('<project_memory file="CLAUDE.md">');
67
- expect(result.prompt).toContain("</project_memory>");
68
- });
69
-
70
- test("loads multiple memory files in canonical priority order", async () => {
71
- const dir = setUpWorkdir({
72
- "AGENTS.md": "# agents content",
73
- "CLAUDE.md": "# claude content",
74
- "CODE-COMPANION.md": "# code companion content",
75
- "AGENT.md": "# agent content",
76
- });
77
- const result = await loadProjectMemory({ cwd: dir });
78
- expect(result.files.map((f) => f.filename)).toEqual([
79
- "AGENTS.md",
80
- "CLAUDE.md",
81
- "CODE-COMPANION.md",
82
- "AGENT.md",
83
- ]);
84
- expect(result.prompt).toContain('<project_memory file="AGENTS.md">');
85
- expect(result.prompt).toContain('<project_memory file="CLAUDE.md">');
86
- expect(result.prompt).toContain('<project_memory file="CODE-COMPANION.md">');
87
- expect(result.prompt).toContain('<project_memory file="AGENT.md">');
88
- });
89
-
90
- test("truncates content exceeding capBytes with a notice", async () => {
91
- const dir = setUpWorkdir({ "CLAUDE.md": "x".repeat(200) });
92
- const result = await loadProjectMemory({ cwd: dir, capBytes: 50 });
93
- expect(result.files.length).toBe(1);
94
- expect(result.files[0]?.truncated).toBe(true);
95
- expect(result.files[0]?.content).toContain("[...truncated to 50 bytes");
96
- });
97
-
98
- test("stops loading once total cap exhausted", async () => {
99
- const dir = setUpWorkdir({
100
- "CLAUDE.md": "a".repeat(100),
101
- "CODE-COMPANION.md": "b".repeat(100),
102
- "AGENT.md": "c".repeat(100),
103
- });
104
- const result = await loadProjectMemory({ cwd: dir, capBytes: 150 });
105
- expect(result.files.length).toBeGreaterThan(0);
106
- expect(result.totalBytes).toBeLessThanOrEqual(150 + 200); // truncation suffix adds bytes
107
- });
108
-
109
- test("ignores non-canonical filenames", async () => {
110
- // Note: avoid case-only-different names — macOS is case-insensitive
111
- // by default so "Claude.md" would collide with "CLAUDE.md".
112
- const dir = setUpWorkdir({
113
- "MEMORY.md": "should be ignored",
114
- "PROJECT.md": "also ignored",
115
- });
116
- const result = await loadProjectMemory({ cwd: dir });
117
- expect(result.files).toEqual([]);
118
- });
119
-
120
- test("honors filenames override", async () => {
121
- const dir = setUpWorkdir({ "PROJECT.md": "custom content" });
122
- const result = await loadProjectMemory({ cwd: dir, filenames: ["PROJECT.md"] });
123
- expect(result.files.length).toBe(1);
124
- expect(result.files[0]?.filename).toBe("PROJECT.md");
125
- });
126
-
127
- test("returns valid result when cwd doesn't exist (no throw)", async () => {
128
- const result = await loadProjectMemory({ cwd: "/this/path/does/not/exist/anywhere" });
129
- expect(result.files).toEqual([]);
130
- expect(result.prompt).toBe("");
131
- });
132
-
133
- test("CANONICAL_MEMORY_FILES exports the right list", () => {
134
- expect(CANONICAL_MEMORY_FILES).toEqual([
135
- "AGENTS.md",
136
- "CLAUDE.md",
137
- "CODE-COMPANION.md",
138
- "AGENT.md",
139
- ]);
140
- });
141
-
142
- test("DEFAULT_PROJECT_MEMORY_CAP_BYTES is 64 KB", () => {
143
- expect(DEFAULT_PROJECT_MEMORY_CAP_BYTES).toBe(64 * 1024);
144
- });
145
- });
@@ -1,134 +0,0 @@
1
- /**
2
- * Auto-loaded project memory — M3.1 of the heavy-hitter plan.
3
- *
4
- * At session-start, the runtime looks for canonical "project memory"
5
- * files in the current working directory and prepends their contents
6
- * to the system prompt. Follows the vendor-neutral agents.md convention
7
- * (https://agents.md) and is compatible with Claude Code's CLAUDE.md
8
- * auto-load behaviour.
9
- *
10
- * Files searched (in priority order, all matches are loaded):
11
- * - AGENTS.md (vendor-neutral convention — agents.md)
12
- * - CLAUDE.md (Claude Code convention)
13
- * - CODE-COMPANION.md (hello-code demo convention)
14
- * - AGENT.md (legacy singular form; retained for compatibility)
15
- *
16
- * Each file's contents are wrapped in:
17
- * <project_memory file="AGENTS.md">
18
- * ...contents...
19
- * </project_memory>
20
- *
21
- * Multiple files concatenate with blank-line separators.
22
- *
23
- * Pillar 3 — Security fabric: every file's contents are classified via
24
- * `boundary-classifier` with origin `"user"` (the developer owns their
25
- * repo). The user-origin default policy is `"pass"`, so classification
26
- * RUNS (and logs trace events) without blocking — which is the right
27
- * stance for a developer-trusted source. If a future deployment wants
28
- * strict policy on these files, pass `severity: "block"` via opts.
29
- *
30
- * Size cap: 64 KB total across all matched files. Larger files load
31
- * the first N bytes plus a `[...truncated]` notice — the prompt cache
32
- * is more valuable than the tail of a large memory file.
33
- */
34
- import { existsSync } from "node:fs";
35
- import { readFile, stat } from "node:fs/promises";
36
- import { join } from "node:path";
37
- import { classifyBoundary } from "@crewhaus/boundary-classifier";
38
-
39
- export const CANONICAL_MEMORY_FILES = [
40
- "AGENTS.md",
41
- "CLAUDE.md",
42
- "CODE-COMPANION.md",
43
- "AGENT.md",
44
- ] as const;
45
-
46
- export const DEFAULT_PROJECT_MEMORY_CAP_BYTES = 64 * 1024;
47
-
48
- export interface ProjectMemoryLoadOptions {
49
- /** Override cwd. Defaults to `process.cwd()`. */
50
- readonly cwd?: string;
51
- /** Override the filename list. Defaults to `CANONICAL_MEMORY_FILES`. */
52
- readonly filenames?: readonly string[];
53
- /** Maximum total bytes across all loaded files. Defaults to 64 KB. */
54
- readonly capBytes?: number;
55
- }
56
-
57
- export interface LoadedMemoryFile {
58
- readonly filename: string;
59
- readonly content: string;
60
- readonly truncated: boolean;
61
- }
62
-
63
- export interface ProjectMemoryLoadResult {
64
- readonly files: readonly LoadedMemoryFile[];
65
- /** Total content bytes across all files (post-truncation). */
66
- readonly totalBytes: number;
67
- /** Wrapped + concatenated content ready to prepend to the system prompt. */
68
- readonly prompt: string;
69
- }
70
-
71
- /**
72
- * Scan cwd for project-memory files and return the rendered prompt block.
73
- * Returns `{ files: [], prompt: "" }` when no files matched — caller can
74
- * conditionally skip the prepend without a length check.
75
- */
76
- export async function loadProjectMemory(
77
- opts: ProjectMemoryLoadOptions = {},
78
- ): Promise<ProjectMemoryLoadResult> {
79
- const cwd = opts.cwd ?? process.cwd();
80
- const filenames = opts.filenames ?? CANONICAL_MEMORY_FILES;
81
- const cap = opts.capBytes ?? DEFAULT_PROJECT_MEMORY_CAP_BYTES;
82
-
83
- const matched: { filename: string; fullPath: string; size: number }[] = [];
84
- for (const filename of filenames) {
85
- const fullPath = join(cwd, filename);
86
- if (!existsSync(fullPath)) continue;
87
- try {
88
- const st = await stat(fullPath);
89
- if (!st.isFile()) continue;
90
- matched.push({ filename, fullPath, size: st.size });
91
- } catch {}
92
- }
93
-
94
- if (matched.length === 0) {
95
- return { files: [], totalBytes: 0, prompt: "" };
96
- }
97
-
98
- const files: LoadedMemoryFile[] = [];
99
- let remaining = cap;
100
- for (const m of matched) {
101
- if (remaining <= 0) break;
102
- let content: string;
103
- try {
104
- content = await readFile(m.fullPath, "utf-8");
105
- } catch {
106
- continue;
107
- }
108
- let truncated = false;
109
- const contentBytes = Buffer.byteLength(content, "utf8");
110
- if (contentBytes > remaining) {
111
- // Truncate at the byte cap, then append a notice.
112
- const buf = Buffer.from(content, "utf-8").subarray(0, remaining);
113
- content = `${buf.toString("utf-8")}\n\n[...truncated to ${remaining} bytes; ${
114
- contentBytes - remaining
115
- } bytes omitted]`;
116
- truncated = true;
117
- }
118
- // Pillar 3: classify with origin "user" — `pass` policy runs the
119
- // classifier and emits trace events without modifying content.
120
- await classifyBoundary(content, { origin: "user" }).catch(() => undefined);
121
- files.push({ filename: m.filename, content, truncated });
122
- remaining -= Buffer.byteLength(content, "utf8");
123
- }
124
-
125
- const sections = files
126
- .map((f) => `<project_memory file="${f.filename}">\n${f.content}\n</project_memory>`)
127
- .join("\n\n");
128
-
129
- return {
130
- files,
131
- totalBytes: files.reduce((sum, f) => sum + Buffer.byteLength(f.content, "utf8"), 0),
132
- prompt: sections,
133
- };
134
- }
@@ -1,80 +0,0 @@
1
- import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2
- import { buildTenant, withTenant } from "@crewhaus/tenancy";
3
- import { resolveSessionRootDir, resolveToolResultRoot } from "./index";
4
-
5
- // Regression — issue #142 (CWE-1230). The managed daemon wraps every gateway
6
- // request in `withTenant(...)`; runtime-core must resolve its session/event-log
7
- // root from that ambient tenant context so two tenants' transcripts never share
8
- // a directory. These tests pin the resolution contract directly (no model loop).
9
-
10
- const ENV_KEYS = ["CREWHAUS_SESSION_DIR"] as const;
11
- const ORIGINAL_ENV: Record<string, string | undefined> = {};
12
-
13
- beforeEach(() => {
14
- for (const key of ENV_KEYS) {
15
- ORIGINAL_ENV[key] = process.env[key];
16
- delete process.env[key];
17
- }
18
- });
19
-
20
- afterEach(() => {
21
- for (const [key, value] of Object.entries(ORIGINAL_ENV)) {
22
- if (value === undefined) delete process.env[key];
23
- else process.env[key] = value;
24
- }
25
- });
26
-
27
- describe("resolveSessionRootDir — tenant isolation (#142)", () => {
28
- test("each tenant resolves to its own disjoint sessionRoot", () => {
29
- const a = buildTenant("tenant-a", { tenantsRoot: "/tmp/ch-tenant-test" });
30
- const b = buildTenant("tenant-b", { tenantsRoot: "/tmp/ch-tenant-test" });
31
-
32
- const rootA = withTenant(a, () => resolveSessionRootDir(undefined)) as string;
33
- const rootB = withTenant(b, () => resolveSessionRootDir(undefined)) as string;
34
-
35
- expect(rootA).toBe(a.sessionRoot);
36
- expect(rootB).toBe(b.sessionRoot);
37
- expect(rootA).not.toBe(rootB);
38
- // Neither tenant's transcripts can land under the other's root.
39
- expect(rootA.startsWith(`${rootB}/`)).toBe(false);
40
- expect(rootB.startsWith(`${rootA}/`)).toBe(false);
41
- });
42
-
43
- test("does NOT fall back to the global default inside a tenant scope", () => {
44
- process.env["CREWHAUS_SESSION_DIR"] = "/tmp/GLOBAL-shared";
45
- const a = buildTenant("tenant-a", { tenantsRoot: "/tmp/ch-tenant-test" });
46
- const root = withTenant(a, () => resolveSessionRootDir(undefined)) as string;
47
- expect(root).toBe(a.sessionRoot);
48
- expect(root).not.toBe("/tmp/GLOBAL-shared");
49
- });
50
-
51
- test("outside any tenant scope, honours env then undefined (unchanged behaviour)", () => {
52
- expect(resolveSessionRootDir(undefined)).toBeUndefined();
53
- process.env["CREWHAUS_SESSION_DIR"] = "/tmp/env-root";
54
- expect(resolveSessionRootDir(undefined)).toBe("/tmp/env-root");
55
- });
56
-
57
- test("an explicit per-call root still wins (trusted caller override)", () => {
58
- const a = buildTenant("tenant-a", { tenantsRoot: "/tmp/ch-tenant-test" });
59
- const root = withTenant(a, () => resolveSessionRootDir("/tmp/explicit")) as string;
60
- expect(root).toBe("/tmp/explicit");
61
- });
62
- });
63
-
64
- // Regression — issue #150 (CWE-1230). The tool-result spill store must be
65
- // rebased per tenant too, not just the session store.
66
- describe("resolveToolResultRoot — tenant isolation (#150)", () => {
67
- test("each tenant resolves to its own toolResultRoot, disjoint", () => {
68
- const a = buildTenant("tenant-a", { tenantsRoot: "/tmp/ch-tenant-test" });
69
- const b = buildTenant("tenant-b", { tenantsRoot: "/tmp/ch-tenant-test" });
70
- const rootA = withTenant(a, () => resolveToolResultRoot()) as string;
71
- const rootB = withTenant(b, () => resolveToolResultRoot()) as string;
72
- expect(rootA).toBe(a.toolResultRoot);
73
- expect(rootB).toBe(b.toolResultRoot);
74
- expect(rootA).not.toBe(rootB);
75
- });
76
-
77
- test("outside a tenant scope, returns undefined (tool-result-store default applies)", () => {
78
- expect(resolveToolResultRoot()).toBeUndefined();
79
- });
80
- });