Skip to content

Commit 6e7ec2c

Browse files
n0mahdclaude
andcommitted
fix(server): read instruction files only under a registered project's folder
Only a write checked that the folder was a project: a read took any absolute folder, so with `cwd: "/"` an id like `project:nested:home/me/notes/AGENTS.md` read any AGENTS.md or CLAUDE.md on the machine. The catalog now refuses a folder that isn't a registered project's workspace root, in `resolve`, `list` and so `read`, before it reads anything, and the git tracking check refuses it too. The home files, which have no folder, are read as before. The manager's own check is gone, since every write resolves its id through the catalog. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
1 parent c0d1557 commit 6e7ec2c

7 files changed

Lines changed: 148 additions & 45 deletions

File tree

‎apps/server/src/instructions/InstructionCatalog.test.ts‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -869,6 +869,61 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("InstructionCatalog"
869869
}),
870870
);
871871

872+
it.effect("reads under a folder only when it is a registered project's workspace root", () =>
873+
Effect.gen(function* () {
874+
const { home, project, write } = yield* makeMachine;
875+
yield* write(".agents/AGENTS.md", "shared text");
876+
yield* write("repos/app/AGENTS.md", "project text");
877+
yield* write("elsewhere/AGENTS.md", "not a project's");
878+
yield* onMachine(home, CLAUDE, (catalog) =>
879+
Effect.gen(function* () {
880+
const refusal = (cwd: string, id: string) =>
881+
catalog.read({ cwd, id }).pipe(
882+
Effect.flip,
883+
Effect.map((error) => [error._tag, error.reason]),
884+
);
885+
const unregistered = ["unregisteredProject"];
886+
887+
// A folder above the project, one beside it, and a relative one reach no file under
888+
// them, even by an id the table builds.
889+
expect(yield* refusal(home, "project:nested:elsewhere/AGENTS.md")).toEqual([
890+
"InstructionError",
891+
...unregistered,
892+
]);
893+
expect(yield* refusal(`${home}/elsewhere`, "project:shared:AGENTS.md")).toEqual([
894+
"InstructionError",
895+
...unregistered,
896+
]);
897+
expect(yield* refusal("repos/app", "project:shared:AGENTS.md")).toEqual([
898+
"InstructionError",
899+
...unregistered,
900+
]);
901+
expect(
902+
yield* catalog.list({ cwd: home }).pipe(
903+
Effect.flip,
904+
Effect.map((error) => error.reason),
905+
),
906+
).toBe("unregisteredProject");
907+
expect(
908+
yield* catalog.resolve({ cwd: home, id: "project:shared:AGENTS.md" }).pipe(
909+
Effect.flip,
910+
Effect.map((error) => error.reason),
911+
),
912+
).toBe("unregisteredProject");
913+
914+
// The registered folder, and the home files without any folder, read as before.
915+
expect(
916+
(yield* catalog.read({ cwd: project, id: "project:shared:AGENTS.md" })).contents,
917+
).toBe("project text");
918+
expect((yield* catalog.read({ id: "global:shared" })).contents).toBe("shared text");
919+
expect(
920+
(yield* catalog.list({})).entries.some((entry) => entry.scope === "global"),
921+
).toBe(true);
922+
}),
923+
);
924+
}),
925+
);
926+
872927
it.effect("refuses ids the table doesn't have", () =>
873928
Effect.gen(function* () {
874929
const { home, project } = yield* makeMachine;

‎apps/server/src/instructions/InstructionCatalog.ts‎

Lines changed: 36 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
5050
import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
5151
import { AGENT_SKILL_FOLDERS } from "@t3tools/provider-core/server/AgentSkillFolders";
5252

53+
import * as ProjectService from "../project/ProjectService.ts";
5354
import { deriveProviderInstanceConfigMap } from "../provider/ProviderInstanceRegistryHydration.ts";
5455
import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
5556
import * as Settings from "../serverSettings.ts";
@@ -183,8 +184,12 @@ export class InstructionCatalog extends Context.Service<
183184
/**
184185
* The instruction files in the project's top folder (when `cwd` is given) and the user's home
185186
* folder, with the agents that read each. Subfolder files come from the project's file index.
187+
* A `cwd` that isn't a registered project's workspace root is refused, here and in `read` and
188+
* `resolve`, before anything under it is read.
186189
*/
187-
readonly list: (input: InstructionListInput) => Effect.Effect<InstructionListResult>;
190+
readonly list: (
191+
input: InstructionListInput,
192+
) => Effect.Effect<InstructionListResult, InstructionError>;
188193
/** The text of one file from `list`, or nothing when it is missing or too large. */
189194
readonly read: (
190195
input: InstructionReadInput,
@@ -207,6 +212,7 @@ const make = Effect.gen(function* () {
207212
const serverSettings = yield* Settings.ServerSettingsService;
208213
const providers = yield* ProviderRegistry.ProviderRegistry;
209214
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
215+
const projects = yield* ProjectService.ProjectService;
210216
const fileSystemContext = yield* Effect.context<FileSystem.FileSystem | Path.Path>();
211217
const homeDirectory =
212218
(platform === "win32" ? environment.USERPROFILE : environment.HOME)?.trim() || NodeOS.homedir();
@@ -228,8 +234,33 @@ const make = Effect.gen(function* () {
228234
};
229235
type TextReader = ReturnType<typeof makeTextReader>;
230236

231-
const absoluteCwd = (cwd: string | undefined) =>
232-
cwd !== undefined && path.isAbsolute(cwd) ? cwd : undefined;
237+
/**
238+
* A project's folder is only read when it is the workspace root of a project the environment
239+
* knows, so an id can't name a file under any path on the machine. Without a `cwd` only the
240+
* agents' home files are reachable.
241+
*/
242+
const requireProject = Effect.fnUntraced(function* (cwd: string | undefined) {
243+
if (cwd === undefined) return undefined;
244+
// The lookup resolves a relative path against the server's own folder, so it never sees one.
245+
const project = path.isAbsolute(cwd)
246+
? yield* projects.getByWorkspaceRoot(cwd).pipe(
247+
Effect.catchTags({
248+
// A folder that is gone or isn't a folder can't be a project's root.
249+
ProjectOperationError: (error) =>
250+
error.operation === "normalize-workspace"
251+
? Effect.succeed(Option.none<never>())
252+
: Effect.die(error),
253+
}),
254+
)
255+
: Option.none();
256+
if (Option.isNone(project)) {
257+
return yield* new InstructionError({
258+
reason: "unregisteredProject",
259+
message: "That folder isn't a project in this environment.",
260+
});
261+
}
262+
return cwd;
263+
});
233264

234265
const sizeOf = Effect.fnUntraced(function* (file: string) {
235266
const info = yield* fileSystem.stat(file).pipe(Effect.option);
@@ -687,7 +718,7 @@ const make = Effect.gen(function* () {
687718
function* (input) {
688719
const [scope = "", kind = "", ...tail] = input.id.split(":");
689720
const rest = tail.join(":");
690-
const cwd = absoluteCwd(input.cwd);
721+
const cwd = yield* requireProject(input.cwd);
691722

692723
if (scope === "project") {
693724
if (cwd === undefined) return yield* unknownEntry();
@@ -785,7 +816,7 @@ const make = Effect.gen(function* () {
785816

786817
const list: InstructionCatalog["Service"]["list"] = Effect.fn("InstructionCatalog.list")(
787818
function* (input) {
788-
const cwd = absoluteCwd(input.cwd);
819+
const cwd = yield* requireProject(input.cwd);
789820
const textOf = makeTextReader();
790821
const instances = yield* loadInstances(cwd);
791822
const claudeInstances = instances.filter((instance) => instance.driver === CLAUDE_DRIVER);

‎apps/server/src/instructions/InstructionManager.test.ts‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -779,7 +779,7 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("InstructionManager"
779779
expect(nested.reason).toBe("unknownEntry");
780780
}),
781781
);
782-
yield* onMachine(home, CLAUDE, ({ manager }) =>
782+
yield* onMachine(home, { ...CLAUDE, registered: [] }, ({ manager }) =>
783783
Effect.gen(function* () {
784784
const unregistered = yield* manager
785785
.share({ cwd: project, id: "project:claude:CLAUDE.md", merge: false })
@@ -1111,7 +1111,7 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("InstructionManager"
11111111
expect(yield* read(".agents/AGENTS.md")).toBe("global shared");
11121112
}),
11131113
);
1114-
yield* onMachine(home, CLAUDE, ({ manager }) =>
1114+
yield* onMachine(home, { ...CLAUDE, registered: [] }, ({ manager }) =>
11151115
Effect.gen(function* () {
11161116
const error = yield* manager
11171117
.delete({ cwd: project, id: "project:claude:CLAUDE.md" })
@@ -1186,6 +1186,21 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("InstructionManager"
11861186
}).pipe(Effect.provide(ProcessRunner.layer)),
11871187
);
11881188

1189+
it.effect("refuses a folder that isn't a registered project, without running git", () =>
1190+
Effect.gen(function* () {
1191+
const { home, project, write } = yield* makeMachine;
1192+
yield* write("repos/app/AGENTS.md", "x");
1193+
yield* onMachine(home, { ...CLAUDE, registered: [] }, ({ tracking }) =>
1194+
Effect.gen(function* () {
1195+
const error = yield* tracking
1196+
.tracked({ cwd: project, ids: ["project:shared:AGENTS.md"] })
1197+
.pipe(Effect.flip);
1198+
expect(error.reason).toBe("unregisteredProject");
1199+
}),
1200+
);
1201+
}),
1202+
);
1203+
11891204
it.effect("counts nothing as tracked outside a repository", () =>
11901205
Effect.gen(function* () {
11911206
const { home, project, write } = yield* makeMachine;

‎apps/server/src/instructions/InstructionManager.ts‎

Lines changed: 7 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@
22
* InstructionManager - changes instruction files and who reads them.
33
*
44
* Every write starts from the id the client sent, which `InstructionCatalog.resolve` looks up in
5-
* the table again, so a client can only reach files the table names. Writes run one request at a
6-
* time, and a project file is only written when its folder is a registered project.
5+
* the table again, so a client can only reach files the table names, and only the files of a
6+
* registered project's folder, which the catalog checks. Writes run one request at a time.
77
*
88
* - A file's text is replaced at its real path behind any links, by temp file and rename, and only
99
* if its revision is still the one the client read.
@@ -42,7 +42,6 @@ import type * as PlatformError from "effect/PlatformError";
4242
import * as Semaphore from "effect/Semaphore";
4343
import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
4444

45-
import * as ProjectService from "../project/ProjectService.ts";
4645
import { editJsoncFile, readSettingsText } from "../skills/JsoncSettings.ts";
4746
import { excludeNewFile } from "../skills/SkillGitExclude.ts";
4847
import { removeLink } from "../skills/SkillLinks.ts";
@@ -129,7 +128,6 @@ const make = Effect.gen(function* () {
129128
const fileSystem = yield* FileSystem.FileSystem;
130129
const path = yield* Path.Path;
131130
const catalog = yield* InstructionCatalog.InstructionCatalog;
132-
const projects = yield* ProjectService.ProjectService;
133131
const writeLock = yield* Semaphore.make(1);
134132
const fileSystemContext = yield* Effect.context<
135133
FileSystem.FileSystem | Path.Path | VcsProcess.VcsProcess
@@ -185,25 +183,6 @@ const make = Effect.gen(function* () {
185183
cannotWrite(file),
186184
);
187185

188-
/** Project files are only written under a folder the environment knows as a project. */
189-
const requireProject = (cwd: string | undefined) =>
190-
cwd === undefined
191-
? Effect.fail(refuse("unknownEntry", "That isn't an instruction file T3 Code manages."))
192-
: projects.getByWorkspaceRoot(cwd).pipe(
193-
Effect.orDie,
194-
Effect.filterOrFail(Option.isSome, () =>
195-
refuse("unregisteredProject", "That folder isn't a project in this environment."),
196-
),
197-
);
198-
199-
const resolveEntry = Effect.fnUntraced(function* (input: {
200-
readonly cwd?: string | undefined;
201-
readonly id: string;
202-
}) {
203-
if (input.id.startsWith("project:")) yield* requireProject(input.cwd);
204-
return yield* catalog.resolve(input);
205-
});
206-
207186
const importTargetOf = (
208187
claudeMd: string,
209188
view: InstructionCatalog.SharedView,
@@ -220,7 +199,7 @@ const make = Effect.gen(function* () {
220199
function* (input) {
221200
return yield* writeLock.withPermits(1)(
222201
Effect.gen(function* () {
223-
const entry = yield* resolveEntry(input);
202+
const entry = yield* catalog.resolve(input);
224203
if (entry.readOnly) {
225204
return yield* refuse("readOnly", "That file is set by your organization.");
226205
}
@@ -425,7 +404,7 @@ const make = Effect.gen(function* () {
425404
) =>
426405
writeLock.withPermits(1)(
427406
Effect.gen(function* () {
428-
const entry = yield* resolveEntry(input);
407+
const entry = yield* catalog.resolve(input);
429408
if (entry.scope !== "global" || entry.kind !== "shared") {
430409
return yield* refuse(
431410
"unknownEntry",
@@ -481,7 +460,7 @@ const make = Effect.gen(function* () {
481460
function* (input) {
482461
yield* writeLock.withPermits(1)(
483462
Effect.gen(function* () {
484-
const entry = yield* resolveEntry(input);
463+
const entry = yield* catalog.resolve(input);
485464
if (entry.kind !== "claude" || entry.relativePath !== "CLAUDE.md") {
486465
return yield* refuse("unknownEntry", "Only a project's CLAUDE.md can be shared.");
487466
}
@@ -543,7 +522,7 @@ const make = Effect.gen(function* () {
543522
function* (input) {
544523
yield* writeLock.withPermits(1)(
545524
Effect.gen(function* () {
546-
const entry = yield* resolveEntry(input);
525+
const entry = yield* catalog.resolve(input);
547526
if (entry.kind !== "agentOwn" || entry.owner === undefined) {
548527
return yield* refuse("unknownEntry", "Only an agent's own instructions can be moved.");
549528
}
@@ -610,7 +589,7 @@ const make = Effect.gen(function* () {
610589
function* (input) {
611590
yield* writeLock.withPermits(1)(
612591
Effect.gen(function* () {
613-
const entry = yield* resolveEntry(input);
592+
const entry = yield* catalog.resolve(input);
614593
if (entry.readOnly) {
615594
return yield* refuse("readOnly", "That file is set by your organization.");
616595
}

‎apps/server/src/instructions/InstructionTracking.ts‎

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,16 @@
88
*
99
* @module InstructionTracking
1010
*/
11-
import type { InstructionTrackedInput, InstructionTrackedResult } from "@t3tools/contracts";
11+
import type {
12+
InstructionError,
13+
InstructionTrackedInput,
14+
InstructionTrackedResult,
15+
} from "@t3tools/contracts";
1216
import * as Context from "effect/Context";
1317
import * as Effect from "effect/Effect";
1418
import * as FileSystem from "effect/FileSystem";
1519
import * as Layer from "effect/Layer";
20+
import * as Option from "effect/Option";
1621
import * as Path from "effect/Path";
1722

1823
import { trackedFiles } from "../vcs/GitTrackedFiles.ts";
@@ -26,9 +31,11 @@ export class InstructionTracking extends Context.Service<
2631
* The ids among `ids` of project files that git tracks. An id that doesn't name a project
2732
* file, a file that sits outside the repository, and every file when git fails count as not
2833
* tracked. A file is tracked by its own path, so a link git tracks counts, whatever it
29-
* points at.
34+
* points at. A folder that isn't a registered project's workspace root is refused.
3035
*/
31-
readonly tracked: (input: InstructionTrackedInput) => Effect.Effect<InstructionTrackedResult>;
36+
readonly tracked: (
37+
input: InstructionTrackedInput,
38+
) => Effect.Effect<InstructionTrackedResult, InstructionError>;
3239
}
3340
>()("t3/instructions/InstructionTracking") {}
3441

@@ -48,8 +55,17 @@ const make = Effect.gen(function* () {
4855
// The path git knows each file by, from the project's real folder.
4956
const files = new Map<string, string>();
5057
for (const id of input.ids) {
51-
const entry = yield* catalog.resolve({ cwd: input.cwd, id }).pipe(Effect.option);
52-
if (entry._tag === "None" || entry.value.scope !== "project") continue;
58+
const entry = yield* catalog.resolve({ cwd: input.cwd, id }).pipe(
59+
Effect.map(Option.some),
60+
Effect.catchTags({
61+
// An id that names nothing here is just not tracked; the folder is refused outright.
62+
InstructionError: (error) =>
63+
error.reason === "unregisteredProject"
64+
? Effect.fail(error)
65+
: Effect.succeed(Option.none()),
66+
}),
67+
);
68+
if (Option.isNone(entry) || entry.value.scope !== "project") continue;
5369
const folder = yield* fileSystem
5470
.realPath(path.dirname(entry.value.path))
5571
.pipe(Effect.orElseSucceed(() => path.dirname(entry.value.path)));

‎apps/server/src/instructions/testing/machine.ts‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -56,14 +56,17 @@ export const makeProject = (workspaceRoot: string): Project => ({
5656
deletedAt: null,
5757
});
5858

59+
/** The machine's own project, in its home folder. */
60+
const PROJECT_FOLDER = "repos/app";
61+
5962
/** A temp home folder, with helpers to put files and links in it, and a project folder. */
6063
export const makeMachine = Effect.gen(function* () {
6164
const fs = yield* FileSystem.FileSystem;
6265
const path = yield* Path.Path;
6366
const home = yield* fs.realPath(
6467
yield* fs.makeTempDirectoryScoped({ prefix: "t3code-instructions-" }),
6568
);
66-
const project = path.join(home, "repos/app");
69+
const project = path.join(home, PROJECT_FOLDER);
6770
yield* fs.makeDirectory(project, { recursive: true });
6871
const write = (relative: string, contents: string) =>
6972
Effect.gen(function* () {
@@ -81,7 +84,7 @@ export const makeMachine = Effect.gen(function* () {
8184
});
8285

8386
export interface MachineOptions {
84-
/** Folders that are projects. */
87+
/** Folders that are projects; the machine's own project when absent. */
8588
readonly registered?: readonly string[];
8689
/** Claude Code's version, by instance id; absent means the status has no version. */
8790
readonly versions?: Readonly<Record<string, string>>;
@@ -118,7 +121,11 @@ const snapshotOf = (
118121
* project folder that matches names exactly, skipping `.git` and `node_modules`.
119122
*/
120123
export const layerFor = (home: string, options: MachineOptions = {}) => {
121-
const registered = options.registered ?? [];
124+
const sameFolder = (a: string, b: string) => a.replaceAll("\\", "/") === b.replaceAll("\\", "/");
125+
const isProject = (root: string) =>
126+
options.registered === undefined
127+
? sameFolder(root, `${home}/${PROJECT_FOLDER}`)
128+
: options.registered.some((folder) => sameFolder(folder, root));
122129
const versions = options.versions ?? {};
123130
const enabled = Object.fromEntries(
124131
(options.providers ?? ["cursor", "grok", "opencode", "antigravity", "pi"]).map((id) => [
@@ -139,7 +146,7 @@ export const layerFor = (home: string, options: MachineOptions = {}) => {
139146
});
140147
const projects = Layer.mock(ProjectService.ProjectService)({
141148
getByWorkspaceRoot: (root) =>
142-
Effect.succeed(registered.includes(root) ? Option.some(makeProject(root)) : Option.none()),
149+
Effect.succeed(isProject(root) ? Option.some(makeProject(root)) : Option.none()),
143150
});
144151
const index = Layer.effect(
145152
WorkspaceEntries.WorkspaceEntries,

‎apps/server/src/mcp/toolkits/instructions/handlers.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ export const layer = McpToolAccess.toLayer(InstructionsToolkit, {
4343
const context = yield* readCaller();
4444
const cwd = yield* projectFolder(context, input.projectId);
4545
const catalog = yield* InstructionCatalog.InstructionCatalog;
46-
return yield* catalog.list({ cwd });
46+
return yield* catalog.list({ cwd }).pipe(Effect.mapError(instructionFailure));
4747
}),
4848
),
4949
t3_instructions_get: McpToolAccess.reads(({ projectId, id }) =>

0 commit comments

Comments
 (0)