Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
fix(mcp): one project validator, dirent budgets, resumable caps
rahmanef632160f5b9586a
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 01aab25d..adc94451 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -14,6 +14,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.**Fixed**+- `mcp` one project validator, dirent budgets, resumable caps- `mcp` contain, bound and uniquely identify project discovery- `mcp` make ChatGPT file imports region agnostic- `mcp` allow ChatGPT India South Central file storagediff --git a/docs/CONNECTORS-GATEWAY-INTEGRATION.md b/docs/CONNECTORS-GATEWAY-INTEGRATION.mdindex 816aa5ae..9a4817c9 100644--- a/docs/CONNECTORS-GATEWAY-INTEGRATION.md+++ b/docs/CONNECTORS-GATEWAY-INTEGRATION.md@@ -4,7 +4,7 @@## Cross-repo contract-MSO currently exposes **26 tool names** (server `1.5.1`, toolset `2026.08.20.4`). The gateway manifest still maps **15** of them through literal `x-upstream` strings:+MSO currently exposes **26 tool names** (server `1.5.2`, toolset `2026.08.20.5`). The gateway manifest still maps **15** of them through literal `x-upstream` strings:```json{ "id": "mso.fs.delete", "x-upstream": "fs_delete" }diff --git a/docs/MCP.md b/docs/MCP.mdindex 7698989a..cc69cb85 100644--- a/docs/MCP.md+++ b/docs/MCP.md@@ -104,8 +104,8 @@ The catalog has a stable server version plus a schema-derived toolset signature.Settings → MCP shows the current version/hash/count and stores a browser-local acknowledgement when the operator marks ChatGPT refreshed. A later signature change becomes an explicit stale-snapshot warning. This does not mutate ChatGPT remotely; it makes the required refresh visible instead of relying on memory.-Current catalog: **26 tools** (14 read, 10 write, 2 exec), server `1.5.1` / toolset-`2026.08.20.4`. `projects_list`, `skills_list` and `skills_read` are the new public+Current catalog: **26 tools** (14 read, 10 write, 2 exec), server `1.5.2` / toolset+`2026.08.20.5`. `projects_list`, `skills_list` and `skills_read` are the new publicnames in this release; `image_generation_status` and `image_generate` were removed(see the migration note below).@@ -127,20 +127,39 @@ when it currently points somewhere legal: accepting it is a TOCTOU bet, becausecan be repointed between the check and the walk. `/` is never a container — "/" as a readroot means browse-anywhere, not "every top-level system directory is a project".-Every project candidate must then be a real, non-hidden, non-symlink directory whose-realpath is still inside its exact container *and* inside an authorized root, owned by-the uid MSO runs as. Ownership is checked **before** any metadata read, so a directory-another user controls never reaches the `package.json` or `.git` readers at all.+**One validator decides, everywhere** (`lib/host/project-candidate.ts`). Enumeration and+*every* `resolveProjectHint` strategy — path, exact name, alias, package, fuzzy — go+through it, so a hint can never reach something `projects_list` refuses to show. It+rejects, in order: a hidden component; a symlinked component (target legal or not — a+link is not a child of this container); an escape from the container or from every+authorized root; a credential path; and a directory not owned by the uid MSO runs as.+Ownership is checked **before** any metadata read, so a directory another user controls+never reaches the `package.json` or `.git` readers at all. A path hint is validated+component by component from the container down, because canonicalizing first and checking+afterwards is exactly what let a symlinked intermediate through.++A caller-supplied `rootHint` gets the same treatment: a symlinked or hidden root is+refused rather than canonicalized into something the caller never named. It is authorized+against *every* configured read root rather than the scan-capped subset — naming a root+never widens the jail, but the jail must not shrink because twelve other roots were+configured ahead of it.### Bounds, and telling the truth about themEvery scan is bounded: 12 containers, 400 entries read per container, 400 projects,60 projects scanned for skills, 200 entries per skill root, 300 project skills, and a4-second wall clock on each of the two walks. Directory iteration uses `opendir` and-stops at the cap rather than materializing the whole listing first. Every metadata read-goes through one byte-capped, `O_NOFOLLOW` reader (`lib/host/bounded-read.ts`): the cap-is checked against `fstat` *before* any bytes move, so an oversized `package.json`,-`SKILL.md` or `packed-refs` costs one stat, not its size.+stops at the cap rather than materializing the whole listing first, and **every dirent+counts against the cap whether or not it is accepted** — counting only the entries we+kept meant a container of a million regular files still cost a million iterations before+the "400 entry" cap was reached. The deadline is enforced *through* the per-entry+`lstat`/`realpath`/metadata work too, which is where a slow or networked filesystem+actually spends its time. The overall project-skill cap is enforced inside the candidate+loop, not merely before each root, so one root cannot carry the total past it.++Every metadata read goes through one byte-capped, `O_NOFOLLOW` reader+(`lib/host/bounded-read.ts`): the cap is checked against `fstat` *before* any bytes move,+so an oversized `package.json`, `SKILL.md` or `packed-refs` costs one stat, not its size.`projects_list`, `skills_list`, `skills_search` and `workflow_start` all return a**scan report**. `truncated:false` means "this is all of it"; hitting any cap sets@@ -149,11 +168,23 @@ is checked against `fstat` *before* any bytes move, so an oversized `package.jsoand a count of entries rejected by the containment/ownership checks. **Do not conclude aproject or skill is absent from a truncated scan** — the tool descriptions say so too.+**Every cap is resumable.** A truncated report carries `scan.continuation` with the+containers still pending, a per-container cursor, and an opaque `cursor` string to pass+back as the `cursor` argument to `projects_list` / `skills_list`. Cursors are positional+in readdir order (`cursorSemantics: "readdir-position"`) and are valid while the+directories are unchanged — making them name-ordered would require visiting every dirent+to find the next N names, which is the unbounded walk the entry cap exists to prevent.+Ordinary paging *within* one scan uses `offset`/`limit` with `hasMore`/`nextOffset`.+### Ids, so nothing shadows anythingA global skill is addressed by bare name. A project is `<rootId>/<name>` and a project-skill is `<rootId>/<project>/<name>`, where `rootId` is a short sha256 of the canonical-container path. That makes ids **globally unique**: two configured roots may each hold a+skill is `<rootId>/<project>/<name>`, where `rootId` is **128 bits** (32 hex characters)+of sha256 over the canonical container path. It was 32 bits, and a review found a real+collision — `/tmp/mso-root-50323` and `/tmp/mso-root-125549` both hashed to `51e156ef` —+which would have merged two roots' same-named projects back into one row. Belt and+braces, nothing dedupes on the hash: the internal key is the full canonical path, so even+a collision cannot merge two containers. That makes ids **globally unique**: two configured roots may each hold a`widget` shipping `deploy`, and both stay visible, readable and searchable. The derived`projects/` container gets its own `rootId` for the same reason, so `~/widget` and`~/projects/widget` cannot collide either. Within one project, `.mso/skills` outranks the@@ -186,6 +217,14 @@ back *inside* its project; the directory and its `SKILL.md` are owned by MSO's umetadata visible, instructions withheld until the operator reviews it and moves it into`~/.mso/skills`. The generic HOME agent roots keep their existing untrusted behaviour.+The `SKILL.md` reader is `O_NOFOLLOW` **at the supplied path**, not at a canonicalized+substitute. It previously realpath'd first and opened the *target*, so a+`SKILL.md -> other/SKILL.md` symlink passed the basename check and was read — the nofollow+promise enforced against a path the caller never gave. A symlinked `SKILL.md` is now not a+skill at all: it is dropped from the catalog rather than listed as untrusted. Parent+containment is validated separately, precisely so the final component is never dragged+through `realpath` again.+`workflow_start` and `skills_search` search this unified catalog; every skill hit carriesits `project`, and the bootstrap carries a `discovery.complete` flag plus a`[Discovery] partial scan` trace line when the catalog was truncated.diff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex 1464253e..4fb9016f 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -8,6 +8,67 @@ Running log of what shipped each phase. Newest at top.> Read those phases as history. **This file is the source of truth for what exists** —> `ARCHITECTURE.md` is no longer maintained and carries a stale-warning banner.+## 2026-08-20 — one validator, dirent-counted budgets, resumable caps (DONE)++A second fail-closed re-review of the discovery hardening found six things still open.+Five of them share a shape: a rule enforced in *one* code path and assumed everywhere+else.++**UID and symlink rules existed only in the walk.** `listProjectDirs()` rejected a+project owned by another uid, but `resolveProjectHint`'s exact-name, alias and path+strategies did not — so `workflow_start` could resolve, and read metadata from, a project+`projects_list` correctly refused to show. `rootHint` went through `resolveReadable()`,+which canonicalizes and therefore *follows* a symlinked root, and a path hint accepted+hidden or symlink-reached directories inside it. There is now ONE validator+(`lib/host/project-candidate.ts`) and every strategy calls it: hidden component, symlinked+component (target legal or not), container/authorized-root escape, credential path, uid+ownership — ownership before any metadata read. A path hint is checked component by+component from the container down, because canonicalizing first and validating afterwards+is precisely what let a symlinked intermediate through. `rootHint` is validated the same+way, and authorized against *every* configured read root rather than the scan-capped+subset, so naming a root neither widens the jail nor shrinks it.++**`readSkillFile` was nofollow at the wrong path.** It realpath'd the supplied path, saw a+basename of `SKILL.md`, and opened the *target* with `O_NOFOLLOW` — enforcing the promise+against a path the caller never gave us. A `SKILL.md -> other/SKILL.md` symlink sailed+through. The supplied path is now opened directly, so any symlink at that component fails+with ELOOP; parent containment is a separate check, kept separate so the final component+is never dragged back through `realpath`. A symlinked `SKILL.md` is no longer an untrusted+skill — it is not a skill, and it is dropped from the catalog.++**Budgets counted the wrong thing.** Both walks incremented their entry cap only for+*accepted* entries, so a container holding a million regular files still cost a million+iterations before the "400 entry" cap was reached — the cap bounded the result, not the+work. Every dirent now consumes budget, and the deadline is enforced through the+per-entry `lstat`/`realpath`/metadata work as well as the dirent loop. The overall+300-project-skill cap moved inside the candidate loop; checking it only before each root+let one root carry the total from just under 300 to nearly 500.++**Caps were reported but not continuable.** A truncated scan named its reason and stopped.+Every cap now emits `scan.continuation`: pending roots, per-root cursors, and an opaque+`cursor` to pass back to `projects_list` / `skills_list` to resume where the walk stopped.+Cursors are positional in readdir order and say so — name-ordered resume would require+visiting every dirent, which is the unbounded walk the cap exists to prevent. Ordinary+paging within one scan gained `hasMore`/`nextOffset`.++**Eight hex characters is not a unique id.** `rootId` was 32 bits of sha256, and a probe+found a genuine collision: `/tmp/mso-root-50323` and `/tmp/mso-root-125549` both hash to+`51e156ef`, which would have merged two roots' same-named projects back into one row —+the exact bug root-qualified ids were introduced to fix. It is 128 bits now, both sides+share one `shortId` rather than each computing its own, and nothing dedupes on the hash at+all: the internal key is the full canonical path, so even a collision cannot merge two+containers. The collision pair is a regression fixture.++Regressions cover each: exact/path/alias uid mismatch, symlinked and hidden `rootHint`+and path hints, `SKILL.md -> SKILL.md`, a root of non-directory entries exhausting the+cap, `maxProjectSkills` overshoot, resumable continuation for entry and project caps, and+the deliberate root-id collision. The positive suites are unchanged and green:+all-agents-all-tools, the exec/read/write ladder, image generation removed everywhere, and+`fs_upload_file` with regional ChatGPT import. `project-candidate.ts`, `project-cursor.ts`,+`project-list.ts` and `project-scan-types.ts` split the work so every file stays under 200+lines. The MCP server/toolset advance to `1.5.2` / `2026.08.20.5`; the catalog stays at+**26 tools** (14 read, 10 write, 2 exec).+## 2026-08-20 — discovery containment, honest bounds and unique ids (DONE)A fail-closed review of the discovery release found three things worth blocking on, anddiff --git a/frontend/slices/assistant/CONTRACT.md b/frontend/slices/assistant/CONTRACT.mdindex 696b6b9d..4c0e12bc 100644--- a/frontend/slices/assistant/CONTRACT.md+++ b/frontend/slices/assistant/CONTRACT.md@@ -89,9 +89,9 @@ The model reaches trusted skills through the `skills.list`, `skills.search` andevery configured project container (each `OS_FS_READ_ROOTS` entry and its `projects/`child), from `.mso/skills`, `.claude/skills`, `.hermes/skills`, `.agents/skills` and`.codex/skills`. A global skill's id is its bare name; a project skill's is-`<rootId>/<project>/<name>`, where `rootId` is a short hash of the canonical container-path — so two projects with the same basename in *different* configured roots stay-distinct, and neither can shadow an operator or official skill. A project skill earns+`<rootId>/<project>/<name>`, where `rootId` is a 128-bit hash of the canonical container+path (32 bits collided in practice) — so two projects with the same basename in+*different* configured roots stay distinct, and neither can shadow an operator or official skill. A project skill earns`local` trust only after realpath containment inside its project, ownership by MSO's uid,and a regular non-symlink `SKILL.md`; the generic HOME agent roots stay untrusted.`skills.read` takes the exact id and refuses an ambiguous bare name rather than guessing.diff --git a/lib/host/project-candidate.test.ts b/lib/host/project-candidate.test.tsnew file mode 100644index 00000000..71b76407--- /dev/null+++ b/lib/host/project-candidate.test.ts@@ -0,0 +1,98 @@+import { afterAll, describe, expect, it, vi } from "vitest";+import { promises as fs } from "fs";+import os from "os";+import path from "path";+import { validateProjectChild, validateProjectDescendant } from "./project-candidate";+import { containerFor } from "./project-containers";++// ONE validator, used by enumeration AND by every resolveProjectHint strategy. The+// previous split — a strict check in the walk, a looser `resolveReadable` in the hint+// path — is exactly how `workflow_start` could resolve a project `projects_list`+// refused to show.+const base = await fs.mkdtemp(path.join(os.tmpdir(), "mso-candidate-"));+const root = path.join(base, "root");+const outside = path.join(base, "outside");+await fs.mkdir(path.join(root, "honest", "nested"), { recursive: true });+await fs.mkdir(path.join(root, ".hidden"), { recursive: true });+await fs.mkdir(path.join(root, "honest", ".hidden-nested"), { recursive: true });+await fs.mkdir(path.join(outside, "target"), { recursive: true });+await fs.mkdir(path.join(root, "inside-target"), { recursive: true });+await fs.writeFile(path.join(root, "afile"), "not a directory");+await fs.symlink(path.join(outside, "target"), path.join(root, "link-out"));+await fs.symlink(path.join(root, "inside-target"), path.join(root, "link-in"));+await fs.symlink(path.join(outside, "target"), path.join(root, "honest", "link-nested"));++const container = containerFor(await fs.realpath(root));+afterAll(async () => { await fs.rm(base, { recursive: true, force: true }); });++describe("validateProjectChild — one direct entry", () => {+ it("accepts a real, visible, owned directory", async () => {+ await expect(validateProjectChild(container, "honest")).resolves.toMatchObject({ ok: true });+ });++ it("rejects a hidden name", async () => {+ await expect(validateProjectChild(container, ".hidden")).resolves.toMatchObject({ ok: false, reason: "hidden" });+ });++ it("rejects a symlink whose target escapes", async () => {+ await expect(validateProjectChild(container, "link-out")).resolves.toMatchObject({ ok: false, reason: "symlink" });+ });++ it("rejects a symlink whose target is INSIDE the container — a link is still not a child", async () => {+ await expect(validateProjectChild(container, "link-in")).resolves.toMatchObject({ ok: false, reason: "symlink" });+ });++ it("rejects a non-directory and a missing entry", async () => {+ await expect(validateProjectChild(container, "afile")).resolves.toMatchObject({ ok: false, reason: "not-directory" });+ await expect(validateProjectChild(container, "nope")).resolves.toMatchObject({ ok: false, reason: "missing" });+ });++ it("rejects a traversing or separator-bearing name", async () => {+ for (const name of ["..", "../outside", "a/b", "a\\b", ""]) {+ await expect(validateProjectChild(container, name), name).resolves.toMatchObject({ ok: false });+ }+ });++ it("rejects a directory owned by another uid, before any metadata read", async () => {+ const real = process.getuid!();+ vi.spyOn(process, "getuid").mockReturnValue(real + 4242);+ await expect(validateProjectChild(container, "honest")).resolves.toMatchObject({ ok: false, reason: "uid" });+ vi.restoreAllMocks();+ });+});++describe("validateProjectDescendant — a whole path below the container", () => {+ it("accepts a nested real path", async () => {+ await expect(validateProjectDescendant(container, path.join(container.path, "honest", "nested")))+ .resolves.toMatchObject({ ok: true });+ });++ it("accepts the container itself", async () => {+ await expect(validateProjectDescendant(container, container.path)).resolves.toMatchObject({ ok: true });+ });++ it("rejects a path with ANY hidden component below the container", async () => {+ await expect(validateProjectDescendant(container, path.join(container.path, "honest", ".hidden-nested")))+ .resolves.toMatchObject({ ok: false, reason: "hidden" });+ });++ it("rejects a path traversing a symlink at ANY depth", async () => {+ await expect(validateProjectDescendant(container, path.join(container.path, "honest", "link-nested")))+ .resolves.toMatchObject({ ok: false, reason: "symlink" });+ await expect(validateProjectDescendant(container, path.join(container.path, "link-in")))+ .resolves.toMatchObject({ ok: false, reason: "symlink" });+ });++ it("rejects a path outside the container", async () => {+ await expect(validateProjectDescendant(container, path.join(outside, "target")))+ .resolves.toMatchObject({ ok: false, reason: "escape" });+ });++ it("rejects on uid mismatch at any depth", async () => {+ const real = process.getuid!();+ vi.spyOn(process, "getuid").mockReturnValue(real + 4242);+ await expect(validateProjectDescendant(container, path.join(container.path, "honest", "nested")))+ .resolves.toMatchObject({ ok: false, reason: "uid" });+ vi.restoreAllMocks();+ });+});diff --git a/lib/host/project-candidate.ts b/lib/host/project-candidate.tsnew file mode 100644index 00000000..4bfcd05b--- /dev/null+++ b/lib/host/project-candidate.ts@@ -0,0 +1,90 @@+// THE shared project-candidate validator.+//+// There used to be two of these: a strict one inside the enumeration walk, and+// `resolveReadable()` standing in for it on every `resolveProjectHint` strategy. That+// split is precisely how `workflow_start` could resolve — and then read metadata from —+// a project that `projects_list` correctly refused to show: a symlinked entry, a hidden+// directory, or one owned by another uid.+//+// One function now decides, and every caller goes through it. The rules, in order:+// hidden — no path component below the container may start with "."+// symlink — no component may BE a symlink, target legal or not. A link is not a+// child of this container, and following it is a TOCTOU bet.+// escape — the canonical result must stay inside the container+// credential — never a denylisted credential path+// uid — owned by the uid MSO runs as, checked BEFORE any metadata read+import { promises as fs } from "fs";+import path from "path";+import { isCredentialPath, isUnderRoot } from "./paths";+import type { ProjectContainer } from "./project-containers";++export type CandidateRejection = "hidden" | "symlink" | "not-directory" | "escape" | "credential" | "uid" | "missing";+export type CandidateResult = { ok: true; path: string } | { ok: false; reason: CandidateRejection };++const currentUid = (): number | undefined => (typeof process.getuid === "function" ? process.getuid() : undefined);++/** A single path component: real, visible, not a link, owned by us. `parent` is already+ * validated (or is the container), so this never re-walks the whole prefix. */+async function validateComponent(parent: string, name: string): Promise<CandidateResult> {+ if (!name || name === "." || name === ".." || name.includes("/") || name.includes("\\")) return { ok: false, reason: "escape" };+ if (name.startsWith(".")) return { ok: false, reason: "hidden" };+ const full = path.join(parent, name);+ const stat = await fs.lstat(full).catch(() => null);+ if (!stat) return { ok: false, reason: "missing" };+ if (stat.isSymbolicLink()) return { ok: false, reason: "symlink" };+ if (!stat.isDirectory()) return { ok: false, reason: "not-directory" };+ const uid = currentUid();+ if (uid !== undefined && stat.uid !== uid) return { ok: false, reason: "uid" };+ if (isCredentialPath(full)) return { ok: false, reason: "credential" };+ return { ok: true, path: full };+}++/**+ * ONE direct child of a container — the enumeration case and the exact-name/alias probe.+ * A final realpath check catches a swap between lstat and here.+ */+export async function validateProjectChild(container: ProjectContainer, name: string): Promise<CandidateResult> {+ const component = await validateComponent(container.path, name);+ if (!component.ok) return component;+ const real = await fs.realpath(component.path).catch(() => null);+ if (real !== component.path || !isUnderRoot(real, container.path)) return { ok: false, reason: "escape" };+ return component;+}++/**+ * A path at ANY depth below a container — the absolute/`~`/relative path-hint case.+ * Validated component by component from the container down, so a symlink or hidden+ * directory three levels in is refused just as a direct child would be. Canonicalizing+ * first and checking afterwards is what let a symlinked intermediate through.+ */+export async function validateProjectDescendant(container: ProjectContainer, target: string): Promise<CandidateResult> {+ const absolute = path.resolve(target);+ if (!isUnderRoot(absolute, container.path)) return { ok: false, reason: "escape" };+ const relative = path.relative(container.path, absolute);+ if (relative === "") return { ok: true, path: container.path };+ let parent = container.path;+ for (const segment of relative.split(path.sep)) {+ const component = await validateComponent(parent, segment);+ if (!component.ok) return component;+ parent = component.path;+ }+ const real = await fs.realpath(parent).catch(() => null);+ if (real !== parent || !isUnderRoot(real, container.path)) return { ok: false, reason: "escape" };+ return { ok: true, path: parent };+}++/** The same rules applied to a caller-supplied ROOT directory, before it is trusted as+ * a container. A symlinked or hidden `rootHint` is refused rather than canonicalized+ * into something the caller never named. */+export async function validateRootHint(absolute: string): Promise<CandidateResult> {+ const stat = await fs.lstat(absolute).catch(() => null);+ if (!stat) return { ok: false, reason: "missing" };+ if (stat.isSymbolicLink()) return { ok: false, reason: "symlink" };+ if (!stat.isDirectory()) return { ok: false, reason: "not-directory" };+ const uid = currentUid();+ if (uid !== undefined && stat.uid !== uid) return { ok: false, reason: "uid" };+ if (isCredentialPath(absolute)) return { ok: false, reason: "credential" };+ const real = await fs.realpath(absolute).catch(() => null);+ if (real !== absolute) return { ok: false, reason: "symlink" };+ return { ok: true, path: absolute };+}diff --git a/lib/host/project-containers.ts b/lib/host/project-containers.tsindex 8d80f953..5e5e64cf 100644--- a/lib/host/project-containers.ts+++ b/lib/host/project-containers.ts@@ -41,6 +41,8 @@ export const PROJECT_LIMITS = {export type AuthorizedRoot = { id: string; configured: string; path: string };+export type { ScanCursor, ScanReport } from "./project-scan-types";+export type ProjectContainer = {/** Short sha256 of the canonical container path. The DERIVED `projects/` child gets* its own id on purpose: without it `~/widget` and `~/projects/widget` would share@@ -52,15 +54,6 @@ export type ProjectContainer = {derived: boolean;};-export type ScanReport = {- truncated: boolean;- truncationReasons: string[];- scannedRoots: string[];- skippedRoots: Array<{ path: string; reason: string }>;- /** Entries rejected by containment, hidden-name, symlink or ownership checks. */- skippedProjects: number;-};-export type ProjectRow = {/** Globally unique: `<rootId>/<name>`. */id: string;@@ -75,7 +68,22 @@ export type ProjectRow = {git?: { branch?: string; head?: string };};-export const shortId = (real: string) => createHash("sha256").update(real).digest("hex").slice(0, 8);+/**+ * 128 bits of sha256 over the canonical container path.+ *+ * This was 8 hex characters — 32 bits — and a review found a REAL collision in the+ * fixture space it was tested in: `/tmp/mso-root-50323` and `/tmp/mso-root-125549`+ * both hashed to `51e156ef`. Two colliding roots holding same-named projects would+ * have merged back into one row, re-creating the exact bug root-qualified ids exist to+ * fix. 32 hex characters make that computationally unreachable — and, belt and braces,+ * nothing DEDUPES on this value: the internal key is the full canonical path (see+ * `containerKey`), so even a collision cannot merge two containers.+ */+export const shortId = (real: string) => createHash("sha256").update(real).digest("hex").slice(0, 32);++/** The internal identity. Always the full canonical path — never the hash — so+ * dedupe/precedence can never be decided by a truncated digest. */+export const containerKey = (real: string) => real;const currentUid = (): number | undefined => (typeof process.getuid === "function" ? process.getuid() : undefined);@@ -108,6 +116,26 @@ export async function authorizedRoots(): Promise<AuthorizedRoot[]> {return out;}+/**+ * EVERY configured root, canonicalized, with NO cap.+ *+ * `authorizedRoots()` caps at `maxRoots` because a SCAN has to be bounded. Authorization+ * is a different question: a root the owner configured is inside the jail whether or not+ * this call had budget to walk it. Using the capped list as the jail predicate is what+ * made an explicitly named `rootHint` unresolvable once 12 other roots were configured.+ */+export async function configuredRootPaths(): Promise<string[]> {+ const out: string[] = [];+ for (const configured of readRootList()) {+ const real = await fs.realpath(configured).catch(() => null);+ if (!real || real === "/" || out.includes(real)) continue;+ if (!(await fs.stat(real).catch(() => null))?.isDirectory()) continue;+ if (isCredentialPath(real)) continue;+ out.push(real);+ }+ return out;+}+/** Roots configured but NOT honoured, so the caller can say so rather than imply the* configuration was fully covered. */export async function overflowRoots(): Promise<Array<{ path: string; reason: string }>> {diff --git a/lib/host/project-containment.test.ts b/lib/host/project-containment.test.tsindex e73493ee..51328791 100644--- a/lib/host/project-containment.test.ts+++ b/lib/host/project-containment.test.ts@@ -179,7 +179,8 @@ describe("project ids are globally unique across roots", () => {const first = await listProjects();const second = await listProjects();expect(first.projects[0].id).toBe(second.projects[0].id);- expect(first.projects[0].rootId).toMatch(/^[a-f0-9]{8}$/);+ // 128 bits, not 32. An 8-hex id had a REAL collision in this fixture space.+ expect(first.projects[0].rootId).toMatch(/^[a-f0-9]{32}$/);});it("still exposes plain container paths through projectRoots()", async () => {diff --git a/lib/host/project-cursor.ts b/lib/host/project-cursor.tsnew file mode 100644index 00000000..7c93a907--- /dev/null+++ b/lib/host/project-cursor.ts@@ -0,0 +1,28 @@+// Encoding for a resumable scan position.+//+// A cap is only honest if the caller can continue past it; a truncated result with no+// way to fetch the rest is data loss with a label on it.+import type { ScanCursor } from "./project-containers";++/** Cursors are positional in readdir order. That is a deliberate trade: making them+ * name-ordered would require visiting every dirent to find the next N names, which is+ * the unbounded walk the entry cap exists to prevent. Valid while the directory is+ * unchanged; `note` says so in the payload. */+export function encodeCursor(cursor: ScanCursor): string {+ return Buffer.from(JSON.stringify(cursor), "utf8").toString("base64url");+}++export function decodeCursor(raw: string | undefined): ScanCursor | undefined {+ if (!raw) return undefined;+ try {+ const parsed = JSON.parse(Buffer.from(raw, "base64url").toString("utf8")) as ScanCursor;+ if (!parsed || typeof parsed !== "object") return undefined;+ return {+ roots: Array.isArray(parsed.roots) ? parsed.roots.filter((r) => typeof r?.root === "string") : [],+ skipRoots: Array.isArray(parsed.skipRoots) ? parsed.skipRoots.filter((r) => typeof r === "string") : [],+ };+ } catch {+ return undefined;+ }+}+diff --git a/lib/host/project-list.ts b/lib/host/project-list.tsnew file mode 100644index 00000000..4445bed4--- /dev/null+++ b/lib/host/project-list.ts@@ -0,0 +1,60 @@+// The paginated, metadata-bearing view of the walk. Kept apart from project-roots.ts so+// the walk stays about containment and budgets, and this stays about presentation.+import path from "path";+import { boundedGitMeta, packageMeta } from "./project-meta";+import { PROJECT_LIMITS, type ProjectRow, type ScanReport } from "./project-containers";+import { decodeCursor } from "./project-cursor";+import { listProjectDirs } from "./project-roots";++export type ListProjectsResult = {+ roots: string[];+ containers: Array<{ id: string; path: string; derived: boolean; authorizedRoot: string }>;+ total: number;+ offset: number;+ limit: number;+ hasMore: boolean;+ nextOffset?: number;+ scan: ScanReport;+ projects: ProjectRow[];+};++/** Bounded, paginated enumeration. Metadata is read only for the returned PAGE —+ * `total` counts directories, so a wide box does not pay for 400 package reads. */+export async function listProjects(+ options: { query?: string; limit?: number; offset?: number; cursor?: string } = {},+): Promise<ListProjectsResult> {+ const { containers, dirs, scan } = await listProjectDirs(decodeCursor(options.cursor));+ const query = options.query?.trim().toLowerCase();+ const matched = query ? dirs.filter(({ dir }) => path.basename(dir).toLowerCase().includes(query)) : dirs;+ const limit = Math.min(Math.max(Math.round(options.limit ?? PROJECT_LIMITS.defaultPageSize), 1), PROJECT_LIMITS.maxPageSize);+ const offset = Math.max(Math.round(options.offset ?? 0), 0);+ const page = matched.slice(offset, offset + limit);+ const projects = await Promise.all(page.map(async ({ container, dir }) => {+ const [pkg, git] = await Promise.all([packageMeta(dir), boundedGitMeta(dir)]);+ const name = path.basename(dir);+ return {+ id: `${container.id}/${name}`,+ name,+ path: dir,+ rootId: container.id,+ root: container.path,+ authorizedRoot: container.authorizedRoot,+ ...(pkg.name ? { packageName: pkg.name } : {}),+ ...(pkg.version ? { packageVersion: pkg.version } : {}),+ ...(git.available ? { git: { branch: git.branch, head: git.head?.sha?.slice(0, 12) } } : {}),+ };+ }));+ const hasMore = offset + page.length < matched.length;+ return {+ roots: containers.map((c) => c.path),+ containers: containers.map(({ id, path: p, derived, authorizedRoot }) => ({ id, path: p, derived, authorizedRoot })),+ total: matched.length,+ offset,+ limit,+ hasMore,+ ...(hasMore ? { nextOffset: offset + page.length } : {}),+ scan,+ projects,+ };+}+diff --git a/lib/host/project-roots.ts b/lib/host/project-roots.tsindex 6ce458df..dac65495 100644--- a/lib/host/project-roots.ts+++ b/lib/host/project-roots.ts@@ -1,42 +1,57 @@// The project WALK: bounded enumeration of the containers project-containers.ts-// authorized, plus the truthful report of everything it could not cover.+// authorized, plus the truthful, RESUMABLE report of everything it could not cover.//-// `truncated:false` means "this is all of it". Hitting a root, entry, project or time-// cap sets `truncated:true` with a named reason, because a silent slice that claims-// completeness is how a model ends up telling the owner a project does not exist.+// Three rules earned the hard way:+// 1. `truncated:false` means "this is all of it". Any cap sets `truncated:true` with+// a named reason — a silent slice that claims completeness is how a model ends up+// telling the owner a project does not exist.+// 2. EVERY dirent counts against the entry cap, accepted or not. Counting only the+// entries we kept meant a container of a million regular files still cost a+// million iterations before the "400 entry" cap was reached.+// 3. A cap is only honest if it can be continued. Every cap emits a cursor, and+// passing it back resumes where the walk stopped.import { promises as fs } from "fs";import path from "path";-import { isCredentialPath, isUnderRoot } from "./paths";-import { boundedGitMeta, packageMeta } from "./project-meta";+import { validateProjectChild } from "./project-candidate";+import { decodeCursor, encodeCursor } from "./project-cursor";import {- authorizedRoots, ownedByUs, overflowRoots, projectContainers,- PROJECT_LIMITS, type ProjectContainer, type ProjectRow, type ScanReport,+ overflowRoots, projectContainers,+ PROJECT_LIMITS, type ProjectContainer, type ProjectRow, type ScanReport, type ScanCursor,} from "./project-containers";export {- authorizedRoots, containerFor, projectContainers, projectRoots, PROJECT_LIMITS,+ authorizedRoots, configuredRootPaths, containerFor, projectContainers, projectRoots, shortId, PROJECT_LIMITS,} from "./project-containers";-export type { AuthorizedRoot, ProjectContainer, ProjectRow, ScanReport } from "./project-containers";+export type { AuthorizedRoot, ProjectContainer, ProjectRow, ScanReport, ScanCursor } from "./project-containers";+export { decodeCursor, encodeCursor } from "./project-cursor";-type Walk = { dirs: string[]; hitEntryCap: boolean; skipped: number };+type Walk = { dirs: string[]; entriesVisited: number; hitEntryCap: boolean; skipped: number };/**- * Bounded `opendir` iteration. Names are collected into an array capped at- * `maxEntriesPerRoot`, so a container with a million entries costs a bounded walk and- * a bounded array rather than one `readdir` that materializes the lot before slicing.+ * Bounded `opendir` iteration. Every dirent yielded increments the budget, so a+ * container full of rejected entries costs the cap and no more. `skipEntries` resumes a+ * previously truncated walk at the same readdir position.*/-async function walkContainer(container: ProjectContainer, containers: Set<string>, authorized: string[], deadlineAt: number): Promise<Walk> {+async function walkContainer(container: ProjectContainer, containerPaths: Set<string>, skipEntries: number, deadlineAt: number): Promise<Walk> {const names: string[] = [];+ let entriesVisited = skipEntries;+ let seen = 0;let hitEntryCap = false;let skipped = 0;const handle = await fs.opendir(container.path).catch(() => null);- if (!handle) return { dirs: [], hitEntryCap: false, skipped: 0 };+ if (!handle) return { dirs: [], entriesVisited, hitEntryCap: false, skipped: 0 };try {for await (const entry of handle) {- if (names.length >= PROJECT_LIMITS.maxEntriesPerRoot || Date.now() > deadlineAt) { hitEntryCap = true; break; }- // isDirectory() is false for a symlink, so a link out of the container is- // dropped here rather than realpath-checked (and possibly followed) later.- if (!entry.isDirectory() || entry.name.startsWith(".")) { if (!entry.isDirectory()) skipped += 1; continue; }+ seen += 1;+ if (seen <= skipEntries) continue;+ // EVERY dirent costs budget — that is the whole point of counting here rather+ // than after the accept/reject decision.+ if (entriesVisited - skipEntries >= PROJECT_LIMITS.maxEntriesPerRoot || Date.now() > deadlineAt) {+ hitEntryCap = true;+ break;+ }+ entriesVisited += 1;+ if (!entry.isDirectory() || entry.name.startsWith(".")) { skipped += 1; continue; }names.push(entry.name);}} catch {@@ -46,18 +61,17 @@ async function walkContainer(container: ProjectContainer, containers: Set<stringconst dirs: string[] = [];for (const name of names) {- const full = path.join(container.path, name);- if (containers.has(full) || isCredentialPath(full)) { skipped += 1; continue; }- const stat = await fs.lstat(full).catch(() => null);- if (!stat?.isDirectory() || stat.isSymbolicLink()) { skipped += 1; continue; }- // Defence in depth against a swap between opendir and here: the entry must still- // canonicalize to itself, inside its exact container AND inside an authorized root.- const real = await fs.realpath(full).catch(() => null);- if (real !== full || !isUnderRoot(real, container.path) || !authorized.some((a) => isUnderRoot(real, a))) { skipped += 1; continue; }- if (!(await ownedByUs(real))) { skipped += 1; continue; }- dirs.push(full);+ // The deadline is enforced THROUGH the metadata work too, not only in the dirent+ // loop: 400 lstat+realpath+stat triples on a cold or networked filesystem is where+ // a slow scan actually spends its time.+ if (Date.now() > deadlineAt) { hitEntryCap = true; break; }+ // `~/projects` under `~` is a CONTAINER, not a project inside its parent.+ if (containerPaths.has(path.join(container.path, name))) { skipped += 1; continue; }+ const candidate = await validateProjectChild(container, name);+ if (!candidate.ok) { skipped += 1; continue; }+ dirs.push(candidate.path);}- return { dirs, hitEntryCap, skipped };+ return { dirs, entriesVisited, hitEntryCap, skipped };}export type ProjectDirs = {@@ -68,88 +82,80 @@ export type ProjectDirs = {/** The one walk. `listProjectDirs()` is this over every discovered container; an* explicit `rootHint` is this over exactly one. */-export async function listProjectDirsIn(containers: ProjectContainer[], extraAuthorized: string[] = []): Promise<ProjectDirs> {+export async function listProjectDirsIn(+ containers: ProjectContainer[],+ options: { explicit?: boolean; cursor?: ScanCursor } = {},+): Promise<ProjectDirs> {const deadlineAt = Date.now() + PROJECT_LIMITS.maxScanMs;- const authorized = [...(await authorizedRoots()).map((r) => r.path), ...extraAuthorized];- const paths = new Set(containers.map((c) => c.path));const dirs: Array<{ container: ProjectContainer; dir: string }> = [];const reasons: string[] = [];const scannedRoots: string[] = [];- const skippedRoots = extraAuthorized.length ? [] : await overflowRoots();+ const skippedRoots = options.explicit ? [] : await overflowRoots();+ const containerPaths = new Set(containers.map((c) => c.path));+ const resumeRoots = new Map((options.cursor?.roots ?? []).map((r) => [r.root, r.entriesConsumed]));+ const skipRoots = new Set(options.cursor?.skipRoots ?? []);+ const cursors: ScanCursor["roots"] = [];+ const pendingRoots: string[] = [];let skippedProjects = 0;- if (skippedRoots.length) reasons.push("maxRoots");+ if (skippedRoots.length) { reasons.push("maxRoots"); pendingRoots.push(...skippedRoots.map((r) => r.path)); }for (const container of containers) {+ if (skipRoots.has(container.path)) continue;if (Date.now() > deadlineAt) {reasons.push("deadline");skippedRoots.push({ path: container.path, reason: "deadline" });+ pendingRoots.push(container.path);continue;}- const walk = await walkContainer(container, paths, authorized, deadlineAt);+ const walk = await walkContainer(container, containerPaths, resumeRoots.get(container.path) ?? 0, deadlineAt);scannedRoots.push(container.path);skippedProjects += walk.skipped;- if (walk.hitEntryCap) reasons.push(`maxEntriesPerRoot:${container.path}`);+ if (walk.hitEntryCap) {+ reasons.push(`maxEntriesPerRoot:${container.path}`);+ cursors.push({ root: container.path, entriesConsumed: walk.entriesVisited });+ }+ let capped = false;for (const dir of walk.dirs) {- if (dirs.length >= PROJECT_LIMITS.maxProjects) { reasons.push("maxProjects"); break; }+ if (dirs.length >= PROJECT_LIMITS.maxProjects) { reasons.push("maxProjects"); capped = true; break; }dirs.push({ container, dir });}- if (reasons.includes("maxProjects")) break;+ if (capped) {+ // Resume this container from where its accepted entries stopped, and leave the+ // remaining containers pending rather than pretending they were covered.+ cursors.push({ root: container.path, entriesConsumed: walk.entriesVisited - walk.dirs.length + dirs.length });+ pendingRoots.push(...containers.slice(containers.indexOf(container) + 1).map((c) => c.path));+ break;+ }}const truncationReasons = [...new Set(reasons)];+ const done = [...new Set(scannedRoots)].filter((r) => !cursors.some((c) => c.root === r) && !pendingRoots.includes(r));return {containers,dirs,- scan: { truncated: truncationReasons.length > 0, truncationReasons, scannedRoots, skippedRoots, skippedProjects },+ scan: {+ truncated: truncationReasons.length > 0,+ truncationReasons,+ scannedRoots,+ skippedRoots,+ skippedProjects,+ ...(truncationReasons.length ? {+ continuation: {+ pendingRoots: [...new Set(pendingRoots)],+ cursors,+ cursorSemantics: "readdir-position" as const,+ note: "Pass `cursor` back to resume. Positions are readdir order and are valid while the directory is unchanged.",+ cursor: encodeCursor({ roots: cursors, skipRoots: done }),+ },+ } : {}),+ },};}/** Every project directory across every container, in container-then-name order. */-export async function listProjectDirs(): Promise<ProjectDirs> {- return listProjectDirsIn(await projectContainers());+export async function listProjectDirs(cursor?: ScanCursor): Promise<ProjectDirs> {+ return listProjectDirsIn(await projectContainers(), { cursor });}-export type ListProjectsResult = {- roots: string[];- containers: Array<{ id: string; path: string; derived: boolean; authorizedRoot: string }>;- total: number;- offset: number;- limit: number;- scan: ScanReport;- projects: ProjectRow[];-};--/** Bounded, paginated enumeration. Metadata is read only for the returned PAGE —- * `total` counts directories, so a wide box does not pay for 400 package reads. */-export async function listProjects(options: { query?: string; limit?: number; offset?: number } = {}): Promise<ListProjectsResult> {- const { containers, dirs, scan } = await listProjectDirs();- const query = options.query?.trim().toLowerCase();- const matched = query ? dirs.filter(({ dir }) => path.basename(dir).toLowerCase().includes(query)) : dirs;- const limit = Math.min(Math.max(Math.round(options.limit ?? PROJECT_LIMITS.defaultPageSize), 1), PROJECT_LIMITS.maxPageSize);- const offset = Math.max(Math.round(options.offset ?? 0), 0);- const page = matched.slice(offset, offset + limit);- const projects = await Promise.all(page.map(async ({ container, dir }) => {- const [pkg, git] = await Promise.all([packageMeta(dir), boundedGitMeta(dir)]);- const name = path.basename(dir);- return {- id: `${container.id}/${name}`,- name,- path: dir,- rootId: container.id,- root: container.path,- authorizedRoot: container.authorizedRoot,- ...(pkg.name ? { packageName: pkg.name } : {}),- ...(pkg.version ? { packageVersion: pkg.version } : {}),- ...(git.available ? { git: { branch: git.branch, head: git.head?.sha?.slice(0, 12) } } : {}),- };- }));- return {- roots: containers.map((c) => c.path),- containers: containers.map(({ id, path: p, derived, authorizedRoot }) => ({ id, path: p, derived, authorizedRoot })),- total: matched.length,- offset,- limit,- scan,- projects,- };-}+export { listProjects } from "./project-list";+export type { ListProjectsResult } from "./project-list";diff --git a/lib/host/project-scan-types.ts b/lib/host/project-scan-types.tsnew file mode 100644index 00000000..f4414620--- /dev/null+++ b/lib/host/project-scan-types.ts@@ -0,0 +1,29 @@+// What a bounded scan could not cover, and how to continue it. Types only — kept+// separate so both the project walk and the skill catalog can describe incompleteness+// in the same shape without importing each other's scanners.++/** A resumable position. Positional in readdir order — see encodeCursor's note. */+export type ScanCursor = {+ roots: Array<{ root: string; entriesConsumed: number }>;+ /** Containers already fully covered by the previous page; skipped on resume. */+ skipRoots: string[];+};++export type ScanReport = {+ truncated: boolean;+ truncationReasons: string[];+ scannedRoots: string[];+ skippedRoots: Array<{ path: string; reason: string }>;+ /** Entries rejected by containment, hidden-name, symlink or ownership checks. */+ skippedProjects: number;+ /** Present ONLY when truncated. Every cap emits a way to continue — a cap the caller+ * cannot resume is just data loss with a label on it. */+ continuation?: {+ pendingRoots: string[];+ cursors: Array<{ root: string; entriesConsumed: number }>;+ cursorSemantics: "readdir-position";+ note: string;+ cursor: string;+ };+};+diff --git a/lib/host/projects.ts b/lib/host/projects.tsindex 12f2ec3c..22b4f296 100644--- a/lib/host/projects.ts+++ b/lib/host/projects.ts@@ -2,8 +2,9 @@ import { promises as fs } from "fs";import path from "path";import { normalizeProjectKey, projectAliasesFor, projectAliasTarget } from "./project-aliases";import { boundedGitMeta, fullGitMeta, packageMeta } from "./project-meta";-import { isUnderRoot, resolveReadable } from "./paths";-import { containerFor, listProjectDirsIn, projectContainers, type ProjectContainer } from "./project-roots";+import { homeDir, isUnderRoot } from "./paths";+import { validateProjectChild, validateProjectDescendant, validateRootHint } from "./project-candidate";+import { configuredRootPaths, containerFor, listProjectDirsIn, projectContainers, type ProjectContainer } from "./project-roots";export type ProjectResolution = {hint: string;@@ -27,32 +28,33 @@ async function resolutionFor(container: ProjectContainer, dir: string, hint: str};}-/**- * The exact-name / alias probe. It must refuse exactly what `projects_list` refuses,- * or a hint quietly reaches a hidden directory or walks a symlink that enumeration- * would never have shown — resolving through `resolveReadable` alone only proves the- * TARGET is inside a read root, not that the ENTRY is a real child of this container.- */-async function probeExactChild(container: ProjectContainer, name: string): Promise<string | null> {- if (!name || name.startsWith(".") || name.includes("/") || name.includes("\\")) return null;- const full = path.join(container.path, name);- const stat = await fs.lstat(full).catch(() => null);- if (!stat?.isDirectory() || stat.isSymbolicLink()) return null;- const real = await fs.realpath(full).catch(() => null);- if (real !== full || !isUnderRoot(real, container.path)) return null;- // The container itself came from an authorized root (or an explicit, readable- // rootHint), so containment there is the jail check.- return full;+function expandHome(p: string): string {+ const h = homeDir();+ if (p === "~") return h;+ if (p.startsWith("~/")) return path.join(h, p.slice(2));+ return path.resolve(p);}-/** The containers a hint may resolve inside. An explicit `rootHint` wins: the caller- * named that root, so it is used even when the global container list is at its cap —- * it still has to pass `resolveReadable`, so it is inside the read jail either way. */+/**+ * The containers a hint may resolve inside. An explicit `rootHint` wins: the caller+ * named that root, so it is used even when the global container list is at its cap.+ *+ * It is validated with the SAME rules as a project entry — a symlinked or hidden+ * rootHint is refused rather than canonicalized into something the caller never named,+ * which is what `resolveReadable()` did. It must also still sit inside an authorized+ * read root, so naming a root never widens the jail.+ */async function containersFor(rootHint?: string): Promise<ProjectContainer[]> {if (!rootHint) return projectContainers();- const real = await resolveReadable(rootHint).catch(() => null);- if (!real || !(await fs.stat(real).catch(() => null))?.isDirectory()) return [];- return [containerFor(real)];+ const absolute = expandHome(rootHint);+ const validated = await validateRootHint(absolute);+ if (!validated.ok) return [];+ // Checked against EVERY configured root, not the scan-capped subset: naming a root+ // must never widen the jail, but the jail must not shrink just because 12 other roots+ // are configured ahead of it.+ const authorized = await configuredRootPaths();+ if (!authorized.some((root) => isUnderRoot(validated.path, root))) return [];+ return [containerFor(validated.path)];}/**@@ -72,13 +74,17 @@ export async function resolveProjectHint(hint: string, rootHint?: string): Promiconst pathHint = raw.startsWith("projects/") ? `~/${raw}` : raw;if (/^(?:~\/|\/|\.\.?\/)/.test(pathHint)) {- const resolved = await resolveReadable(pathHint).catch(() => null);- const isDir = resolved ? (await fs.stat(resolved).catch(() => null))?.isDirectory() === true : false;- // With an explicit rootHint a path hint may not leave that root — otherwise- // `../elsewhere` would silently escape the root the caller scoped the search to.- const owner = isDir ? containers.find((c) => isUnderRoot(resolved!, c.path)) : undefined;- if (isDir && (!rootHint || owner)) return resolutionFor(owner ?? containerFor(resolved!), resolved!, raw, "path");- if (rootHint && isDir && !owner) return null;+ // A path hint gets the SAME component-by-component validation an enumerated entry+ // gets — hidden, symlinked or foreign-uid components are refused at every depth,+ // rather than canonicalized away by a single resolveReadable() call.+ const absolute = expandHome(pathHint);+ for (const container of containers) {+ if (!isUnderRoot(absolute, container.path)) continue;+ const candidate = await validateProjectDescendant(container, absolute);+ if (candidate.ok) return resolutionFor(container, candidate.path, raw, "path");+ return null; // it belongs to this container and was refused; do not try a wider one+ }+ return null;}const query = normalizeProjectKey(raw);@@ -89,15 +95,14 @@ export async function resolveProjectHint(hint: string, rootHint?: string): Promiconst directName = aliasTarget ?? (/^[a-z0-9._-]+$/i.test(raw) ? raw : undefined);if (directName) {for (const container of containers) {- const candidate = await probeExactChild(container, directName);- if (candidate) return resolutionFor(container, candidate, raw, aliasTarget ? "alias" : "name");+ const candidate = await validateProjectChild(container, directName);+ if (candidate.ok) return resolutionFor(container, candidate.path, raw, aliasTarget ? "alias" : "name");}}- // Package/fuzzy runs over the SAME containers the exact probe used — including an- // explicit rootHint that is absent from the globally capped list. Filtering a global- // walk by root was the bug: a named-but-uncapped root could never match here.- const { dirs } = await listProjectDirsIn(containers, rootHint ? containers.map((c) => c.path) : []);+ // Package/fuzzy runs over the SAME containers — and therefore the same validator —+ // the exact probe used, including an explicit rootHint absent from the capped list.+ const { dirs } = await listProjectDirsIn(containers, { explicit: Boolean(rootHint) });const candidates = await Promise.all(dirs.map(async ({ container, dir }) => {const name = path.basename(dir);const meta = await packageMeta(dir);diff --git a/lib/mcp/dispatch.test.ts b/lib/mcp/dispatch.test.tsindex 7c8954cc..3f1c3d2a 100644--- a/lib/mcp/dispatch.test.ts+++ b/lib/mcp/dispatch.test.ts@@ -44,7 +44,7 @@ describe("protocol", () => {it("publishes server and toolset metadata so action drift is visible", async () => {const r = await dispatch({ id: 1, method: "initialize" }, "exec");const result = r.result as { serverInfo: { version: string }; _meta: { toolset: { toolCount: number; hash: string } } };- expect(result.serverInfo.version).toBe("1.5.1");+ expect(result.serverInfo.version).toBe("1.5.2");expect(result._meta.toolset.toolCount).toBe(TOOLS.length);expect(result._meta.toolset.hash).toMatch(/^[a-f0-9]{16}$/);});diff --git a/lib/mcp/tools-discovery-read.test.ts b/lib/mcp/tools-discovery-read.test.tsnew file mode 100644index 00000000..e94a7f3c--- /dev/null+++ b/lib/mcp/tools-discovery-read.test.ts@@ -0,0 +1,115 @@+import { afterAll, describe, expect, it, vi } from "vitest";+vi.mock("server-only", () => ({}));+import { promises as fs } from "fs";+import os from "os";+import path from "path";++// Same fixture as tools-discovery.test.ts (see its header). This half covers+// skills_read: exact ids, ambiguity refusal and withheld untrusted instructions.+//+// TWO configured containers, each holding a project called `widget`. That duplicate is+// the point: it is exactly the case that used to collapse into one row, hiding a whole+// project's skills from every client. OS_FS_READ_ROOTS is pointed at both so the project+// half of the catalog is deterministic; the GLOBAL half still comes from the real repo+// (`claude-skills/`), which is what these tools are supposed to merge, so assertions+// check containment rather than exact equality.+const base = await fs.mkdtemp(path.join(os.tmpdir(), "mso-discovery-"));+const rootA = path.join(base, "root-a");+const rootB = path.join(base, "root-b");+const widgetA = path.join(rootA, "widget");+const widgetB = path.join(rootB, "widget");+const gadget = path.join(rootA, "gadget");++async function skill(dir: string, name: string, description: string, body = "step one\n") {+ const target = path.join(dir, name);+ await fs.mkdir(target, { recursive: true });+ await fs.writeFile(path.join(target, "SKILL.md"), `---\nname: ${name}\ndescription: ${description}\n---\n\n# ${name}\n\n${body}`);+}++await skill(path.join(widgetA, ".claude/skills"), "widget-deploy", "Ship the widget service from root A.");+await fs.writeFile(path.join(widgetA, "package.json"), JSON.stringify({ name: "widget", version: "0.1.0" }));+await skill(path.join(widgetB, ".claude/skills"), "widget-deploy", "Ship the widget service from root B.");+// A project whose skills ROOT escapes the project via symlink: the SKILL.md is a real+// regular file, so it is discoverable — but containment fails, so it is untrusted and+// its instructions are withheld.+const escaped = path.join(base, "escaped-skills");+await skill(escaped, "gadget-wild", "Unverified, outside its project.");+await fs.mkdir(path.join(gadget, ".codex"), { recursive: true });+await fs.symlink(escaped, path.join(gadget, ".codex/skills"));++// A project skill whose SKILL.md is itself a SYMLINK to another real SKILL.md. This is+// not "untrusted", it is not a skill at all: the reader is nofollow at that component.+await fs.mkdir(path.join(widgetA, ".mso/skills/borrowed"), { recursive: true });+await fs.symlink(+ path.join(widgetA, ".claude/skills/widget-deploy/SKILL.md"),+ path.join(widgetA, ".mso/skills/borrowed/SKILL.md"),+);++const previous = process.env.OS_FS_READ_ROOTS;+process.env.OS_FS_READ_ROOTS = `${rootA}:${rootB}`;+const { DISCOVERY_TOOLS } = await import("./tools-discovery");+const { projectRefFor } = await import("@/lib/skills/project-skills");++/** Ids are COMPUTED the way the catalog computes them — never typed by hand, because+ * the whole fix is that they depend on which configured root the project came from. */+const projectId = async (dir: string) => projectRefFor(dir, await fs.realpath(path.dirname(dir))).id;+const skillId = async (dir: string, name: string) => `${await projectId(dir)}/${name}`;++const tool = (name: string) => {+ const found = DISCOVERY_TOOLS.find((t) => t.name === name);+ if (!found) throw new Error(`missing ${name}`);+ return found;+};+const run = (name: string, args: Record<string, unknown> = {}) => tool(name).run(args, { scope: "read" as const });++type SkillRow = { id: string; trust: string; instructionsReadable: boolean; project?: { id: string; name: string } };+type Scan = { truncated: boolean; truncationReasons: string[] };++afterAll(async () => {+ if (previous === undefined) delete process.env.OS_FS_READ_ROOTS;+ else process.env.OS_FS_READ_ROOTS = previous;+ await fs.rm(base, { recursive: true, force: true });+});++describe("skills_read reads the exact catalog id only", () => {+ it("returns instructions for a trusted project skill", async () => {+ const result = await run("skills_read", { name: await skillId(widgetA, "widget-deploy") }) as+ { content: string; project: { name: string }; trust: string };+ expect(result.trust).toBe("local");+ expect(result.project.name).toBe("widget");+ expect(result.content).toContain("# widget-deploy");+ expect(result.content).toContain("root A");+ });++ it("returns instructions for an official global skill", async () => {+ const result = await run("skills_read", { name: "mso" }) as { content: string; trust: string };+ expect(result.trust).toBe("official");+ expect(result.content.length).toBeGreaterThan(0);+ });++ it("withholds instructions for an untrusted skill but still reports metadata", async () => {+ const result = await run("skills_read", { name: await skillId(gadget, "gadget-wild") }) as+ { instructionsWithheld: boolean; reason: string; content?: string; trust: string };+ expect(result).toMatchObject({ instructionsWithheld: true, trust: "untrusted" });+ expect(result.content).toBeUndefined();+ expect(result.reason).toContain("~/.mso/skills");+ });++ it("REFUSES an ambiguous bare name and lists the exact ids", async () => {+ // Two projects called `widget`, each shipping `widget-deploy`. Guessing here would+ // hand the model another project's instructions under the name it asked for.+ await expect(run("skills_read", { name: "widget-deploy" })).rejects.toThrow(/ambiguous across projects/);+ await expect(run("skills_read", { name: "widget/widget-deploy" })).rejects.toThrow(/ambiguous across projects/);+ await expect(run("skills_read", { name: "widget-deploy" })).rejects.toThrow(await projectId(widgetA));+ });++ it("resolves an UNambiguous bare project-skill name", async () => {+ await expect(run("skills_read", { name: "gadget-wild" })).resolves.toMatchObject({+ id: await skillId(gadget, "gadget-wild"),+ });+ });++ it("refuses an unknown id rather than guessing", async () => {+ await expect(run("skills_read", { name: "does-not-exist" })).rejects.toThrow(/skills_list/);+ });+});diff --git a/lib/mcp/tools-discovery.test.ts b/lib/mcp/tools-discovery.test.tsindex fee84094..1406182b 100644--- a/lib/mcp/tools-discovery.test.ts+++ b/lib/mcp/tools-discovery.test.ts@@ -26,10 +26,21 @@ async function skill(dir: string, name: string, description: string, body = "steawait skill(path.join(widgetA, ".claude/skills"), "widget-deploy", "Ship the widget service from root A.");await fs.writeFile(path.join(widgetA, "package.json"), JSON.stringify({ name: "widget", version: "0.1.0" }));await skill(path.join(widgetB, ".claude/skills"), "widget-deploy", "Ship the widget service from root B.");-// A project skill whose SKILL.md is a symlink: discoverable, but never trusted.-await fs.mkdir(path.join(gadget, ".codex/skills/gadget-wild"), { recursive: true });-await fs.writeFile(path.join(gadget, "SKILL.md"), "---\nname: gadget-wild\ndescription: Unverified.\n---\n\n# wild\n");-await fs.symlink(path.join(gadget, "SKILL.md"), path.join(gadget, ".codex/skills/gadget-wild/SKILL.md"));+// A project whose skills ROOT escapes the project via symlink: the SKILL.md is a real+// regular file, so it is discoverable — but containment fails, so it is untrusted and+// its instructions are withheld.+const escaped = path.join(base, "escaped-skills");+await skill(escaped, "gadget-wild", "Unverified, outside its project.");+await fs.mkdir(path.join(gadget, ".codex"), { recursive: true });+await fs.symlink(escaped, path.join(gadget, ".codex/skills"));++// A project skill whose SKILL.md is itself a SYMLINK to another real SKILL.md. This is+// not "untrusted", it is not a skill at all: the reader is nofollow at that component.+await fs.mkdir(path.join(widgetA, ".mso/skills/borrowed"), { recursive: true });+await fs.symlink(+ path.join(widgetA, ".claude/skills/widget-deploy/SKILL.md"),+ path.join(widgetA, ".mso/skills/borrowed/SKILL.md"),+);const previous = process.env.OS_FS_READ_ROOTS;process.env.OS_FS_READ_ROOTS = `${rootA}:${rootB}`;@@ -107,7 +118,7 @@ describe("skills_list spans global and project roots", () => {expect(skills.map((s) => s.id)).toEqual(expect.arrayContaining([a, b]));});- it("marks a project skill with a symlinked SKILL.md untrusted and unreadable", async () => {+ it("marks a project skill outside its project untrusted and unreadable", async () => {const { skills } = await run("skills_list", { limit: 200 }) as { skills: SkillRow[] };const wild = await skillId(gadget, "gadget-wild");expect(skills.find((s) => s.id === wild)).toMatchObject({@@ -115,6 +126,20 @@ describe("skills_list spans global and project roots", () => {});});+ it("DROPS a skill whose SKILL.md is a symlink — nofollow means it is not a skill", async () => {+ const { skills } = await run("skills_list", { limit: 200 }) as { skills: SkillRow[] };+ const borrowed = await skillId(widgetA, "borrowed");+ expect(skills.map((s) => s.id)).not.toContain(borrowed);+ });++ it("reports resumable continuation only when the scan was truncated", async () => {+ const { scan } = await run("skills_list", { limit: 200 }) as {+ scan: Scan & { continuation?: { cursor: string } };+ };+ expect(scan.truncated).toBe(false);+ expect(scan.continuation).toBeUndefined();+ });+it("filters by an exact projectId", async () => {const only = await run("skills_list", { project: await projectId(widgetA) }) as { skills: SkillRow[]; ambiguousProjects?: unknown };expect(only.skills.map((s) => s.id)).toEqual([await skillId(widgetA, "widget-deploy")]);@@ -137,46 +162,3 @@ describe("skills_list spans global and project roots", () => {expect(official.skills.some((s) => s.project)).toBe(false);});});--describe("skills_read reads the exact catalog id only", () => {- it("returns instructions for a trusted project skill", async () => {- const result = await run("skills_read", { name: await skillId(widgetA, "widget-deploy") }) as- { content: string; project: { name: string }; trust: string };- expect(result.trust).toBe("local");- expect(result.project.name).toBe("widget");- expect(result.content).toContain("# widget-deploy");- expect(result.content).toContain("root A");- });-- it("returns instructions for an official global skill", async () => {- const result = await run("skills_read", { name: "mso" }) as { content: string; trust: string };- expect(result.trust).toBe("official");- expect(result.content.length).toBeGreaterThan(0);- });-- it("withholds instructions for an untrusted skill but still reports metadata", async () => {- const result = await run("skills_read", { name: await skillId(gadget, "gadget-wild") }) as- { instructionsWithheld: boolean; reason: string; content?: string; trust: string };- expect(result).toMatchObject({ instructionsWithheld: true, trust: "untrusted" });- expect(result.content).toBeUndefined();- expect(result.reason).toContain("~/.mso/skills");- });-- it("REFUSES an ambiguous bare name and lists the exact ids", async () => {- // Two projects called `widget`, each shipping `widget-deploy`. Guessing here would- // hand the model another project's instructions under the name it asked for.- await expect(run("skills_read", { name: "widget-deploy" })).rejects.toThrow(/ambiguous across projects/);- await expect(run("skills_read", { name: "widget/widget-deploy" })).rejects.toThrow(/ambiguous across projects/);- await expect(run("skills_read", { name: "widget-deploy" })).rejects.toThrow(await projectId(widgetA));- });-- it("resolves an UNambiguous bare project-skill name", async () => {- await expect(run("skills_read", { name: "gadget-wild" })).resolves.toMatchObject({- id: await skillId(gadget, "gadget-wild"),- });- });-- it("refuses an unknown id rather than guessing", async () => {- await expect(run("skills_read", { name: "does-not-exist" })).rejects.toThrow(/skills_list/);- });-});diff --git a/lib/mcp/tools-discovery.ts b/lib/mcp/tools-discovery.tsindex 668f9918..0c486428 100644--- a/lib/mcp/tools-discovery.ts+++ b/lib/mcp/tools-discovery.ts@@ -28,7 +28,8 @@ export const DISCOVERY_TOOLS: McpTool[] = ["Returns a globally unique id (<rootId>/<name>, so two roots may hold a project of the same name), absolute path, its container root, package name/version and bounded Git branch/head read straight off .git with no shell. " +"USE THIS FIRST when the user names a project you have not located — it is one call, needs no shell scope, and its id or path is the input to workflow_start. " +"Hidden directories, symlinks, credential paths and directories not owned by the MSO user are excluded. " +- "ALWAYS check `scan.truncated`: when true the listing is incomplete and `scan.truncationReasons` says which cap was hit — do not report that a project is absent from a truncated scan.",+ "ALWAYS check `scan.truncated`: when true the listing is incomplete and `scan.truncationReasons` says which cap was hit — do not report that a project is absent from a truncated scan. " ++ "Every cap is resumable: pass `scan.continuation.cursor` back as `cursor` to continue, and use `nextOffset`/`hasMore` for ordinary paging within one scan.",scope: "read",annotations: READ_ONLY,limit: { key: "projects.list", max: 30, windowMs: 60_000 },@@ -36,8 +37,13 @@ export const DISCOVERY_TOOLS: McpTool[] = [query: { type: "string", description: "Optional case-insensitive substring matched against the directory name." },limit: { type: "number", minimum: 1, maximum: PROJECT_LIMITS.maxPageSize, description: `Page size. Default ${PROJECT_LIMITS.defaultPageSize}.` },offset: { type: "number", minimum: 0, description: "Page offset into the deterministic container-then-name ordering. Default 0." },+ cursor: { type: "string", description: "scan.continuation.cursor from a truncated call, to resume the walk where it stopped." },+ }),+ run: (a) => listProjects({+ query: opt(a, "query"),+ cursor: opt(a, "cursor"),+ ...page(a, PROJECT_LIMITS.maxPageSize, PROJECT_LIMITS.defaultPageSize),}),- run: (a) => listProjects({ query: opt(a, "query"), ...page(a, PROJECT_LIMITS.maxPageSize, PROJECT_LIMITS.defaultPageSize) }),},{name: "skills_list",@@ -46,7 +52,7 @@ export const DISCOVERY_TOOLS: McpTool[] = ["(.mso/skills, .claude/skills, .hermes/skills, .agents/skills, .codex/skills) of every project across every configured container. " +"Each row carries the exact catalog id to pass to skills_read — a project skill is <rootId>/<project>/<name>, so two projects may ship the same skill name in the same or different roots — plus trust, source and its project. " +"Trust is earned, not assumed: a project skill is only `local` after realpath containment, owner uid and a regular non-symlink SKILL.md. " +- "Check `scan.truncated` before concluding a skill does not exist.",+ "Check `scan.truncated` before concluding a skill does not exist; when it is true, pass `scan.continuation.cursor` back as `cursor` to resume the scan.",scope: "read",annotations: READ_ONLY,limit: { key: "skills.list", max: 30, windowMs: 60_000 },@@ -56,12 +62,13 @@ export const DISCOVERY_TOOLS: McpTool[] = [query: { type: "string", description: "Optional case-insensitive substring matched against id and description." },limit: { type: "number", minimum: 1, maximum: SKILL_PAGE_MAX, description: "Page size. Default 100." },offset: { type: "number", minimum: 0, description: "Page offset into the id-sorted catalog. Default 0." },+ cursor: { type: "string", description: "scan.continuation.cursor from a truncated call, to resume the catalog build where it stopped." },}),run: async (a) => {const project = opt(a, "project");const trust = opt(a, "trust");const query = opt(a, "query")?.toLowerCase();- const { skills: all, scan } = await catalogSkillsDetailed();+ const { skills: all, scan } = await catalogSkillsDetailed({ cursor: opt(a, "cursor") });const matched = all.filter((skill) => {if (project && !(skill.project?.id === project || skill.project?.path === project || skill.project?.name === project)) return false;if (trust && skill.trust !== trust) return false;@@ -76,13 +83,17 @@ export const DISCOVERY_TOOLS: McpTool[] = [.filter((row, i, rows) => rows.findIndex((r) => r.projectId === row.projectId) === i): undefined;const { limit, offset } = page(a, SKILL_PAGE_MAX, 100);+ const pageRows = matched.slice(offset, offset + limit);+ const hasMore = offset + pageRows.length < matched.length;return {total: matched.length,offset,limit,+ hasMore,+ ...(hasMore ? { nextOffset: offset + pageRows.length } : {}),scan,...(ambiguousProjects ? { ambiguousProjects } : {}),- skills: matched.slice(offset, offset + limit).map((skill) => ({+ skills: pageRows.map((skill) => ({id: skill.id,name: skill.name,description: skill.description,diff --git a/lib/mcp/toolset.ts b/lib/mcp/toolset.tsindex f6fc3492..bd2ca363 100644--- a/lib/mcp/toolset.ts+++ b/lib/mcp/toolset.ts@@ -2,9 +2,9 @@ import { createHash } from "crypto";import type { Scope } from "./scope";import type { McpTool } from "./tool-kit";-export const MCP_SERVER_VERSION = "1.5.1";-export const MCP_TOOLSET_VERSION = "2026.08.20.4";-export const MCP_TOOLSET_CHANGED_AT = "2026-08-20T15:30:00Z";+export const MCP_SERVER_VERSION = "1.5.2";+export const MCP_TOOLSET_VERSION = "2026.08.20.5";+export const MCP_TOOLSET_CHANGED_AT = "2026-08-20T16:00:00Z";export type McpToolsetInfo = {serverVersion: string;diff --git a/lib/skills/catalog-bounds.test.ts b/lib/skills/catalog-bounds.test.tsindex b44b822b..25298eee 100644--- a/lib/skills/catalog-bounds.test.ts+++ b/lib/skills/catalog-bounds.test.ts@@ -50,7 +50,7 @@ describe("project skill ids are globally unique across roots", () => {const [row] = await catalogSkills({ appDir: await temp(), homeDir: await temp(), projects: refs(a) });expect(row.project).toBeDefined();expect(row.id).toBe(`${row.project!.rootId}/${row.project!.name}/${row.name}`);- expect(row.project!.rootId).toMatch(/^[a-f0-9]{8}$/);+ expect(row.project!.rootId).toMatch(/^[a-f0-9]{32}$/);expect(row.project!.id).toBe(`${row.project!.rootId}/${row.project!.name}`);});diff --git a/lib/skills/catalog-nofollow.test.ts b/lib/skills/catalog-nofollow.test.tsnew file mode 100644index 00000000..a140105e--- /dev/null+++ b/lib/skills/catalog-nofollow.test.ts@@ -0,0 +1,163 @@+import { afterEach, describe, expect, it } from "vitest";+import { mkdir, mkdtemp, rm, symlink, writeFile } from "fs/promises";+import os from "os";+import path from "path";+import { catalogSkills, catalogSkillsDetailed, readSkillFile } from "./catalog";+import { SKILL_SCAN_LIMITS } from "./catalog-types";+import { projectRefFor } from "./project-skills";++const temps: string[] = [];+async function temp() {+ const dir = await mkdtemp(path.join(os.tmpdir(), "mso-nofollow-"));+ temps.push(dir);+ return dir;+}+afterEach(async () => { await Promise.all(temps.splice(0).map((d) => rm(d, { recursive: true, force: true }))); });++const body = (name: string) => `---\nname: ${name}\ndescription: ${name} desc\n---\n\n# ${name}\n`;++async function skill(root: string, name: string) {+ const dir = path.join(root, name);+ await mkdir(dir, { recursive: true });+ await writeFile(path.join(dir, "SKILL.md"), body(name));+ return dir;+}++describe("readSkillFile is nofollow at the SKILL.md itself", () => {+ it("reads a regular SKILL.md", async () => {+ const root = await temp();+ const dir = await skill(root, "real");+ await expect(readSkillFile(path.join(dir, "SKILL.md"))).resolves.toContain("# real");+ });++ it("refuses a SKILL.md that is a symlink to ANOTHER SKILL.md", async () => {+ // This is the case the previous implementation accepted: it realpath'd first, saw a+ // basename of SKILL.md, and opened the TARGET with O_NOFOLLOW — so the nofollow+ // promise was enforced against a path the caller never supplied.+ const root = await temp();+ const donor = await skill(root, "donor");+ const dir = path.join(root, "borrower");+ await mkdir(dir, { recursive: true });+ await symlink(path.join(donor, "SKILL.md"), path.join(dir, "SKILL.md"));+ await expect(readSkillFile(path.join(dir, "SKILL.md"))).resolves.toBeNull();+ });++ it("refuses a SKILL.md symlinked to an unrelated file", async () => {+ const root = await temp();+ const secret = path.join(root, "config");+ await writeFile(secret, "secret");+ const dir = path.join(root, "sneaky");+ await mkdir(dir, { recursive: true });+ await symlink(secret, path.join(dir, "SKILL.md"));+ await expect(readSkillFile(path.join(dir, "SKILL.md"))).resolves.toBeNull();+ });++ it("refuses a path whose final component is not named SKILL.md", async () => {+ const root = await temp();+ const other = path.join(root, "NOTES.md");+ await writeFile(other, "x");+ await expect(readSkillFile(other)).resolves.toBeNull();+ });++ it("drops a symlinked SKILL.md from the catalog entirely", async () => {+ const app = await temp();+ const root = path.join(app, "claude-skills");+ await skill(root, "honest");+ const donor = await skill(root, "donor");+ const linked = path.join(root, "linked");+ await mkdir(linked, { recursive: true });+ await symlink(path.join(donor, "SKILL.md"), path.join(linked, "SKILL.md"));++ const rows = await catalogSkills({ appDir: app, homeDir: await temp(), projects: [] });+ expect(rows.map((r) => r.id).sort()).toEqual(["donor", "honest"]);+ });+});++describe("skill root walks are bounded by DIRENTS, not by accepted entries", () => {+ it("stops after the entry cap even when every entry is a regular file", async () => {+ // A root full of rejected entries used to cost one iteration each with no budget+ // consumed, so the advertised cap bounded nothing.+ const app = await temp();+ const root = path.join(app, "claude-skills");+ await mkdir(root, { recursive: true });+ await Promise.all(+ Array.from({ length: SKILL_SCAN_LIMITS.maxEntriesPerRoot + 25 }, (_, i) =>+ writeFile(path.join(root, `junk-${String(i).padStart(4, "0")}.txt`), "x")),+ );+ const { scan } = await catalogSkillsDetailed({ appDir: app, homeDir: await temp(), projects: [] });+ expect(scan.truncated).toBe(true);+ expect(scan.truncationReasons.some((r) => r.startsWith("maxEntriesPerRoot"))).toBe(true);+ });+});++describe("the overall project-skill cap is enforced inside the loop", () => {+ it("never exceeds maxProjectSkills, even when one root would overshoot it", async () => {+ const workspace = await temp();+ // Each project ships more skills than the remaining budget, so a per-root check+ // alone would let the total sail past the cap.+ const perProject = 40;+ const projectCount = Math.ceil((SKILL_SCAN_LIMITS.maxProjectSkills + 60) / perProject);+ const projects = [];+ for (let p = 0; p < projectCount; p += 1) {+ const dir = path.join(workspace, `proj-${String(p).padStart(3, "0")}`);+ const root = path.join(dir, ".claude/skills");+ await mkdir(root, { recursive: true });+ await Promise.all(Array.from({ length: perProject }, (_, i) =>+ mkdir(path.join(root, `s${String(i).padStart(3, "0")}`), { recursive: true })+ .then(() => writeFile(path.join(root, `s${String(i).padStart(3, "0")}`, "SKILL.md"), body("s")))));+ projects.push(projectRefFor(dir, workspace));+ }++ const { skills, scan } = await catalogSkillsDetailed({ appDir: await temp(), homeDir: await temp(), projects });+ const projectSkills = skills.filter((s) => s.project);+ expect(projectSkills.length).toBeLessThanOrEqual(SKILL_SCAN_LIMITS.maxProjectSkills);+ expect(scan.truncated).toBe(true);+ expect(scan.truncationReasons).toContain("maxProjectSkills");+ });+});++describe("skill scans expose resumable continuation for every cap", () => {+ it("emits a continuation cursor and pending roots when a cap is hit", async () => {+ const app = await temp();+ const root = path.join(app, "claude-skills");+ await mkdir(root, { recursive: true });+ await Promise.all(+ Array.from({ length: SKILL_SCAN_LIMITS.maxEntriesPerRoot + 10 }, (_, i) =>+ skill(root, `s${String(i).padStart(4, "0")}`)),+ );+ const first = await catalogSkillsDetailed({ appDir: app, homeDir: await temp(), projects: [] });+ expect(first.scan.truncated).toBe(true);+ expect(first.scan.continuation).toBeDefined();+ expect(first.scan.continuation!.cursor).toBeTruthy();+ expect(first.scan.continuation!.cursors.some((c) => c.root === root)).toBe(true);++ const second = await catalogSkillsDetailed({+ appDir: app, homeDir: await temp(), projects: [], cursor: first.scan.continuation!.cursor,+ });+ // The resumed page returns the entries the first one could not reach.+ expect(second.skills.length).toBeGreaterThan(0);+ const firstIds = new Set(first.skills.map((s) => s.id));+ expect(second.skills.some((s) => !firstIds.has(s.id))).toBe(true);+ });++ it("omits continuation entirely when nothing was truncated", async () => {+ const app = await temp();+ await skill(path.join(app, "claude-skills"), "one");+ const { scan } = await catalogSkillsDetailed({ appDir: app, homeDir: await temp(), projects: [] });+ expect(scan.truncated).toBe(false);+ expect(scan.continuation).toBeUndefined();+ });+});++describe("root ids survive a real 8-hex collision", () => {+ it("keeps both colliding roots' same-named projects visible", async () => {+ // /tmp/mso-root-50323 and /tmp/mso-root-125549 both hash to 51e156ef at 8 hex —+ // a collision found by an actual probe, not a hypothetical.+ const a = projectRefFor("/tmp/mso-root-50323/widget", "/tmp/mso-root-50323");+ const b = projectRefFor("/tmp/mso-root-125549/widget", "/tmp/mso-root-125549");+ expect(a.rootId.slice(0, 8)).toBe(b.rootId.slice(0, 8));+ expect(a.rootId).not.toBe(b.rootId);+ expect(a.id).not.toBe(b.id);+ expect(a.rootId).toMatch(/^[a-f0-9]{32}$/);+ });+});diff --git a/lib/skills/catalog-scan.ts b/lib/skills/catalog-scan.tsindex c723f2fd..527504f8 100644--- a/lib/skills/catalog-scan.ts+++ b/lib/skills/catalog-scan.ts@@ -19,17 +19,23 @@ export type RootSpec = {};/**- * Skills intentionally live outside OS_FS_READ_ROOTS. Only an exact SKILL.md is- * readable here: the path is realpath'd and its basename checked, so a link to- * ~/.ssh/config resolves to basename "config" and is refused, while a link to another- * SKILL.md stays equivalent to placing one in a skill root (handled by trust policy).- * The realpath is then opened O_NOFOLLOW under a byte cap — an oversized SKILL.md is- * skipped rather than loaded, because it is untrusted content.+ * Skills intentionally live outside OS_FS_READ_ROOTS, so the read itself is the guard.+ *+ * The SUPPLIED path is opened, not a canonicalized substitute. The previous version+ * realpath'd first and then opened the *target* with O_NOFOLLOW, which enforced the+ * nofollow promise against a path the caller never gave us: a `SKILL.md -> other/SKILL.md`+ * symlink passed the basename check and was read. Now the final component must itself be+ * a regular file — `O_NOFOLLOW` fails with ELOOP on any symlink, whatever it points at —+ * and the byte cap is checked against `fstat` before any bytes move, because an oversized+ * SKILL.md is untrusted content we decline rather than truncate.+ *+ * Parent containment is a SEPARATE concern and belongs to the caller (`scanRoot` for the+ * root, `projectSkillTrust` for a project): canonicalizing the parent here would drag the+ * final component through `realpath` again and reopen exactly this hole.*/export async function readSkillFile(file: string): Promise<string | null> {- const real = await fs.realpath(file).catch(() => null);- if (!real || path.basename(real) !== SKILL_FILE) return null;- return readBoundedRegularFile(real, SKILL_SCAN_LIMITS.maxSkillBytes);+ if (path.basename(file) !== SKILL_FILE) return null;+ return readBoundedRegularFile(file, SKILL_SCAN_LIMITS.maxSkillBytes);}export function skillDescription(md: string): string {@@ -66,27 +72,39 @@ async function verifiedBundledSkill(dir: string, md: string): Promise<Pick<Skill/** Bounded `opendir` walk of ONE skill root — global roots included, which previously* had no entry budget at all. Names are capped before anything is stat'd or read. */-async function skillDirNames(root: string, deadlineAt: number): Promise<{ names: string[]; hitCap: boolean }> {+async function skillDirNames(root: string, deadlineAt: number, skipEntries = 0): Promise<{ names: string[]; hitCap: boolean; entriesVisited: number }> {const names: string[] = [];let hitCap = false;+ let entriesVisited = skipEntries;+ let seen = 0;const handle = await fs.opendir(root).catch(() => null);- if (!handle) return { names, hitCap };+ if (!handle) return { names, hitCap, entriesVisited };try {for await (const entry of handle) {- if (names.length >= SKILL_SCAN_LIMITS.maxEntriesPerRoot || Date.now() > deadlineAt) { hitCap = true; break; }+ seen += 1;+ if (seen <= skipEntries) continue;+ // EVERY dirent costs budget, accepted or not. Counting only directories meant a+ // root holding a million regular files still required a million iterations before+ // the advertised entry cap was reached.+ if (entriesVisited - skipEntries >= SKILL_SCAN_LIMITS.maxEntriesPerRoot || Date.now() > deadlineAt) { hitCap = true; break; }+ entriesVisited += 1;if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;names.push(entry.name);}} catch {// A root that vanishes mid-walk yields what we already have.}- return { names: names.sort((a, b) => a.localeCompare(b)), hitCap };+ return { names: names.sort((a, b) => a.localeCompare(b)), hitCap, entriesVisited };}-export async function scanRoot(spec: RootSpec, deadlineAt: number): Promise<{ found: Array<{ skill: SkillInfo; priority: number }>; hitCap: boolean }> {- const { names, hitCap } = await skillDirNames(spec.path, deadlineAt);+export async function scanRoot(spec: RootSpec, deadlineAt: number, skipEntries = 0): Promise<{ found: Array<{ skill: SkillInfo; priority: number }>; hitCap: boolean; entriesVisited: number }> {+ const { names, hitCap: dirCap, entriesVisited } = await skillDirNames(spec.path, deadlineAt, skipEntries);+ let hitCap = dirCap;const found: Array<{ skill: SkillInfo; priority: number }> = [];for (const name of names) {+ // The deadline is enforced THROUGH the per-skill stat/read work too, not only in+ // the dirent loop, which is where a slow filesystem actually spends its time.+ if (Date.now() > deadlineAt) { hitCap = true; break; }const dir = path.join(spec.path, name);if (!(await fs.stat(dir).catch(() => null))?.isDirectory()) continue;const file = path.join(dir, SKILL_FILE);@@ -118,6 +136,6 @@ export async function scanRoot(spec: RootSpec, deadlineAt: number): Promise<{ fo},});}- return { found, hitCap };+ return { found, hitCap, entriesVisited };}diff --git a/lib/skills/catalog-types.ts b/lib/skills/catalog-types.tsindex 4820ee5e..97ce5610 100644--- a/lib/skills/catalog-types.ts+++ b/lib/skills/catalog-types.ts@@ -46,6 +46,17 @@ export type SkillInfo = {};};+/** A resumable position in a skill scan. Positional in readdir order, like the project+ * walk's cursor: name-ordered resume would require visiting every dirent, which is the+ * unbounded walk the entry cap exists to prevent. */+export type SkillScanCursor = {+ roots: Array<{ root: string; entriesConsumed: number }>;+ /** Roots fully covered by the previous page; skipped on resume. */+ skipRoots: string[];+ /** Projects already consumed, so a maxProjects/maxProjectSkills cap can be continued. */+ projectOffset: number;+};+/** What a catalog build could NOT cover. Mirrors lib/host's ScanReport so the two* discovery surfaces report incompleteness the same way. */export type SkillScanReport = {@@ -53,6 +64,16 @@ export type SkillScanReport = {truncationReasons: string[];scannedRoots: number;scannedProjects: number;+ /** Present ONLY when truncated. A cap the caller cannot resume is data loss with a+ * label on it, so every cap emits a way to continue. */+ continuation?: {+ pendingRoots: string[];+ cursors: Array<{ root: string; entriesConsumed: number }>;+ pendingProjects: number;+ cursorSemantics: "readdir-position";+ note: string;+ cursor: string;+ };};export const skillIsExecutableByDefault = (skill: Pick<SkillInfo, "trust">): boolean => skill.trust !== "untrusted";diff --git a/lib/skills/catalog.ts b/lib/skills/catalog.tsindex fc99e1b0..76a81fbf 100644--- a/lib/skills/catalog.ts+++ b/lib/skills/catalog.ts@@ -3,13 +3,13 @@ import path from "path";import { scanRoot, type RootSpec } from "./catalog-scan";import {SKILL_FILE, SKILL_SCAN_LIMITS, skillIsExecutableByDefault,- type ProjectRef, type SkillInfo, type SkillScanReport, type SkillSource, type SkillTrust,+ type ProjectRef, type SkillInfo, type SkillScanCursor, type SkillScanReport, type SkillSource, type SkillTrust,} from "./catalog-types";import { discoveredProjects, projectSkillRoots } from "./project-skills";export { SKILL_FILE, SKILL_SCAN_LIMITS, skillIsExecutableByDefault };export { readSkillFile, skillDescription } from "./catalog-scan";-export type { ProjectRef, SkillInfo, SkillScanReport, SkillSource, SkillTrust };+export type { ProjectRef, SkillInfo, SkillScanCursor, SkillScanReport, SkillSource, SkillTrust };type CatalogOptions = {appDir?: string;@@ -17,8 +17,29 @@ type CatalogOptions = {/** Projects to scan for per-project skill roots. Defaults to every project across* every configured container; pass `[]` to catalog global roots only. */projects?: ProjectRef[];+ /** A `scan.continuation.cursor` from a truncated build, to resume it. */+ cursor?: string;};+export function encodeSkillCursor(cursor: SkillScanCursor): string {+ return Buffer.from(JSON.stringify(cursor), "utf8").toString("base64url");+}++export function decodeSkillCursor(raw: string | undefined): SkillScanCursor | undefined {+ if (!raw) return undefined;+ try {+ const parsed = JSON.parse(Buffer.from(raw, "base64url").toString("utf8")) as SkillScanCursor;+ if (!parsed || typeof parsed !== "object") return undefined;+ return {+ roots: Array.isArray(parsed.roots) ? parsed.roots.filter((r) => typeof r?.root === "string") : [],+ skipRoots: Array.isArray(parsed.skipRoots) ? parsed.skipRoots.filter((r) => typeof r === "string") : [],+ projectOffset: Number.isFinite(parsed.projectOffset) ? Math.max(0, Math.floor(parsed.projectOffset)) : 0,+ };+ } catch {+ return undefined;+ }+}+/*** Root priority is a security boundary, not just display order.*@@ -53,6 +74,10 @@ export async function catalogSkillsDetailed(options: CatalogOptions = {}): Promiconst appDir = options.appDir ?? process.cwd();const homeDir = options.homeDir ?? os.homedir();const deadlineAt = Date.now() + SKILL_SCAN_LIMITS.maxScanMs;+ const cursor = decodeSkillCursor(options.cursor);+ const resumeRoots = new Map((cursor?.roots ?? []).map((r) => [r.root, r.entriesConsumed]));+ const skipRoots = new Set(cursor?.skipRoots ?? []);+ const projectOffset = cursor?.projectOffset ?? 0;const reasons: string[] = [];let projects = options.projects;@@ -61,7 +86,8 @@ export async function catalogSkillsDetailed(options: CatalogOptions = {}): Promiprojects = discovered.projects;reasons.push(...discovered.truncationReasons);}- const { roots: projectRoots, truncated: projectsCapped } = await projectSkillRoots(projects);+ const remaining = projects.slice(projectOffset);+ const { roots: projectRoots, truncated: projectsCapped } = await projectSkillRoots(remaining);if (projectsCapped) reasons.push("maxProjects");const specs: RootSpec[] = [@@ -72,27 +98,69 @@ export async function catalogSkillsDetailed(options: CatalogOptions = {}): Promi];const chosen = new Map<string, { skill: SkillInfo; priority: number }>();+ const cursors: SkillScanCursor["roots"] = [];+ const pendingRoots: string[] = [];+ const doneRoots: string[] = [];+ const consumedProjects = new Set<string>();let projectSkills = 0;- for (const spec of specs) {- if (Date.now() > deadlineAt) { reasons.push("deadline"); break; }- if (spec.project && projectSkills >= SKILL_SCAN_LIMITS.maxProjectSkills) { reasons.push("maxProjectSkills"); break; }- const { found, hitCap } = await scanRoot(spec, deadlineAt);- if (hitCap) reasons.push(`maxEntriesPerRoot:${spec.path}`);+ let stoppedAt = -1;++ for (const [index, spec] of specs.entries()) {+ if (skipRoots.has(spec.path)) { doneRoots.push(spec.path); continue; }+ if (Date.now() > deadlineAt) { reasons.push("deadline"); stoppedAt = index; break; }+ if (spec.project && projectSkills >= SKILL_SCAN_LIMITS.maxProjectSkills) {+ reasons.push("maxProjectSkills");+ stoppedAt = index;+ break;+ }+ const { found, hitCap, entriesVisited } = await scanRoot(spec, deadlineAt, resumeRoots.get(spec.path) ?? 0);+ if (hitCap) {+ reasons.push(`maxEntriesPerRoot:${spec.path}`);+ cursors.push({ root: spec.path, entriesConsumed: entriesVisited });+ } else {+ doneRoots.push(spec.path);+ }+ let overflowed = false;for (const candidate of found) {+ // The overall cap is checked INSIDE the loop. Checking it only before scanRoot+ // let one root carry the total from just under 300 to nearly 500.+ if (spec.project && projectSkills >= SKILL_SCAN_LIMITS.maxProjectSkills) {+ reasons.push("maxProjectSkills");+ overflowed = true;+ break;+ }if (spec.project) projectSkills += 1;const current = chosen.get(candidate.skill.id);if (!current || candidate.priority > current.priority) chosen.set(candidate.skill.id, candidate);}+ if (spec.project) consumedProjects.add(spec.project.id);+ if (overflowed) { stoppedAt = index; break; }}+ if (stoppedAt >= 0) pendingRoots.push(...specs.slice(stoppedAt).map((r) => r.path));const truncationReasons = [...new Set(reasons)];+ const pendingProjects = Math.max(0, projects.length - projectOffset - consumedProjects.size);return {skills: [...chosen.values()].map(({ skill }) => skill).sort((a, b) => a.id.localeCompare(b.id)),scan: {truncated: truncationReasons.length > 0,truncationReasons,scannedRoots: specs.length,- scannedProjects: Math.min(projects.length, SKILL_SCAN_LIMITS.maxProjects),+ scannedProjects: consumedProjects.size,+ ...(truncationReasons.length ? {+ continuation: {+ pendingRoots: [...new Set(pendingRoots)],+ cursors,+ pendingProjects,+ cursorSemantics: "readdir-position" as const,+ note: "Pass `cursor` back to resume. Positions are readdir order and are valid while the directories are unchanged.",+ cursor: encodeSkillCursor({+ roots: cursors,+ skipRoots: [...new Set(doneRoots)],+ projectOffset: projectOffset + consumedProjects.size,+ }),+ },+ } : {}),},};}diff --git a/lib/skills/project-skills.ts b/lib/skills/project-skills.tsindex bbccdafe..63aae6c3 100644--- a/lib/skills/project-skills.ts+++ b/lib/skills/project-skills.ts@@ -15,10 +15,9 @@// Anything else is cataloged as `untrusted`: visible for inspection, instructions// withheld. The generic HOME agent roots (~/.claude/skills, …) keep their existing// untrusted behaviour — this promotion is for project-scoped roots only.-import { createHash } from "crypto";import { promises as fs } from "fs";import path from "path";-import { listProjectDirs } from "@/lib/host/project-roots";+import { listProjectDirs, shortId } from "@/lib/host/project-roots";import { SKILL_FILE, SKILL_SCAN_LIMITS, type ProjectRef, type SkillTrust } from "./catalog-types";/** Where a project may keep skills. `.mso/skills` is the explicit MSO root — the@@ -53,7 +52,9 @@ function contains(parent: string, child: string): boolean {/** The same short-hash identity `lib/host/project-roots` assigns a container, so a* skill's `project.rootId` and a `projects_list` row's `rootId` are the same value. */export function projectRefFor(dir: string, containerPath: string): ProjectRef {- const rootId = createHash("sha256").update(containerPath).digest("hex").slice(0, 8);+ // The SAME function lib/host uses, not a second copy of the recipe. A local+ // reimplementation is how the two sides silently drifted to different widths.+ const rootId = shortId(containerPath);const name = path.basename(dir);return { id: `${rootId}/${name}`, name, path: dir, rootId };}diff --git a/skills/README.md b/skills/README.mdindex e530474e..23444409 100644--- a/skills/README.md+++ b/skills/README.md@@ -17,8 +17,10 @@ The assistant lists/loads only `official`, `verified`, and `local` instructions## Ids: a project skill cannot shadow anythingA global skill is addressed by its bare **name**. A project is `<rootId>/<name>` and a-project skill is `<rootId>/<project>/<name>`, where `rootId` is a short sha256 of the-canonical container path. That makes ids **globally unique**, which the bare+project skill is `<rootId>/<project>/<name>`, where `rootId` is **128 bits** (32 hex+characters) of sha256 over the canonical container path — it was 32 bits, and a review+found a real collision between two `/tmp` roots. Nothing dedupes on the hash either: the+internal key is the full canonical path. That makes ids **globally unique**, which the bare`<project>/<name>` form was not: two *different configured roots* may each hold a`widget` shipping `deploy`, and both stay visible, readable and searchable instead ofone silently winning. The derived `projects/` container gets its own `rootId` for the@@ -37,7 +39,9 @@ only when all three hold:1. **Containment** — the skill directory realpaths back inside its project, so a`.claude/skills -> /tmp/attacker` symlink is *discovered*, not followed.2. **Ownership** — the skill directory and its `SKILL.md` belong to the uid MSO runs as.-3. **Shape** — `SKILL.md` is a regular file, not a symlink to somewhere else.+3. **Shape** — `SKILL.md` is a regular file, not a symlink to somewhere else. The reader+ is `O_NOFOLLOW` at that exact path, so a `SKILL.md -> other/SKILL.md` link is not an+ untrusted skill, it is not a skill at all and is dropped from the catalog.Anything else is cataloged `untrusted`. The generic HOME agent roots keep their existinguntrusted behaviour; this promotion applies to project-scoped roots only.@@ -45,13 +49,16 @@ untrusted behaviour; this promotion applies to project-scoped roots only.Scans are bounded and say so. Caps: 12 containers, 400 entries per container, 400projects, 60 projects scanned for skills, 200 entries per skill root, 300 projectskills, a 256 KiB `SKILL.md`, and a 4-second wall clock per walk. Directory iteration-uses `opendir` and stops at the cap rather than reading the whole listing first, and-every file read goes through one byte-capped `O_NOFOLLOW` reader that checks the cap-against `fstat` before any bytes move.+uses `opendir` and stops at the cap rather than reading the whole listing first, **every+dirent counts against the cap whether or not it is accepted**, the deadline is enforced+through the per-entry stat/read work, the 300-skill total is enforced inside the+candidate loop, and every file read goes through one byte-capped `O_NOFOLLOW` reader that+checks the cap against `fstat` before any bytes move.Every discovery response carries a **scan report**. `truncated:false` means "this is all-of it"; hitting a cap sets `truncated:true` and names the reason. Do not conclude a skill-is absent from a truncated scan.+of it"; hitting a cap sets `truncated:true`, names the reason, and includes+`continuation` — pending roots, per-root cursors and an opaque `cursor` to pass back and+resume. Do not conclude a skill is absent from a truncated scan.## Contract