diff --git a/docs/organization-projects.md b/docs/organization-projects.md index 8691349..b412a60 100644 --- a/docs/organization-projects.md +++ b/docs/organization-projects.md @@ -34,10 +34,12 @@ an absolute `baseDir`. After preflight it: 1. Prepares missing repositories in the existing `//projects/-` layout. Existing source checkouts keep their branch and edits. -2. Creates or reuses a UID-scoped storage container below - `//organization-projects//`. The folder opened - in Claude is a child named exactly after the project, including case and spaces: - `Ontology`, never `ontology-`. Identity remains in the parent and manifests. +2. Creates or reuses the project's container, + `//organization-projects/-`, beside the + organization's other projects. The UID keeps projects of different backends apart. + The folder opened in Claude or Codex is a child named exactly after the project, + including case and spaces: `Ontology`, never `ontology-`. Identity remains in + the container and manifests. 3. Prepares independent branch checkouts beneath the container's `repositories/`, alongside the named workspace. Cloning uses `--reference-if-able --dissociate` to reuse local objects without sharing mutable @@ -58,6 +60,22 @@ becomes `ready`. This means the checkouts are prepared, not that a Claude sessio has attached them. Existing schema 1 containers reuse their repository paths and copy their instructions into the named child without moving or recloning repos. Project renames rename the child workspace while retaining checkout paths. +Earlier versions put each container one level deeper, in a folder named after a hash +of the backend address (`organization-projects/<16 hex>/-`). The next +setup of such a project moves its container up, rewrites the paths its manifests +record and removes the emptied hash folder. The checkouts are standalone clones, so Git +is unaffected, but a chat or terminal open in the old folder must reopen the new one. +Two hashed copies of one project are refused rather than guessed between. + +The resulting layout of a repositories folder: + +``` +// + projects/-/ one checkout per repository + organization-projects/-/ one container per project set up locally + / the folder opened: AGENTS.md or CLAUDE.md + repositories/-/-/ the project's branch checkouts +``` The result includes a local root and `claude://code/new?folder=...` link. Claude's host adapter uses `readOrganizationProjectWorkspace` to validate both manifests diff --git a/package-lock.json b/package-lock.json index 1950efb..b7bcf9a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@dev-mainsequence/devtools", - "version": "0.3.19", + "version": "0.3.20", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@dev-mainsequence/devtools", - "version": "0.3.19", + "version": "0.3.20", "license": "MIT", "bin": { "ms-devtools": "dist/runner.js" diff --git a/package.json b/package.json index 1acba06..71780e9 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@dev-mainsequence/devtools", - "version": "0.3.19", + "version": "0.3.20", "description": "Shared MainSequence developer actions, project operations, MCP client and command runner", "license": "MIT", "engines": { diff --git a/src/shared/organizationProjectWorkspace.ts b/src/shared/organizationProjectWorkspace.ts index 705b3a8..0ca5e03 100644 --- a/src/shared/organizationProjectWorkspace.ts +++ b/src/shared/organizationProjectWorkspace.ts @@ -1,6 +1,6 @@ import * as fs from 'node:fs/promises'; import * as path from 'node:path'; -import { createHash, randomUUID } from 'node:crypto'; +import { randomUUID } from 'node:crypto'; import { HostServices, SessionService, ToolingError } from './models'; import { OrganizationProjectClient, projectUid } from './organizationProjects'; import { canonicalRepositoryDir, projectContext, repositoriesFolder, repositorySetupInfo, safeSlug } from './repositories'; @@ -86,6 +86,44 @@ async function namedDirectory(parent: string, name: string, uid: string): Promis return path.join(parent, names[0] || `${safeSlug(name)}-${uid}`); } +/** + * Earlier versions kept each project one level deeper, in a folder named after a hash of the backend address: + * `organization-projects/<16 hex>/-`. The UID in the name already keeps projects of different + * backends apart, so this moves the project's container up beside the others and rewrites the paths its + * manifests record. Its checkouts are standalone clones (`--dissociate`), so moving them keeps Git intact. + * The emptied hash folder is removed; anything else in it stays. + */ +async function adoptHashedContainer(projectsRoot: string, container: string, uid: string, backend: string, state: ExecutionState, progress?: (message: string) => void) { + if (await exists(container) || !await exists(projectsRoot)) return; + const found: string[] = []; + for (const entry of await fs.readdir(projectsRoot)) { + if (!/^[0-9a-f]{16}$/.test(entry)) continue; + const parent = path.join(projectsRoot, entry), stat = await fs.lstat(parent); + if (!stat.isDirectory() || stat.isSymbolicLink()) continue; + for (const name of await fs.readdir(parent)) if (name === uid || name.endsWith(`-${uid}`)) found.push(path.join(parent, name)); + } + if (!found.length) return; + if (found.length > 1) throw new ToolingError('INVALID_REQUEST', `Multiple workspace folders match ${uid}. Resolve the duplicate folders first.`); + const from = found[0]; + await ordinaryDirectory(from); + const manifestPath = path.join(from, '.mainsequence-project.json'); + if (!await exists(manifestPath)) throw new ToolingError('INVALID_REQUEST', `${from} has no project manifest. Move or remove it before setting up this project.`); + const manifest = await readManifest(manifestPath); + if (manifest.backend !== backend || manifest.projectUid !== uid) throw new ToolingError('INVALID_REQUEST', 'This workspace belongs to another project or backend.'); + const moved = (value: unknown) => typeof value === 'string' && (value === from || value.startsWith(from + path.sep)) ? path.join(container, path.relative(from, value)) : value; + const updated = { ...manifest, ...(typeof manifest.root === 'string' ? { root: moved(manifest.root) } : {}), + ...(Array.isArray(manifest.repositories) ? { repositories: manifest.repositories.map((row: any) => ({ ...row, path: moved(row?.path) })) } : {}) }; + progress?.(`Moving the project workspace to ${container}.`); + state.mutationStarted = true; + await fs.rename(from, container); + await atomicJson(path.join(container, '.mainsequence-project.json'), updated); + if (typeof updated.root === 'string' && await exists(path.join(updated.root, '.mainsequence-project.json'))) { + const rootManifest = await readManifest(path.join(updated.root, '.mainsequence-project.json')); + if (JSON.stringify(rootManifest) === JSON.stringify(manifest)) await atomicJson(path.join(updated.root, '.mainsequence-project.json'), updated); + } + await fs.rmdir(path.dirname(from)).catch(() => {}); +} + /** Stable, independent branch checkouts. No reset, stash, force checkout, deletion or automatic pull. */ export async function setupOrganizationProject(input: Input, options: Options): Promise { const { session, signal, state } = options; @@ -117,7 +155,9 @@ export async function setupOrganizationProject(input: Input, options: Options): // The UID identifies the storage container, never the folder opened/displayed by Claude. // Repositories are siblings of the named workspace: /add-dir must register each one, // instead of treating nested checkouts as already covered by the working directory. - const container = await namedDirectory(path.join(base, org, 'organization-projects', createHash('sha256').update(backend).digest('hex').slice(0, 16)), project.name, uid); + const projectsRoot = path.join(base, org, 'organization-projects'); + const container = await namedDirectory(projectsRoot, project.name, uid); + await adoptHashedContainer(projectsRoot, container, uid, backend, state, host.progress); const root = path.join(container, displayName); const manifestPath = path.join(container, '.mainsequence-project.json'); await ordinaryDirectory(container); diff --git a/tests/organization-projects.test.cjs b/tests/organization-projects.test.cjs index 9bc5183..3788c34 100644 --- a/tests/organization-projects.test.cjs +++ b/tests/organization-projects.test.cjs @@ -172,3 +172,38 @@ test('workspace membership cannot point outside its managed repository container for(const folder of [root,path.dirname(root)])await fs.writeFile(path.join(folder,'.mainsequence-project.json'),JSON.stringify(manifest)); await assert.rejects(readOrganizationProjectWorkspace(root),/membership/); }); +test('a project lives in /organization-projects/-, beside the others, with no backend folder', async t => { + const f = await fixture(t, true), first = await f.tooling.dispatch(f.input); assert.equal(first.status, 'success', JSON.stringify(first)); + const container = path.dirname(first.data.root), parts = path.relative(f.baseDir, container).split(path.sep); + assert.equal(parts.length, 3, container); assert.equal(parts[1], 'organization-projects'); assert.equal(parts[2], `ontology-${uid(1)}`); + for (const repo of first.data.repositories) assert.ok(repo.path.startsWith(path.join(container, 'repositories') + path.sep), repo.path); + for (const repo of first.data.repositories) assert.equal(path.relative(f.baseDir, repo.sourcePath).split(path.sep)[1], 'projects', 'the repositories themselves stay in projects/'); +}); +test('a workspace in an older backend-hash folder moves up once, keeping its checkouts, edits and instructions', async t => { + const f = await fixture(t, true), first = await f.tooling.dispatch(f.input); assert.equal(first.status, 'success', JSON.stringify(first)); + const w = first.data, container = path.dirname(w.root), projectsRoot = path.dirname(container); + // Recreate the older layout: the same container one level deeper, its manifests recording those paths. + const hashed = path.join(projectsRoot, '0123456789abcdef'), old = path.join(hashed, path.basename(container)); + await fs.mkdir(hashed); await fs.rename(container, old); + const rewrite = value => value.split(container).join(old); + for (const file of [path.join(old, '.mainsequence-project.json'), path.join(old, 'Ontology', '.mainsequence-project.json')]) await fs.writeFile(file, rewrite(await fs.readFile(file, 'utf8'))); + await fs.writeFile(path.join(old, 'Ontology', 'AGENTS.md'), 'Keep my instructions'); + await fs.writeFile(path.join(old, 'repositories', path.relative(path.join(container, 'repositories'), w.repositories[0].path), 'notes.txt'), 'keep my edit'); + const clones = f.calls.filter(c => c.args[0] === 'clone').length, progress = []; + const tool = createDevTools({ host: { ...f.host, progress: message => progress.push(message) }, session: f.auth, env: { ...process.env }, store: null }); + const again = await tool.dispatch(f.input); assert.equal(again.status, 'success', JSON.stringify(again)); + assert.equal(again.data.root, w.root); assert.deepEqual(again.data.repositories.map(r => r.path), w.repositories.map(r => r.path)); + assert.equal(f.calls.filter(c => c.args[0] === 'clone').length, clones, 'nothing is cloned again'); + assert.ok(progress.includes(`Moving the project workspace to ${container}.`)); + await assert.rejects(fs.lstat(hashed), { code: 'ENOENT' }, 'the emptied backend folder is removed'); + assert.equal(await fs.readFile(path.join(w.root, 'AGENTS.md'), 'utf8'), 'Keep my instructions'); + assert.equal(await fs.readFile(path.join(w.repositories[0].path, 'notes.txt'), 'utf8'), 'keep my edit'); + for (const repo of again.data.repositories) assert.equal(f.git(repo.path, ['branch', '--show-current']), repo.branch); + const read = await readOrganizationProjectWorkspace(w.root); assert.deepEqual(read.repositories.map(r => r.path), w.repositories.map(r => r.path)); + assert.doesNotMatch(await fs.readFile(path.join(container, '.mainsequence-project.json'), 'utf8'), /0123456789abcdef/); + // A second hashed copy of the same project is never guessed between. + await fs.mkdir(path.join(projectsRoot, 'fedcba9876543210', path.basename(container)), { recursive: true }); + await fs.mkdir(path.join(projectsRoot, '0123456789abcdef', path.basename(container)), { recursive: true }); + await fs.rename(container, container + '-moved-away'); + assert.match((await f.tooling.dispatch(f.input)).summary, /Multiple workspace folders match/); +}); diff --git a/tests/project-tools.test.cjs b/tests/project-tools.test.cjs index 027dfed..692d4f5 100644 --- a/tests/project-tools.test.cjs +++ b/tests/project-tools.test.cjs @@ -363,10 +363,12 @@ async function projectFixture(t) { test('mcp-catalog answers from the shared file at once, re-reads the saved connections on request and scopes by environment', async t => { const f = await projectFixture(t); - const cached = await f.create().dispatch({ action: 'mcp-catalog', backend }); + // Not a timeout test: a generous budget keeps a loaded machine (parallel test files) from starving the local MCP. + const create = () => f.create({ projectRequestTimeoutMs: 5000 }); + const cached = await create().dispatch({ action: 'mcp-catalog', backend }); assert.equal(cached.status, 'success', cached.summary); assert.equal(cached.data.count, 0); assert.equal(cached.data.refreshed, false); assert.equal(cached.data.file, f.catalogFile); assert.match(cached.summary, /from the shared catalog/); - const refreshed = await f.create().dispatch({ action: 'mcp-catalog', backend, environmentUid, refresh: 'force' }); + const refreshed = await create().dispatch({ action: 'mcp-catalog', backend, environmentUid, refresh: 'force' }); assert.equal(refreshed.status, 'success', refreshed.summary); assert.equal(refreshed.data.refreshed, true); assert.equal(refreshed.data.count, 1); assert.match(refreshed.summary, /1 project MCP tools from 1 saved connections, catalogs re-read\./); const name = projectToolName(backend, environmentUid, releaseUid, 'set_value'); @@ -375,20 +377,20 @@ test('mcp-catalog answers from the shared file at once, re-reads the saved conne assert.deepEqual(refreshed.data.connections, [{ backend, releaseUid, environmentUid, environmentName: 'Research', name: 'metatable-mcp', tools: 1 }]); assert.equal(refreshed.data.environmentUid, environmentUid); assert.deepEqual(refreshed.data.unavailable, []); assert.equal(refreshed.data.error, null); assert.doesNotMatch(await fs.readFile(f.catalogFile, 'utf8'), /fixture-release-token|resource_metadata_url/); - const again = await f.create().dispatch({ action: 'mcp-catalog', backend }); + const again = await create().dispatch({ action: 'mcp-catalog', backend }); assert.equal(again.data.count, 1, 'the next process registers from the file without a network request'); assert.equal(again.data.refreshed, false); - assert.equal((await f.create().dispatch({ action: 'mcp-catalog', backend, environmentUid: '10000000-0000-4000-8000-000000000009' })).data.count, 0, 'another environment sees none of them'); - assert.equal((await f.create().dispatch({ action: 'mcp-catalog', backend, refresh: true })).data.refreshed, false, 'a fresh cache is not re-read without force'); - assert.equal((await f.create().dispatch({ action: 'mcp-catalog', backend, environmentUid: 'research' })).error.code, 'INVALID_REQUEST'); - assert.equal((await f.create().dispatch({ action: 'mcp-catalog', backend, refresh: 'yes' })).error.code, 'INVALID_REQUEST'); + assert.equal((await create().dispatch({ action: 'mcp-catalog', backend, environmentUid: '10000000-0000-4000-8000-000000000009' })).data.count, 0, 'another environment sees none of them'); + assert.equal((await create().dispatch({ action: 'mcp-catalog', backend, refresh: true })).data.refreshed, false, 'a fresh cache is not re-read without force'); + assert.equal((await create().dispatch({ action: 'mcp-catalog', backend, environmentUid: 'research' })).error.code, 'INVALID_REQUEST'); + assert.equal((await create().dispatch({ action: 'mcp-catalog', backend, refresh: 'yes' })).error.code, 'INVALID_REQUEST'); // A failed re-read reports why and still returns what the file holds. f.state.endpoint = 'https://127.0.0.1:1'; await f.save(); - const degraded = await f.create().dispatch({ action: 'mcp-catalog', backend, refresh: 'force' }); + const degraded = await create().dispatch({ action: 'mcp-catalog', backend, refresh: 'force' }); assert.equal(degraded.status, 'success', degraded.summary); assert.deepEqual(degraded.data.unavailable, ['metatable-mcp']); assert.equal(degraded.data.retained, 1); assert.equal(degraded.data.count, 1); assert.match(degraded.summary, /metatable-mcp could not be read now; earlier tools stay registered/); assert.equal(degraded.data.connections[0].unavailable.code, 'BACKEND_UNREACHABLE'); // The next process (a Claude Desktop worker is one per action) sees the mark from the file, with no refresh of its own. - const seen = await f.create().dispatch({ action: 'mcp-catalog', backend }); + const seen = await create().dispatch({ action: 'mcp-catalog', backend }); assert.equal(seen.data.refreshed, false); assert.deepEqual(seen.data.unavailable, ['metatable-mcp']); assert.match(seen.summary, /could not be read now/); });