Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(project): acceptance project binding (#21392)

Arvin Xu5c3a8e0ca13d
diff --git a/apps/cli/src/commands/acceptance/index.create.test.ts b/apps/cli/src/commands/acceptance/index.create.test.ts
index 1b8a2b86bc9..9969a2fcc1a 100644
--- a/apps/cli/src/commands/acceptance/index.create.test.ts
+++ b/apps/cli/src/commands/acceptance/index.create.test.ts
@@ -19,6 +19,7 @@ const publishFlow = vi.fn();
const createRun = vi.fn();
const attachRun = vi.fn();
const getUserState = vi.fn();
+const findProject = vi.fn();
let output: ReturnType<typeof vi.spyOn>;
const run = async (args: string[]) => {
@@ -37,6 +38,7 @@ beforeEach(() => {
publishFlow: { mutate: publishFlow },
attachRun: { mutate: attachRun },
},
+ project: { find: { query: findProject } },
user: { getUserState: { query: getUserState } },
verify: { createRun: { mutate: createRun } },
} as unknown as Awaited<ReturnType<typeof getTrpcClient>>);
@@ -100,6 +102,22 @@ describe('acceptance create', () => {
},
);
+ it('files the acceptance under the project --project names', async () => {
+ findProject.mockResolvedValue({ data: { id: 'prj_lobe', name: 'LobeHub' } });
+ ensure.mockImplementationOnce(async (input) => ({
+ ...input,
+ id: acceptanceId,
+ status: 'pending',
+ }));
+
+ await run(['create', '--requirement', requirement, '--project', 'LOBE']);
+
+ expect(findProject).toHaveBeenCalledWith({ id: 'LOBE' });
+ expect(ensure).toHaveBeenCalledWith(expect.objectContaining({ projectId: 'prj_lobe' }));
+ const text = output.mock.calls.map(([line]) => line).join('\n');
+ expect(text).toContain('LobeHub');
+ });
+
it('prints the acceptance ID, URL and absence of new rounds in human-readable output', async () => {
await run(['create', '--requirement', requirement]);
const text = output.mock.calls.map(([line]) => line).join('\n');
diff --git a/apps/cli/src/commands/acceptance/index.ts b/apps/cli/src/commands/acceptance/index.ts
index ceff266b37e..6073f014354 100644
--- a/apps/cli/src/commands/acceptance/index.ts
+++ b/apps/cli/src/commands/acceptance/index.ts
@@ -22,6 +22,7 @@ import {
unsetLanguageWarning,
} from './language';
import { attachPlanCommands } from './plan';
+import { projectEnsureInput, resolveAcceptanceProject, warnIfFiledElsewhere } from './project';
import { attachRubricCommands } from './rubric';
import { attachAcceptanceRunCommands } from './run';
import type { ReviewAnnotationRegion } from './utils';
@@ -143,13 +144,18 @@ export function registerAcceptanceCommands(parent: Command, options?: { deprecat
'--subject <type:id>',
'Reuse or create for task/topic/document/standalone; omit for a new standalone acceptance',
)
+ .option(
+ '--project <ref>',
+ "File under a project (id, slug or identifier such as LOBE), overriding the subject's own; otherwise the subject's project, then the one in .agents/acceptance/config.json",
+ )
.option(
'--json [fields]',
- 'Output JSON, optionally select fields (acceptanceId, acceptanceUrl, requirement, status, subject)',
+ 'Output JSON, optionally select fields (acceptanceId, acceptanceUrl, projectId, requirement, status, subject)',
)
.action(
async (options: {
json?: boolean | string;
+ project?: string;
requirement: string;
subject?: string;
title?: string;
@@ -174,7 +180,17 @@ export function registerAcceptanceCommands(parent: Command, options?: { deprecat
{ path: '--requirement', text: requirement },
{ path: '--title', text: title },
]);
- const result = await client.acceptance.ensure.mutate({ ...subject, requirement, title });
+ const project = await resolveAcceptanceProject(client, {
+ flag: options.project,
+ startDirs: [process.cwd()],
+ });
+ const result = await client.acceptance.ensure.mutate({
+ ...subject,
+ ...projectEnsureInput(project),
+ requirement,
+ title,
+ });
+ warnIfFiledElsewhere(project, result);
const acceptanceUrl = new URL(
`/acceptance/${encodeURIComponent(result.id)}`,
resolveServerUrl(),
@@ -185,6 +201,7 @@ export function registerAcceptanceCommands(parent: Command, options?: { deprecat
{
acceptanceId: result.id,
acceptanceUrl,
+ projectId: result.projectId,
requirement: result.requirement,
status: result.status,
subject: { subjectId: result.subjectId, subjectType: result.subjectType },
@@ -195,6 +212,9 @@ export function registerAcceptanceCommands(parent: Command, options?: { deprecat
}
console.log(`${pc.bold('acceptance')}: ${result.id} (${result.status})`);
+ if (project && result.projectId === project.id) {
+ console.log(`${pc.bold('project')}: ${project.name}`);
+ }
console.log(`${pc.bold('open acceptance')}: ${acceptanceUrl}`);
console.log(
pc.dim(
diff --git a/apps/cli/src/commands/acceptance/project.ts b/apps/cli/src/commands/acceptance/project.ts
new file mode 100644
index 00000000000..d5c589f7c88
--- /dev/null
+++ b/apps/cli/src/commands/acceptance/project.ts
@@ -0,0 +1,94 @@
+import path from 'node:path';
+
+import { TRPCClientError } from '@trpc/client';
+
+import type { TrpcClient } from '../../api/client';
+import { log } from '../../utils/logger';
+import { findDeclaredProject } from './utils';
+
+export interface AcceptanceProject {
+ id: string;
+ name: string;
+ /** `--project` or the repository's `.agents/acceptance/config.json`. */
+ source: 'config' | 'flag';
+}
+
+/**
+ * The `acceptance.ensure` fields for a resolved project. A named project
+ * overrides the subject's own; a repository's declaration only fills in when
+ * the subject has none β€” a task or conversation filed under a project keeps it.
+ */
+export const projectEnsureInput = (project: AcceptanceProject | undefined) => {
+ if (!project) return {};
+ return project.source === 'flag' ? { projectId: project.id } : { fallbackProjectId: project.id };
+};
+
+const isNotFound = (error: unknown) =>
+ error instanceof TRPCClientError && error.data?.code === 'NOT_FOUND';
+
+/**
+ * The project a delivery is filed under when the caller says so: `--project`,
+ * else the project the repository declares (see {@link projectEnsureInput} for
+ * how each ranks against the subject's own). Neither β†’ undefined.
+ *
+ * A `--project` that names nothing is a typo the caller must fix, so it fails
+ * before anything is written. A repository's declaration is shared by everyone
+ * who checks it out, including people in a workspace without that project β€”
+ * their round still publishes, just ungrouped.
+ */
+export async function resolveAcceptanceProject(
+ client: TrpcClient,
+ options: { flag?: string; startDirs: string[] },
+): Promise<AcceptanceProject | undefined> {
+ const flag = options.flag?.trim();
+ if (options.flag !== undefined && !flag) throw new Error('--project must not be empty');
+ if (flag) {
+ try {
+ const { data } = await client.project.find.query({ id: flag });
+ return { id: data.id, name: data.name, source: 'flag' };
+ } catch (error) {
+ if (isNotFound(error)) {
+ throw new Error(`--project "${flag}" matches no project in this workspace.`, {
+ cause: error,
+ });
+ }
+ throw error;
+ }
+ }
+
+ const declared = findDeclaredProject(options.startDirs);
+ if (!declared) return;
+ const file = path.relative(process.cwd(), declared.file) || declared.file;
+ if (declared.kind === 'invalid') {
+ log.warn(`Ignoring ${file}: ${declared.reason}.`);
+ return;
+ }
+
+ try {
+ const { data } = await client.project.find.query({ id: declared.project });
+ return { id: data.id, name: data.name, source: 'config' };
+ } catch (error) {
+ if (!isNotFound(error)) throw error;
+ log.warn(
+ `${file} files acceptances under project "${declared.project}", which this workspace does not have β€” publishing ungrouped.`,
+ );
+ }
+}
+
+/**
+ * A named project only files an acceptance that has none yet β€” a delivery
+ * already grouped is never moved by a later round. Say so when that is why
+ * `--project` did not take, instead of letting the caller believe it did. A
+ * repository's declaration yielding to an existing project is its design, not
+ * news.
+ */
+export function warnIfFiledElsewhere(
+ project: AcceptanceProject | undefined,
+ acceptance: { projectId?: string | null },
+) {
+ if (project?.source !== 'flag') return;
+ if (!acceptance.projectId || acceptance.projectId === project.id) return;
+ log.warn(
+ `This acceptance is already filed under another project, so it stays there instead of "${project.name}". Move it from the acceptance list.`,
+ );
+}
diff --git a/apps/cli/src/commands/acceptance/run/ingest.project.test.ts b/apps/cli/src/commands/acceptance/run/ingest.project.test.ts
new file mode 100644
index 00000000000..d60fdef27a4
--- /dev/null
+++ b/apps/cli/src/commands/acceptance/run/ingest.project.test.ts
@@ -0,0 +1,230 @@
+import { mkdir, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+
+import { TRPCClientError } from '@trpc/client';
+import { describe, expect, it, vi } from 'vitest';
+
+import { log } from '../../../utils/logger';
+import type * as VerifyHelpers from '../utils';
+import { usePublicationHarness } from './testUtils';
+
+vi.mock('../../../api/client', () => ({ getTrpcClient: vi.fn() }));
+vi.mock('../../../api/workspace', () => ({ resolveWorkspaceId: vi.fn() }));
+vi.mock('../../../settings', () => ({ resolveServerUrl: vi.fn() }));
+vi.mock('../../../utils/uploadLocalFile', () => ({ uploadLocalFile: vi.fn() }));
+vi.mock('../utils', async (importOriginal) => ({
+ ...(await importOriginal<typeof VerifyHelpers>()),
+ pullRequestFromBranch: vi.fn(),
+}));
+
+const notFound = () =>
+ new TRPCClientError('Project not found', {
+ result: { error: { data: { code: 'NOT_FOUND' } } } as never,
+ });
+
+describe('lh acceptance run ingest β€” project filing', () => {
+ const h = usePublicationHarness();
+ const { client, run } = h;
+
+ /** The report directory doubles as the repository root its adapter lives in. */
+ const declareProject = async (config: unknown) => {
+ await mkdir(path.join(h.dir, '.agents', 'acceptance'), { recursive: true });
+ await writeFile(
+ path.join(h.dir, '.agents', 'acceptance', 'config.json'),
+ typeof config === 'string' ? config : JSON.stringify(config),
+ );
+ };
+
+ const writeReport = () =>
+ writeFile(
+ path.join(h.dir, 'result.json'),
+ JSON.stringify({
+ cases: [{ id: 'screen', name: 'The result is shown', status: 'passed' }],
+ title: 'Result display',
+ }),
+ );
+
+ it("offers the project the repository's config declares as the fallback for a new acceptance", async () => {
+ await writeReport();
+ await declareProject({ project: 'LOBE' });
+ client.project.find.query.mockResolvedValue({ data: { id: 'prj_lobe', name: 'LobeHub' } });
+ client.acceptance.ensure.mutate.mockResolvedValue({
+ id: 'acceptance-1',
+ projectId: 'prj_lobe',
+ });
+
+ await run('ingest', h.dir, '--json');
+
+ expect(client.project.find.query).toHaveBeenCalledWith({ id: 'LOBE' });
+ expect(client.acceptance.ensure.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({ fallbackProjectId: 'prj_lobe' }),
+ );
+ });
+
+ it("stays quiet when the subject's own project outranks the declared one", async () => {
+ await writeReport();
+ await declareProject({ project: 'LOBE' });
+ client.project.find.query.mockResolvedValue({ data: { id: 'prj_lobe', name: 'LobeHub' } });
+ client.acceptance.ensure.mutate.mockResolvedValue({
+ id: 'acceptance-1',
+ projectId: 'prj_task',
+ });
+
+ await run('ingest', h.dir, '--json');
+
+ expect(vi.mocked(log.warn)).not.toHaveBeenCalledWith(
+ expect.stringContaining('already filed under another project'),
+ );
+ });
+
+ it('lets --project override the repository declaration', async () => {
+ await writeReport();
+ await declareProject({ project: 'LOBE' });
+ client.project.find.query.mockResolvedValue({ data: { id: 'prj_other', name: 'Other' } });
+
+ await run('ingest', h.dir, '--project', 'other', '--json');
+
+ expect(client.project.find.query).toHaveBeenCalledExactlyOnceWith({ id: 'other' });
+ const input = client.acceptance.ensure.mutate.mock.calls[0][0];
+ expect(input).toEqual(expect.objectContaining({ projectId: 'prj_other' }));
+ expect(input).not.toHaveProperty('fallbackProjectId');
+ });
+
+ it('fails an unknown --project before anything is published', async () => {
+ await writeReport();
+ client.project.find.query.mockRejectedValue(notFound());
+
+ await expect(run('ingest', h.dir, '--project', 'NOPE', '--json')).rejects.toThrow(
+ '--project "NOPE" matches no project in this workspace.',
+ );
+ expect(client.acceptance.ensure.mutate).not.toHaveBeenCalled();
+ expect(client.verify.createRun.mutate).not.toHaveBeenCalled();
+ });
+
+ it('publishes ungrouped, with a warning, when the declared project is not in this workspace', async () => {
+ await writeReport();
+ await declareProject({ project: 'LOBE' });
+ client.project.find.query.mockRejectedValue(notFound());
+
+ await run('ingest', h.dir, '--json');
+
+ expect(vi.mocked(log.warn)).toHaveBeenCalledWith(
+ expect.stringContaining('publishing ungrouped'),
+ );
+ expect(client.acceptance.ensure.mutate.mock.calls[0][0]).not.toHaveProperty(
+ 'fallbackProjectId',
+ );
+ expect(client.verify.createRun.mutate).toHaveBeenCalled();
+ });
+
+ it('ignores a malformed config instead of failing the round', async () => {
+ await writeReport();
+ await declareProject('{ "project": ');
+
+ await run('ingest', h.dir, '--json');
+
+ expect(vi.mocked(log.warn)).toHaveBeenCalledWith(expect.stringContaining('not valid JSON'));
+ expect(client.project.find.query).not.toHaveBeenCalled();
+ expect(client.verify.createRun.mutate).toHaveBeenCalled();
+ });
+
+ describe('with --acceptance', () => {
+ const existing = (projectId: string | null, subjectType = 'standalone', status = 'delivered') =>
+ client.acceptance.getBundle.query.mockResolvedValue({
+ acceptance: {
+ id: 'acceptance-1',
+ projectId,
+ status,
+ subjectId: `${subjectType}-1`,
+ subjectType,
+ workspaceId: null,
+ },
+ });
+
+ it('files an ungrouped acceptance under the named project', async () => {
+ await writeReport();
+ existing(null);
+ client.project.find.query.mockResolvedValue({ data: { id: 'prj_lobe', name: 'LobeHub' } });
+
+ await run('ingest', h.dir, '--acceptance', 'acceptance-1', '--project', 'LOBE', '--json');
+
+ expect(client.acceptance.setProject.mutate).toHaveBeenCalledWith({
+ id: 'acceptance-1',
+ projectId: 'prj_lobe',
+ });
+ });
+
+ it("files an ungrouped standalone acceptance under the repository's project", async () => {
+ await writeReport();
+ await declareProject({ project: 'LOBE' });
+ existing(null);
+ client.project.find.query.mockResolvedValue({ data: { id: 'prj_lobe', name: 'LobeHub' } });
+
+ await run('ingest', h.dir, '--acceptance', 'acceptance-1', '--json');
+
+ expect(client.acceptance.setProject.mutate).toHaveBeenCalledWith({
+ id: 'acceptance-1',
+ projectId: 'prj_lobe',
+ });
+ });
+
+ it("leaves a topic's ungrouped acceptance to its own project instead of the repository's", async () => {
+ await writeReport();
+ await declareProject({ project: 'LOBE' });
+ existing(null, 'topic');
+ client.project.find.query.mockResolvedValue({ data: { id: 'prj_lobe', name: 'LobeHub' } });
+
+ await run('ingest', h.dir, '--acceptance', 'acceptance-1', '--json');
+
+ expect(client.acceptance.setProject.mutate).not.toHaveBeenCalled();
+ });
+
+ it('writes nothing when the acceptance is already accepted', async () => {
+ await writeReport();
+ existing(null, 'standalone', 'accepted');
+ client.project.find.query.mockResolvedValue({ data: { id: 'prj_lobe', name: 'LobeHub' } });
+ vi.spyOn(process, 'exit').mockImplementation((() => {
+ throw new Error('exit');
+ }) as never);
+
+ await expect(
+ run('ingest', h.dir, '--acceptance', 'acceptance-1', '--project', 'LOBE', '--json'),
+ ).rejects.toThrow('exit');
+
+ expect(client.acceptance.setProject.mutate).not.toHaveBeenCalled();
+ });
+
+ it('writes nothing when the round is identical to the last one', async () => {
+ await writeReport();
+ await writeFile(path.join(h.dir, 'report.md'), 'Same report.');
+ existing(null);
+ client.acceptance.getBundle.query.mockResolvedValue({
+ acceptance: (await client.acceptance.getBundle.query()).acceptance,
+ rounds: [{ report: { content: 'Same report.' }, run: { id: 'run-old', roundIndex: 1 } }],
+ });
+ client.project.find.query.mockResolvedValue({ data: { id: 'prj_lobe', name: 'LobeHub' } });
+ vi.spyOn(process, 'exit').mockImplementation((() => {
+ throw new Error('exit');
+ }) as never);
+
+ await expect(
+ run('ingest', h.dir, '--acceptance', 'acceptance-1', '--project', 'LOBE', '--json'),
+ ).rejects.toThrow('exit');
+
+ expect(client.acceptance.setProject.mutate).not.toHaveBeenCalled();
+ });
+
+ it('leaves an acceptance already filed elsewhere where it is, and says so', async () => {
+ await writeReport();
+ existing('prj_elsewhere');
+ client.project.find.query.mockResolvedValue({ data: { id: 'prj_lobe', name: 'LobeHub' } });
+
+ await run('ingest', h.dir, '--acceptance', 'acceptance-1', '--project', 'LOBE', '--json');
+
+ expect(client.acceptance.setProject.mutate).not.toHaveBeenCalled();
+ expect(vi.mocked(log.warn)).toHaveBeenCalledWith(
+ expect.stringContaining('already filed under another project'),
+ );
+ });
+ });
+});
diff --git a/apps/cli/src/commands/acceptance/run/ingest.ts b/apps/cli/src/commands/acceptance/run/ingest.ts
index 6f7dd67b688..04ee696994e 100644
--- a/apps/cli/src/commands/acceptance/run/ingest.ts
+++ b/apps/cli/src/commands/acceptance/run/ingest.ts
@@ -14,6 +14,7 @@ import { ensureAcceptanceDirIgnoredFor } from '../../../utils/acceptanceDir';
import { outputJson } from '../../../utils/format';
import { log } from '../../../utils/logger';
import { assertReportLanguage, ingestLanguageFields, languageSummary } from '../language';
+import { projectEnsureInput, resolveAcceptanceProject, warnIfFiledElsewhere } from '../project';
import {
deriveReportVerdict,
type EvidenceType,
@@ -50,6 +51,7 @@ export interface IngestReportOptions {
json?: boolean | string;
open?: boolean;
operation?: string;
+ project?: string;
requirement?: string;
source?: string;
subject?: string;
@@ -246,6 +248,12 @@ export async function ingestReportAction(
title,
}),
);
+ // The repository the report was written in names the project; a report in a
+ // scratch directory falls back to where the command runs.
+ const project = await resolveAcceptanceProject(client, {
+ flag: options.project,
+ startDirs: [dir, process.cwd()],
+ });
if (options.dryRun) {
const checked =
language.status === 'enforced'
@@ -260,6 +268,7 @@ export async function ingestReportAction(
dryRun: true,
language: languageSummary(language),
planItems: plan?.length ?? 0,
+ projectId: project?.id ?? null,
},
typeof options.json === 'string' ? options.json : undefined,
);
@@ -285,6 +294,9 @@ export async function ingestReportAction(
);
process.exit(1);
}
+ if (options.project) {
+ log.warn('--project is ignored: a Task plan round is filed with its Task.');
+ }
return ingestIntoPlanRound(client, {
authoredPlan: plan,
caseMetadata,
@@ -336,6 +348,7 @@ export async function ingestReportAction(
};
} else {
acceptance = await client.acceptance.ensure.mutate({
+ ...projectEnsureInput(project),
requirement,
subjectId: subject!.ref.subjectId,
subjectType: subject!.ref.subjectType,
@@ -368,6 +381,7 @@ export async function ingestReportAction(
);
process.exit(1);
}
+ warnIfFiledElsewhere(project, acceptance);
// The in-app conversation that ran this harness, if any (env-supplied).
// Strictly the authoring conversation. `--operation` names the Agent Run
// under test and is passed to `createRun` below β€” a different relation.
@@ -397,6 +411,20 @@ export async function ingestReportAction(
);
process.exit(1);
}
+ // An acceptance named by id skips `ensure`, so apply its precedence here: a
+ // `--project` files an ungrouped acceptance, while the repository's default
+ // only fills a standalone one β€” a task or conversation defers to its own
+ // project, which the server files when the round attaches. Placed after
+ // every rejection guard so a round that publishes nothing writes nothing.
+ if (
+ requestedAcceptanceId &&
+ project &&
+ !acceptance.projectId &&
+ (project.source === 'flag' || acceptance.subjectType === 'standalone')
+ ) {
+ await client.acceptance.setProject.mutate({ id: acceptance.id, projectId: project.id });
+ acceptance = { ...acceptance, projectId: project.id };
+ }
const run = await client.verify.createRun.mutate({
context,
goal,
@@ -671,6 +699,9 @@ export async function ingestReportAction(
? 'standalone'
: `${subject!.ref.subjectType}:${subject!.ref.subjectId}`;
console.log(`${pc.bold('acceptance')}: ${acceptanceId} ${pc.dim(`(${subjectLabel})`)}`);
+ if (project && acceptance.projectId === project.id) {
+ console.log(`${pc.bold('project')}: ${project.name}`);
+ }
if (options.open || partial) {
// The acceptance page is the only report page β€” an old /verify link only
// redirects here. `?r=<roundIndex>` is this round's fixed snapshot.
@@ -699,6 +730,10 @@ export function withIngestReportOptions(cmd: Command): Command {
'--requirement <text>',
'Acceptance requirement recorded when the aggregate is first created',
)
+ .option(
+ '--project <ref>',
+ "File an ungrouped acceptance under a project (id, slug or identifier such as LOBE), overriding the subject's own; otherwise the subject's project, then the one in .agents/acceptance/config.json",
+ )
.option('--open', 'Print the in-app URL to open the report')
.option(
'--dry-run',
diff --git a/apps/cli/src/commands/acceptance/run/testUtils.ts b/apps/cli/src/commands/acceptance/run/testUtils.ts
index 83e757bec4c..c84b6175498 100644
--- a/apps/cli/src/commands/acceptance/run/testUtils.ts
+++ b/apps/cli/src/commands/acceptance/run/testUtils.ts
@@ -26,7 +26,9 @@ export const usePublicationHarness = () => {
ensure: { mutate: vi.fn() },
getBundle: { query: vi.fn() },
linkPullRequest: { mutate: vi.fn() },
+ setProject: { mutate: vi.fn() },
},
+ project: { find: { query: vi.fn() } },
verify: {
createRun: { mutate: vi.fn() },
getRun: { query: vi.fn() },
diff --git a/apps/cli/src/commands/acceptance/utils/index.ts b/apps/cli/src/commands/acceptance/utils/index.ts
index 024f1dba17d..d72f574521c 100644
--- a/apps/cli/src/commands/acceptance/utils/index.ts
+++ b/apps/cli/src/commands/acceptance/utils/index.ts
@@ -2,6 +2,7 @@ export * from './annotation';
export * from './evidence';
export * from './options';
export * from './plan';
+export * from './project';
export * from './reportContext';
export * from './subject';
export * from './values';
diff --git a/apps/cli/src/commands/acceptance/utils/project.test.ts b/apps/cli/src/commands/acceptance/utils/project.test.ts
new file mode 100644
index 00000000000..c203d7dddc8
--- /dev/null
+++ b/apps/cli/src/commands/acceptance/utils/project.test.ts
@@ -0,0 +1,72 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { findDeclaredProject } from './project';
+
+describe('findDeclaredProject', () => {
+ let root: string;
+
+ const adapter = (repo: string, config?: string) => {
+ const dir = path.join(root, repo, '.agents', 'acceptance');
+ mkdirSync(dir, { recursive: true });
+ if (config !== undefined) writeFileSync(path.join(dir, 'config.json'), config);
+ return dir;
+ };
+ const dir = (...segments: string[]) => {
+ const target = path.join(root, ...segments);
+ mkdirSync(target, { recursive: true });
+ return target;
+ };
+
+ beforeEach(() => {
+ root = mkdtempSync(path.join(tmpdir(), 'lh-acceptance-project-'));
+ });
+ afterEach(() => rmSync(root, { force: true, recursive: true }));
+
+ it('reads the project from the nearest repository above the start directory', () => {
+ const configDir = adapter('repo', '{ "project": " LOBE " }');
+
+ expect(findDeclaredProject([dir('repo', '.acceptances', 'topic-1', 'round')])).toEqual({
+ file: path.join(configDir, 'config.json'),
+ kind: 'declared',
+ project: 'LOBE',
+ });
+ });
+
+ it("stops at a nested repository's adapter instead of inheriting its parent's project", () => {
+ adapter('repo', '{ "project": "CLOUD" }');
+ adapter(path.join('repo', 'lobehub'));
+
+ expect(findDeclaredProject([dir('repo', 'lobehub', 'src')])).toBeUndefined();
+ });
+
+ it('falls back to the next start directory only when the first is outside any repository', () => {
+ adapter('repo', '{ "project": "LOBE" }');
+
+ expect(findDeclaredProject([dir('scratch', 'round'), dir('repo', 'src')])).toEqual(
+ expect.objectContaining({ project: 'LOBE' }),
+ );
+ });
+
+ it('declares nothing when the config has no project', () => {
+ adapter('repo', '{}');
+
+ expect(findDeclaredProject([dir('repo')])).toBeUndefined();
+ });
+
+ it.each([
+ ['{ "project": ', 'not valid JSON'],
+ ['["LOBE"]', 'expected a JSON object'],
+ ['{ "project": 42 }', '"project" must be a non-empty string'],
+ ['{ "project": " " }', '"project" must be a non-empty string'],
+ ])('reports %s as invalid', (config, reason) => {
+ adapter('repo', config);
+
+ expect(findDeclaredProject([dir('repo')])).toEqual(
+ expect.objectContaining({ kind: 'invalid', reason }),
+ );
+ });
+});
diff --git a/apps/cli/src/commands/acceptance/utils/project.ts b/apps/cli/src/commands/acceptance/utils/project.ts
new file mode 100644
index 00000000000..e5459752434
--- /dev/null
+++ b/apps/cli/src/commands/acceptance/utils/project.ts
@@ -0,0 +1,70 @@
+import { existsSync, readFileSync, statSync } from 'node:fs';
+import path from 'node:path';
+
+/** A repository's own acceptance adapter directory. */
+export const ACCEPTANCE_ADAPTER_DIR = path.join('.agents', 'acceptance');
+/** Machine-readable settings beside the adapter's `PROJECT.md`. */
+export const ACCEPTANCE_CONFIG_FILE = 'config.json';
+
+export type DeclaredProject =
+ | { file: string; kind: 'declared'; project: string }
+ | { file: string; kind: 'invalid'; reason: string };
+
+const isDirectory = (dir: string) => {
+ try {
+ return statSync(dir).isDirectory();
+ } catch {
+ return false;
+ }
+};
+
+/**
+ * The repository a delivery came from: the NEAREST `.agents/acceptance/`
+ * walking up from `startDir`. A nested checkout (a submodule) is its own
+ * repository and never inherits its parent's settings.
+ */
+export function findAcceptanceAdapterDir(startDir: string): string | undefined {
+ let dir = path.resolve(startDir);
+ while (true) {
+ const adapterDir = path.join(dir, ACCEPTANCE_ADAPTER_DIR);
+ if (isDirectory(adapterDir)) return adapterDir;
+ const parent = path.dirname(dir);
+ if (parent === dir) return undefined;
+ dir = parent;
+ }
+}
+
+/**
+ * The project a repository files its acceptances under, from
+ * `.agents/acceptance/config.json` β†’ `{ "project": "LOBE" }` (a project id,
+ * slug or identifier). The first start directory inside a repository decides β€”
+ * a report written to a scratch directory falls back to the working directory.
+ * Returns undefined when nothing is declared.
+ */
+export function findDeclaredProject(startDirs: string[]): DeclaredProject | undefined {
+ for (const startDir of startDirs) {
+ const adapterDir = findAcceptanceAdapterDir(startDir);
+ if (!adapterDir) continue;
+ const file = path.join(adapterDir, ACCEPTANCE_CONFIG_FILE);
+ return existsSync(file) ? readDeclaredProject(file) : undefined;
+ }
+}
+
+const readDeclaredProject = (file: string): DeclaredProject | undefined => {
+ let config: unknown;
+ try {
+ config = JSON.parse(readFileSync(file, 'utf8'));
+ } catch {
+ return { file, kind: 'invalid', reason: 'not valid JSON' };
+ }
+ if (!config || typeof config !== 'object' || Array.isArray(config)) {
+ return { file, kind: 'invalid', reason: 'expected a JSON object' };
+ }
+
+ const { project } = config as { project?: unknown };
+ if (project === undefined) return undefined;
+ if (typeof project !== 'string' || !project.trim()) {
+ return { file, kind: 'invalid', reason: '"project" must be a non-empty string' };
+ }
+ return { file, kind: 'declared', project: project.trim() };
+};
diff --git a/apps/server/src/routers/lambda/acceptance/subject.ts b/apps/server/src/routers/lambda/acceptance/subject.ts
index 5b4370992f6..8e6b58b44f3 100644
--- a/apps/server/src/routers/lambda/acceptance/subject.ts
+++ b/apps/server/src/routers/lambda/acceptance/subject.ts
@@ -19,6 +19,16 @@ export const subjectRouter = router({
* explicitly requested subject is always kept exact.
*/
foldTaskRunTopic: z.boolean().optional(),
+ /**
+ * The project the delivery's repository declares β€” used only when
+ * the subject implies none. Only fills an aggregate that has none yet.
+ */
+ fallbackProjectId: z.string().min(1).optional(),
+ /**
+ * A project the caller names, overriding the one the subject implies.
+ * Only fills an aggregate that has none yet.
+ */
+ projectId: z.string().min(1).optional(),
requirement: z.string().max(2000).optional(),
subjectId: z.string(),
subjectType: subjectTypeSchema,
@@ -26,7 +36,12 @@ export const subjectRouter = router({
}),
)
.mutation(async ({ ctx, input }) => {
- const defaults = { requirement: input.requirement, title: input.title };
+ const defaults = {
+ fallbackProjectId: input.fallbackProjectId,
+ projectId: input.projectId,
+ requirement: input.requirement,
+ title: input.title,
+ };
try {
return input.foldTaskRunTopic
? await ctx.acceptanceService.ensureForIngest(
diff --git a/apps/server/src/routers/lambda/project.ts b/apps/server/src/routers/lambda/project.ts
index bbea3986db2..693a0740d3a 100644
--- a/apps/server/src/routers/lambda/project.ts
+++ b/apps/server/src/routers/lambda/project.ts
@@ -200,7 +200,7 @@ export const projectRouter = router({
try {
const project = await withMainAgent(
ctx.projectModel,
- requireResult(await ctx.projectModel.findByIdOrSlug(input.id)),
+ requireResult(await ctx.projectModel.findByReference(input.id)),
);
const [agents, completionReviews, knowledgeBases, tasks, works] = await Promise.all([
ctx.projectModel.listAgents(project.id),
@@ -231,7 +231,7 @@ export const projectRouter = router({
return {
data: await withMainAgent(
ctx.projectModel,
- requireResult(await ctx.projectModel.findByIdOrSlug(input.id)),
+ requireResult(await ctx.projectModel.findByReference(input.id)),
),
success: true,
};
@@ -272,6 +272,9 @@ export const projectRouter = router({
// Keep the released API contract so old clients receive a clear business error.
// Project moves are paused while project-scoped task numbering is redesigned.
+ // Re-enabling them must also move the task's acceptances (and those of its
+ // run topics): `acceptances.project_id` is copied from the task when filed,
+ // unless the publisher named another project explicitly.
moveTask: projectWriteProcedure
.input(idInput.extend({ taskId: z.string() }))
.mutation(async () => {
diff --git a/apps/server/src/services/verify/__tests__/acceptanceDecision.test.ts b/apps/server/src/services/verify/__tests__/acceptanceDecision.test.ts
index 4c24897a03e..0e8eb3b63ff 100644
--- a/apps/server/src/services/verify/__tests__/acceptanceDecision.test.ts
+++ b/apps/server/src/services/verify/__tests__/acceptanceDecision.test.ts
@@ -13,6 +13,8 @@ const mocks = vi.hoisted(() => ({
findRunById: vi.fn(),
foldIntoRound: vi.fn(),
ensureForSubject: vi.fn(),
+ fillProject: vi.fn(),
+ taskTopicFindByTopicId: vi.fn(),
listResultsByRun: vi.fn(),
listByAcceptance: vi.fn(),
setDecision: vi.fn(),
@@ -25,6 +27,7 @@ vi.mock('@/database/models/acceptance', () => ({
AcceptanceModel: vi.fn(function () {
return {
ensureForSubject: mocks.ensureForSubject,
+ fillProject: mocks.fillProject,
findById: mocks.findById,
findPolicyById: mocks.findPolicyById,
updatePolicyStatus: mocks.updatePolicyStatus,
@@ -64,6 +67,11 @@ vi.mock('@/database/models/topic', () => ({
return { findOwnTopicById: mocks.findOwnTopicById };
}),
}));
+vi.mock('@/database/models/taskTopic', () => ({
+ TaskTopicModel: vi.fn(function () {
+ return { findByTopicId: mocks.taskTopicFindByTopicId };
+ }),
+}));
vi.mock('@/database/models/document', () => ({ DocumentModel: vi.fn() }));
vi.mock('@/server/services/task', () => ({ TaskService: vi.fn() }));
vi.mock('@/server/workflows/expertiseRejection', () => ({
@@ -181,6 +189,32 @@ describe('AcceptanceService decision gating', () => {
expect(mocks.attachToAcceptance).toHaveBeenCalledWith('run-2', 'acc-1', undefined);
});
+ it("files an ungrouped acceptance under its subject's project when a round lands", async () => {
+ mocks.findById.mockResolvedValue({ ...acceptance('delivered'), projectId: null });
+ mocks.findOwnTopicById.mockResolvedValue({ projectId: 'project-topic' });
+ mocks.findRunById.mockResolvedValue({ acceptanceId: null, id: 'run-2' });
+ mocks.attachToAcceptance.mockResolvedValue({ acceptanceId: 'acc-1', id: 'run-2' });
+
+ await service().attachRun('run-2', 'acc-1');
+
+ expect(mocks.fillProject).toHaveBeenCalledWith('acc-1', 'project-topic');
+ });
+
+ it('leaves a grouped acceptance alone, and still attaches when the subject cannot be read', async () => {
+ mocks.findById.mockResolvedValue({ ...acceptance('delivered'), projectId: 'project-kept' });
+ mocks.findRunById.mockResolvedValue({ acceptanceId: null, id: 'run-2' });
+ mocks.attachToAcceptance.mockResolvedValue({ acceptanceId: 'acc-1', id: 'run-2' });
+
+ await service().attachRun('run-2', 'acc-1');
+ expect(mocks.findOwnTopicById).not.toHaveBeenCalled();
+
+ mocks.findById.mockResolvedValue({ ...acceptance('delivered'), projectId: null });
+ mocks.findOwnTopicById.mockRejectedValue(new Error('db down'));
+
+ await expect(service().attachRun('run-2', 'acc-1')).resolves.toMatchObject({ id: 'run-2' });
+ expect(mocks.fillProject).not.toHaveBeenCalled();
+ });
+
it('distils the previous round once a new one lands', async () => {
mocks.findById.mockResolvedValue(acceptance('rejected'));
mocks.findRunById.mockResolvedValue({ acceptanceId: null, id: 'run-2' });
diff --git a/apps/server/src/services/verify/__tests__/acceptanceSubjects.test.ts b/apps/server/src/services/verify/__tests__/acceptanceSubjects.test.ts
index 4d16a8ef285..651dc1af3c3 100644
--- a/apps/server/src/services/verify/__tests__/acceptanceSubjects.test.ts
+++ b/apps/server/src/services/verify/__tests__/acceptanceSubjects.test.ts
@@ -11,6 +11,7 @@ const mocks = vi.hoisted(() => ({
documentFindById: vi.fn(),
ensureForSubject: vi.fn(),
goalFindByNode: vi.fn(),
+ projectFindById: vi.fn(),
taskResolve: vi.fn(),
taskTopicFindByTopicId: vi.fn(),
topicFindOwnTopicById: vi.fn(),
@@ -46,6 +47,11 @@ vi.mock('@/database/models/goal', () => ({
return { findByNode: mocks.goalFindByNode };
}),
}));
+vi.mock('@/database/models/project', () => ({
+ ProjectModel: vi.fn(function () {
+ return { findById: mocks.projectFindById };
+ }),
+}));
vi.mock('@/server/services/task', () => ({ TaskService: vi.fn() }));
const service = () => new AcceptanceService({} as any, 'user-1', 'ws-1');
@@ -134,6 +140,78 @@ describe('AcceptanceService subjects', () => {
});
});
+ it("files a project conversation topic under the topic's own project", async () => {
+ mocks.topicFindOwnTopicById.mockResolvedValue({
+ projectId: 'project-topic',
+ title: 'Project chat',
+ });
+
+ await service().ensureForSubject('topic', 'topic-1');
+
+ expect(mocks.taskTopicFindByTopicId).not.toHaveBeenCalled();
+ expect(mocks.ensureForSubject).toHaveBeenCalledWith('topic', 'topic-1', {
+ config: undefined,
+ projectId: 'project-topic',
+ requirement: undefined,
+ });
+ });
+
+ it('files under a project the caller names instead of the one the subject implies', async () => {
+ mocks.topicFindOwnTopicById.mockResolvedValue({
+ projectId: 'project-topic',
+ title: 'Project chat',
+ });
+ mocks.projectFindById.mockResolvedValue({ id: 'project-named' });
+
+ await service().ensureForSubject('topic', 'topic-1', { projectId: 'project-named' });
+
+ expect(mocks.projectFindById).toHaveBeenCalledWith('project-named');
+ expect(mocks.ensureForSubject).toHaveBeenCalledWith('topic', 'topic-1', {
+ config: undefined,
+ projectId: 'project-named',
+ requirement: undefined,
+ });
+ });
+
+ it("keeps the subject's own project over the repository's fallback", async () => {
+ mocks.topicFindOwnTopicById.mockResolvedValue({
+ projectId: 'project-topic',
+ title: 'Project chat',
+ });
+
+ await service().ensureForSubject('topic', 'topic-1', { fallbackProjectId: 'project-repo' });
+
+ expect(mocks.projectFindById).not.toHaveBeenCalled();
+ expect(mocks.ensureForSubject).toHaveBeenCalledWith(
+ 'topic',
+ 'topic-1',
+ expect.objectContaining({ projectId: 'project-topic' }),
+ );
+ });
+
+ it("files under the repository's fallback when the subject implies no project", async () => {
+ mocks.projectFindById.mockResolvedValue({ id: 'project-repo' });
+
+ await service().ensureForSubject('standalone', 'standalone-1', {
+ fallbackProjectId: 'project-repo',
+ });
+
+ expect(mocks.ensureForSubject).toHaveBeenCalledWith(
+ 'standalone',
+ 'standalone-1',
+ expect.objectContaining({ projectId: 'project-repo' }),
+ );
+ });
+
+ it('rejects a named project the caller cannot read, before creating anything', async () => {
+ mocks.projectFindById.mockResolvedValue(null);
+
+ await expect(
+ service().ensureForSubject('standalone', 'standalone-1', { projectId: 'project-x' }),
+ ).rejects.toThrow('project "project-x" not found in the current workspace');
+ expect(mocks.ensureForSubject).not.toHaveBeenCalled();
+ });
+
it('stores a standalone title as metadata without a project', async () => {
await service().ensureForSubject('standalone', 'standalone-1', { title: 'Report' });
diff --git a/apps/server/src/services/verify/acceptanceService/index.ts b/apps/server/src/services/verify/acceptanceService/index.ts
index d313ddd68f0..3608fed67bc 100644
--- a/apps/server/src/services/verify/acceptanceService/index.ts
+++ b/apps/server/src/services/verify/acceptanceService/index.ts
@@ -46,6 +46,7 @@ import { reviewChecks } from './reviewChecks';
import { statusFromRound } from './statusRollup';
import {
type AcceptanceSubjectSummary,
+ assertProjectExists,
assertSubjectExists,
resolveCanonicalSubjectId,
resolveRunTopicTaskId,
@@ -130,14 +131,34 @@ export class AcceptanceService {
};
}
- /** Get (or create) the aggregate for a subject, validating the subject first. */
+ /**
+ * Get (or create) the aggregate for a subject, validating the subject first.
+ *
+ * Project precedence: a `projectId` the caller names (a CLI `--project`),
+ * then the one the subject implies, then `fallbackProjectId` β€” the project
+ * the delivery's repository declares, a default too broad to override a
+ * task's or conversation's own project. Either way it only files an
+ * aggregate that has no project yet: a delivery already grouped is moved by
+ * hand, never by the next round.
+ */
ensureForSubject = async (
subjectType: AcceptanceSubjectType,
subjectId: string,
- defaults?: { config?: AcceptanceConfig; requirement?: string; title?: string },
+ defaults?: {
+ config?: AcceptanceConfig;
+ fallbackProjectId?: string;
+ projectId?: string;
+ requirement?: string;
+ title?: string;
+ },
): Promise<AcceptanceItem> => {
const canonicalId = await assertSubjectExists(this.deps, subjectType, subjectId);
- const projectId = await resolveSubjectProjectId(this.deps, subjectType, canonicalId);
+ const projectId = defaults?.projectId
+ ? await assertProjectExists(this.deps, defaults.projectId)
+ : ((await resolveSubjectProjectId(this.deps, subjectType, canonicalId)) ??
+ (defaults?.fallbackProjectId
+ ? await assertProjectExists(this.deps, defaults.fallbackProjectId)
+ : null));
return this.acceptanceModel.ensureForSubject(subjectType, canonicalId, {
config: defaults?.config,
projectId,
@@ -160,7 +181,12 @@ export class AcceptanceService {
ensureForIngest = async (
subjectType: AcceptanceSubjectType,
subjectId: string,
- defaults?: { requirement?: string; title?: string },
+ defaults?: {
+ fallbackProjectId?: string;
+ projectId?: string;
+ requirement?: string;
+ title?: string;
+ },
): Promise<AcceptanceItem> => {
const taskId =
subjectType === 'topic' ? await resolveRunTopicTaskId(this.deps, subjectId) : undefined;
@@ -187,6 +213,26 @@ export class AcceptanceService {
return this.attachResolvedRun(runId, acceptance);
};
+ /**
+ * File an ungrouped acceptance under the project its subject implies when a
+ * round lands. Appending by acceptance id skips `ensureForSubject`, so an
+ * aggregate created before its subject carried a project would otherwise
+ * stay ungrouped on every re-verification. Best effort: filing never blocks
+ * a round.
+ */
+ private fileUnderSubjectProject = async (acceptance: AcceptanceItem) => {
+ try {
+ const projectId = await resolveSubjectProjectId(
+ this.deps,
+ acceptance.subjectType,
+ acceptance.subjectId,
+ );
+ if (projectId) await this.acceptanceModel.fillProject(acceptance.id, projectId);
+ } catch (error) {
+ log('could not file acceptance %s under its subject project: %O', acceptance.id, error);
+ }
+ };
+
private attachResolvedRun = async (
runId: string,
acceptance: AcceptanceItem,
@@ -211,6 +257,7 @@ export class AcceptanceService {
}
await assertPlanLeavesAcceptedChecksAlone(this.deps, existing, acceptanceId);
+ if (!acceptance.projectId) await this.fileUnderSubjectProject(acceptance);
// A round that is still only planned has nothing to preserve: the incoming
// run folds into it instead of pushing the ledger to yet another number.
diff --git a/apps/server/src/services/verify/acceptanceService/subjects.ts b/apps/server/src/services/verify/acceptanceService/subjects.ts
index efa1a72efcd..139cd209927 100644
--- a/apps/server/src/services/verify/acceptanceService/subjects.ts
+++ b/apps/server/src/services/verify/acceptanceService/subjects.ts
@@ -3,6 +3,7 @@ import debug from 'debug';
import { DocumentModel } from '@/database/models/document';
import { GoalModel } from '@/database/models/goal';
+import { ProjectModel } from '@/database/models/project';
import { TaskModel } from '@/database/models/task';
import { TaskTopicModel } from '@/database/models/taskTopic';
import { TopicModel } from '@/database/models/topic';
@@ -109,6 +110,18 @@ export const resolveRunTopicTaskId = async (
export const goalOfGate = (deps: AcceptanceServiceDeps, nodeId: string) =>
new GoalModel(deps.db, deps.userId, deps.workspaceId).findByNode(nodeId);
+/** A project named by id must be readable in the caller's scope; resolves to its id. */
+export const assertProjectExists = async (
+ deps: AcceptanceServiceDeps,
+ projectId: string,
+): Promise<string> => {
+ const project = await new ProjectModel(deps.db, deps.userId, deps.workspaceId).findById(
+ projectId,
+ );
+ if (!project) throw new Error(`project "${projectId}" not found in the current workspace`);
+ return project.id;
+};
+
export const resolveSubjectProjectId = async (
deps: AcceptanceServiceDeps,
subjectType: AcceptanceSubjectType,
@@ -122,6 +135,13 @@ export const resolveSubjectProjectId = async (
}
if (subjectType === 'goal_gate') return (await goalOfGate(deps, subjectId))?.projectId ?? null;
if (subjectType === 'topic') {
+ // A project conversation carries its project itself; only a topic outside
+ // one falls back to the project of the task it runs.
+ const topic = await new TopicModel(deps.db, deps.userId, deps.workspaceId).findOwnTopicById(
+ subjectId,
+ );
+ if (topic?.projectId) return topic.projectId;
+
const taskTopic = await new TaskTopicModel(
deps.db,
deps.userId,
diff --git a/packages/database/src/models/__tests__/acceptance.test.ts b/packages/database/src/models/__tests__/acceptance.test.ts
index f78b207ccfa..b10e63147d8 100644
--- a/packages/database/src/models/__tests__/acceptance.test.ts
+++ b/packages/database/src/models/__tests__/acceptance.test.ts
@@ -142,6 +142,25 @@ describe('AcceptanceModel', () => {
expect((await model.findById(acceptance.id))?.projectId).toBeNull();
});
+ it('fills a project only on an ungrouped acceptance it owns', async () => {
+ const projectModel = new ProjectModel(serverDB, userId);
+ const first = await projectModel.create({ identifier: 'FILA', name: 'First' });
+ const second = await projectModel.create({ identifier: 'FILB', name: 'Second' });
+ const model = new AcceptanceModel(serverDB, userId);
+ const acceptance = await model.ensureForSubject('topic', topicId);
+
+ // Another user's model cannot file it.
+ expect(
+ await new AcceptanceModel(serverDB, otherUserId).fillProject(acceptance.id, first.id),
+ ).toBe(false);
+ expect((await model.findById(acceptance.id))?.projectId).toBeNull();
+
+ expect(await model.fillProject(acceptance.id, first.id)).toBe(true);
+ // Once grouped, a later fill leaves it where it is.
+ expect(await model.fillProject(acceptance.id, second.id)).toBe(false);
+ expect((await model.findById(acceptance.id))?.projectId).toBe(first.id);
+ });
+
it('keeps the first standalone display title and backfills one when initially absent', async () => {
const model = new AcceptanceModel(serverDB, userId);
const subjectId = 'standalone-external-delivery';
diff --git a/packages/database/src/models/__tests__/project.test.ts b/packages/database/src/models/__tests__/project.test.ts
index 8c8bf470a33..d675618bf16 100644
--- a/packages/database/src/models/__tests__/project.test.ts
+++ b/packages/database/src/models/__tests__/project.test.ts
@@ -145,13 +145,33 @@ describe('ProjectModel', () => {
const project = await createProject(model, { name: 'Apollo', slug: 'apollo' });
await createProject(otherModel, { name: 'Other Apollo', slug: 'other-apollo' });
- expect(await model.findByIdOrSlug('apollo')).toEqual(
+ expect(await model.findByReference('apollo')).toEqual(
expect.objectContaining({ id: project.id }),
);
- expect(await model.findByIdOrSlug(project.id)).toEqual(
+ expect(await model.findByReference(project.id)).toEqual(
expect.objectContaining({ slug: 'apollo' }),
);
- expect(await model.findByIdOrSlug('other-apollo')).toBeNull();
+ expect(await model.findByReference('other-apollo')).toBeNull();
+ });
+
+ it('resolves a project by its identifier, case-insensitively, within the current scope', async () => {
+ const project = await model.create({ identifier: 'APLO', name: 'Apollo' });
+ await otherModel.create({ identifier: 'OTHR', name: 'Other' });
+
+ expect(await model.findByReference('APLO')).toEqual(
+ expect.objectContaining({ id: project.id }),
+ );
+ expect(await model.findByReference('aplo')).toEqual(
+ expect.objectContaining({ id: project.id }),
+ );
+ expect(await model.findByReference('OTHR')).toBeNull();
+ });
+
+ it('prefers an exact id or slug over another project whose identifier matches', async () => {
+ const bySlug = await createProject(model, { name: 'By slug', slug: 'crux' });
+ await model.create({ identifier: 'CRUX', name: 'By identifier' });
+
+ expect(await model.findByReference('crux')).toEqual(expect.objectContaining({ id: bySlug.id }));
});
it('finds a bounded set of readable projects', async () => {
diff --git a/packages/database/src/models/acceptance.ts b/packages/database/src/models/acceptance.ts
index 683fc71804a..6d06d711fc4 100644
--- a/packages/database/src/models/acceptance.ts
+++ b/packages/database/src/models/acceptance.ts
@@ -449,6 +449,20 @@ export class AcceptanceModel {
};
};
+ /**
+ * File an ungrouped acceptance under a project. Never moves one already
+ * grouped: the `project_id IS NULL` guard lets a filing that landed in the
+ * meantime β€” by hand, or by another round β€” win. Resolves whether it wrote.
+ */
+ fillProject = async (id: string, projectId: string): Promise<boolean> => {
+ const rows = await this.db
+ .update(acceptances)
+ .set({ projectId })
+ .where(and(eq(acceptances.id, id), isNull(acceptances.projectId), this.ownership()))
+ .returning({ id: acceptances.id });
+ return rows.length > 0;
+ };
+
update = async (
id: string,
value: Partial<
diff --git a/packages/database/src/models/project.ts b/packages/database/src/models/project.ts
index 0a324dfc24b..54c05f8d60a 100644
--- a/packages/database/src/models/project.ts
+++ b/packages/database/src/models/project.ts
@@ -268,11 +268,30 @@ export class ProjectModel {
.where(and(inArray(projects.id, ids), this.readable()));
}
- async findByIdOrSlug(reference: string) {
+ /**
+ * Resolve what a person or a repository config would write to name a
+ * project: its id, its slug, or its task identifier (`LOBE`, matched
+ * case-insensitively). An exact id beats a slug, and a slug beats an
+ * identifier, so one project's identifier never shadows another's slug.
+ */
+ async findByReference(reference: string) {
+ const identifier = reference.trim().toUpperCase();
const [project] = await this.db
.select()
.from(projects)
- .where(and(or(eq(projects.id, reference), eq(projects.slug, reference)), this.readable()))
+ .where(
+ and(
+ or(
+ eq(projects.id, reference),
+ eq(projects.slug, reference),
+ eq(projects.identifier, identifier),
+ ),
+ this.readable(),
+ ),
+ )
+ .orderBy(
+ sql`CASE WHEN ${projects.id} = ${reference} THEN 0 WHEN ${projects.slug} = ${reference} THEN 1 ELSE 2 END`,
+ )
.limit(1);
return project ?? null;
}