From 852797a897e9c6871c477321ec8816eecc729157 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sat, 3 Oct 2026 02:00:46 -0400 Subject: [PATCH] section 7: Phase 7: Committed repo file, trust and move between personal and repo --- backend/src/routes/repo-project-config.ts | 38 +- backend/src/services/project-config.ts | 319 +++++++++++++++- backend/test/mocks/bun-sqlite.ts | 25 +- .../test/routes/repo-project-config.test.ts | 112 ++++++ backend/test/services/project-config.test.ts | 354 +++++++++++++++++- shared/src/schemas/project-config.ts | 22 ++ shared/src/types/index.ts | 2 + 7 files changed, 859 insertions(+), 13 deletions(-) diff --git a/backend/src/routes/repo-project-config.ts b/backend/src/routes/repo-project-config.ts index 58ba8158..343e5b22 100644 --- a/backend/src/routes/repo-project-config.ts +++ b/backend/src/routes/repo-project-config.ts @@ -3,7 +3,7 @@ import type { Context } from 'hono' import type { ContentfulStatusCode } from 'hono/utils/http-status' import type { Database } from 'bun:sqlite' import type { Repo } from '@opencode-manager/shared/types' -import { UpdateProjectActionsRequestSchema, UpdateWorktreeSetupRequestSchema } from '@opencode-manager/shared/schemas' +import { UpdateProjectActionsRequestSchema, UpdateWorktreeSetupRequestSchema, TrustRepoConfigRequestSchema, MoveProjectItemRequestSchema } from '@opencode-manager/shared/schemas' import * as repoService from '../services/repo' import { resolveRepoWorkingDirectory } from '../services/repo' import { getRepoById } from '../db/queries' @@ -129,5 +129,41 @@ export function createRepoProjectConfigRoutes( } }) + app.post('/:id/project-config/trust', async (c) => { + const body = await c.req.json().catch(() => ({})) + const parsed = TrustRepoConfigRequestSchema.safeParse(body) + if (!parsed.success) { + return c.json({ error: 'Invalid request', details: parsed.error.flatten() }, 400) + } + + const resolved = await resolveRepoDirectory(c, c.req.param('id'), parsed.data.directory) + if (resolved instanceof Response) return resolved + + try { + await deps.projectConfigService.trustRepoFile(resolved.repo, resolved.directory, parsed.data.hash) + return c.json(await deps.projectConfigService.getConfig(resolved.repo, resolved.directory)) + } catch (error: unknown) { + return handleProjectConfigError(c, error) + } + }) + + app.post('/:id/project-config/move', async (c) => { + const body = await c.req.json().catch(() => ({})) + const parsed = MoveProjectItemRequestSchema.safeParse(body) + if (!parsed.success) { + return c.json({ error: 'Invalid request', details: parsed.error.flatten() }, 400) + } + + const resolved = await resolveRepoDirectory(c, c.req.param('id'), parsed.data.directory) + if (resolved instanceof Response) return resolved + + try { + await deps.projectConfigService.moveItem(resolved.repo, resolved.directory, parsed.data) + return c.json(await deps.projectConfigService.getConfig(resolved.repo, resolved.directory)) + } catch (error: unknown) { + return handleProjectConfigError(c, error) + } + }) + return app } diff --git a/backend/src/services/project-config.ts b/backend/src/services/project-config.ts index 0e35a05c..190324e2 100644 --- a/backend/src/services/project-config.ts +++ b/backend/src/services/project-config.ts @@ -1,19 +1,46 @@ +import { createHash } from 'node:crypto' +import fs from 'node:fs' +import path from 'node:path' import { z } from 'zod' import type { Database } from 'bun:sqlite' import type { Repo } from '@opencode-manager/shared/types' import { ProjectActionSchema, + RepoProjectFileSchema, WorktreeSetupCommandsSchema, + type MoveProjectItemRequest, type ProjectAction, type ProjectConfigResponse, + type RepoProjectFile, } from '@opencode-manager/shared/schemas' import { getRepoByDirectory, getRepoSetting, setRepoSetting } from '../db/queries' +import { getErrorMessage } from '../utils/error-utils' import type { GitService } from './git/GitService' import type { GitAuthService } from './git-auth' const PROJECT_ACTIONS_KEY = 'projectActions' const WORKTREE_SETUP_KEY = 'worktreeSetupCommands' const REPO_CONFIG_TRUST_KEY = 'repoConfigTrustHash' +const REPO_FILE_RELATIVE_PATH = path.join('.ocm', 'project.json') + +export interface RepoFileState { + exists: boolean + file: RepoProjectFile | null + hash: string | null + error?: string +} + +interface MoveCommit { + repoFile: RepoProjectFile | null + personalActions?: ProjectAction[] + personalSetup?: string[] + trustHash: string | null +} + +interface RepoFileSnapshot { + exists: boolean + content: Buffer | null +} export class ProjectConfigError extends Error { constructor( @@ -67,24 +94,300 @@ export class ProjectConfigService { async getConfig(repo: Repo, directory: string): Promise { const projectRepo = await this.resolveProjectRepo(repo) - const actions = this.getPersonalActions(projectRepo).map((action) => ({ ...action, source: 'personal' as const })) - const worktreeSetup = this.getPersonalSetup(projectRepo).map((command) => ({ command, source: 'personal' as const })) - const hash: string | null = null - void directory + const repoFile = this.readRepoFile(directory) + const warnings: string[] = [] + + const actions: ProjectConfigResponse['actions'] = this.getPersonalActions(projectRepo).map((action) => ({ + ...action, + source: 'personal' as const, + })) + const actionIds = new Set(actions.map((action) => action.id)) + + for (const action of repoFile.file?.projectActions ?? []) { + if (actionIds.has(action.id)) { + warnings.push(`Repository action "${action.id}" was ignored because a personal action uses the same id`) + continue + } + actionIds.add(action.id) + actions.push({ ...action, source: 'repo' }) + } + + const worktreeSetup: ProjectConfigResponse['worktreeSetup'] = this.getPersonalSetup(projectRepo).map((command) => ({ + command, + source: 'personal' as const, + })) + for (const command of repoFile.file?.setupWorktree ?? []) { + worktreeSetup.push({ command, source: 'repo' }) + } + + const trusted = + repoFile.hash !== null && + repoFile.hash === getRepoSetting(this.database, projectRepo.id, REPO_CONFIG_TRUST_KEY) return { actions, worktreeSetup, repoFile: { path: '.ocm/project.json', - exists: false, - trusted: hash !== null && hash === getRepoSetting(this.database, projectRepo.id, REPO_CONFIG_TRUST_KEY), - hash, - warnings: [], + exists: repoFile.exists, + trusted, + hash: repoFile.hash, + ...(repoFile.error ? { error: repoFile.error } : {}), + warnings, }, } } + readRepoFile(directory: string): RepoFileState { + const filePath = this.getRepoFilePath(directory) + if (!fs.existsSync(filePath)) { + return { exists: false, file: null, hash: null } + } + + try { + const parsed = RepoProjectFileSchema.safeParse(JSON.parse(fs.readFileSync(filePath, 'utf8'))) + if (!parsed.success) { + return { exists: true, file: null, hash: null, error: 'Invalid repository config' } + } + return { exists: true, file: parsed.data, hash: this.hashRepoFile(parsed.data) } + } catch (error: unknown) { + return { exists: true, file: null, hash: null, error: getErrorMessage(error) } + } + } + + hashRepoFile(file: RepoProjectFile): string { + const executable = { + actions: (file.projectActions ?? []).map(({ id, command, url }) => ({ id, command, url: url ?? null })), + setup: file.setupWorktree ?? [], + } + return createHash('sha256').update(JSON.stringify(executable)).digest('hex') + } + + async trustRepoFile(repo: Repo, directory: string, hash: string): Promise { + const projectRepo = await this.resolveProjectRepo(repo) + const repoFile = this.readRepoFile(directory) + if (repoFile.hash === null || repoFile.hash !== hash) { + throw new ProjectConfigError(409, 'Repository config changed', 'REPO_CONFIG_CHANGED') + } + this.setRepoTrust(projectRepo, repoFile.hash) + } + + async moveItem(repo: Repo, directory: string, request: MoveProjectItemRequest): Promise { + const projectRepo = await this.resolveProjectRepo(repo) + const filePath = this.getRepoFilePath(directory) + const state = this.readRepoFile(directory) + const commit = + request.to === 'repo' + ? this.planMoveToRepo(projectRepo, state, request) + : this.planMoveToPersonal(projectRepo, state, request) + + this.commitMove(projectRepo, filePath, commit) + } + + private planMoveToRepo(projectRepo: Repo, state: RepoFileState, request: MoveProjectItemRequest): MoveCommit { + if (state.exists && !state.file) { + throw new ProjectConfigError(409, 'Repository config is invalid') + } + + const file: RepoProjectFile = state.file ? { ...state.file } : { version: 1 } + + if (request.kind === 'action') { + const personal = this.getPersonalActions(projectRepo) + const action = personal.find((item) => item.id === request.id) + if (!action) { + throw new ProjectConfigError(404, 'Action not found') + } + const repoActions = file.projectActions ?? [] + if (repoActions.some((existing) => existing.id === action.id)) { + throw new ProjectConfigError(409, 'Action already exists in repository config') + } + const nextFile: RepoProjectFile = { ...file, projectActions: [...repoActions, action] } + this.assertRepoFileValid(nextFile) + return { + repoFile: nextFile, + personalActions: personal.filter((item) => item.id !== action.id), + trustHash: this.hashRepoFile(nextFile), + } + } + + const personal = this.getPersonalSetup(projectRepo) + const index = personal.indexOf(request.command) + if (index === -1) { + throw new ProjectConfigError(404, 'Setup command not found') + } + const nextFile: RepoProjectFile = { + ...file, + setupWorktree: [...(file.setupWorktree ?? []), request.command], + } + const nextPersonal = personal.filter((_, itemIndex) => itemIndex !== index) + this.assertRepoFileValid(nextFile) + this.assertPersonalSetupValid(nextPersonal) + return { repoFile: nextFile, personalSetup: nextPersonal, trustHash: this.hashRepoFile(nextFile) } + } + + private planMoveToPersonal(projectRepo: Repo, state: RepoFileState, request: MoveProjectItemRequest): MoveCommit { + const file = state.file + if (!file) { + throw new ProjectConfigError(404, 'Item not found') + } + + if (request.kind === 'action') { + const repoActions = file.projectActions ?? [] + const action = repoActions.find((item) => item.id === request.id) + if (!action) { + throw new ProjectConfigError(404, 'Action not found') + } + const nextFile = this.pruneRepoFile({ + ...file, + projectActions: repoActions.filter((item) => item.id !== action.id), + }) + const personalActions = [...this.getPersonalActions(projectRepo), action] + return nextFile + ? { repoFile: nextFile, personalActions, trustHash: this.hashRepoFile(nextFile) } + : { repoFile: null, personalActions, trustHash: null } + } + + const repoSetup = file.setupWorktree ?? [] + const index = repoSetup.indexOf(request.command) + if (index === -1) { + throw new ProjectConfigError(404, 'Setup command not found') + } + const nextFile = this.pruneRepoFile({ + ...file, + setupWorktree: repoSetup.filter((_, itemIndex) => itemIndex !== index), + }) + const personalSetup = [...this.getPersonalSetup(projectRepo), request.command] + this.assertPersonalSetupValid(personalSetup) + return nextFile + ? { repoFile: nextFile, personalSetup, trustHash: this.hashRepoFile(nextFile) } + : { repoFile: null, personalSetup, trustHash: null } + } + + private pruneRepoFile(file: RepoProjectFile): RepoProjectFile | null { + const next: RepoProjectFile = { ...file } + if (next.projectActions && next.projectActions.length === 0) { + delete next.projectActions + } + if (next.setupWorktree && next.setupWorktree.length === 0) { + delete next.setupWorktree + } + if (Object.keys(next).every((key) => key === 'version')) { + return null + } + this.assertRepoFileValid(next) + return next + } + + private commitMove(projectRepo: Repo, filePath: string, commit: MoveCommit): void { + const snapshot = this.snapshotFile(filePath) + let fileMutated = false + + try { + this.database.transaction(() => { + if (commit.repoFile === null) { + fs.rmSync(filePath, { force: true }) + } else { + this.writeRepoFile(filePath, commit.repoFile) + } + fileMutated = true + + if (commit.personalActions !== undefined) { + this.setPersonalActions(projectRepo, commit.personalActions) + } + if (commit.personalSetup !== undefined) { + this.setPersonalSetup(projectRepo, commit.personalSetup) + } + this.setRepoTrust(projectRepo, commit.trustHash) + })() + } catch (error) { + if (fileMutated) { + this.restoreFile(filePath, snapshot) + } + throw error + } + + if (commit.repoFile === null) { + this.removeOcmDirIfEmpty(filePath) + } + } + + private assertRepoFileValid(file: RepoProjectFile): void { + const result = RepoProjectFileSchema.safeParse(file) + if (!result.success) { + throw new ProjectConfigError( + 409, + 'Repository config limit exceeded', + 'PROJECT_CONFIG_LIMIT_EXCEEDED', + result.error.flatten(), + ) + } + } + + private assertPersonalSetupValid(commands: string[]): void { + const result = WorktreeSetupCommandsSchema.safeParse(commands) + if (!result.success) { + throw new ProjectConfigError( + 409, + 'Personal setup command limit exceeded', + 'PROJECT_CONFIG_LIMIT_EXCEEDED', + result.error.flatten(), + ) + } + } + + private setRepoTrust(projectRepo: Repo, hash: string | null): void { + setRepoSetting(this.database, projectRepo.id, REPO_CONFIG_TRUST_KEY, hash) + } + + private getRepoFilePath(directory: string): string { + return path.join(directory, REPO_FILE_RELATIVE_PATH) + } + + private writeRepoFile(filePath: string, file: RepoProjectFile): void { + fs.mkdirSync(path.dirname(filePath), { recursive: true }) + const tmpPath = `${filePath}.tmp` + try { + fs.writeFileSync(tmpPath, `${JSON.stringify(file, null, 2)}\n`) + fs.renameSync(tmpPath, filePath) + } catch (error) { + fs.rmSync(tmpPath, { force: true }) + throw error + } + } + + private snapshotFile(filePath: string): RepoFileSnapshot { + try { + return { exists: true, content: fs.readFileSync(filePath) } + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') { + return { exists: false, content: null } + } + throw error + } + } + + private restoreFile(filePath: string, snapshot: RepoFileSnapshot): void { + if (!snapshot.exists || snapshot.content === null) { + fs.rmSync(filePath, { force: true }) + return + } + fs.mkdirSync(path.dirname(filePath), { recursive: true }) + fs.writeFileSync(filePath, snapshot.content) + } + + private removeOcmDirIfEmpty(filePath: string): void { + const dir = path.dirname(filePath) + try { + if (fs.readdirSync(dir).length === 0) { + fs.rmdirSync(dir) + } + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') { + throw error + } + } + } + private readStoredJson(repoId: number, key: string, schema: z.ZodType): T | null { const raw = getRepoSetting(this.database, repoId, key) if (!raw) { diff --git a/backend/test/mocks/bun-sqlite.ts b/backend/test/mocks/bun-sqlite.ts index 724b3db8..a6b657cf 100644 --- a/backend/test/mocks/bun-sqlite.ts +++ b/backend/test/mocks/bun-sqlite.ts @@ -3,6 +3,7 @@ import { DatabaseSync } from 'node:sqlite' // Adapter to make node:sqlite compatible with bun:sqlite API export class Database { private db: DatabaseSync + private transactionDepth = 0 constructor(path: string) { this.db = new DatabaseSync(path) @@ -37,14 +38,32 @@ export class Database { transaction void>(fn: T) { return (...args: unknown[]) => { - this.db.exec('BEGIN') + const nested = this.transactionDepth > 0 + const savepoint = `ocm_sp_${this.transactionDepth}` + if (nested) { + this.db.exec(`SAVEPOINT ${savepoint}`) + } else { + this.db.exec('BEGIN') + } + this.transactionDepth += 1 try { const result = fn(...args) - this.db.exec('COMMIT') + if (nested) { + this.db.exec(`RELEASE ${savepoint}`) + } else { + this.db.exec('COMMIT') + } return result } catch (e) { - this.db.exec('ROLLBACK') + if (nested) { + this.db.exec(`ROLLBACK TO ${savepoint}`) + this.db.exec(`RELEASE ${savepoint}`) + } else { + this.db.exec('ROLLBACK') + } throw e + } finally { + this.transactionDepth -= 1 } } } diff --git a/backend/test/routes/repo-project-config.test.ts b/backend/test/routes/repo-project-config.test.ts index df1f0599..38583a10 100644 --- a/backend/test/routes/repo-project-config.test.ts +++ b/backend/test/routes/repo-project-config.test.ts @@ -1,6 +1,9 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest' import { Hono } from 'hono' import { Database } from 'bun:sqlite' +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' import { migrate } from '../../src/db/migration-runner' import { allMigrations } from '../../src/db/migrations' import { createRepo } from '../../src/db/queries' @@ -172,4 +175,113 @@ describe('Repo Project Config Routes', () => { expect(res.status).toBe(400) expect(await res.json()).toEqual({ error: 'Directory is not part of this repository' }) }) + + it('returns 400 for an invalid trust request', async () => { + seedRepo(db) + + const res = await app.request('/1/project-config/trust', { + method: 'POST', + headers: jsonHeaders, + body: JSON.stringify({ hash: 'not-a-hash' }), + }) + + expect(res.status).toBe(400) + }) + + it('returns 409 when trusting a stale hash', async () => { + seedRepo(db) + + const res = await app.request('/1/project-config/trust', { + method: 'POST', + headers: jsonHeaders, + body: JSON.stringify({ hash: 'a'.repeat(64) }), + }) + + expect(res.status).toBe(409) + expect((await res.json() as { code: string }).code).toBe('REPO_CONFIG_CHANGED') + }) + + it('returns 400 for an invalid move request', async () => { + seedRepo(db) + + const res = await app.request('/1/project-config/move', { + method: 'POST', + headers: jsonHeaders, + body: JSON.stringify({ kind: 'action', id: 'serve', to: 'nowhere' }), + }) + + expect(res.status).toBe(400) + }) + + it('returns 404 when moving an unknown item', async () => { + seedRepo(db) + + const res = await app.request('/1/project-config/move', { + method: 'POST', + headers: jsonHeaders, + body: JSON.stringify({ kind: 'action', id: 'missing', to: 'repo' }), + }) + + expect(res.status).toBe(404) + }) + + it('moves a personal action into the repo file and returns it as trusted', async () => { + seedRepo(db) + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'ocm-route-move-')) + vi.mocked(resolveRepoWorkingDirectory).mockResolvedValue(directory) + const action = { id: 'serve', name: 'Serve', command: 'pnpm dev', autoOpenUrl: false } + + try { + await app.request('/1/project-config/actions', { + method: 'PUT', + headers: jsonHeaders, + body: JSON.stringify({ actions: [action] }), + }) + + const res = await app.request('/1/project-config/move', { + method: 'POST', + headers: jsonHeaders, + body: JSON.stringify({ kind: 'action', id: 'serve', to: 'repo' }), + }) + + expect(res.status).toBe(200) + const body = await res.json() as { actions: unknown[]; repoFile: { exists: boolean; trusted: boolean } } + expect(body.repoFile.exists).toBe(true) + expect(body.repoFile.trusted).toBe(true) + expect(body.actions).toEqual([{ ...action, source: 'repo' }]) + } finally { + fs.rmSync(directory, { recursive: true, force: true }) + } + }) + + it('returns 409 when moving a setup command into a repository already at capacity', async () => { + seedRepo(db) + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'ocm-route-move-')) + vi.mocked(resolveRepoWorkingDirectory).mockResolvedValue(directory) + + try { + await app.request('/1/project-config/worktree-setup', { + method: 'PUT', + headers: jsonHeaders, + body: JSON.stringify({ commands: ['personal-cmd'] }), + }) + const repoFileDir = path.join(directory, '.ocm') + fs.mkdirSync(repoFileDir, { recursive: true }) + fs.writeFileSync( + path.join(repoFileDir, 'project.json'), + JSON.stringify({ version: 1, setupWorktree: Array.from({ length: 20 }, (_, index) => `repo-${index}`) }), + ) + + const res = await app.request('/1/project-config/move', { + method: 'POST', + headers: jsonHeaders, + body: JSON.stringify({ kind: 'setup', command: 'personal-cmd', to: 'repo' }), + }) + + expect(res.status).toBe(409) + expect((await res.json() as { code: string }).code).toBe('PROJECT_CONFIG_LIMIT_EXCEEDED') + } finally { + fs.rmSync(directory, { recursive: true, force: true }) + } + }) }) diff --git a/backend/test/services/project-config.test.ts b/backend/test/services/project-config.test.ts index c21f84e9..34f7f0d3 100644 --- a/backend/test/services/project-config.test.ts +++ b/backend/test/services/project-config.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect, beforeEach, afterEach, beforeAll, afterAll } from 'vitest' +import { describe, it, expect, beforeEach, afterEach, beforeAll, afterAll, vi } from 'vitest' import { Database } from 'bun:sqlite' import { execSync } from 'node:child_process' import fs from 'node:fs' @@ -193,3 +193,355 @@ describe('ProjectConfigService worktree resolution', () => { expect(config.worktreeSetup).toEqual([{ command: 'pnpm install', source: 'personal' }]) }) }) + +describe('ProjectConfigService repository file', () => { + let db: Database + let service: ProjectConfigService + let repo: Repo + let directory: string + + function repoFilePath(): string { + return path.join(directory, '.ocm', 'project.json') + } + + function writeRepoFile(content: unknown): void { + fs.mkdirSync(path.dirname(repoFilePath()), { recursive: true }) + fs.writeFileSync(repoFilePath(), typeof content === 'string' ? content : JSON.stringify(content, null, 2)) + } + + beforeEach(() => { + db = new Database(':memory:') + migrate(db, allMigrations) + service = createService(db) + directory = fs.mkdtempSync(path.join(os.tmpdir(), 'ocm-repo-file-')) + repo = createRepo(db, { + localPath: directory, + sourcePath: directory, + defaultBranch: 'main', + cloneStatus: 'ready', + clonedAt: Date.now(), + isLocal: true, + }) + }) + + afterEach(() => { + db.close() + fs.rmSync(directory, { recursive: true, force: true }) + }) + + it('reports an untrusted repository file with a hash and its items', async () => { + writeRepoFile({ version: 1, projectActions: [{ id: 'repo-serve', name: 'Serve', command: 'pnpm dev' }] }) + + const config = await service.getConfig(repo, directory) + + expect(config.repoFile.exists).toBe(true) + expect(config.repoFile.trusted).toBe(false) + expect(config.repoFile.hash).toMatch(/^[a-f0-9]{64}$/) + expect(config.actions).toEqual([ + { id: 'repo-serve', name: 'Serve', command: 'pnpm dev', autoOpenUrl: false, source: 'repo' }, + ]) + }) + + it('rejects trusting a stale hash', async () => { + writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev' }] }) + + await expect(service.trustRepoFile(repo, directory, 'a'.repeat(64))).rejects.toMatchObject({ + status: 409, + code: 'REPO_CONFIG_CHANGED', + }) + }) + + it('keeps trust across a name-only edit and drops it on a command edit', async () => { + writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev' }] }) + const first = await service.getConfig(repo, directory) + await service.trustRepoFile(repo, directory, first.repoFile.hash ?? '') + expect((await service.getConfig(repo, directory)).repoFile.trusted).toBe(true) + + writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve renamed', command: 'pnpm dev' }] }) + expect((await service.getConfig(repo, directory)).repoFile.trusted).toBe(true) + + writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve renamed', command: 'pnpm dev --host' }] }) + expect((await service.getConfig(repo, directory)).repoFile.trusted).toBe(false) + }) + + it('reports invalid JSON with an error and no repository items', async () => { + writeRepoFile('{not json') + + const config = await service.getConfig(repo, directory) + + expect(config.repoFile.exists).toBe(true) + expect(config.repoFile.error).toBeTruthy() + expect(config.repoFile.hash).toBeNull() + expect(config.actions).toEqual([]) + }) + + it('reports a schema-invalid file with an error and no repository items', async () => { + writeRepoFile({ version: 2 }) + + const config = await service.getConfig(repo, directory) + + expect(config.repoFile.error).toBeTruthy() + expect(config.actions).toEqual([]) + }) + + it('moves an action personal to repo preserving unknown keys and marking it trusted', async () => { + service.setPersonalActions(repo, [createAction()]) + writeRepoFile({ version: 1, customKey: 'keep-me' }) + + await service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'repo' }) + + const raw = JSON.parse(fs.readFileSync(repoFilePath(), 'utf8')) as { customKey: string; projectActions: unknown[] } + expect(raw.customKey).toBe('keep-me') + expect(raw.projectActions).toEqual([createAction()]) + expect(service.getPersonalActions(repo)).toEqual([]) + + const config = await service.getConfig(repo, directory) + expect(config.repoFile.trusted).toBe(true) + expect(config.actions).toEqual([{ ...createAction(), source: 'repo' }]) + }) + + it('deletes the file and .ocm directory when the last item moves back', async () => { + writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev' }] }) + + await service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'personal' }) + + expect(fs.existsSync(repoFilePath())).toBe(false) + expect(fs.existsSync(path.join(directory, '.ocm'))).toBe(false) + expect(service.getPersonalActions(repo)).toEqual([createAction()]) + }) + + it('moves a setup command personal to repo and back', async () => { + service.setPersonalSetup(repo, ['pnpm install']) + + await service.moveItem(repo, directory, { kind: 'setup', command: 'pnpm install', to: 'repo' }) + let config = await service.getConfig(repo, directory) + expect(config.worktreeSetup).toEqual([{ command: 'pnpm install', source: 'repo' }]) + expect(config.repoFile.trusted).toBe(true) + + await service.moveItem(repo, directory, { kind: 'setup', command: 'pnpm install', to: 'personal' }) + config = await service.getConfig(repo, directory) + expect(config.worktreeSetup).toEqual([{ command: 'pnpm install', source: 'personal' }]) + expect(config.repoFile.exists).toBe(false) + }) + + it('drops a colliding repository action and warns', async () => { + service.setPersonalActions(repo, [createAction()]) + writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Repo Serve', command: 'pnpm repo-dev' }] }) + + const config = await service.getConfig(repo, directory) + + expect(config.actions).toEqual([{ ...createAction(), source: 'personal' }]) + expect(config.repoFile.warnings).toHaveLength(1) + expect(config.repoFile.warnings[0]).toContain('serve') + }) + + it('rejects moving an unknown personal action', async () => { + await expect(service.moveItem(repo, directory, { kind: 'action', id: 'missing', to: 'repo' })).rejects.toMatchObject({ + status: 404, + }) + }) + + it('rejects moving an unknown repository action', async () => { + writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev' }] }) + + await expect(service.moveItem(repo, directory, { kind: 'action', id: 'missing', to: 'personal' })).rejects.toMatchObject({ + status: 404, + }) + }) + + it('rejects moving a setup command into a repository already at capacity', async () => { + const repoCommands = Array.from({ length: 20 }, (_, index) => `repo-${index}`) + writeRepoFile({ version: 1, setupWorktree: repoCommands }) + const first = await service.getConfig(repo, directory) + await service.trustRepoFile(repo, directory, first.repoFile.hash ?? '') + const originalBytes = fs.readFileSync(repoFilePath(), 'utf8') + service.setPersonalSetup(repo, ['personal-cmd']) + + await expect( + service.moveItem(repo, directory, { kind: 'setup', command: 'personal-cmd', to: 'repo' }), + ).rejects.toMatchObject({ status: 409, code: 'PROJECT_CONFIG_LIMIT_EXCEEDED' }) + + expect(fs.readFileSync(repoFilePath(), 'utf8')).toBe(originalBytes) + expect(service.getPersonalSetup(repo)).toEqual(['personal-cmd']) + expect((await service.getConfig(repo, directory)).repoFile.trusted).toBe(true) + }) + + it('rejects moving a setup command into personal storage already at capacity', async () => { + const personalCommands = Array.from({ length: 20 }, (_, index) => `personal-${index}`) + service.setPersonalSetup(repo, personalCommands) + writeRepoFile({ version: 1, setupWorktree: ['repo-cmd'] }) + const first = await service.getConfig(repo, directory) + await service.trustRepoFile(repo, directory, first.repoFile.hash ?? '') + const originalBytes = fs.readFileSync(repoFilePath(), 'utf8') + + await expect( + service.moveItem(repo, directory, { kind: 'setup', command: 'repo-cmd', to: 'personal' }), + ).rejects.toMatchObject({ status: 409, code: 'PROJECT_CONFIG_LIMIT_EXCEEDED' }) + + expect(fs.readFileSync(repoFilePath(), 'utf8')).toBe(originalBytes) + expect(service.getPersonalSetup(repo)).toEqual(personalCommands) + expect((await service.getConfig(repo, directory)).repoFile.trusted).toBe(true) + }) + + it('allows a setup command to fill the repository up to its capacity', async () => { + writeRepoFile({ version: 1, setupWorktree: Array.from({ length: 19 }, (_, index) => `repo-${index}`) }) + service.setPersonalSetup(repo, ['personal-cmd']) + + await service.moveItem(repo, directory, { kind: 'setup', command: 'personal-cmd', to: 'repo' }) + + const raw = JSON.parse(fs.readFileSync(repoFilePath(), 'utf8')) as { setupWorktree: string[] } + expect(raw.setupWorktree).toHaveLength(20) + expect(service.getPersonalSetup(repo)).toEqual([]) + }) + + it('allows a setup command to fill personal storage up to its capacity', async () => { + service.setPersonalSetup(repo, Array.from({ length: 19 }, (_, index) => `personal-${index}`)) + writeRepoFile({ version: 1, setupWorktree: ['repo-cmd'] }) + + await service.moveItem(repo, directory, { kind: 'setup', command: 'repo-cmd', to: 'personal' }) + + expect(service.getPersonalSetup(repo)).toHaveLength(20) + expect(fs.existsSync(repoFilePath())).toBe(false) + }) + + it('restores the repository file and personal settings when the file write fails', async () => { + service.setPersonalActions(repo, [createAction()]) + const renameSpy = vi.spyOn(fs, 'renameSync').mockImplementationOnce(() => { + throw new Error('disk full') + }) + + await expect(service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'repo' })).rejects.toThrow('disk full') + renameSpy.mockRestore() + + expect(fs.existsSync(repoFilePath())).toBe(false) + expect(service.getPersonalActions(repo)).toEqual([createAction()]) + + await service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'repo' }) + expect(service.getPersonalActions(repo)).toEqual([]) + expect(fs.existsSync(repoFilePath())).toBe(true) + }) + + it('keeps the repository file and personal settings when the delete fails', async () => { + writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev' }] }) + const originalBytes = fs.readFileSync(repoFilePath(), 'utf8') + const rmSpy = vi.spyOn(fs, 'rmSync').mockImplementationOnce(() => { + throw new Error('read-only') + }) + + await expect(service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'personal' })).rejects.toThrow( + 'read-only', + ) + rmSpy.mockRestore() + + expect(fs.readFileSync(repoFilePath(), 'utf8')).toBe(originalBytes) + expect(service.getPersonalActions(repo)).toEqual([]) + + await service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'personal' }) + expect(fs.existsSync(repoFilePath())).toBe(false) + expect(service.getPersonalActions(repo)).toEqual([createAction()]) + }) + + it('keeps the repository file when the file write fails moving back', async () => { + writeRepoFile({ + version: 1, + projectActions: [ + { id: 'serve', name: 'Serve', command: 'pnpm dev' }, + { id: 'test', name: 'Test', command: 'pnpm test' }, + ], + }) + const originalBytes = fs.readFileSync(repoFilePath(), 'utf8') + const renameSpy = vi.spyOn(fs, 'renameSync').mockImplementationOnce(() => { + throw new Error('disk full') + }) + + await expect(service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'personal' })).rejects.toThrow( + 'disk full', + ) + renameSpy.mockRestore() + + expect(fs.readFileSync(repoFilePath(), 'utf8')).toBe(originalBytes) + expect(service.getPersonalActions(repo)).toEqual([]) + + await service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'personal' }) + expect(service.getPersonalActions(repo)).toEqual([createAction()]) + }) + + it('restores the repository file and personal settings when the settings write fails', async () => { + service.setPersonalActions(repo, [createAction()]) + const setSpy = vi.spyOn(service, 'setPersonalActions').mockImplementationOnce(() => { + throw new Error('settings write failed') + }) + + await expect(service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'repo' })).rejects.toThrow( + 'settings write failed', + ) + setSpy.mockRestore() + + expect(fs.existsSync(repoFilePath())).toBe(false) + expect(service.getPersonalActions(repo)).toEqual([createAction()]) + + await service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'repo' }) + expect(fs.existsSync(repoFilePath())).toBe(true) + expect(service.getPersonalActions(repo)).toEqual([]) + }) + + it('restores the repository file and rolls back personal settings when the trust write fails', async () => { + service.setPersonalActions(repo, [createAction()]) + const trustSeam = service as unknown as { setRepoTrust(repo: Repo, hash: string | null): void } + const trustSpy = vi.spyOn(trustSeam, 'setRepoTrust').mockImplementationOnce(() => { + throw new Error('trust write failed') + }) + + await expect(service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'repo' })).rejects.toThrow( + 'trust write failed', + ) + trustSpy.mockRestore() + + expect(fs.existsSync(repoFilePath())).toBe(false) + expect(service.getPersonalActions(repo)).toEqual([createAction()]) + expect((await service.getConfig(repo, directory)).repoFile.exists).toBe(false) + + await service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'repo' }) + expect((await service.getConfig(repo, directory)).repoFile.trusted).toBe(true) + }) + + it('keeps the repository file when the settings write fails moving back', async () => { + writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev' }] }) + const originalBytes = fs.readFileSync(repoFilePath(), 'utf8') + const setSpy = vi.spyOn(service, 'setPersonalActions').mockImplementationOnce(() => { + throw new Error('settings write failed') + }) + + await expect(service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'personal' })).rejects.toThrow( + 'settings write failed', + ) + setSpy.mockRestore() + + expect(fs.readFileSync(repoFilePath(), 'utf8')).toBe(originalBytes) + expect(service.getPersonalActions(repo)).toEqual([]) + + await service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'personal' }) + expect(service.getPersonalActions(repo)).toEqual([createAction()]) + expect(fs.existsSync(repoFilePath())).toBe(false) + }) + + it('keeps the repository file when the trust write fails moving back', async () => { + writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev' }] }) + const originalBytes = fs.readFileSync(repoFilePath(), 'utf8') + const trustSeam = service as unknown as { setRepoTrust(repo: Repo, hash: string | null): void } + const trustSpy = vi.spyOn(trustSeam, 'setRepoTrust').mockImplementationOnce(() => { + throw new Error('trust write failed') + }) + + await expect(service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'personal' })).rejects.toThrow( + 'trust write failed', + ) + trustSpy.mockRestore() + + expect(fs.readFileSync(repoFilePath(), 'utf8')).toBe(originalBytes) + expect(service.getPersonalActions(repo)).toEqual([]) + + await service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'personal' }) + expect(service.getPersonalActions(repo)).toEqual([createAction()]) + }) +}) diff --git a/shared/src/schemas/project-config.ts b/shared/src/schemas/project-config.ts index 3ad6763f..e0a774da 100644 --- a/shared/src/schemas/project-config.ts +++ b/shared/src/schemas/project-config.ts @@ -61,6 +61,26 @@ export const UpdateWorktreeSetupRequestSchema = z.object({ commands: WorktreeSetupCommandsSchema, }) +export const TrustRepoConfigRequestSchema = z.object({ + directory: z.string().optional(), + hash: z.string().regex(/^[a-f0-9]{64}$/), +}) + +export const MoveProjectItemRequestSchema = z.discriminatedUnion('kind', [ + z.object({ + kind: z.literal('action'), + id: z.string(), + to: ProjectItemSourceSchema, + directory: z.string().optional(), + }), + z.object({ + kind: z.literal('setup'), + command: z.string(), + to: ProjectItemSourceSchema, + directory: z.string().optional(), + }), +]) + export type ProjectActionIcon = z.infer export type ProjectAction = z.infer export type WorktreeSetupCommands = z.infer @@ -69,3 +89,5 @@ export type RepoProjectFile = z.infer export type ProjectConfigResponse = z.infer export type UpdateProjectActionsRequest = z.infer export type UpdateWorktreeSetupRequest = z.infer +export type TrustRepoConfigRequest = z.infer +export type MoveProjectItemRequest = z.infer diff --git a/shared/src/types/index.ts b/shared/src/types/index.ts index 6b067f45..0c61269b 100644 --- a/shared/src/types/index.ts +++ b/shared/src/types/index.ts @@ -175,4 +175,6 @@ export type { ProjectConfigResponse, UpdateProjectActionsRequest, UpdateWorktreeSetupRequest, + TrustRepoConfigRequest, + MoveProjectItemRequest, } from '../schemas/project-config'