✨ Add account types and enforce per-user wish permissions

- Provide six account types and custom combinations of wish, code review,
  release and management permissions, applied on each authenticated request.
- Enforce frontend-only accounts when submitting, answering, widening and
  reverting wishes; require every contributor to have full access before
  skipping backend code review.
- Gate code review and release decisions by their specific permissions.
- Rework member management to create and edit account types, permissions and
  project access, and reflect those permissions throughout the console.
- Update the manual and architecture docs with permission tests and
  end-to-end coverage.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
eust-w 2026-10-28 12:07:08 +08:00
parent 17553e2f8f
commit addf330b10
28 changed files with 1350 additions and 446 deletions

View File

@ -53,6 +53,7 @@ import { assertVerificationProfile, verificationPolicyDigest } from './verificat
import { IntegrationLeases } from './integration-lease.js';
import { captureLesson, projectLessons } from './lessons.js';
import { describeProviderEvent } from './provider-events.js';
import { backendDefined, personWishScope, requirePermission, wishScopeOf } from './permissions.js';
export const now = () => new Date().toISOString();
export function record(tenantId: string): Entity {
@ -364,6 +365,16 @@ export class ControlPlane {
this.validateKey(key);
return this.store.transaction(actor.tenantId, async tx => {
const project = await projectAccess(tx, actor, projectId);
const scope = wishScopeOf(actor, project);
if (scope === 'none') throw new DomainError('WISH_FORBIDDEN', 'Your account cannot submit wishes', 403);
// Whoever may only wish for frontend changes gets frontend-only wishes.
const frontendOnly = backendDefined(project) && scope === 'frontend' ? true : data.frontendOnly;
if (frontendOnly && data.frontendOnly === false)
throw new DomainError(
'FRONTEND_ONLY_ACCOUNT',
'Your account may only wish for frontend changes; ask someone who may change backend code',
403,
);
const localPoc = boundPocProject(project, this.env);
if (localPoc && (data.sourceBranch || data.provider !== 'claude-code'))
throw new DomainError(
@ -418,6 +429,7 @@ export class ControlPlane {
reservedTokens: data.budget.maxTokens,
usedTokens: 0,
activeMilliseconds: 0,
...(frontendOnly !== undefined ? { frontendOnly } : {}),
...(extras.revertOf ? { revertOf: extras.revertOf } : {}),
} as Run;
const blocked = startBlocker(provider, project);
@ -472,8 +484,22 @@ export class ControlPlane {
return this.store.transaction(actor.tenantId, async tx => {
const run = await must<Run>(tx, 'run', id);
const project = await projectAccess(tx, actor, run.projectId);
// Adding to a requirement is wishing: not beyond what the person may wish for themselves.
if (
data.action === 'answer' &&
backendDefined(project) &&
wishScopeOf(actor, project) === 'frontend' &&
(!run.frontendOnly || data.allowBackend)
)
throw new DomainError(
'FRONTEND_ONLY_ACCOUNT',
data.allowBackend
? 'Your account may only wish for frontend changes; someone who may change backend code widens the wish'
: 'This run may change backend code, and your account may only wish for frontend changes',
403,
);
return idempotent(tx, `command:${actor.userId}:${id}:${key}`, data, async () => {
const result = await this.applyCommand(tx, run, project, data);
const result = await this.applyCommand(tx, run, project, data, actor.userId);
if (data.allowBackend)
await tx.event(id, 'run.scope', 'The wish may change backend code from now on.', {
frontendOnly: false,
@ -497,6 +523,8 @@ export class ControlPlane {
acceptanceCriteria?: string[];
allowBackend?: true;
},
/** Who adds to the requirement with an answer. */
by?: string,
): Promise<Run> {
const id = run.id;
if (terminal(run)) throw new DomainError('TERMINAL_RUN', 'Submit a new wish to change a completed task');
@ -550,6 +578,8 @@ export class ControlPlane {
wish.revision += 1;
wish.goal = `${wish.goal}\n\n${answer}`;
if (data.allowBackend) run.frontendOnly = false;
if (by && by !== run.requestedBy && !run.contributors?.includes(by))
run.contributors = [...(run.contributors ?? []), by];
if (data.acceptanceCriteria) wish.acceptanceCriteria = data.acceptanceCriteria;
await tx.put('wish', wish);
run.revision = wish.revision;
@ -615,9 +645,9 @@ export class ControlPlane {
requireHuman(actor);
requireRole(actor, ['owner', 'admin', 'developer']);
this.validateKey(key);
const { original, integration, existing } = await this.store.read(actor.tenantId, async tx => {
const { original, integration, existing, project } = await this.store.read(actor.tenantId, async tx => {
const original = await must<Run>(tx, 'run', id);
await projectAccess(tx, actor, original.projectId);
const project = await projectAccess(tx, actor, original.projectId);
const integration = original.integratedCommit
? (await tx.list<Evidence>('evidence', { runId: id })).find(
evidence =>
@ -630,7 +660,7 @@ export class ControlPlane {
const existing = (await tx.list<Run>('run', { projectId: original.projectId })).find(
run => run.revertOf?.runId === id && !terminal(run),
);
return { original, integration, existing };
return { original, integration, existing, project };
});
if (existing) return { wish_id: existing.wishId, run_id: existing.id, status_url: `/runs/${existing.id}` };
if (!original.integratedCommit)
@ -640,6 +670,13 @@ export class ControlPlane {
'REVERT_UNAVAILABLE',
'Where the target branch stood before this run integrated is not recorded; submit a wish that undoes the change instead',
);
// Only a frontend-only run is known to have left backend code alone.
if (backendDefined(project) && !original.frontendOnly && wishScopeOf(actor, project) === 'frontend')
throw new DomainError(
'FRONTEND_ONLY_ACCOUNT',
'This run may have changed backend code; ask someone who may change backend code to take it back',
403,
);
const commit = original.integratedCommit.slice(0, 12);
return this.submit(
actor,
@ -653,6 +690,7 @@ export class ControlPlane {
],
provider: original.provider,
budget: { maxTokens: Math.min(original.budget.maxTokens, 300_000), maxMinutes: 60, maxRepairRounds: 3 },
...(backendDefined(project) ? { frontendOnly: Boolean(original.frontendOnly) } : {}),
},
key,
{
@ -690,8 +728,12 @@ export class ControlPlane {
// A run from another branch also brings that branch's commits, which the change does not show.
const touches = paths.length > 0 || (Boolean(run.sourceBranch) && Boolean(project.codeReview?.paths.length));
if (!touches) return { required: false as const };
// Whoever may change backend code directly needs no review of their own change.
if (run.requestedBy && project.codeReview?.trustedMembers?.includes(run.requestedBy)) {
// A backend change needs no review when everyone who asked for it may merge backend code directly.
const people = [run.requestedBy, ...(run.contributors ?? [])].filter((person): person is string =>
Boolean(person),
);
const scopes = await Promise.all(people.map(person => personWishScope(tx, person, project)));
if (people.length && scopes.every(scope => scope === 'full')) {
const recorded = (await tx.events(id)).some(
event => event.type === 'code_review.skipped' && event.data?.sourceCommit === input.sourceCommit,
);
@ -699,8 +741,13 @@ export class ControlPlane {
await tx.event(
id,
'code_review.skipped',
`The change touches ${paths.length} backend path(s); whoever asked for it may change backend code directly, so it needs no review.`,
{ sourceCommit: input.sourceCommit, requestedBy: run.requestedBy, paths: paths.slice(0, 50) },
`The change touches ${paths.length} backend path(s); everyone who asked for it may change backend code directly, so it needs no review.`,
{
sourceCommit: input.sourceCommit,
requestedBy: run.requestedBy,
...(run.contributors?.length ? { contributors: run.contributors } : {}),
paths: paths.slice(0, 50),
},
);
return { required: false as const };
}
@ -753,7 +800,7 @@ export class ControlPlane {
*/
async decideCodeReview(actor: Actor, id: string, input: unknown, key?: string) {
requireHuman(actor);
requireRole(actor, ['owner', 'admin']);
requirePermission(actor, 'reviewCode');
const data = codeReviewDecisionInput.parse(input);
this.validateKey(key);
return this.store.transaction(actor.tenantId, async tx => {
@ -765,7 +812,8 @@ export class ControlPlane {
);
if (!review || review.sourceCommit !== data.sourceCommit)
throw new DomainError('REVIEW_STALE', 'The change under review changed; reload it and review again');
if (isProduction(this.env) && review.requestedBy === actor.userId)
// Only someone who could have merged the change directly may approve their own, and nobody in production.
if (review.requestedBy === actor.userId && (isProduction(this.env) || wishScopeOf(actor, project) !== 'full'))
throw new DomainError('SELF_REVIEW', 'Someone other than the requester reviews the change', 403);
const who = actor.displayName ?? actor.userId;
await tx.put('code_review', {
@ -786,10 +834,13 @@ export class ControlPlane {
const waiting = run.status === 'waiting' && run.waitingReason === 'code_review';
if (data.decision === 'approve')
return waiting ? this.applyCommand(tx, run, project, { action: 'resume' }) : run;
return this.applyCommand(tx, run, project, {
action: 'answer',
message: `代码审核未通过(${who}):${data.comment}`,
});
return this.applyCommand(
tx,
run,
project,
{ action: 'answer', message: `代码审核未通过(${who}):${data.comment}` },
actor.userId,
);
});
});
}

View File

@ -23,6 +23,7 @@ import {
import type { Store, Transaction } from '../db/store.js';
import { executionLease, executionScope, must, projectAccess, record, setWaiting, touch } from './control-plane.js';
import { digest, requireHuman, requireRole } from './policy.js';
import { requirePermission } from './permissions.js';
const createInput = z
.object({
@ -375,7 +376,7 @@ export class GitHubIntegration {
}
}
async authorizeMerge(actor: Actor, id: string, input: { expectedHeadSha: string; expectedBaseSha: string }) {
requireRole(actor, ['owner', 'admin', 'deployer']);
requirePermission(actor, 'releases');
requireHuman(actor);
const observed = await this.reconcilePullRequest(actor, id);
return this.store.transaction(actor.tenantId, async tx => {
@ -407,7 +408,7 @@ export class GitHubIntegration {
}
async merge(actor: Actor, id: string) {
if (actor.kind !== 'verifier') {
requireRole(actor, ['owner', 'admin', 'deployer']);
requirePermission(actor, 'releases');
requireHuman(actor);
}
const observed = await this.reconcilePullRequest(actor, id);

View File

@ -1,13 +1,20 @@
import { randomBytes, randomInt, scryptSync, timingSafeEqual } from 'node:crypto';
import {
accountTypeOf,
accountTypes,
DomainError,
isProduction,
localAccountInput,
localAccountPatch,
localLoginInput,
normalizePermissions,
roleFor,
rolePermissions,
type AccountType,
type Actor,
type Entity,
type LocalAccountView,
type Permissions,
type Project,
type Role,
} from '@wishforge/contracts';
@ -19,7 +26,7 @@ import { requireHuman, requireRole } from './policy.js';
/**
* A person of a local deployment, signing in with a password of their own. The web console
* checks the password here and then calls the API with its local credential plus the person's
* account ID and password version, so each person acts with their own role.
* account ID and password version, so each person acts with their own permissions.
*/
interface LocalAccount extends Entity {
username: string;
@ -29,6 +36,11 @@ interface LocalAccount extends Entity {
/** Changes when the password is reset, which ends the person's existing sessions. */
passwordVersion: number;
createdBy: string;
/**
* What the person may do; their role follows from it. Absent on accounts from before
* permissions, where the role alone decides.
*/
permissions?: Permissions;
}
/** The deployment's tenant for the local credential; see Authenticator.authenticate. */
@ -51,32 +63,50 @@ function credential(password: string) {
return { salt, passwordHash: hash(password, salt).toString('hex') };
}
function view(account: LocalAccount, role: Role | undefined, projects: Project[]): LocalAccountView {
const own = projects.filter(project => project.memberIds.includes(account.id));
const permissions = account.permissions
? normalizePermissions(account.permissions)
: rolePermissions(role ?? 'viewer');
const type = accountTypeOf(permissions);
return {
id: account.id,
username: account.username,
displayName: account.displayName,
role: role ?? 'viewer',
role: role ?? roleFor(permissions),
active: Boolean(role),
createdAt: account.createdAt,
createdBy: account.createdBy,
projectIds: own.map(project => project.id),
backendProjectIds: own
.filter(project => project.codeReview?.trustedMembers?.includes(account.id))
.map(project => project.id),
projectIds: projects.filter(project => project.memberIds.includes(account.id)).map(project => project.id),
permissions,
...(type ? { type } : {}),
};
}
/** A project where `userId` may, or may no longer, change backend code without a review. */
function withBackend(project: Project, userId: string, backend: boolean): Project | undefined {
const policy = project.codeReview ?? { paths: [], exceptPaths: [] };
const trusted = policy.trustedMembers ?? [];
if (trusted.includes(userId) === backend) return undefined;
/** An account type's permissions, or the ones given, as kept: managing includes everything else. */
function granted(data: { type?: AccountType; permissions?: Permissions }): Permissions | undefined {
if (data.permissions) return normalizePermissions(data.permissions);
return data.type ? { ...accountTypes[data.type] } : undefined;
}
const samePermissions = (a: Permissions, b: Permissions) =>
a.wish === b.wish && a.reviewCode === b.reviewCode && a.releases === b.releases && a.manage === b.manage;
/**
* The project with `userId` in it or not, as `member` says. A person with permissions of their own
* is no longer one of the project's trusted members: their account decides what they may change.
*/
function withMember(project: Project, userId: string, member: boolean): Project | undefined {
const present = project.memberIds.includes(userId);
const trusted = project.codeReview?.trustedMembers ?? [];
const wasTrusted = trusted.includes(userId);
if (present === member && !wasTrusted) return undefined;
return {
...touch(project),
codeReview: {
...policy,
trustedMembers: backend ? [...trusted, userId] : trusted.filter(member => member !== userId),
},
memberIds:
present === member
? project.memberIds
: member
? [...project.memberIds, userId]
: project.memberIds.filter(id => id !== userId),
...(wasTrusted
? { codeReview: { ...project.codeReview!, trustedMembers: trusted.filter(id => id !== userId) } }
: {}),
};
}
@ -125,6 +155,8 @@ export class LocalAccounts {
if (members.length >= effectiveEntitlements(await tx.tenant()).limits.maxMembers)
throw new DomainError('MEMBER_LIMIT', 'Tenant active-member allowance is exhausted', 429);
const password = newPassword();
const permissions = granted(data)!;
const role = roleFor(permissions);
const account: LocalAccount = {
...record(actor.tenantId),
id,
@ -133,31 +165,26 @@ export class LocalAccounts {
...credential(password),
passwordVersion: 1,
createdBy: actor.userId,
permissions,
};
await tx.put('local_account', account);
await tx.putMembership({ userId: id, role: data.role, active: true });
await tx.putMembership({ userId: id, role, active: true });
const projects: Project[] = [];
for (const project of await tx.list<Project>('project')) {
if (data.projectIds && !data.projectIds.includes(project.id)) {
projects.push(project);
continue;
}
let next = project.memberIds.includes(id)
? project
: { ...touch(project), memberIds: [...project.memberIds, id] };
next = withBackend(next, id, data.backend) ?? next;
if (next !== project) await tx.put('project', next);
projects.push(next);
const next = withMember(project, id, !data.projectIds || data.projectIds.includes(project.id));
if (next) await tx.put('project', next);
projects.push(next ?? project);
}
await tx.put('entitlement_event', {
...record(actor.tenantId),
action: 'member.invited',
actorId: actor.userId,
targetSubject: id,
role: data.role,
role,
permissions,
});
// The password is shown this once; only its hash is kept.
return { account: view(account, data.role, projects), password };
return { account: view(account, role, projects), password };
});
}
async update(actor: Actor, id: string, input: unknown) {
@ -166,22 +193,40 @@ export class LocalAccounts {
return this.store.transaction(actor.tenantId, async tx => {
const account = await must<LocalAccount>(tx, 'local_account', id);
const current = (await tx.members()).find(member => member.userId === id && member.active);
const role = data.role ?? current?.role ?? 'viewer';
const before = account.permissions
? normalizePermissions(account.permissions)
: rolePermissions(current?.role ?? 'viewer');
const permissions = granted(data);
const changed = Boolean(permissions && (!account.permissions || !samePermissions(permissions, before)));
const role = permissions ? roleFor(permissions) : (current?.role ?? roleFor(before));
const active = data.active ?? Boolean(current);
if (id === actor.userId && (!active || role !== current?.role))
throw new DomainError('SELF_ACCOUNT_CHANGE', 'Ask another administrator to change your own role or access');
const next = data.displayName ? { ...touch(account), displayName: data.displayName } : account;
const all = await tx.list<Project>('project');
const moved = all.some(
project => data.projectIds && data.projectIds.includes(project.id) !== project.memberIds.includes(id),
);
if (id === actor.userId && (!active || changed || moved))
throw new DomainError(
'SELF_ACCOUNT_CHANGE',
'Ask another administrator to change your own permissions, projects or access',
);
const next =
data.displayName || changed
? {
...touch(account),
...(data.displayName ? { displayName: data.displayName } : {}),
...(changed ? { permissions } : {}),
}
: account;
if (next !== account) await tx.put('local_account', next);
const projects: Project[] = [];
for (const project of await tx.list<Project>('project')) {
const changed =
data.backend !== undefined && project.memberIds.includes(id)
? withBackend(project, id, data.backend)
: undefined;
if (changed) await tx.put('project', changed);
projects.push(changed ?? project);
for (const project of all) {
const member = data.projectIds ? data.projectIds.includes(project.id) : project.memberIds.includes(id);
// A project of theirs can still count them as trusted from before they had permissions.
const updated = data.projectIds || next.permissions ? withMember(project, id, member) : undefined;
if (updated) await tx.put('project', updated);
projects.push(updated ?? project);
}
if (active !== Boolean(current) || role !== current?.role) {
if (active !== Boolean(current) || role !== current?.role || changed) {
if (active && !current) {
const members = (await tx.members()).filter(member => member.active);
if (members.length >= effectiveEntitlements(await tx.tenant()).limits.maxMembers)
@ -190,10 +235,11 @@ export class LocalAccounts {
await tx.putMembership({ userId: id, role, active });
await tx.put('entitlement_event', {
...record(actor.tenantId),
action: active ? 'member.role_changed' : 'member.disabled',
action: active ? (changed ? 'member.permissions_changed' : 'member.role_changed') : 'member.disabled',
actorId: actor.userId,
targetSubject: id,
role,
...(changed ? { permissions } : {}),
});
}
return view(next, active ? role : undefined, projects);
@ -260,6 +306,7 @@ export class LocalAccounts {
kind: 'human',
clientId: 'wishforge-web',
displayName: account.displayName,
...(account.permissions ? { permissions: normalizePermissions(account.permissions) } : {}),
};
}
}

View File

@ -0,0 +1,46 @@
import {
DomainError,
normalizePermissions,
rolePermissions,
wishScopeIn,
type Actor,
type Entity,
type Permissions,
type Project,
type WishScope,
} from '@wishforge/contracts';
import type { Transaction } from '../db/store.js';
const actions: Record<'reviewCode' | 'releases' | 'manage', string> = {
reviewCode: 'review code changes',
releases: 'approve, reject or roll back releases',
manage: 'manage this deployment',
};
const trusted = (project: Project, userId: string) => Boolean(project.codeReview?.trustedMembers?.includes(userId));
/** Whether the project says which code is backend; without that, every change is frontend code. */
export const backendDefined = (project: Project) => Boolean(project.codeReview?.paths.length);
/** What the actor may do: the permissions of their own account, or else what their role allows. */
export function permissionsOf(actor: Actor): Permissions {
return actor.permissions ? normalizePermissions(actor.permissions) : rolePermissions(actor.role);
}
export function requirePermission(actor: Actor, permission: keyof typeof actions) {
if (!permissionsOf(actor)[permission])
throw new DomainError('FORBIDDEN', `Your account cannot ${actions[permission]}`, 403);
}
/** What the actor may wish for in the project. */
export function wishScopeOf(actor: Actor, project: Project): WishScope {
return wishScopeIn(permissionsOf(actor), Boolean(actor.permissions), trusted(project, actor.userId));
}
/**
* What a person may wish for in the project now, for a decision made on their behalf (whether
* their change needs a review): nothing once they no longer belong to the deployment.
*/
export async function personWishScope(tx: Transaction, userId: string, project: Project): Promise<WishScope> {
const role = await tx.membership(userId);
if (!role) return 'none';
const own = userId.startsWith('local:')
? (await tx.get<Entity & { permissions?: Permissions }>('local_account', userId))?.permissions
: undefined;
return wishScopeIn(own ?? rolePermissions(role), Boolean(own), trusted(project, userId));
}

View File

@ -33,6 +33,7 @@ import {
} from './control-plane.js';
import { captureLesson } from './lessons.js';
import { digest, releaseRisk, requireRole, requireHuman } from './policy.js';
import { requirePermission } from './permissions.js';
import { applicationUrlFor, assertApplicationConfigured, assertApplicationAccepted } from './application-access.js';
import { assertVerificationProfile, verificationPolicyDigest } from './verification-policy.js';
@ -276,7 +277,7 @@ export class Releases {
}
async request(actor: Actor, input: unknown, key?: string) {
requireRole(actor, ['owner', 'admin', 'deployer']);
requirePermission(actor, 'releases');
const data = releaseInput.parse(input);
return this.store.transaction(actor.tenantId, async tx => {
const run = await must<Run>(tx, 'run', data.runId);
@ -431,7 +432,7 @@ export class Releases {
return { run, environment, project };
}
async decide(actor: Actor, id: string, input: { decision: string; bindingDigest: string }) {
requireRole(actor, ['owner', 'admin', 'deployer']);
requirePermission(actor, 'releases');
requireHuman(actor);
if (!['approve', 'reject'].includes(input.decision))
throw new DomainError('INVALID_DECISION', 'Choose approve or reject', 400);
@ -657,7 +658,7 @@ export class Releases {
};
}
async rollback(actor: Actor, id: string, key?: string) {
requireRole(actor, ['owner', 'admin', 'deployer']);
requirePermission(actor, 'releases');
requireHuman(actor);
return this.store.transaction(actor.tenantId, async tx => {
const release = await must<Release>(tx, 'release', id);

View File

@ -45,6 +45,7 @@ import { Entitlements, requireCapacity } from './domain/entitlements.js';
import { requireRole, requireHuman } from './domain/policy.js';
import { configuredVerificationProfiles, selectVerificationProfile } from './domain/verification-policy.js';
import { LocalAccounts, localAccountsEnabled } from './domain/local-accounts.js';
import { permissionsOf } from './domain/permissions.js';
import { WishRefiner } from './domain/wish-refiner.js';
import { notificationsConfigured } from './domain/notifications.js';
@ -183,7 +184,15 @@ export class ApiController {
constructor(@Inject(Services) private s: Services) {}
@Get('identity') identity(@Req() req: AuthRequest) {
const { userId, role, kind, displayName } = req.actor;
return ok({ userId, role, kind, ...(displayName ? { displayName } : {}) });
return ok({
userId,
role,
kind,
...(displayName ? { displayName } : {}),
permissions: permissionsOf(req.actor),
// Permissions of one's own account apply as they are; a role's can be raised by a project.
permissionSource: req.actor.permissions ? 'account' : 'role',
});
}
/** What this deployment offers, so the console shows only what works here. */
@Get('capabilities') capabilities(@Req() req: AuthRequest) {

View File

@ -2995,3 +2995,41 @@ ul.criteria-choices {
line-height: 1.7;
color: var(--muted);
}
.type-options {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 8px;
}
.permission-tags {
display: flex;
flex-wrap: wrap;
gap: 5px;
}
.permission-details .permission-wish {
display: flex;
align-items: center;
gap: 10px;
}
.permission-details .permission-wish select {
min-height: 34px;
padding: 5px 10px;
font-size: 13px;
width: auto;
}
.permission-matrix td,
.permission-matrix th {
vertical-align: top;
}
.permission-matrix td:nth-child(n + 3),
.permission-matrix th:nth-child(n + 3) {
text-align: center;
white-space: nowrap;
}
fieldset:disabled .scope-option,
fieldset:disabled label {
cursor: not-allowed;
opacity: 0.65;
}
.member-scopes {
font-size: 13px;
}

View File

@ -31,7 +31,7 @@ const navigation = [
['/providers', '执行器', Settings2],
['/agent', 'Agent 配置', Bot],
['/usage', '用量', BarChart3],
['/members', '成员', Users],
['/members', '成员与权限', Users],
] as const;
export function ConsoleShell({ children }: { children: ReactNode }) {
const pathname = usePathname();

View File

@ -6,6 +6,7 @@ import { resourceState } from '@/lib/readiness';
import type { Dashboard } from '@/lib/types';
import { ButtonLink, EmptyState, ErrorNotice, Loading, PageHeader, Panel } from '@/components/ui';
import { RunTable } from '@/components/run-table';
import { useMayWish } from '@/lib/permissions';
const journey = [
['许愿与澄清', '将想法转化为可执行的任务,与 Agent 一起澄清细节。'],
['独立工作区', '在独立任务分支实现代码,按环境配置完成构建与验证。'],
@ -14,6 +15,7 @@ const journey = [
['部署与观察', '部署到目标环境,并持续观察运行状态。'],
];
export function DashboardView() {
const mayWish = useMayWish();
const { data: cachedData, error, isLoading, isValidating, mutate } = useResource<Dashboard>('/dashboard', 10000);
const data = error && [401, 403].includes(error.status) ? undefined : cachedData;
const connectionState = resourceState(Boolean(data), Boolean(error), isValidating);
@ -53,10 +55,12 @@ export function DashboardView() {
title="工作概览"
description="从一句愿望,到有证据的交付。"
action={
<ButtonLink href="/runs/new">
<Plus size={19} />
提交愿望
</ButtonLink>
mayWish ? (
<ButtonLink href="/runs/new">
<Plus size={19} />
提交愿望
</ButtonLink>
) : undefined
}
/>
{error ? (

View File

@ -1,8 +1,17 @@
'use client';
import { useState } from 'react';
import { Copy, KeyRound, Plus, UserRound } from 'lucide-react';
import { Copy, KeyRound, Pencil, Plus, UserRound } from 'lucide-react';
import {
accountTypeNames,
accountTypeOf,
accountTypes,
normalizePermissions,
wishScopes,
type Permissions,
} from '@wishforge/contracts/permissions';
import { formatTime, messageOf, mutateApi, useResource } from '@/lib/api';
import type { Identity, LocalAccount, Project, Role } from '@/lib/types';
import type { Identity, LocalAccount, Project } from '@/lib/types';
import { accountTypeLabels, permissionPhrases, typeName, wishScopeLabels } from '@/lib/permissions';
import {
Button,
EmptyState,
@ -17,32 +26,6 @@ import {
Status,
} from '@/components/ui';
export const roleLabels: Record<Role, string> = {
owner: '所有者',
admin: '管理员',
developer: '开发者',
deployer: '部署者',
viewer: '只读',
};
const assignable: Role[] = ['admin', 'developer', 'deployer', 'viewer'];
/** What code a person may change directly; which paths are backend code is each project's setting. */
const codeScopes = {
frontend: '仅前端(改后端要审核)',
backend: '前端和后端',
} as const;
function codeScope(account: LocalAccount): keyof typeof codeScopes | 'mixed' | undefined {
if (!account.projectIds.length) return undefined;
if (!account.backendProjectIds.length) return 'frontend';
return account.backendProjectIds.length === account.projectIds.length ? 'backend' : 'mixed';
}
const roleHints: Record<Role, string> = {
owner: '本机服务的维护者,拥有全部权限',
admin: '管理成员、项目设置、预算;可以审核代码、审批发布',
developer: '提交愿望、继续或暂停运行、补充需求、撤销改动',
deployer: '审批和回滚发布',
viewer: '只能查看',
};
/** Shows a password once, for the administrator to hand over; it is not kept anywhere readable. */
function PasswordOnce({ title, password, onClose }: { title: string; password: string; onClose: () => void }) {
const [copied, setCopied] = useState(false);
@ -73,15 +56,244 @@ function PasswordOnce({ title, password, onClose }: { title: string; password: s
);
}
/** Everyone signs in with an account of their own, so the system knows who did what. */
/** Every account type next to what it may do. */
function PermissionMatrix() {
const mark = (allowed: boolean) => (allowed ? '✓' : '—');
return (
<div className="table-scroll">
<table className="data-table permission-matrix" aria-label="账户类型与权限">
<thead>
<tr>
<th>账户类型</th>
<th>许愿</th>
<th>审核代码</th>
<th>审批发布</th>
<th>管理</th>
</tr>
</thead>
<tbody>
{accountTypeNames.map(type => {
const permissions = accountTypes[type];
return (
<tr key={type}>
<td>
<strong>{accountTypeLabels[type].name}</strong>
<div className="muted text-small">{accountTypeLabels[type].hint}</div>
</td>
<td>{wishScopeLabels[permissions.wish]}</td>
<td>{mark(permissions.reviewCode)}</td>
<td>{mark(permissions.releases)}</td>
<td>{mark(permissions.manage)}</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
}
function Phrases({ permissions }: { permissions: Permissions }) {
return (
<div className="permission-tags">
{permissionPhrases(permissions).map(phrase => (
<span key={phrase} className="status">
{phrase}
</span>
))}
</div>
);
}
const sameSet = (a: string[], b: string[]) => a.length === b.length && a.every(item => b.includes(item));
const samePermissions = (a: Permissions, b: Permissions) =>
a.wish === b.wish && a.reviewCode === b.reviewCode && a.releases === b.releases && a.manage === b.manage;
/**
* Adding an account, or changing one: an account type fills in the permissions, which can then be
* adjusted one by one. Administrators cannot change their own permissions or projects.
*/
function AccountForm({
account,
projects,
self,
onClose,
onSaved,
}: {
account?: LocalAccount;
projects: Project[];
self: boolean;
onClose: () => void;
onSaved: (created?: { account: LocalAccount; password: string }) => Promise<void>;
}) {
const [username, setUsername] = useState('');
const [displayName, setDisplayName] = useState(account?.displayName ?? '');
const [permissions, setPermissions] = useState<Permissions>(account?.permissions ?? { ...accountTypes.frontend });
const [projectIds, setProjectIds] = useState(account?.projectIds ?? projects.map(project => project.id));
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const shown = normalizePermissions(permissions);
const type = accountTypeOf(shown);
const change = (next: Partial<Permissions>) => setPermissions(normalizePermissions({ ...permissions, ...next }));
async function save(event: React.FormEvent) {
event.preventDefault();
setBusy(true);
setError('');
try {
if (!account) {
const created = await mutateApi<{ account: LocalAccount; password: string }>('/local-accounts', {
username: username.trim(),
displayName: displayName.trim(),
permissions: shown,
projectIds,
});
await onSaved(created);
} else {
// Only what changed: an administrator may rename themselves, nothing more.
const patch = {
...(displayName.trim() !== account.displayName ? { displayName: displayName.trim() } : {}),
...(!samePermissions(shown, account.permissions) ? { permissions: shown } : {}),
...(!sameSet(projectIds, account.projectIds) ? { projectIds } : {}),
};
if (Object.keys(patch).length)
await mutateApi(`/local-accounts/${encodeURIComponent(account.id)}`, patch, 'PATCH');
await onSaved();
}
} catch (failure) {
setError(messageOf(failure));
} finally {
setBusy(false);
}
}
return (
<Modal
wide
title={account ? `${account.displayName} 的账户` : '添加成员'}
description={account ? `登录名 ${account.username}` : '创建后会生成一个初始密码。'}
onClose={onClose}
>
<form className="form-stack" onSubmit={save}>
{account ? null : (
<Field label="登录名" hint="2–32 位小写字母、数字、点、横线或下划线,例如 zhanghm。">
<input
required
pattern="[a-z0-9][a-z0-9_.\-]{1,31}"
value={username}
onChange={event => setUsername(event.target.value.toLowerCase())}
/>
</Field>
)}
<Field label="显示名" hint="在运行记录、审核和审批里显示,例如真实姓名。">
<input required maxLength={60} value={displayName} onChange={event => setDisplayName(event.target.value)} />
</Field>
{self ? <Notice>不能修改自己的权限和项目,请让另一位管理员修改。</Notice> : null}
<fieldset className="field scope-field" disabled={self}>
<legend className="field-label">账户类型</legend>
<div className="type-options">
{accountTypeNames.map(name => (
<label key={name} className={type === name ? 'scope-option selected' : 'scope-option'}>
<input
type="radio"
name="account-type"
checked={type === name}
onChange={() => setPermissions({ ...accountTypes[name] })}
/>
<span>
<strong>{accountTypeLabels[name].name}</strong>
<small>{accountTypeLabels[name].hint}</small>
</span>
</label>
))}
</div>
</fieldset>
<fieldset className="checkbox-list permission-details" disabled={self}>
<legend>具体权限{type ? '' : '(自定义)'}</legend>
<label className="permission-wish">
<span>许愿</span>
<select
value={shown.wish}
disabled={shown.manage}
onChange={event => change({ wish: event.target.value as Permissions['wish'] })}
>
{wishScopes.map(scope => (
<option key={scope} value={scope}>
{wishScopeLabels[scope]}
</option>
))}
</select>
</label>
<label>
<input
type="checkbox"
checked={shown.reviewCode}
disabled={shown.manage}
onChange={event => change({ reviewCode: event.target.checked })}
/>
审核代码:批准或驳回别人改到后端的改动
</label>
<label>
<input
type="checkbox"
checked={shown.releases}
disabled={shown.manage}
onChange={event => change({ releases: event.target.checked })}
/>
审批发布:批准、拒绝和回滚发布
</label>
<label>
<input
type="checkbox"
checked={shown.manage}
onChange={event =>
setPermissions(
event.target.checked ? { ...accountTypes.admin } : { ...accountTypes.admin, manage: false },
)
}
/>
管理:成员与权限、项目设置、环境、执行器、预算(包含以上全部权限)
</label>
</fieldset>
{projects.length ? (
<fieldset className="checkbox-list" disabled={self}>
<legend>可以进入的项目</legend>
{projects.map(project => (
<label key={project.id}>
<input
type="checkbox"
checked={projectIds.includes(project.id)}
onChange={event =>
setProjectIds(
event.target.checked ? [...projectIds, project.id] : projectIds.filter(id => id !== project.id),
)
}
/>
{project.name}
</label>
))}
</fieldset>
) : null}
<p className="field-hint">
哪些代码算后端,在各项目的「项目设置 · 代码权限」里定义;项目没有定义时,所有代码都算前端。
</p>
<FormError message={error} />
<div className="modal-actions">
<Button type="button" variant="secondary" onClick={onClose}>
取消
</Button>
<Button busy={busy} disabled={!displayName.trim() || (!account && !username.trim())}>
{account ? '保存' : '创建账号'}
</Button>
</div>
</form>
</Modal>
);
}
/** Everyone signs in with an account of their own; its type says what they may do. */
export function MembersView() {
const identity = useResource<Identity>('/identity');
const manager = identity.data && ['owner', 'admin'].includes(identity.data.role);
const manager = Boolean(identity.data?.permissions?.manage);
const accounts = useResource<LocalAccount[]>(manager ? '/local-accounts' : null, 30000);
const projects = useResource<Project[]>(manager ? '/projects' : null);
const [adding, setAdding] = useState(false);
const [form, setForm] = useState({ username: '', displayName: '', role: 'developer' as Role, backend: false });
const [projectIds, setProjectIds] = useState<string[] | undefined>();
const [editing, setEditing] = useState<LocalAccount | 'new'>();
const [password, setPassword] = useState<{ title: string; value: string }>();
const [resetting, setResetting] = useState<LocalAccount>();
const [busy, setBusy] = useState('');
@ -100,15 +312,16 @@ export function MembersView() {
setBusy('');
}
}
const chosen = projectIds ?? projects.data?.map(project => project.id) ?? [];
const projectNames = (ids: string[]) =>
ids.map(id => projects.data?.find(project => project.id === id)?.name ?? id.slice(0, 8)).join('、');
return (
<>
<PageHeader
title="成员"
description="每个人用自己的账号登录,系统才知道愿望是谁提的、改动由谁审核、发布由谁批准。"
title="成员与权限"
description="每个人用自己的账号登录。账户类型决定这个人能做什么:能不能许愿、许愿能不能改后端、能不能审核代码和审批发布。"
action={
manager ? (
<Button onClick={() => setAdding(true)}>
<Button onClick={() => setEditing('new')}>
<Plus size={16} />
添加成员
</Button>
@ -117,89 +330,72 @@ export function MembersView() {
/>
{identity.error ? (
<ErrorNotice error={identity.error} retry={() => void identity.mutate()} />
) : identity.isLoading ? (
) : identity.isLoading || !identity.data ? (
<Loading />
) : !manager ? (
<Notice>只有所有者或管理员可以管理成员。你的角色是「{roleLabels[identity.data!.role]}」。</Notice>
<Panel title="我的权限">
<p className="panel-intro">
你的账户类型是「{typeName(identity.data.permissions)}」。只有管理员可以添加成员和分配权限。
</p>
<Phrases permissions={identity.data.permissions} />
</Panel>
) : (
<Panel title="账号">
<p className="panel-intro">
本机管理员(凭据文件里的账号)是所有者,不在下面的列表里。停用的账号立即无法再操作;重置密码会让对方已登录的会话失效。「代码权限」为「仅前端」的人改到后端代码时,改动要先经所有者或管理员审核才能合入;哪些路径算后端代码,在项目设置的「代码权限」里定义。
停用的账号立即无法再操作;重置密码会让对方已登录的会话失效。改了账户类型或权限,对方的下一个操作就按新权限执行。
</p>
{accounts.error ? (
<ErrorNotice error={accounts.error} retry={() => void accounts.mutate()} />
) : accounts.isLoading ? (
<Loading />
) : accounts.data?.length ? (
) : (
<div className="table-scroll">
<table className="data-table" aria-label="成员账号">
<thead>
<tr>
<th>成员</th>
<th>角色</th>
<th>代码权限</th>
<th>账户类型</th>
<th>能做什么</th>
<th>项目</th>
<th>状态</th>
<th>创建</th>
<th>
<span className="sr-only">操作</span>
</th>
</tr>
</thead>
<tbody>
{accounts.data.map(account => (
<tr>
<td>
<strong>本机管理员</strong>
<div className="muted text-small">凭据文件里的账号</div>
</td>
<td>管理员</td>
<td>
<Phrases permissions={accountTypes.admin} />
</td>
<td className="muted text-small">全部项目</td>
<td>
<Status value="ready" label="可用" />
</td>
<td className="muted text-small">不能在这里修改</td>
</tr>
{accounts.data?.map(account => (
<tr key={account.id}>
<td>
<strong>{account.displayName}</strong>
<div className="muted text-small">{account.username}</div>
<div className="muted text-small">
{account.username} · {formatTime(account.createdAt)} 创建
</div>
</td>
<td>{typeName(account.permissions)}</td>
<td>
<select
aria-label={`${account.displayName} 的角色`}
value={account.role}
disabled={!account.active || busy === `role:${account.id}`}
onChange={event =>
void act(`role:${account.id}`, () =>
mutateApi(
`/local-accounts/${encodeURIComponent(account.id)}`,
{ role: event.target.value },
'PATCH',
),
)
}
>
{assignable.map(role => (
<option key={role} value={role}>
{roleLabels[role]}
</option>
))}
</select>
<Phrases permissions={account.permissions} />
</td>
<td>
{codeScope(account) ? (
<select
aria-label={`${account.displayName} 的代码权限`}
value={codeScope(account)}
disabled={!account.active || busy === `scope:${account.id}`}
onChange={event =>
void act(`scope:${account.id}`, () =>
mutateApi(
`/local-accounts/${encodeURIComponent(account.id)}`,
{ backend: event.target.value === 'backend' },
'PATCH',
),
)
}
>
{codeScope(account) === 'mixed' ? (
<option value="mixed" disabled>
部分项目可改后端
</option>
) : null}
<option value="frontend">{codeScopes.frontend}</option>
<option value="backend">{codeScopes.backend}</option>
</select>
<td className="text-small">
{account.projectIds.length ? (
projectNames(account.projectIds)
) : (
<span className="muted text-small">没有项目</span>
<span className="muted">无</span>
)}
</td>
<td>
@ -208,9 +404,12 @@ export function MembersView() {
label={account.active ? '可用' : '已停用'}
/>
</td>
<td className="muted text-small">{formatTime(account.createdAt)}</td>
<td>
<div className="button-group">
<Button variant="ghost" disabled={!account.active} onClick={() => setEditing(account)}>
<Pencil size={15} />
编辑
</Button>
<Button variant="ghost" onClick={() => setResetting(account)}>
<KeyRound size={15} />
重置密码
@ -237,115 +436,39 @@ export function MembersView() {
</tbody>
</table>
</div>
) : (
)}
{accounts.data && !accounts.data.length ? (
<EmptyState
compact
icon={<UserRound size={34} strokeWidth={1.35} />}
title="还没有成员账号"
description="添加成员后,把生成的密码交给对方,对方就能用自己的账号登录。"
description="添加成员并选好账户类型,把生成的密码交给对方,对方就能用自己的账号登录。"
/>
)}
{!adding && !resetting ? <FormError message={error} /> : null}
<dl className="role-legend">
{(Object.keys(roleLabels) as Role[]).map(role => (
<div key={role}>
<dt>{roleLabels[role]}</dt>
<dd>{roleHints[role]}</dd>
</div>
))}
</dl>
) : null}
{!editing && !resetting ? <FormError message={error} /> : null}
</Panel>
)}
{adding ? (
<Modal title="添加成员" description="创建后会生成一个初始密码。" onClose={() => setAdding(false)}>
<form
className="form-stack"
onSubmit={event => {
event.preventDefault();
void act('create', () =>
mutateApi<{ account: LocalAccount; password: string }>('/local-accounts', {
username: form.username.trim(),
displayName: form.displayName.trim(),
role: form.role,
projectIds: chosen,
backend: form.backend,
}),
).then(created => {
if (!created) return;
setAdding(false);
setForm({ username: '', displayName: '', role: 'developer', backend: false });
setProjectIds(undefined);
setPassword({ title: `${created.account.displayName} 的初始密码`, value: created.password });
});
}}
>
<Field label="登录名" hint="2–32 位小写字母、数字、点、横线或下划线,例如 zhanghm。">
<input
required
pattern="[a-z0-9][a-z0-9_.\-]{1,31}"
value={form.username}
onChange={event => setForm({ ...form, username: event.target.value.toLowerCase() })}
/>
</Field>
<Field label="显示名" hint="在运行记录、审核和审批里显示,例如真实姓名。">
<input
required
maxLength={60}
value={form.displayName}
onChange={event => setForm({ ...form, displayName: event.target.value })}
/>
</Field>
<Field label="角色" hint={roleHints[form.role]}>
<select value={form.role} onChange={event => setForm({ ...form, role: event.target.value as Role })}>
{assignable.map(role => (
<option key={role} value={role}>
{roleLabels[role]}
</option>
))}
</select>
</Field>
<Field
label="代码权限"
hint="「仅前端」的人改到后端代码时,改动先等所有者或管理员审核;后端代码的范围在项目设置里定义。"
>
<select
value={form.backend ? 'backend' : 'frontend'}
onChange={event => setForm({ ...form, backend: event.target.value === 'backend' })}
>
<option value="frontend">{codeScopes.frontend}</option>
<option value="backend">{codeScopes.backend}</option>
</select>
</Field>
{projects.data?.length ? (
<fieldset className="checkbox-list">
<legend>可以进入的项目</legend>
{projects.data.map(project => (
<label key={project.id}>
<input
type="checkbox"
checked={chosen.includes(project.id)}
onChange={event =>
setProjectIds(
event.target.checked ? [...chosen, project.id] : chosen.filter(id => id !== project.id),
)
}
/>
{project.name}
</label>
))}
</fieldset>
) : null}
<FormError message={error} />
<div className="modal-actions">
<Button type="button" variant="secondary" onClick={() => setAdding(false)}>
取消
</Button>
<Button busy={busy === 'create'} disabled={!form.username.trim() || !form.displayName.trim()}>
创建账号
</Button>
</div>
</form>
</Modal>
{identity.data ? (
<Panel title="账户类型">
<p className="panel-intro">
添加或编辑成员时选一个类型,再按需要单独调整某项权限(调整后显示为「自定义」)。许愿能不能改后端,只看「许愿」这一项;哪些代码算后端,在各项目的「项目设置
· 代码权限」里定义。
</p>
<PermissionMatrix />
</Panel>
) : null}
{editing && projects.data ? (
<AccountForm
account={editing === 'new' ? undefined : editing}
projects={projects.data}
self={editing !== 'new' && editing.id === identity.data?.userId}
onClose={() => setEditing(undefined)}
onSaved={async created => {
setEditing(undefined);
await accounts.mutate();
if (created) setPassword({ title: `${created.account.displayName} 的初始密码`, value: created.password });
}}
/>
) : null}
{resetting ? (
<Modal

View File

@ -3,6 +3,7 @@ import { useState } from 'react';
import { messageOf, mutateApi, useResource } from '@/lib/api';
import type { Environment, LocalAccount, Project, VerificationProfile } from '@/lib/types';
import { personName } from '@/lib/people';
import { typeName, wishScopeLabels } from '@/lib/permissions';
import { Button, ErrorNotice, Field, FormError, Modal, Notice } from '@/components/ui';
import { invalidGlob } from '@wishforge/contracts/path-rules';
@ -56,8 +57,10 @@ export function ProjectSettings({
const [reviewPaths, setReviewPaths] = useState(project.codeReview?.paths.join('\n') ?? '');
const [exceptPaths, setExceptPaths] = useState(project.codeReview?.exceptPaths.join('\n') ?? '');
const [trusted, setTrusted] = useState(project.codeReview?.trustedMembers ?? []);
// Names for the people of the project; elsewhere than a local deployment there are none to read.
const accounts = useResource<LocalAccount[]>('/local-accounts');
// Where people have accounts of their own, their accounts say what they may change; elsewhere
// the project lets people merge backend changes directly.
const capabilities = useResource<{ localAccounts: boolean }>('/capabilities');
const accounts = useResource<LocalAccount[]>(capabilities.data?.localAccounts ? '/local-accounts' : null);
const nameOf = (userId: string) =>
accounts.data?.find(account => account.id === userId)?.displayName ?? personName(userId);
const [wishRules, setWishRules] = useState(project.wishRules ?? '');
@ -233,7 +236,7 @@ export function ProjectSettings({
<div>
<h3>代码权限</h3>
<p className="field-hint">
改到「后端代码」的运行,验证通过后先停在「等待代码审核」,所有者或管理员批准后才合入;提交人在下面「可以直接改后端代码的人」里时不用审核。前端与其他放行的代码,验证通过就合入。
在这里划出哪些代码算后端。只能改前端的人碰不到它;其他人改到它时,有「直接合入」权限的验证通过就合入,没有的先停在「等待代码审核」,由有「审核代码」权限的人批准。前端与其他放行的代码,验证通过就合入。
</p>
</div>
<Field
@ -260,7 +263,25 @@ export function ProjectSettings({
placeholder={'frontend/\n**/*.md'}
/>
</Field>
{project.memberIds?.length ? (
{capabilities.data?.localAccounts ? (
<div className="checkbox-list member-scopes">
<strong>谁能改什么</strong>
{(project.memberIds ?? []).map(userId => {
const account = accounts.data?.find(candidate => candidate.id === userId);
return (
<span key={userId}>
{account?.displayName ?? personName(userId)}:
{account
? `${typeName(account.permissions)} · ${wishScopeLabels[account.permissions.wish]}${account.active ? '' : '(已停用)'}`
: userId === '11111111-1111-4111-8111-111111111111'
? `管理员 · ${wishScopeLabels.full}`
: '按角色'}
</span>
);
})}
<span className="field-hint">每个人能许愿改什么,在「成员与权限」页按人设置。</span>
</div>
) : project.memberIds?.length ? (
<fieldset className="checkbox-list">
<legend>可以直接改后端代码的人</legend>
{project.memberIds.map(userId => (

View File

@ -4,7 +4,7 @@ import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { ArrowRight, ArrowUpRight, FolderGit2, GitBranch, Laptop, Plus, Search, Settings2 } from 'lucide-react';
import { formatTime, messageOf, mutateApi, safeUrl, useResource } from '@/lib/api';
import type { IdeBranch, Project, Run, Workspace } from '@/lib/types';
import type { IdeBranch, Identity, Project, Run, Workspace } from '@/lib/types';
import {
Button,
ButtonLink,
@ -166,6 +166,8 @@ function CreateProject({ onClose, onCreated }: { onClose: () => void; onCreated:
);
}
export function ProjectView({ id }: { id: string }) {
const identity = useResource<Identity>('/identity');
const mayWish = identity.data?.permissions?.wish !== 'none';
const projects = useResource<Project[]>('/projects');
const runs = useResource<Run[]>(`/runs?project=${id}`, 10000);
const workspaces = useResource<Workspace[]>(`/projects/${id}/workspaces`, 10000);
@ -221,14 +223,18 @@ export function ProjectView({ id }: { id: string }) {
back={{ href: '/projects', label: '项目空间' }}
action={
<div className="button-group">
<Button variant="secondary" onClick={() => setShowSettings(true)}>
<Settings2 size={16} />
项目设置
</Button>
<ButtonLink href={`/runs/new?project=${id}`}>
<Plus size={18} />
提交愿望
</ButtonLink>
{identity.data?.permissions?.manage ? (
<Button variant="secondary" onClick={() => setShowSettings(true)}>
<Settings2 size={16} />
项目设置
</Button>
) : null}
{mayWish ? (
<ButtonLink href={`/runs/new?project=${id}`}>
<Plus size={18} />
提交愿望
</ButtonLink>
) : null}
</div>
}
/>
@ -279,7 +285,11 @@ export function ProjectView({ id }: { id: string }) {
(放行 <code>{project.codeReview.exceptPaths.join('、')}</code>)
</>
) : null}
的改动先审核再合入;{project.codeReview.trustedMembers?.length ?? 0} 人可以直接改后端
算后端代码:只能改前端的人碰不到它,其他人改到它时按各自的权限直接合入或先审核(见
<Link className="text-link" href="/members">
成员与权限
</Link>
)
</>
) : (
'不区分前后端,验证通过后直接合入'
@ -317,9 +327,11 @@ export function ProjectView({ id }: { id: string }) {
<span>
{branch.commit.slice(0, 7)} · {formatTime(branch.updatedAt)}
</span>
<ButtonLink secondary href={`/runs/new?project=${id}&branch=${encodeURIComponent(branch.name)}`}>
提交愿望合入
</ButtonLink>
{mayWish ? (
<ButtonLink secondary href={`/runs/new?project=${id}&branch=${encodeURIComponent(branch.name)}`}>
提交愿望合入
</ButtonLink>
) : null}
</li>
))}
</ul>

View File

@ -3,7 +3,7 @@ import Link from 'next/link';
import { useState } from 'react';
import { ArrowRight, ArrowUpRight, Box, Check, ChevronDown, RotateCcw, ShieldCheck, X } from 'lucide-react';
import { formatTime, messageOf, mutateApi, shortId, safeUrl, useResource } from '@/lib/api';
import type { Environment, Release } from '@/lib/types';
import type { Environment, Identity, Release } from '@/lib/types';
import { browserId } from '@/lib/browser-id';
import { riskReasonLabel } from '@/lib/risk';
import { personName } from '@/lib/people';
@ -45,6 +45,9 @@ function releaseAccessUrl(release: Release) {
return release.status === 'healthy' ? safeUrl(release.deliveryUrl) : undefined;
}
export function ReleasesView() {
const identity = useResource<Identity>('/identity');
// Approving, rejecting and rolling back is for whoever may decide on releases; anyone may read a review.
const decider = Boolean(identity.data?.permissions?.releases);
const { data, error, isLoading, mutate } = useResource<Release[]>('/releases', 7000);
const environments = useResource<Environment[]>('/environments');
const environmentName = (id: string) => environments.data?.find(environment => environment.id === id)?.name ?? id;
@ -106,7 +109,7 @@ export function ReleasesView() {
<ArrowUpRight size={15} />
</a>
) : null}
{rollbackable(release) ? (
{decider && rollbackable(release) ? (
<Button variant="secondary" onClick={() => setRollback(release)}>
<RotateCcw size={16} />
回滚
@ -140,7 +143,12 @@ export function ReleasesView() {
)}
</Panel>
{selected ? (
<ApprovalDialog release={selected} onClose={() => setSelected(null)} onSaved={() => void mutate()} />
<ApprovalDialog
release={selected}
decider={decider}
onClose={() => setSelected(null)}
onSaved={() => void mutate()}
/>
) : null}
{rollback ? (
<RollbackDialog
@ -253,7 +261,18 @@ function RollbackDialog({
</Modal>
);
}
function ApprovalDialog({ release, onClose, onSaved }: { release: Release; onClose: () => void; onSaved: () => void }) {
function ApprovalDialog({
release,
decider,
onClose,
onSaved,
}: {
release: Release;
/** Whether the signed-in person may approve or reject releases. */
decider: boolean;
onClose: () => void;
onSaved: () => void;
}) {
const [confirmed, setConfirmed] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
@ -340,21 +359,27 @@ function ApprovalDialog({ release, onClose, onSaved }: { release: Release; onClo
<Loading />
) : null}
<ReleaseBinding release={release} />
<label className="checkbox-label">
<input type="checkbox" checked={confirmed} onChange={event => setConfirmed(event.target.checked)} />
<span>我已核对以上源代码、制品、目标环境和验证证据。</span>
</label>
<FormError message={error} />
<div className="modal-actions">
<Button variant="danger" busy={busy} onClick={() => void decide('reject')}>
<X size={16} />
拒绝
</Button>
<Button busy={busy} disabled={!confirmed} onClick={() => void decide('approve')}>
<Check size={16} />
批准此版本
</Button>
</div>
{decider ? (
<>
<label className="checkbox-label">
<input type="checkbox" checked={confirmed} onChange={event => setConfirmed(event.target.checked)} />
<span>我已核对以上源代码、制品、目标环境和验证证据。</span>
</label>
<FormError message={error} />
<div className="modal-actions">
<Button variant="danger" busy={busy} onClick={() => void decide('reject')}>
<X size={16} />
拒绝
</Button>
<Button busy={busy} disabled={!confirmed} onClick={() => void decide('approve')}>
<Check size={16} />
批准此版本
</Button>
</div>
</>
) : (
<Notice>等待有「审批发布」权限的人批准或拒绝。</Notice>
)}
</div>
</Modal>
);

View File

@ -59,9 +59,11 @@ import { eventLabel } from '@/lib/events';
import { browserId } from '@/lib/browser-id';
import { credentialSourceLabel, initialWishProvider, wishProviderReady } from '@/lib/readiness';
import { personName } from '@/lib/people';
import { mayWishBackend, useMayWish, wishScopeFor } from '@/lib/permissions';
import type { CodeReview } from '@/lib/types';
export function RunsView() {
const mayWish = useMayWish();
const runs = useResource<Run[]>('/runs', 5000);
const projects = useResource<Project[]>('/projects');
const [search, setSearch] = useState('');
@ -83,10 +85,12 @@ export function RunsView() {
title="运行记录"
description="从意图到验收,查看每一次执行的完整轨迹。"
action={
<ButtonLink href="/runs/new">
<Plus size={18} />
提交愿望
</ButtonLink>
mayWish ? (
<ButtonLink href="/runs/new">
<Plus size={18} />
提交愿望
</ButtonLink>
) : undefined
}
/>
{runs.error ? <ErrorNotice error={runs.error} retry={() => void runs.mutate()} /> : null}
@ -326,12 +330,13 @@ function frontendArea(policy: { paths: string[]; exceptPaths: string[] }) {
/** Whether a wish may change backend code, where the project says which code that is. */
function ScopeChoice({
policy,
backendAllowed,
scope,
frontendOnly,
onChange,
}: {
policy: { paths: string[]; exceptPaths: string[] };
backendAllowed: boolean;
/** What the person may wish for: only frontend changes leaves them nothing to choose. */
scope: 'frontend' | 'review' | 'full';
frontendOnly: boolean;
onChange: (frontendOnly: boolean) => void;
}) {
@ -341,17 +346,27 @@ function ScopeChoice({
title: '只改前端',
detail: `${frontendArea(policy)}。改到后端代码时,平台会把这些改动恢复原样,让 Agent 只改前端重做。`,
},
{
value: false,
title: '前端和后端',
detail: backendAllowed
? '可以改后端代码。你有这个项目的后端权限,验证通过就直接合入。'
: '可以改后端代码。你没有这个项目的后端权限,改到后端代码时,验证通过后要所有者或管理员审核才合入。',
},
...(scope === 'frontend'
? []
: [
{
value: false,
title: '前端和后端',
detail:
scope === 'full'
? '可以改后端代码。你的账户可以直接合入,验证通过就合入。'
: '可以改后端代码。你的账户改到后端时,验证通过后要有「审核代码」权限的人批准才合入。',
},
]),
];
return (
<fieldset className="field scope-field">
<legend className="field-label">代码范围</legend>
{scope === 'frontend' ? (
<span className="field-hint">
你的账户只能许愿改前端;需要改后端时,请有后端权限的人提交,或让管理员调整你的账户类型。
</span>
) : null}
{options.map(option => (
<label key={option.title} className={frontendOnly === option.value ? 'scope-option selected' : 'scope-option'}>
<input
@ -442,7 +457,8 @@ export function NewWishView() {
const provider = chosenProvider ?? initialWishProvider(providers.data, Boolean(localPoc));
// The choice exists where the project says which code is backend.
const scopePolicy = project?.codeReview?.paths.length ? project.codeReview : undefined;
const backendAllowed = Boolean(identity.data && scopePolicy?.trustedMembers?.includes(identity.data.userId));
const scope = wishScopeFor(identity.data, project);
const mayWish = scope !== 'none';
const maxTokens = chosenMaxTokens ?? (localPoc && provider === 'claude-code' ? 1000000 : 300000);
const branches = useResource<IdeBranch[]>(effectiveProject ? `/projects/${effectiveProject}/branches` : null);
const targetBranch = projects.data?.find(project => project.id === effectiveProject)?.targetBranch ?? 'main';
@ -500,7 +516,7 @@ export function NewWishView() {
provider,
budget: { maxTokens, maxMinutes, maxRepairRounds },
...(sourceBranch ? { sourceBranch } : {}),
...(scopePolicy ? { frontendOnly } : {}),
...(scopePolicy ? { frontendOnly: frontendOnly || scope === 'frontend' } : {}),
},
'POST',
idempotencyKey,
@ -562,11 +578,11 @@ export function NewWishView() {
/>
</Field>
{refineAction('goal')}
{scopePolicy ? (
{scopePolicy && scope && scope !== 'none' ? (
<ScopeChoice
policy={scopePolicy}
backendAllowed={backendAllowed}
frontendOnly={frontendOnly}
scope={scope}
frontendOnly={frontendOnly || scope === 'frontend'}
onChange={setFrontendOnly}
/>
) : null}
@ -690,9 +706,17 @@ export function NewWishView() {
retrying={projects.isValidating}
/>
) : null}
{mayWish ? null : (
<Notice tone="warning">
你的账户不能提交愿望。需要的话,请管理员在「成员与权限」里调整你的账户类型。
</Notice>
)}
<div className="form-submit">
<p>提交后可在运行详情中补充信息、暂停或取消。</p>
<Button busy={busy} disabled={!effectiveProject || !goal.trim() || !criteria.trim() || !providerReady}>
<Button
busy={busy}
disabled={!effectiveProject || !goal.trim() || !criteria.trim() || !providerReady || !mayWish}
>
<Send size={16} />
提交愿望
</Button>
@ -744,7 +768,8 @@ export function NewWishView() {
}
export function RunDetailView({ id }: { id: string }) {
const runResource = useResource<Run>(`/runs/${id}`, 5000);
const identity = useResource<{ kind: string; role: string; userId: string }>('/identity');
const identity = useResource<Identity>('/identity');
const projectResource = useResource<Project>(runResource.data ? `/projects/${runResource.data.projectId}` : null);
const [confirmRevert, setConfirmRevert] = useState(false);
const router = useRouter();
const events = useResource<RunEvent[]>(`/runs/${id}/events`, 5000);
@ -794,22 +819,23 @@ export function RunDetailView({ id }: { id: string }) {
const budgetExhausted =
(run.usedTokens ?? 0) >= (run.budget.maxTokens ?? 0) ||
(run.activeMilliseconds ?? 0) >= (run.budget.maxMinutes ?? 0) * 60_000;
const permissions = identity.data?.kind === 'human' ? identity.data.permissions : undefined;
const scope = identity.data?.kind === 'human' ? wishScopeFor(identity.data, projectResource.data) : undefined;
// Adding to a run, or taking it back, is wishing: a run that may change backend code needs backend permission.
const withinScope = Boolean(
scope &&
scope !== 'none' &&
(!projectResource.data?.codeReview?.paths.length || run.frontendOnly || mayWishBackend(scope)),
);
// A frontend-only wish whose agent asked to change backend code, or kept changing it.
const backendWanted =
run.status === 'waiting' &&
run.frontendOnly === true &&
(run.waitingReason === 'clarification' ||
(run.waitingReason === 'repair_exhausted' && run.lastFailure?.kind === 'scope')) &&
identity.data?.kind === 'human' &&
['owner', 'admin', 'developer'].includes(identity.data.role);
const canUpdateBudget =
identity.data?.kind === 'human' &&
['owner', 'admin'].includes(identity.data.role) &&
['waiting', 'paused'].includes(run.status);
const canRevert =
Boolean(run.integratedCommit) &&
identity.data?.kind === 'human' &&
['owner', 'admin', 'developer'].includes(identity.data.role);
(run.waitingReason === 'repair_exhausted' && run.lastFailure?.kind === 'scope'));
const mayWiden = Boolean(backendWanted && scope && mayWishBackend(scope));
const canUpdateBudget = Boolean(permissions?.manage) && ['waiting', 'paused'].includes(run.status);
const canRevert = Boolean(run.integratedCommit) && withinScope;
async function revert() {
setBusy(true);
setError('');
@ -882,7 +908,7 @@ export function RunDetailView({ id }: { id: string }) {
{run.status === 'waiting' && run.waitingReason === 'code_review' ? (
<CodeReviewPanel
run={run}
role={identity.data?.kind === 'human' ? identity.data.role : undefined}
reviewer={Boolean(permissions?.reviewCode)}
showChanges={() => setTab('changes')}
onDecided={async () => {
await Promise.all([runResource.mutate(), events.mutate()]);
@ -898,19 +924,29 @@ export function RunDetailView({ id }: { id: string }) {
<Link href={waitingLink.href}>{waitingLink.label}</Link>
</p>
) : null}
{backendWanted ? (
{mayWiden ? (
<div className="scope-unlock">
<p>
这个愿望只能改前端。确实要改后端时,可以放开代码范围:之后可以改后端代码,运行从规划重新开始;改到后端时要不要审核,仍按提交人的后端权限决定。
这个愿望只能改前端。确实要改后端时,可以放开代码范围:之后可以改后端代码,运行从规划重新开始;改到后端的改动,只有提交人和补充过需求的人都能直接合入时才不用审核。
</p>
<Button type="button" variant="secondary" onClick={() => setConfirmScope(true)}>
<LockOpen size={15} />
改为前端和后端并继续
</Button>
</div>
) : backendWanted ? (
<p className="panel-note">这个愿望只能改前端。需要改后端时,请可以许愿改后端的人在这里放开代码范围。</p>
) : null}
<p className="panel-note">如需修改目标,可在下面补充需求;补充会创建新的需求版本并重新验证。</p>
<details className="requirement-amendment">
{withinScope ? (
<p className="panel-note">如需修改目标,可在下面补充需求;补充会创建新的需求版本并重新验证。</p>
) : scope ? (
<p className="panel-note">
{scope === 'none'
? '你的账户不能许愿,也不能补充需求。'
: '这个运行可以改后端代码,而你的账户只能许愿改前端,不能补充需求。'}
</p>
) : null}
<details className="requirement-amendment" hidden={!withinScope}>
<summary>补充或修改需求</summary>
<form
onSubmit={event => {
@ -1138,7 +1174,7 @@ export function RunDetailView({ id }: { id: string }) {
{confirmScope ? (
<Modal
title="改为前端和后端并继续"
description="这个愿望之后可以改后端代码,运行带着这个决定从规划重新开始(需求版本加一)。提交人没有后端权限时,改到后端代码的改动验证通过后还要等所有者或管理员审核。"
description="这个愿望之后可以改后端代码,运行带着这个决定从规划重新开始(需求版本加一)。提交人或补充过需求的人不能直接合入后端改动时,验证通过后还要有「审核代码」权限的人批准。"
onClose={() => setConfirmScope(false)}
>
<div className="modal-body">
@ -1190,15 +1226,16 @@ export function RunDetailView({ id }: { id: string }) {
</>
);
}
/** A change touching paths held for review waits here until an owner or administrator decides. */
/** A change touching backend code waits here until someone who may review code decides. */
function CodeReviewPanel({
run,
role,
reviewer,
showChanges,
onDecided,
}: {
run: Run;
role?: string;
/** Whether the signed-in person may review code. */
reviewer: boolean;
showChanges: () => void;
onDecided: () => Promise<void>;
}) {
@ -1209,7 +1246,6 @@ function CodeReviewPanel({
const [error, setError] = useState('');
const [key] = useState(browserId);
const current = review.data;
const reviewer = role === 'owner' || role === 'admin';
async function decide(decision: 'approve' | 'reject') {
if (!current) return;
setBusy(decision);
@ -1300,7 +1336,7 @@ function CodeReviewPanel({
</div>
</div>
) : (
<Notice>等待所有者或管理员审核。审核通过后运行自动继续。</Notice>
<Notice>等待有「审核代码」权限的人审核。审核通过后运行自动继续。</Notice>
)}
</>
)}

View File

@ -49,7 +49,7 @@ const labels: Record<string, string> = {
'code_review.requested': '请求代码审核',
'code_review.approved': '代码审核通过',
'code_review.rejected': '代码审核驳回',
'code_review.skipped': '有后端权限,免审核',
'code_review.skipped': '可以直接合入,免审核',
'github.pr.requested': '已创建拉取请求',
'github.pr.observed': '拉取请求状态',
};

View File

@ -0,0 +1,55 @@
import {
accountTypeOf,
mayWishBackend,
wishScopeIn,
type AccountType,
type Permissions,
type WishScope,
} from '@wishforge/contracts/permissions';
import { useResource } from './api';
import type { Identity, Project } from './types';
export const wishScopeLabels: Record<WishScope, string> = {
none: '不能许愿',
frontend: '只改前端',
review: '前端和后端,后端改动要审核',
full: '前端和后端,直接合入',
};
/** Each account type: its name, and who it is for. */
export const accountTypeLabels: Record<AccountType, { name: string; hint: string }> = {
admin: { name: '管理员', hint: '负责整个工作空间:成员与权限、项目设置、环境与执行器' },
fullstack: { name: '全栈开发', hint: '可信的开发者:前端和后端的改动验证通过就合入' },
reviewed: { name: '开发(后端需审核)', hint: '新同事或外部协作者:改到后端代码要有人审核' },
frontend: { name: '前端开发', hint: '只做页面和样式:碰不到后端代码' },
releaser: { name: '发布负责人', hint: '负责上线:审批、拒绝和回滚发布,不许愿' },
viewer: { name: '只读访客', hint: '只看项目、运行和发布的进度' },
};
export const CUSTOM_TYPE = '自定义';
export const typeName = (permissions: Permissions) => {
const type = accountTypeOf(permissions);
return type ? accountTypeLabels[type].name : CUSTOM_TYPE;
};
/** What a person may do, one short phrase each, for lists. */
export function permissionPhrases(permissions: Permissions): string[] {
if (permissions.manage) return ['全部权限'];
return [
`许愿:${wishScopeLabels[permissions.wish]}`,
...(permissions.reviewCode ? ['审核代码'] : []),
...(permissions.releases ? ['审批发布'] : []),
];
}
/** What the signed-in person may wish for in the project, as the control plane decides it. */
export function wishScopeFor(identity: Identity | undefined, project: Project | undefined): WishScope | undefined {
if (!identity?.permissions || !project) return undefined;
return wishScopeIn(
identity.permissions,
identity.permissionSource === 'account',
Boolean(project.codeReview?.trustedMembers?.includes(identity.userId)),
);
}
export { mayWishBackend };
/** Whether the signed-in person may submit wishes at all; assumed until known. */
export function useMayWish() {
const identity = useResource<Identity>('/identity');
return identity.data?.permissions?.wish !== 'none';
}

View File

@ -34,6 +34,7 @@ export type Project = {
};
export type { ProviderId } from '@wishforge/contracts';
import type { ProviderId } from '@wishforge/contracts';
import type { AccountType, Permissions } from '@wishforge/contracts/permissions';
/** A branch people pushed from the IDE; a wish starting from it verifies and merges it. */
export type IdeBranch = { name: string; commit: string; updatedAt: string };
export type Run = {
@ -243,7 +244,16 @@ export type Environment = {
[key: string]: unknown;
};
/** Who the console acts as. */
export type Identity = { userId: string; role: Role; kind: string; displayName?: string };
export type Identity = {
userId: string;
role: Role;
kind: string;
displayName?: string;
/** What the person may do. */
permissions: Permissions;
/** `account`: their own account's permissions; `role`: their role's, which a project can raise. */
permissionSource: 'account' | 'role';
};
export type Role = 'owner' | 'admin' | 'developer' | 'deployer' | 'viewer';
/** A person with an account of their own on a local deployment. */
export type LocalAccount = {
@ -256,8 +266,10 @@ export type LocalAccount = {
createdBy: string;
/** Projects the person may work in. */
projectIds: string[];
/** Of those, where the person may change backend code without a review. */
backendProjectIds: string[];
/** What the person may do in those projects; the role follows from them. */
permissions: Permissions;
/** The account type with exactly these permissions; absent for a combination of their own. */
type?: AccountType;
};
/** A person's review of an exact change before it reaches the target branch. */
export type CodeReview = {

View File

@ -86,7 +86,7 @@ export const waitingGuides: Record<WaitingReason, WaitingGuide> = {
code_review: {
title: '等待代码审核',
action:
'改动涉及后端代码,而提交人没有直接改后端的权限;改动已经通过受保护检查。所有者或管理员在下方「代码审核」里查看改动后批准或驳回:批准后自动继续合入,不再重复检查;驳回时写下要改什么,执行器会按意见再改一轮。',
'改动涉及后端代码,而提交人或补充过需求的人不能直接合入后端改动;改动已经通过受保护检查。有「审核代码」权限的人在下方「代码审核」里查看改动后批准或驳回:批准后自动继续合入,不再重复检查;驳回时写下要改什么,执行器会按意见再改一轮。',
link: run => ({ href: `/projects/${run.projectId}`, label: '查看项目的代码权限' }),
resumable: false,
},

View File

@ -211,7 +211,7 @@ sequenceDiagram
### 4.3 集成与交付
1. **代码审核**:验证通过后、取得集成租约之前,verifier 把本次改动的路径交给控制面(`/internal/runs/:id/code-review`)。项目划出的后端代码(`codeReview.paths`,减去放行的 `exceptPaths`;glob,`dir/` 表示整个目录)被改到,或运行从其他分支开始时,除非提交人在 `codeReview.trustedMembers`(可以直接改后端的人,时间线记 `code_review.skipped`)里,控制面记一条绑定需求版本与 commit 的待审核记录(`code_review`),运行停在 integrate 阶段的 `code_review` 等待。所有者或管理员批准后运行自动继续,复用这次验证证据直接集成;驳回时审核意见作为补充需求,生成新的需求版本交给执行器。审核由控制面裁决:verifier 每次集成前都重新询问,继续运行绕不过去。生产模式下请求人不能审核自己的改动。
1. **代码审核**:验证通过后、取得集成租约之前,verifier 把本次改动的路径交给控制面(`/internal/runs/:id/code-review`)。项目划出的后端代码(`codeReview.paths`,减去放行的 `exceptPaths`;glob,`dir/` 表示整个目录)被改到,或运行从其他分支开始时,控制面按**现在**的权限检查提出需求的每个人:提交人(`requestedBy`)和补充过需求、放开过代码范围或驳回过审核的人(`contributors`)。都能直接合入(许愿范围 `full`)时跳过审核,时间线记 `code_review.skipped`;否则记一条绑定需求版本与 commit 的待审核记录(`code_review`),运行停在 integrate 阶段的 `code_review` 等待。有 `reviewCode` 权限的人批准后运行自动继续,复用这次验证证据直接集成;驳回时审核意见作为补充需求,生成新的需求版本交给执行器。审核由控制面裁决:verifier 每次集成前都重新询问,继续运行绕不过去。请求人只有自己能直接合入时才可以批准自己的改动,生产模式下一律不能。
2. verifier 取得**项目集成租约**(控制面 fence,同一项目同时只有一个运行在集成)。
3. 在独立的裸仓库(远端的缓存)中准备候选 commit:目标分支未移动时,候选就是已验证的 commit(快进);否则把已验证的 commit 合并到目标分支的最新提交上。
4. 候选与已验证 commit 不同时,对候选重新执行完整验证。候选未通过某项检查时,verifier 先在不带本次改动的目标分支上单独跑到这项检查:目标分支能通过,说明问题出在两者合在一起,按一轮修复处理;目标分支同样失败,再检查运行的起点,起点能通过才说明是之后推送的提交弄坏了分支,运行进入 `target_broken` 等待,检查点换回已验证的 commit,不让执行器去改别人的代码;起点也失败时,这个运行可能正是来修它的,仍按一轮修复处理。这些对照检查不记录证据。合并冲突时提交失败的集成证据(冲突文件与目标 commit),按一轮修复处理:修复轮先把最新目标分支合并进工作区,冲突标记交给执行器解决,检查点以该目标 commit 为基线。
@ -309,7 +309,7 @@ PostgreSQL,所有租户数据表都启用强制行级安全(`app.tenant_id`
| `github_operation` | PR 与合并操作 |
| `bundle` / `lesson` | Agent 配置版本;项目经验 |
| `code_review` | 运行、需求版本、被审核的 commit 与基线、命中的路径、状态(pending / approved / rejected / invalidated)、决定人与意见 |
| `local_account` | 本机部署的个人账号:登录名、显示名、scrypt 密码哈希、密码版本(重置后旧会话失效);角色在 `memberships` |
| `local_account` | 本机部署的个人账号:登录名、显示名、scrypt 密码哈希、密码版本(重置后旧会话失效)、权限(`permissions`);角色由权限推出,存在 `memberships` |
| `notification` | 已发送的飞书通知(以通知键为 ID,避免重复发送) |
| `policy` | 租户级策略(如当前激活的 Agent 配置) |
@ -335,7 +335,7 @@ MCP 工具:`list_projects`、`submit_wish`、`get_run`、`get_run_events`、`a
| 身份 | 来源 | 能做什么 |
|---|---|---|
| human | Web 客户端签发的 OIDC token;本机部署中为控制台以本机凭据转发、并附上个人账号与密码版本的请求(`X-WishForge-Local-User`,只在开发令牌下生效,控制台代理从不转发浏览器自带的这个头) | 角色范围内的全部 `/v1` 操作,包括审批与配置 |
| human | Web 客户端签发的 OIDC token;本机部署中为控制台以本机凭据转发、并附上个人账号与密码版本的请求(`X-WishForge-Local-User`,只在开发令牌下生效,控制台代理从不转发浏览器自带的这个头) | 权限范围内的全部 `/v1` 操作(见下文「权限」),包括审批与配置 |
| connector | 其他 OIDC 客户端(MCP) | 提交与控制愿望、查询、请求发布;不能审批、不能管理凭据与环境 |
| executor | 运行级 JWT(`kind=worker`,绑定租户/运行/代次,4 小时) | 本运行的租约、心跳、事件、检查点、阶段推进(不能宣布成功) |
| verifier | 运行级 JWT(`kind=verifier`) | 本运行的验证、集成、构建证据与变更分类 |
@ -344,6 +344,10 @@ MCP 工具:`list_projects`、`submit_wish`、`get_run`、`get_run_events`、`a
| runner | 每个环境一个令牌(数据库只存哈希,可轮换) | 拉取本环境的签名任务、回报结果 |
| IDE 网关 | 每租户网关令牌 | 签发工作区启动码、查询授权(首次凭用户的 access token,之后按已授权的用户复核)、为有编辑会话的用户申请工作区的仓库写令牌 |
权限:每个人有四项权限(`packages/contracts/src/permissions.ts`):许愿范围 `wish`(`none`、`frontend` 只改前端、`review` 前后端但后端改动要审核、`full` 前后端直接合入)、`reviewCode` 审核代码、`releases` 请求/审批/回滚发布(含 GitHub 合并授权)、`manage` 管理(包含其余全部)。本机部署的个人账号把权限存在 `local_account` 上,创建和修改时按六种账户类型(`admin`、`fullstack`、`reviewed`、`frontend`、`releaser`、`viewer`)或自定义组合给出,角色由权限推出(`manage`→admin,能许愿→developer,能审批发布→deployer,否则 viewer),其余按角色的检查不变;认证时权限随 Actor 带上,修改立即生效。没有个人权限的人(本机管理员、OIDC 用户、早于权限的旧账号)按角色取默认权限:owner/admin 全部,developer 为 `review`(项目的 `codeReview.trustedMembers` 可在该项目把它提到 `full`),deployer 只有 `releases`,viewer 什么都没有。
控制面在以下位置强制执行,不依赖控制台隐藏按钮:提交愿望(`none` 拒绝;项目划出后端代码时,`frontend` 的愿望一律 `frontendOnly`,显式要求改后端则拒绝);补充需求(`frontend` 不能补充可以改后端的运行,也不能用 `allowBackend` 放开代码范围);撤销(`frontend` 只能撤销只改前端的运行);代码审核决定(`reviewCode`);发布请求、审批与回滚(`releases`);集成前是否跳过审核(见 4.3)。
信任边界:
- **执行器不可信**:Agent 生成的代码、仓库中的脚本和测试都可能是恶意的。执行器拿不到原始模型密钥(生产经模型代理)、拿不到其他运行的令牌,也不能推进到 `succeeded`。Agent 的文件工具限定在工作区内,可以写入工作区里的 `.git/config`、`.gitattributes`,而 Git 对每条命令都读取仓库本地配置、没有环境变量能禁用它;因此在生成检查点和修复轮合并前,平台先把工作区的 `.git/config` 收敛到安全白名单(只保留 `core` 基础项、`remote`、`branch`、`extensions`),丢弃会执行命令的 `filter`/`diff`/`merge` 驱动、`core.fsmonitor`/`sshCommand`、`[include]` 和 `url.*.insteadOf` 传输改写。驱动名由 Agent 任选,`-c` 覆盖不了,配置本身才是着力点。

View File

@ -15,7 +15,7 @@
## 合入
- 项目划出后端代码(`codeReview.paths`,glob;`exceptPaths` 为放行的前端与其他路径)时,验证通过后、合入前,改到后端代码(或运行从其他分支开始)而提交人不在 `trustedMembers` 里的运行进入 `code_review` 等待,由所有者或管理员批准后才合入;批准绑定被审核的 commit 与需求版本。声明只改前端(`frontendOnly`)的愿望改到后端代码时不运行检查,失败类型为 `scope`:修复轮开始前平台把这些文件恢复到运行开始时的内容,Agent 只改前端重做。改动路径不做重命名识别,挪动的文件在新旧两个位置都算改到。
- 项目划出后端代码(`codeReview.paths`,glob;`exceptPaths` 为放行的前端与其他路径)时,验证通过后、合入前,改到后端代码(或运行从其他分支开始)、而提交人或补充过需求的人不能直接合入(许愿范围不是 `full`)的运行进入 `code_review` 等待,由有「审核代码」权限的人批准后才合入;批准绑定被审核的 commit 与需求版本。声明只改前端(`frontendOnly`)的愿望改到后端代码时不运行检查,失败类型为 `scope`:修复轮开始前平台把这些文件恢复到运行开始时的内容,Agent 只改前端重做。改动路径不做重命名识别,挪动的文件在新旧两个位置都算改到。
- 撤销运行(`revertOf`)在目标分支最新代码上三方反向应用被撤销运行合入前后两个 commit 之间的改动,之后的提交保留;冲突时由执行器解决,之后照常验证与合入。
- verifier 在独立的裸仓库(远端的缓存)中准备候选 commit:目标分支没有移动时直接使用已验证的 commit;否则把它合并到目标分支的最新提交上,并对合并结果重新验证。
- 推送使用 `--force-with-lease` 并先做祖先检查;推送时目标分支又前进了,就基于新的提交重新准备候选,最多三次。

View File

@ -26,7 +26,7 @@
- **Agent 说了不算**:代码合不合格,由与 Agent 完全隔离的验证器在干净的目录里运行「受保护检查」来判定。Agent 不能跳过、修改或伪造这些检查。
- **全程有证据**:每次验证、合入、构建、部署都有记录,绑定精确的代码提交(commit)和镜像摘要(digest),随时可查。
- **会自己修**:检查没通过时,Agent 拿着失败的命令和输出继续修,最多修到你设定的轮数。
- **有人把关**:项目可以划出「后端代码」,每个愿望提交时选「只改前端」或「前端和后端」;只改前端的愿望碰不到后端,没有后端权限的人改到后端时,验证通过后先等人审核再合入;改动涉及迁移、鉴权、构建配方、依赖等敏感内容时,发布会停下来等人审批;环境也可以设置为每次发布都要人确认。
- **有人把关**:每个人的账户类型决定能许愿改什么。项目可以划出「后端代码」:只能改前端的人提的愿望碰不到后端,不能直接合入后端的人改到后端时,验证通过后先等人审核再合入;改动涉及迁移、鉴权、构建配方、依赖等敏感内容时,发布会停下来等人审批;环境也可以设置为每次发布都要人确认。
- **能撤回**:线上版本可以一键回滚;已经合入的改动可以一键撤销,撤销同样走验证和发布。
- **越用越好**:运行中积累的「项目经验」会自动带进同一项目后续的任务里。
@ -65,7 +65,7 @@
| **受保护检查** | 项目设置里的验证命令 | Agent 改不了;POC 是 TypeScript 检查、前端测试、前端构建、Go 测试 |
| **证据** | 验证、合入、构建、部署各步的结果记录 | 在运行详情的「验证证据」里看每条命令的退出码、耗时和输出 |
| **修复轮** | 检查失败后 Agent 的一次修复 | 次数受「最多修复轮次」限制 |
| **代码权限** | 谁可以直接改后端代码 | 项目设置里划出哪些路径算后端代码,并选出可以直接改后端的人;其他人的改动改到后端时,验证通过后停在「等待代码审核」,所有者或管理员批准才合入 |
| **代码权限** | 哪些代码算后端 | 项目设置里划出哪些路径算后端代码;每个人能不能改后端、改了要不要审核,看各自的账户类型(见 4.12) |
| **代码范围** | 这个愿望能不能改后端 | 提交愿望时选:「只改前端」的愿望改到后端代码时,平台把这些改动恢复原样,让 Agent 只改前端重做;「前端和后端」的愿望可以改后端,按提交人的代码权限决定要不要审核 |
| **合入** | 把验证通过的代码推到目标分支 | 目标分支被别人改过时,会先合并、**重新验证**再推 |
| **发布** | 把构建好的镜像部署到目标环境 | 风险高时等人审批;POC 环境平时自动发布 |
@ -76,7 +76,7 @@
| **项目经验** | 从过往运行中沉淀的经验条目 | 自动带进同一项目后续运行的提示词,可以停用、删除 |
| **Agent 配置** | 执行器用的提示词模板与模型,有版本 | 管理员可新建、激活、回滚;每个运行固定使用提交时的版本 |
| **代次** | 运行的一次执行尝试 | 每次「继续」都会产生新代次,旧代次的执行进程立即失效 |
| **成员与角色** | 每个人自己的账号 | 管理员在「成员」页创建;角色决定能做什么(见 14.1) |
| **账户类型** | 每个人账号的权限 | 管理员在「成员与权限」页创建账号时选:管理员、全栈开发、开发(后端需审核)、前端开发、发布负责人、只读访客(见 4.12) |
| **撤销运行** | 把某个运行合入的改动从目标分支上撤掉的新运行 | 在运行详情点「撤销这次改动」生成,照常验证和发布 |
### 2.1 阶段
@ -89,7 +89,7 @@
| 规划 | 执行器 | 准备工作区 | 几秒 |
| 实现 | 执行器 | Agent 写代码,产出检查点 | 小改动约 1 分钟 |
| 验证 | 验证器 | 在干净目录里安装依赖、跑受保护检查 | 约 2.5 分钟 |
| 合入 | 验证器 | 没有后端权限的人改到后端代码时先等代码审核;推送到目标分支(必要时先合并、再验证) | 约 20 秒;需要合并时再加约 2.5 分钟;审核等待的时间另计 |
| 合入 | 验证器 | 改到后端代码、而提出需求的人不能直接合入时先等代码审核;推送到目标分支(必要时先合并、再验证) | 约 20 秒;需要合并时再加约 2.5 分钟;审核等待的时间另计 |
| 构建 | 验证器 | 构建镜像(仅配置了交付的项目) | 只构建 api 约 3 分钟;三个组件全重建约 7 分钟 |
| 发布 | Runner | 部署到目标环境(可能先等审批) | 约 1.5 分钟 |
| 验收 | 控制面 | 部署检查通过,运行完成 | — |
@ -116,7 +116,7 @@
以下以本机 POC 为例。
1. **打开网页**:在这台 Mac 上打开 http://localhost:3000 ;同一局域网的其他电脑打开 `http://<这台 Mac 的局域网 IP>:3000`(这个地址须已被维护者放行,见 [12.4](#124-局域网访问与登录))。
2. **登录**:在登录页填自己的账号和密码(由管理员在「成员」页创建后交给你;维护者也可以用本机管理员账号),点「进入工作空间」。会话从登录起 1 小时后失效,期间操作不会延长。
2. **登录**:在登录页填自己的账号和密码(由管理员在「成员与权限」页创建后交给你;维护者也可以用本机管理员账号),点「进入工作空间」。会话从登录起 1 小时后失效,期间操作不会延长。
3. **提交愿望**:点「工作概览」或「运行记录」右上角的「+ 提交愿望」。项目空间选 POC 项目,在「你的愿望」里写要什么,在「验收标准」里每行写一条;拿不准怎么写时,点愿望下面的「AI 优化愿望」或验收标准下面的「AI 生成验收标准」,确认改写结果后再提交。执行器保持 Claude Code,点「提交愿望」。
4. **看进度**:页面会跳到运行详情。「阶段事件」标签页实时显示 Agent 的回复、改了哪些文件、验证结果和部署进度。
5. **看结果**:运行完成后,「交付结果」里有「访问应用 ↗」,「代码变更」里是这次改动的 diff,「验证证据」里是每条检查的结果。
@ -140,7 +140,7 @@
| 执行器 | `/providers` | 执行器状态与凭据 |
| Agent 配置 | `/agent` | 提示词与模型的版本 |
| 用量 | `/usage` | 配额、用量明细、导出 |
| 成员 | `/members` | 账号与角色(所有者、管理员可管理) |
| 成员与权限 | `/members` | 账号与账户类型(管理员可管理;其他人看自己的权限) |
- **右上角**:当前登录人的名字和「退出登录」(点了直接退出,没有确认);刷新图标「刷新数据」会重新读取当前页面。
- **自动刷新**:页面每隔几秒自动更新(运行列表约 5 秒),运行中的详情页通过实时推送更新,不需要手动刷新。
@ -169,7 +169,7 @@
**项目详情**页右上角有「⚙ 项目设置」和「+ 提交愿望」,页面包含四块:
- **代码仓库**:仓库地址、目标分支、仓库状态(可用 / 不可用 / 未创建)、代码权限(哪些算后端代码、几个人可以直接改后端)。平台仓库没建好时有「重试创建仓库」。
- **代码仓库**:仓库地址、目标分支、仓库状态(可用 / 不可用 / 未创建)、代码权限(哪些算后端代码,谁能改它见「成员与权限」)。项目设置按钮只有管理员看得到。平台仓库没建好时有「重试创建仓库」。
- **云 IDE**:开发环境与从 IDE 推上来的分支,见[第 11 章](#11-云-ide)。
- **项目运行**:这个项目的运行,「查看全部 →」跳到筛选好的运行记录。
- **项目经验**:自动沉淀和手动添加的经验。新运行的提示词会带上最近 5 条启用中的经验。
@ -188,7 +188,7 @@
| 依赖安装命令 | 同样每行一个 JSON 数组,例如 `["npm","ci"]`;在执行器开始前和每次验证前各运行一次,可以联网;留空时使用仓库里 `wishforge.yaml` 的 `dev.install`;安装失败不消耗修复轮数 |
| 代码权限 · 后端代码路径 | 每行一个,相对仓库根目录:目录以 `/` 结尾(如 `backend/`),`*` 匹配一层,`**` 匹配任意层(如 `**/*.go`)。写 `**` 表示除了下一栏放行的路径,其余都算后端。留空表示不区分前后端 |
| 代码权限 · 前端与其他放行的路径 | 同样每行一个;同时命中两边时算放行,例如 `src/`、`tests/frontend/`、`**/*.md` |
| 代码权限 · 可以直接改后端代码的人 | 勾选项目里可以直接改后端的人:他们提交的愿望改到后端代码也直接合入;其他人的改到后端时,验证通过后先停在「等待代码审核」。也可以在「成员」页按人设置(见 4.12)。划出后端代码后,提交愿望时会出现「代码范围」(见 4.4) |
| 代码权限 · 谁能改什么 | 列出项目里每个人的账户类型和许愿范围,在「成员与权限」页修改(见 4.12)。划出后端代码后,提交愿望时会出现「代码范围」(见 4.4)。用组织身份登录、没有本地账号的部署里,这里是「可以直接改后端代码的人」勾选框 |
| 愿望优化规则 | AI 优化愿望和验收标准时额外遵守的规则,最多 4000 字,例如「验收标准必须包含新增的单元测试」 |
| 配置容器构建与发布目标 | 勾选后填写交付配置:镜像仓库、目标环境、架构(Linux / AMD64 或 ARM64)、容器端口(默认 3000)、Dockerfile 路径、健康检查路径(默认 `/health`)、构建源码目录、冒烟检查(JSON 数组,如 `[{"path":"/","expectedStatus":200}]`)。**交付一旦配置就不能再关掉** |
@ -204,7 +204,7 @@
|---|---|
| 项目空间 | 选择项目 |
| 你的愿望 | 必填,8~20000 字。第一行写目标,可以再写「范围:」「不改:」各一行;细节写进验收标准,不需要预先拆分技术步骤 |
| 代码范围 | 项目划出了后端代码时才显示,默认「只改前端」。**只改前端**:只能改项目放行的路径(POC 是 `src/`、`tests/frontend/`、`**/*.md`),Agent 一开始就被告知,做不到时会停下来提问(之后可以在运行详情放开,见 4.5);改到后端代码时不运行检查,平台在下一轮开始前把这些文件恢复原样(新建的删掉),让 Agent 只改前端重做,算一轮修复。**前端和后端**:可以改后端;你有这个项目的后端权限时验证通过就合入,没有时先等代码审核。选项下面会写明你有没有后端权限 |
| 代码范围 | 项目划出了后端代码时才显示,默认「只改前端」。**只改前端**:只能改项目放行的路径(POC 是 `src/`、`tests/frontend/`、`**/*.md`),Agent 一开始就被告知,做不到时会停下来提问(之后可以在运行详情放开,见 4.5);改到后端代码时不运行检查,平台在下一轮开始前把这些文件恢复原样(新建的删掉),让 Agent 只改前端重做,算一轮修复。**前端和后端**:可以改后端;你的账户能直接合入时验证通过就合入,否则先等代码审核,选项下面会写明。账户类型是「前端开发」时只有「只改前端」,没得选 |
| 起点 | 默认是目标分支的最新代码;平台托管仓库的项目可以选从 IDE 推送的分支,验证通过后一并合入。POC 只能从 `poc` 开始 |
| 验收标准 | 必填,每行一条,最多 30 条 |
| 执行器 | 只列出这台部署能用的执行器;POC 只有 Claude Code |
@ -239,9 +239,9 @@
- 「取消运行」会弹出确认框「取消本次运行」,选「确认取消」才执行,选「保留运行」放弃。
- 预算已经用完时,「继续」是灰的,需要先调整预算。
4. **等待说明**(仅等待处理时):原因的中文标题、后端给出的具体说明(多为英文)、该怎么做,有时附带链接(如「管理执行器」「去审批」)。下面可以展开「**补充或修改需求**」,写补充说明或回答问题后点「发送补充」:这会产生新的需求版本,运行从规划阶段重新开始。这个表单只在等待处理时出现,只能写文字说明,不能在这里改验收标准。只改前端的愿望停在「执行器需要你的补充」、或者因为一直改到后端而用完了修复轮时,这里还有「**改为前端和后端并继续**」:确认后这个愿望可以改后端代码,运行带着这个决定从规划阶段重新开始(需求版本加一),确认框里可以顺便回答 Agent 的其他问题;时间线记一条「代码范围改为前端和后端」。改到后端时要不要审核,仍按提交人的后端权限决定。所有者、管理员和开发者可以操作。
5. **代码审核**(仅等待代码审核时):列出改到的后端代码和提交人,「代码变更」链接跳到完整改动。所有者或管理员勾选「我已查看「代码变更」里的全部改动」后可以「批准合入」;或写下审核意见后「驳回并说明」。批准后运行自动继续合入,不再重复检查;驳回后意见作为补充需求交给执行器再改一轮,改完会再次等待审核。其他角色只能看到「等待所有者或管理员审核」。
6. **运行预算**(仅 Owner/Admin,且运行处于等待处理或已暂停时):显示已用 Token 和已执行时间,展开「调整预算」可以改 Token 上限(最多 200 万)、时间上限(最多 180 分钟)、修复轮次上限(最多 3),点「保存预算」。保存不会自动继续,还要再点「继续」。
4. **等待说明**(仅等待处理时):原因的中文标题、后端给出的具体说明(多为英文)、该怎么做,有时附带链接(如「管理执行器」「去审批」)。下面可以展开「**补充或修改需求**」,写补充说明或回答问题后点「发送补充」:这会产生新的需求版本,运行从规划阶段重新开始。这个表单只在等待处理时出现,只能写文字说明,不能在这里改验收标准。只改前端的愿望停在「执行器需要你的补充」、或者因为一直改到后端而用完了修复轮时,这里还有「**改为前端和后端并继续**」:确认后这个愿望可以改后端代码,运行带着这个决定从规划阶段重新开始(需求版本加一),确认框里可以顺便回答 Agent 的其他问题;时间线记一条「代码范围改为前端和后端」。之后改到后端时,只有提交人和所有补充过需求的人都能直接合入才不用审核。只有能许愿改后端的人看得到这个按钮;只能改前端的人看到的是「请可以许愿改后端的人放开」。同样,只能改前端的人不能给可以改后端的运行补充需求,补充表单会换成一句说明。
5. **代码审核**(仅等待代码审核时):列出改到的后端代码和提交人,「代码变更」链接跳到完整改动。有「审核代码」权限的人勾选「我已查看「代码变更」里的全部改动」后可以「批准合入」;或写下审核意见后「驳回并说明」。批准后运行自动继续合入,不再重复检查;驳回后意见作为补充需求交给执行器再改一轮,改完会再次等待审核。不能批准自己提的改动,除非自己本来就能直接合入。没有这项权限的人只能看到「等待有「审核代码」权限的人审核」。
6. **运行预算**(仅管理员,且运行处于等待处理或已暂停时):显示已用 Token 和已执行时间,展开「调整预算」可以改 Token 上限(最多 200 万)、时间上限(最多 180 分钟)、修复轮次上限(最多 3),点「保存预算」。保存不会自动继续,还要再点「继续」。
7. **交付结果**:部署验收通过后显示「访问应用 ↗」;未配置交付的项目显示合入的提交。
8. **四个标签页**:
@ -312,21 +312,45 @@
### 4.11 界面上值得注意的几点
- **没有二次确认的操作**:暂停、继续、审批对话框里的「拒绝」、激活和回滚 Agent 配置、停用和删除项目经验、创建开发环境、重试创建仓库、修改成员角色、停用或启用成员、退出登录。点之前想清楚。
- **没有二次确认的操作**:暂停、继续、审批对话框里的「拒绝」、激活和回滚 Agent 配置、停用和删除项目经验、创建开发环境、重试创建仓库、修改成员的账户类型和权限(编辑后点「保存」)、停用或启用成员、退出登录。点之前想清楚。
- **有确认的操作**:取消运行、回滚发布、撤销这次改动、批准代码审核(须先勾选)、批准发布(须先勾选)、重置成员密码、暂停工作区、撤销凭据、解锁环境、注册 Runner。
- **英文内容**:等待说明的具体内容、时间线说明、发布失败原因、表单里的错误信息来自后端,多为英文。
- 等待说明里的「打开项目设置」只会打开项目页,还要再点「⚙ 项目设置」。
### 4.12 成员
### 4.12 成员与权限
每个人用自己的账号登录,系统才知道愿望是谁提的、改动由谁审核、发布由谁批准。所有者和管理员可以在「成员」页:
每个人用自己的账号登录,系统才知道愿望是谁提的、改动由谁审核、发布由谁批准。每个账号有一个**账户类型**,决定这个人能做什么:
- 「+ 添加成员」:填登录名(2~32 位小写字母、数字、点、横线或下划线)、显示名、角色、代码权限,勾选可以进入的项目(默认全部)。创建后弹出初始密码,**只显示这一次**,复制后通过可信的渠道交给对方。
- 改角色、改代码权限:直接在列表里选。代码权限有「仅前端(改后端要审核)」和「前端和后端」两种,作用于这个人能进入的所有项目;哪些路径算后端代码在项目设置里定义(见 4.3)。各项目分别设置时,列表显示「部分项目可改后端」。
| 账户类型 | 适合谁 | 许愿 | 审核代码 | 审批发布 | 管理 |
|---|---|---|---|---|---|
| 管理员 | 负责整个工作空间 | 前端和后端,直接合入 | ✓ | ✓ | ✓ |
| 全栈开发 | 可信的开发者 | 前端和后端,直接合入 | — | — | — |
| 开发(后端需审核) | 新同事或外部协作者 | 前端和后端,后端改动要审核 | — | — | — |
| 前端开发 | 只做页面和样式的人 | 只改前端 | — | — | — |
| 发布负责人 | 负责上线的人 | 不能许愿 | — | ✓ | — |
| 只读访客 | 只看进度的人 | 不能许愿 | — | — | — |
四项权限的含义:
- **许愿**:能不能提愿望,愿望能不能改后端。哪些代码算后端,在各项目的「项目设置 · 代码权限」里定义;项目没有定义时,所有代码都算前端。
- **只改前端**:提的愿望一律「只改前端」,提交表单里没有「前端和后端」可选;Agent 改到后端时,平台恢复原样让它只改前端重做。也不能给可以改后端的运行补充需求、放开它的代码范围,或撤销它。
- **前端和后端,后端改动要审核**:可以选「前端和后端」;改到后端的改动验证通过后,等有「审核代码」权限的人批准才合入。
- **前端和后端,直接合入**:改到后端的改动验证通过就合入。但只要有不能直接合入的人给这个运行补充过需求(或放开过代码范围),改到后端时仍要审核(见 6.3)。
- **审核代码**:在运行详情的「代码审核」里批准或驳回改到后端的改动。不能批准自己提的改动,除非自己本来就能直接合入。
- **审批发布**:在「部署与审批」页批准、拒绝和回滚发布。
- **管理**:成员与权限、项目设置、环境与 Runner、执行器、Agent 配置、预算、项目经验、用量导出;包含以上全部权限。
管理员在「成员与权限」页:
- 「+ 添加成员」:填登录名(2~32 位小写字母、数字、点、横线或下划线)、显示名,选账户类型;需要时在「具体权限」里单独调整某项(调整后显示为「自定义」,例如「前端开发」加上「审批发布」),再勾选可以进入的项目(默认全部)。创建后弹出初始密码,**只显示这一次**,复制后通过可信的渠道交给对方。
- 「编辑」:改显示名、账户类型或具体权限、可以进入的项目。保存后对方的下一个操作就按新权限执行,不用重新登录。
- 「重置密码」:生成新密码(同样只显示一次),对方已登录的会话立即失效。
- 「停用」/「启用」:停用后对方立即无法再操作。不能停用自己或改自己的角色。
- 「停用」/「启用」:停用后对方立即无法再操作。
- 不能修改自己的权限和项目,也不能停用自己,要请另一位管理员操作。
本机管理员(凭据文件里的账号)是所有者,不在列表里;它的代码权限在项目设置里勾选。角色说明见 14.1。
列表第一行是本机管理员(凭据文件里的账号):账户类型是管理员,拥有全部权限,不能在这里修改。不是管理员的人打开这一页,看到的是自己的账户类型和权限。
界面会按权限隐藏做不了的操作:例如不能许愿的人看不到「+ 提交愿望」;没有「审批发布」权限的人能打开「审阅发布」看内容,但没有批准和拒绝按钮。
---
@ -340,7 +364,7 @@
- **写具体的结果**,不写模糊的方向。✗「优化一下下载功能」;✓「下载文件名要包含数据集类型,例如 `xxx-episode.zip`」。
- **点明位置**:知道在哪个文件、哪个函数时直接写上,Agent 会少走弯路。
- **写清边界**:「只加测试,不修改 `src/` 下的代码」「不要改接口返回格式」这类限制非常有用。
- **选对代码范围**:只动页面、样式、前端测试和文档的愿望选「只改前端」,平台会保证它碰不到后端;需要改接口、数据库、服务端逻辑时选「前端和后端」。拿不准时先选只改前端:Agent 发现必须改后端时会停下来提问,你确认需要的话在运行详情点「改为前端和后端并继续」。
- **选对代码范围**:只动页面、样式、前端测试和文档的愿望选「只改前端」,平台会保证它碰不到后端;需要改接口、数据库、服务端逻辑时选「前端和后端」(账户类型是「前端开发」时只能只改前端)。拿不准时先选只改前端:Agent 发现必须改后端时会停下来提问,你确认需要的话在运行详情点「改为前端和后端并继续」。
- **一个愿望只做一件事**:大需求拆成几个小愿望,每个都能独立验证、独立上线,出问题也容易定位。
### 5.2 验收标准:写成能检查的句子
@ -361,7 +385,7 @@
| 最长运行(分钟) | 运行的最长执行时间,包含验证、构建和修复 | 默认 30 分钟。POC 上一次完整运行约 9 分钟,可能需要修复或全量重建时给 60~90 分钟 |
| 最多修复轮次 | 检查失败后最多自动修几次 | 默认 3(也是上限) |
预算用完运行会停在「预算已用完」,**已完成的工作不会丢**;Owner/Admin 调整预算后点「继续」。
预算用完运行会停在「预算已用完」,**已完成的工作不会丢**;管理员调整预算后点「继续」。
### 5.4 示例
@ -424,7 +448,7 @@ POC 打开了 Seatbelt 沙箱,受保护检查在 macOS 沙箱里运行:读
### 6.3 合入
项目划出了后端代码、这次改动改到了它、而提交人没有直接改后端的权限时,验证通过后先停在「**等待代码审核**」(提交人有权限时直接合入,时间线记一条「有后端权限,免审核」):所有者或管理员在运行详情查看改动后批准,运行才继续合入(不再重复检查);驳回时审核意见作为补充需求交给 Agent 再改一轮。继续运行绕不过审核。
项目划出了后端代码、这次改动改到了它时,先看提出需求的人:提交人和所有补充过需求(或放开过代码范围)的人都能「直接合入」,就直接合入,时间线记一条「可以直接合入,免审核」;只要有一个人不能,验证通过后先停在「**等待代码审核**」:有「审核代码」权限的人在运行详情查看改动后批准,运行才继续合入(不再重复检查);驳回时审核意见作为补充需求交给 Agent 再改一轮。继续运行绕不过审核。能不能直接合入按现在的账户类型算:审核前调低了谁的权限,就按调低后的算。
| 情况 | WishForge 怎么做 |
|---|---|
@ -459,7 +483,7 @@ POC 打开了 Seatbelt 沙箱,受保护检查在 macOS 沙箱里运行:读
| **继续** | 已暂停,或大多数等待处理 | 重新开始执行(产生新代次),从最近的检查点接着做。对于「修复轮数已用完」「与目标分支的最新代码冲突」,继续表示授权再修一轮 |
| **取消运行** | 未结束的运行 | 结束运行,不可恢复。**已经合入目标分支的代码不会被撤回** |
| **补充需求** | 等待处理时 | 追加说明或回答问题,需求版本加一,运行从规划阶段重新开始;旧版本的验证结果和审批全部作废,修复轮次重新计算 |
| **调整预算** | 等待处理或已暂停时,仅 Owner/Admin | 修改 Token、时间、修复轮次上限,已用量保留;保存后仍需点「继续」 |
| **调整预算** | 等待处理或已暂停时,仅管理员 | 修改 Token、时间、修复轮次上限,已用量保留;保存后仍需点「继续」 |
---
@ -473,7 +497,7 @@ POC 打开了 Seatbelt 沙箱,受保护检查在 macOS 沙箱里运行:读
| 项目仓库未就绪 | 仓库不可用、起点分支不存在,或 POC 的 `poc` 分支被强推后已不包含这次合入的提交 | 在项目页重试仓库创建或推送起点分支,然后点「继续」;说明里出现 `POC_SOURCE_REWRITTEN` 时取消运行,需要的话重新提交愿望 |
| 执行环境未就绪 | 没能启动执行进程 | 系统会自动重试;维护者恢复服务后也可以点「继续」 |
| 没有可用的执行进程 | 执行进程没有按时接手 | 点「继续」,系统以新代次重新派发 |
| 预算已用完 | token 或时长用完 | Owner/Admin 在「运行预算」里调整后点「继续」 |
| 预算已用完 | token 或时长用完 | 管理员在「运行预算」里调整后点「继续」 |
| 执行器需要你的补充 | Agent 动手前提了问题 | 展开「补充或修改需求」回答,运行从规划阶段继续(这时没有「继续」按钮)。只改前端的愿望问能不能改后端时,点「改为前端和后端并继续」 |
| 缺少验证配置 | 项目没配受保护检查 | 在项目设置里配置验证命令后点「继续」 |
| 修复轮数已用完,验证仍未通过 | 修了几轮还是没过;或者只改前端的愿望几轮下来还是要改后端(说明里列出后端文件) | 看「验证证据」里的失败输出;点「继续」再修一轮,或补充需求,或取消。确实需要改后端时点「改为前端和后端并继续」 |
@ -482,7 +506,7 @@ POC 打开了 Seatbelt 沙箱,受保护检查在 macOS 沙箱里运行:读
| 需要人工确认 | 某个外部操作结果未知 | 查看「阶段事件」确认实际情况,再「继续」或取消 |
| 与目标分支的最新代码冲突 | 合入冲突,且修复轮已用完 | 点「继续」,Agent 基于最新代码再修一轮;或取消 |
| 目标分支自身未通过检查 | 别人推到目标分支的提交让检查失败了,不是本次改动造成的 | 修好目标分支后点「继续」,运行合并到最新代码并重新检查;或取消 |
| 等待代码审核 | 改动已通过检查,但改到了后端代码,而提交人没有直接改后端的权限 | 所有者或管理员在运行详情的「代码审核」里批准或驳回(这时没有「继续」按钮) |
| 等待代码审核 | 改动已通过检查,但改到了后端代码,而提交人或补充过需求的人不能直接合入 | 有「审核代码」权限的人在运行详情的「代码审核」里批准或驳回(这时没有「继续」按钮) |
| 等待 GitHub 合并 | (GitHub 项目)等 PR 审核合并 | 在 GitHub 上审核合并后点「继续」 |
| GitHub 应用未配置 | (GitHub 项目)缺少 GitHub App 授权 | 请运维安装授权后点「继续」 |
| 发布等待审批 | 发布需要人工审批 | 有权限的人到「部署与审批」页审阅(这时没有「继续」按钮) |
@ -517,7 +541,7 @@ POC 环境默认没有勾选「每次发布都需人工确认」,所以只改
### 8.2 怎么审批
所有者、管理员和部署者可以审批。配置了飞书通知时,待审批的发布会推送到飞书群并 @ 决策人,点消息里的「去审批」直达这一页。
有「审批发布」权限的人(管理员、发布负责人,或单独给了这项权限的人)可以审批;其他人能打开「审阅发布」看内容,但没有批准和拒绝按钮。配置了飞书通知时,待审批的发布会推送到飞书群并 @ 决策人,点消息里的「去审批」直达这一页。
1. 打开「部署与审批」,找到状态为「待审批」的发布,点「🛡 审阅发布」。
2. 核对目标环境、需求与验收标准、独立验证结果、提交与镜像、审批原因。
@ -533,8 +557,8 @@ POC 环境默认没有勾选「每次发布都需人工确认」,所以只改
### 8.3 回滚与撤销
- **自动回滚**:部署后的验收检查不通过时,如果这次发布允许自动回滚(不含迁移等不可逆改动,组件来源都已知),会自动切回上一个版本。
- **回滚线上版本**:在「部署与审批」页,环境当前线上的发布有「回滚」按钮(所有者、管理员、部署者可用),确认后由 Runner 把环境换回这次发布之前的版本并检查。只能退回紧挨着的上一个版本,而且要求两次发布的配置兼容;不满足时会提示原因。**回滚只换线上运行的版本,目标分支上的代码不变**:下一次发布会把这些代码重新部署上去。
- **撤销这次改动**:运行详情页上,已经合入过代码的运行有「撤销这次改动」(所有者、管理员、开发者可用)。确认后生成一个新的「撤销运行」:先由 Git 在目标分支最新代码上把这次合入的改动反向应用,**之后别人提交的改动保留**;只有和之后的提交改到同一处时,才交给执行器处理冲突。然后照常验证、审核、合入、构建和发布。线上出问题时,通常先「回滚」止损,再「撤销这次改动」把代码也退掉。
- **回滚线上版本**:在「部署与审批」页,环境当前线上的发布有「回滚」按钮(有「审批发布」权限的人才看得到),确认后由 Runner 把环境换回这次发布之前的版本并检查。只能退回紧挨着的上一个版本,而且要求两次发布的配置兼容;不满足时会提示原因。**回滚只换线上运行的版本,目标分支上的代码不变**:下一次发布会把这些代码重新部署上去。
- **撤销这次改动**:运行详情页上,已经合入过代码的运行有「撤销这次改动」(能许愿的人可用;只能改前端的人只能撤销「只改前端」的运行)。确认后生成一个新的「撤销运行」:先由 Git 在目标分支最新代码上把这次合入的改动反向应用,**之后别人提交的改动保留**;只有和之后的提交改到同一处时,才交给执行器处理冲突。然后照常验证、审核、合入、构建和发布。线上出问题时,通常先「回滚」止损,再「撤销这次改动」把代码也退掉。
---
@ -542,7 +566,7 @@ POC 环境默认没有勾选「每次发布都需人工确认」,所以只改
### 9.1 本机 POC 的现状
- **每人一个账号**:管理员在「成员」页为每个人创建账号并分配角色,系统会记下愿望是谁提的、代码由谁审核、发布由谁批准。角色决定能做什么(见 14.1);同一角色的人仍然可以操作彼此的运行,团队内部要约定好,不要动别人的运行。
- **每人一个账号**:管理员在「成员与权限」页为每个人创建账号并选好账户类型,系统会记下愿望是谁提的、代码由谁审核、发布由谁批准。账户类型决定能做什么(见 4.12);能许愿的人仍然可以暂停、继续或取消彼此的运行,团队内部要约定好,不要动别人的运行。
- **一次只执行一个运行**:POC 只有 1 个执行名额。后提交的愿望显示「排队中」;前一个运行完成,或停下来等审批、等部署时,下一个会在几秒内开始。
- **愿望只能从 `poc` 分支开始**。
- **飞书通知**:维护者配置好飞书机器人后,待审批的发布、待审核的代码、需要人处理的运行、上线结果都会推送到飞书群(见 12.9)。
@ -683,7 +707,7 @@ node scripts/build-local-web.mjs
### 12.4 局域网访问与登录
- 本机管理员的登录凭据保存在 `.wishforge/local-access.json`(权限 0600),含账号、密码和会话签名材料。**不要上传、贴到聊天或日志里**。其他人用管理员在「成员」页创建的个人账号登录(见 4.12),不要把本机管理员的密码分给大家。
- 本机管理员的登录凭据保存在 `.wishforge/local-access.json`(权限 0600),含账号、密码和会话签名材料。**不要上传、贴到聊天或日志里**。其他人用管理员在「成员与权限」页创建的个人账号登录(见 4.12),不要把本机管理员的密码分给大家。
- 本机 IP 变化后,新地址需要放行才能访问,否则返回 403「请求来源不被允许」。查看和应用新地址:
```bash
@ -700,7 +724,7 @@ npm run local:network -- --address <新的局域网 IP> --apply
应用后 `stop` 再 `start`,并从另一台设备实际登录验证。
- **有人离开团队**:在「成员」页停用他的账号即可。**更换本机管理员密码**:删除 `.wishforge/local-access.json`,运行 `node scripts/setup-local-access.mjs` 重新生成;所有人的登录会话(包括成员账号)都会失效,需要重新登录。
- **有人离开团队**:在「成员与权限」页停用这个人的账号即可。**更换本机管理员密码**:删除 `.wishforge/local-access.json`,运行 `node scripts/setup-local-access.mjs` 重新生成;所有人的登录会话(包括成员账号)都会失效,需要重新登录。
- 局域网 HTTP 会明文传输登录信息,只在可信网络中使用;需要公网访问时使用经批准的 HTTPS 入口。
- 15 分钟内密码输错超过 8 次后,校验会限速(每 2 秒最多一次),不会把人锁在外面。
@ -740,7 +764,7 @@ node --import tsx scripts/configure-local-poc-plan.ts 20000000
- **`host` 模式没有完整隔离**:Agent 写的代码和项目测试在这台 Mac 上运行,只用于可信的项目和模型。
- **镜像构建凭据**:集群里的镜像构建能读到推送镜像仓库的凭据,而 Dockerfile 可以被 Agent 修改,构建又发生在审批之前。建议运维把这份凭据收窄到只能推送这几个镜像仓库,并限制构建 Pod 的出网。
- **账号与角色**:本机管理员拥有全部权限,不要把它的密码分给大家;其他人用自己的账号,按需给最小的角色。开发模式下请求人可以批准自己的发布和审核自己的改动,要求「别人来批」需靠团队约定。
- **账号与权限**:本机管理员拥有全部权限,不要把它的密码分给大家;其他人用自己的账号,按需给最小的账户类型(例如只做页面的人给「前端开发」)。开发模式下请求人可以批准自己的发布和审核自己的改动,要求「别人来批」需靠团队约定。
### 12.9 飞书通知
@ -835,18 +859,19 @@ POC 一次只执行一个运行,前面的运行还在执行时新愿望会排
## 14. 附录
### 14.1 角色与权限
### 14.1 账户类型与权限
| 角色 | 能做什么 |
账户类型和四项权限见 4.12。各项权限包含的操作:
| 权限 | 包含的操作 |
|---|---|
| 所有者(Owner)/ 管理员(Admin) | 全部操作:成员管理(含代码权限)、项目设置(含代码权限)、代码审核、调整预算、项目经验、执行器凭据、环境与 Runner(含「每次发布都需人工确认」)、Agent 配置、用量明细与导出、审批与回滚发布 |
| 开发者(Developer) | 创建项目、提交愿望、AI 优化、继续/暂停/取消、补充需求、撤销改动、使用云 IDE |
| 部署者(Deployer) | 审批发布、回滚发布 |
| 只读(Viewer) | 只读 |
| 查看(所有人) | 查看自己能进入的项目、运行、代码变更、证据和发布 |
| 许愿 | 提交愿望、AI 优化、继续/暂停/取消运行、补充需求、撤销改动、创建项目、使用云 IDE;能不能改后端见 4.12 |
| 审核代码 | 批准或驳回代码审核 |
| 审批发布 | 批准、拒绝、回滚发布(含 GitHub 合并授权) |
| 管理 | 成员与权限、项目设置(含代码权限)、调整预算、项目经验、执行器凭据、环境与 Runner(含「每次发布都需人工确认」)、Agent 配置、用量明细与导出;包含以上全部 |
界面上大多数按钮对所有人可见,没有权限的操作在点击后由后端拒绝。本机管理员账号是所有者。
角色之外还有**代码权限**(「仅前端」或「前端和后端」),只决定改到后端代码的改动要不要先审核,和角色无关:开发者也可以有后端权限,管理员也可以只有前端权限(他审核别人的改动不受影响)。每个愿望的**代码范围**(「只改前端」或「前端和后端」)由提交人选择,决定这个愿望能不能碰后端:只改前端的愿望不论谁提交都碰不到后端。
本机管理员是管理员。用组织身份(OIDC)登录的部署没有「成员与权限」页,按角色决定:管理员(含所有者)拥有全部权限;开发者能许愿,改到后端要审核,除非项目设置把这个人列为「可以直接改后端代码的人」;部署者审批和回滚发布;只读只能查看。
### 14.2 相关文档

View File

@ -8,6 +8,7 @@
"./providers": "./src/providers.ts",
"./release-risk": "./src/release-risk.ts",
"./path-rules": "./src/path-rules.ts",
"./permissions": "./src/permissions.ts",
"./wish": "./src/wish.ts"
},
"scripts": {

View File

@ -5,6 +5,7 @@ import type { DeliveryConfig, IntegrationLease, ResourceAllocation } from './ent
import { z } from 'zod';
import { providerEventTypes, providers, type ProviderId } from './providers.js';
import { CODE_REVIEW_PATTERN_LIMIT, invalidGlob, type CodeReviewPolicy } from './path-rules.js';
import { accountTypeNames, wishScopes, type AccountType, type Permissions } from './permissions.js';
export const API_VERSION = 1;
export const roles = ['owner', 'admin', 'developer', 'deployer', 'viewer'] as const;
@ -79,6 +80,8 @@ export interface Actor {
/** From the person's sign-in token, when it carries them; never from a stored profile. */
displayName?: string;
email?: string;
/** The person's own permissions, from their account; without them, the role decides. */
permissions?: Permissions;
}
export interface VerificationProfile {
id: string;
@ -147,8 +150,10 @@ export interface LocalAccountView {
createdBy: string;
/** Projects the person may work in. */
projectIds: string[];
/** Of those, the projects where the person may change backend code without a review. */
backendProjectIds: string[];
/** What the person may do in those projects; the role follows from them. */
permissions: Permissions;
/** The account type with exactly these permissions; absent for a combination of their own. */
type?: AccountType;
}
export interface Budget {
maxTokens: number;
@ -203,6 +208,11 @@ export interface Run extends Entity {
pendingStartId?: string;
/** The user who submitted the wish. */
requestedBy?: string;
/**
* Others who added to the requirement since: answers, a widened code scope, a reviewer's request
* for changes. A backend change merges without a review only if everyone here and the submitter may.
*/
contributors?: string[];
lease?: Lease;
leaseOwnerId?: string;
leaseOwnerKind?: Actor['kind'];
@ -501,8 +511,20 @@ export const wishRefinementInput = z
})
.strict();
export const wishRulesInput = z.string().trim().max(4000);
/** Roles a local account can hold; the owner is the deployment's operator. */
export const localAccountRoles = ['admin', 'developer', 'deployer', 'viewer'] as const;
export const permissionsInput = z
.object({
wish: z.enum(wishScopes),
reviewCode: z.boolean(),
releases: z.boolean(),
manage: z.boolean(),
})
.strict();
/** An account type, or permissions of the person's own: one of the two. */
const accountGrant = {
type: z.enum(accountTypeNames).optional(),
permissions: permissionsInput.optional(),
};
const oneGrant = (value: { type?: unknown; permissions?: unknown }) => !(value.type && value.permissions);
export const localAccountInput = z
.object({
username: z
@ -510,23 +532,24 @@ export const localAccountInput = z
.trim()
.regex(/^[a-z0-9][a-z0-9_.-]{1,31}$/, 'Use 2–32 lowercase letters, digits, dots, dashes or underscores'),
displayName: text.max(60),
role: z.enum(localAccountRoles),
...accountGrant,
/** Projects the person may work in; all projects when omitted. */
projectIds: z.array(text.max(200)).max(200).optional(),
/** Whether the person may change backend code in those projects without a review. */
backend: z.boolean().default(false),
})
.strict();
.strict()
.refine(value => Boolean(value.type || value.permissions), 'Choose an account type or give the permissions')
.refine(oneGrant, 'Choose an account type or give the permissions, not both');
export const localAccountPatch = z
.object({
displayName: text.max(60).optional(),
role: z.enum(localAccountRoles).optional(),
active: z.boolean().optional(),
/** Backend permission in every project the person works in. */
backend: z.boolean().optional(),
...accountGrant,
/** The projects the person may work in from now on. */
projectIds: z.array(text.max(200)).max(200).optional(),
})
.strict()
.refine(value => Object.values(value).some(field => field !== undefined), 'Change at least one field');
.refine(value => Object.values(value).some(field => field !== undefined), 'Change at least one field')
.refine(oneGrant, 'Choose an account type or give the permissions, not both');
export const localLoginInput = z.object({ username: z.string().max(64), password: z.string().max(256) }).strict();
export const releaseInput = z
.object({
@ -738,4 +761,5 @@ export * from './redaction.js';
export * from './change-paths.js';
export * from './release-risk.js';
export * from './path-rules.js';
export * from './permissions.js';
export * from './wish.js';

View File

@ -0,0 +1,88 @@
// Imports nothing: the console bundles this module directly (see tests/console-bundle.test.ts).
/**
* What a person may wish for. Backend code is what a project's code permission rules name
* (`codeReview.paths` minus `exceptPaths`); in a project without such rules every change is
* frontend code.
* - `none`: no wishes;
* - `frontend`: only wishes that leave backend code alone;
* - `review`: backend code too, merged once someone who reviews code approves the change;
* - `full`: backend code too, merged as soon as the change passes the checks.
*/
export const wishScopes = ['none', 'frontend', 'review', 'full'] as const;
export type WishScope = (typeof wishScopes)[number];
/** What a person may do, besides seeing the projects they belong to. */
export interface Permissions {
wish: WishScope;
/** Approve or reject a backend change someone else asked for, before it merges. */
reviewCode: boolean;
/** Request, approve, reject and roll back releases. */
releases: boolean;
/** Members and their permissions, project settings, environments, executors and budgets; includes everything else. */
manage: boolean;
}
/** Ready-made sets of permissions, named for what people do. */
export const accountTypes = {
admin: { wish: 'full', reviewCode: true, releases: true, manage: true },
fullstack: { wish: 'full', reviewCode: false, releases: false, manage: false },
reviewed: { wish: 'review', reviewCode: false, releases: false, manage: false },
frontend: { wish: 'frontend', reviewCode: false, releases: false, manage: false },
releaser: { wish: 'none', reviewCode: false, releases: true, manage: false },
viewer: { wish: 'none', reviewCode: false, releases: false, manage: false },
} as const satisfies Record<string, Permissions>;
export const accountTypeNames = ['admin', 'fullstack', 'reviewed', 'frontend', 'releaser', 'viewer'] as const;
export type AccountType = (typeof accountTypeNames)[number];
/** Managing includes every other permission; nothing but the four permissions is kept. */
export function normalizePermissions(permissions: Permissions): Permissions {
const { wish, reviewCode, releases, manage }: Permissions = permissions.manage ? accountTypes.admin : permissions;
return { wish, reviewCode, releases, manage };
}
/** The account type with exactly these permissions; undefined for a combination of one's own. */
export function accountTypeOf(permissions: Permissions): AccountType | undefined {
const own = normalizePermissions(permissions);
return accountTypeNames.find(name => {
const type: Permissions = accountTypes[name];
return (
type.wish === own.wish &&
type.reviewCode === own.reviewCode &&
type.releases === own.releases &&
type.manage === own.manage
);
});
}
type RoleName = 'owner' | 'admin' | 'developer' | 'deployer' | 'viewer';
/** The role behind a set of permissions; the role decides everything the permissions do not name. */
export function roleFor(permissions: Permissions): Exclude<RoleName, 'owner'> {
const own = normalizePermissions(permissions);
if (own.manage) return 'admin';
if (own.wish !== 'none') return 'developer';
if (own.releases) return 'deployer';
return 'viewer';
}
/** What a role allows by itself, for people without permissions of their own. */
export function rolePermissions(role: RoleName): Permissions {
const type: Record<RoleName, AccountType> = {
owner: 'admin',
admin: 'admin',
developer: 'reviewed',
deployer: 'releaser',
viewer: 'viewer',
};
return { ...accountTypes[type[role]] };
}
/**
* What someone may wish for in one project. People without permissions of their own (the
* operator, sign-ins from an identity provider) can be let merge backend changes directly by the
* project (`trusted`: its `codeReview.trustedMembers`).
*/
export function wishScopeIn(permissions: Permissions, own: boolean, trusted: boolean): WishScope {
const scope = normalizePermissions(permissions).wish;
return !own && trusted && scope === 'review' ? 'full' : scope;
}
/** Whether the scope lets a person wish for backend changes at all. */
export const mayWishBackend = (scope: WishScope) => scope === 'review' || scope === 'full';

View File

@ -27,9 +27,9 @@ describe('console bundle', () => {
}
expect(valueImports).toEqual([]);
});
it('takes the provider catalog, the release risk reasons, the path rules and the wish format from entries that import nothing', async () => {
it('takes the provider catalog, release risk reasons, path rules, wish format and permissions from entries that import nothing', async () => {
const manifest = JSON.parse(await readFile('packages/contracts/package.json', 'utf8'));
for (const entry of ['providers', 'release-risk', 'path-rules', 'wish']) {
for (const entry of ['providers', 'release-risk', 'path-rules', 'wish', 'permissions']) {
expect(manifest.exports[`./${entry}`]).toBe(`./src/${entry}.ts`);
expect(await readFile(`packages/contracts/src/${entry}.ts`, 'utf8')).not.toMatch(
/^\s*(?:import|export)\b.*\bfrom\s/m,

View File

@ -1,13 +1,15 @@
/**
* People of a local deployment sign in with accounts of their own, so each acts with their own
* role (requirements FR-A1): the console checks passwords through the control plane, then calls
* it with the local credential and the person's account.
* permissions (requirements FR-A1): the console checks passwords through the control plane, then
* calls it with the local credential and the person's account.
*/
import { beforeEach, describe, expect, it } from 'vitest';
import type { Actor, Project } from '@wishforge/contracts';
import { accountTypes, type Actor, type Entity, type Project } from '@wishforge/contracts';
import { Authenticator } from '../apps/api/src/auth.js';
import { ControlPlane } from '../apps/api/src/domain/control-plane.js';
import { LocalAccounts } from '../apps/api/src/domain/local-accounts.js';
import { permissionsOf, personWishScope } from '../apps/api/src/domain/permissions.js';
import { Releases } from '../apps/api/src/domain/releases.js';
import { MemoryStore } from './helpers/memory-store.js';
const devToken = 'local-console-credential-0123456789';
@ -27,13 +29,15 @@ beforeEach(async () => {
repositoryUrl: 'https://example.org/pilot.git',
});
});
const create = (username: string, role = 'developer') =>
accounts.create(console_, { username, displayName: `${username} 名`, role });
const create = (username: string, type = 'fullstack') =>
accounts.create(console_, { username, displayName: `${username} 名`, type });
const signIn = (username: string, version = '1') =>
auth.authenticate(`Bearer ${devToken}`, { user: `local:${username}`, version });
describe('local accounts', () => {
it('creates an account with a one-time password and lets it into the projects', async () => {
const { account, password } = await create('zhanghm');
expect(account).toMatchObject({ id: 'local:zhanghm', role: 'developer', active: true });
expect(account).toMatchObject({ id: 'local:zhanghm', role: 'developer', active: true, type: 'fullstack' });
expect(password).toMatch(/^[A-Za-z0-9]{16}$/);
expect(await accounts.list(console_)).toEqual([expect.objectContaining({ username: 'zhanghm' })]);
const stored = await db.read('demo', tx => tx.get<Project>('project', project.id));
@ -86,36 +90,129 @@ describe('local accounts', () => {
expect(await accounts.list(console_)).toEqual([expect.objectContaining({ active: false })]);
});
it('records who may change backend code directly, in each of their projects', async () => {
it('gives each account a type, or permissions of its own, and the role that goes with them', async () => {
const roles = {
admin: 'admin',
fullstack: 'developer',
reviewed: 'developer',
frontend: 'developer',
releaser: 'deployer',
viewer: 'viewer',
} as const;
for (const [type, role] of Object.entries(roles)) {
const { account } = await create(`a-${type}`, type);
expect(account).toMatchObject({ role, type, permissions: accountTypes[type as keyof typeof roles] });
expect(permissionsOf(await signIn(`a-${type}`))).toEqual(accountTypes[type as keyof typeof roles]);
}
// A combination of one's own has no type; managing includes everything else.
const { account: custom } = await accounts.create(console_, {
username: 'lead',
displayName: 'Lead',
permissions: { wish: 'frontend', reviewCode: true, releases: true, manage: false },
});
expect(custom).toMatchObject({ role: 'developer', permissions: { wish: 'frontend', reviewCode: true } });
expect(custom).not.toHaveProperty('type');
expect(
await accounts.update(console_, 'local:lead', {
permissions: { wish: 'none', reviewCode: false, releases: false, manage: true },
}),
).toMatchObject({ role: 'admin', type: 'admin', permissions: accountTypes.admin });
await expect(
accounts.create(console_, {
username: 'both',
displayName: 'Both',
type: 'viewer',
permissions: accountTypes.viewer,
}),
).rejects.toThrow();
await expect(accounts.create(console_, { username: 'none', displayName: 'None' })).rejects.toThrow();
});
it('changes what a person may do at once, and which projects they are in', async () => {
const other = await new ControlPlane(db, env).createProject(console_, {
name: 'Other',
repositoryUrl: 'https://example.org/other.git',
});
const { account } = await accounts.create(console_, {
username: 'backend-dev',
displayName: '后端',
role: 'developer',
backend: true,
username: 'wang',
displayName: '王',
type: 'frontend',
projectIds: [project.id],
});
expect(account).toMatchObject({ projectIds: [project.id], backendProjectIds: [project.id] });
const trusted = async () =>
(await db.read('demo', tx => tx.get<Project>('project', project.id)))?.codeReview?.trustedMembers ?? [];
expect(await trusted()).toEqual(['local:backend-dev']);
expect(await accounts.update(console_, 'local:backend-dev', { backend: false })).toMatchObject({
backendProjectIds: [],
expect(account.projectIds).toEqual([project.id]);
const member = async (id: string) =>
(await db.read('demo', tx => tx.get<Project>('project', id)))?.memberIds.includes('local:wang');
expect(await member(other.id)).toBe(false);
const updated = await accounts.update(console_, 'local:wang', { type: 'releaser', projectIds: [other.id] });
expect(updated).toMatchObject({ role: 'deployer', type: 'releaser', projectIds: [other.id] });
expect([await member(project.id), await member(other.id)]).toEqual([false, true]);
// Signed in already, the person acts with the new permissions on the next request.
expect(await signIn('wang')).toMatchObject({ role: 'deployer', permissions: accountTypes.releaser });
});
it('lets an account decide what it is allowed to, and nothing else', async () => {
const releases = new Releases(db, env);
await accounts.create(console_, {
username: 'sun',
displayName: '孙',
permissions: { ...accountTypes.frontend, releases: true },
});
expect(await trusted()).toEqual([]);
const { account: frontend } = await create('frontend-dev');
expect(frontend).toMatchObject({ projectIds: [project.id], backendProjectIds: [] });
await create('wang', 'frontend');
const decision = { decision: 'approve', bindingDigest: 'sha256:0' };
// Allowed to: the release itself does not exist. Not allowed to: refused before looking.
await expect(releases.decide(await signIn('sun'), 'missing', decision)).rejects.toMatchObject({
code: 'NOT_FOUND',
});
await expect(releases.decide(await signIn('wang'), 'missing', decision)).rejects.toMatchObject({
code: 'FORBIDDEN',
});
await expect(releases.rollback(await signIn('wang'), 'missing', 'rollback-0001')).rejects.toMatchObject({
code: 'FORBIDDEN',
});
});
it('decides for people without permissions of their own by their role, which a project can raise', async () => {
const { account } = await create('old');
// An account from before permissions: only its membership says what it may do.
await db.transaction('demo', async tx => {
const { permissions: _, ...stored } = (await tx.get<Entity & { permissions?: unknown }>(
'local_account',
account.id,
))!;
await tx.put('local_account', stored);
const current = (await tx.get<Project>('project', project.id))!;
await tx.put('project', {
...current,
codeReview: { paths: ['**'], exceptPaths: [], trustedMembers: [account.id] },
});
});
const person = await signIn('old');
expect(person.permissions).toBeUndefined();
expect(permissionsOf(person)).toEqual(accountTypes.reviewed);
const stored = (await db.read('demo', tx => tx.get<Project>('project', project.id)))!;
expect(await db.read('demo', tx => personWishScope(tx, account.id, stored))).toBe('full');
// Given permissions of its own, the project's trust no longer applies to it.
await accounts.update(console_, account.id, { type: 'reviewed' });
const after = (await db.read('demo', tx => tx.get<Project>('project', project.id)))!;
expect(after.codeReview?.trustedMembers).toEqual([]);
expect(await db.read('demo', tx => personWishScope(tx, account.id, after))).toBe('review');
await accounts.update(console_, account.id, { active: false });
expect(await db.read('demo', tx => personWishScope(tx, account.id, after))).toBe('none');
});
it('leaves managing accounts to owners and administrators', async () => {
await create('zhanghm');
const developer = await auth.authenticate(`Bearer ${devToken}`, { user: 'local:zhanghm', version: '1' });
await expect(accounts.list(developer)).rejects.toMatchObject({ code: 'FORBIDDEN' });
await expect(
accounts.create(developer, { username: 'other', displayName: 'Other', role: 'admin' }),
accounts.create(developer, { username: 'other', displayName: 'Other', type: 'admin' }),
).rejects.toMatchObject({ code: 'FORBIDDEN' });
await accounts.update(console_, 'local:zhanghm', { role: 'admin' });
const admin = await auth.authenticate(`Bearer ${devToken}`, { user: 'local:zhanghm', version: '1' });
await expect(accounts.update(admin, 'local:zhanghm', { active: false })).rejects.toMatchObject({
code: 'SELF_ACCOUNT_CHANGE',
});
await accounts.update(console_, 'local:zhanghm', { type: 'admin' });
const admin = await signIn('zhanghm');
for (const change of [{ active: false }, { type: 'fullstack' }, { projectIds: [] }])
await expect(accounts.update(admin, 'local:zhanghm', change)).rejects.toMatchObject({
code: 'SELF_ACCOUNT_CHANGE',
});
// One's own name, and permissions given again unchanged, are fine.
await expect(
accounts.update(admin, 'local:zhanghm', { displayName: '张', type: 'admin', projectIds: [project.id] }),
).resolves.toMatchObject({ displayName: '张' });
});
it('exists only in local deployments', async () => {

View File

@ -12,15 +12,20 @@ import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promis
import os from 'node:os';
import path from 'node:path';
import { promisify } from 'node:util';
import type {
Actor,
CheckpointRecord,
Environment,
Evidence,
Lesson,
Project,
Release,
Run,
import {
accountTypes,
roleFor,
type AccountType,
type Actor,
type Permissions,
type CheckpointRecord,
type Environment,
type Evidence,
type Lesson,
type Project,
type Release,
type Role,
type Run,
} from '@wishforge/contracts';
import { executeCommand, type CommandExecutor, type HostCheckSandbox, type ProviderStart } from '@wishforge/runtime';
import { ManagedProvider } from '../packages/runtime/src/providers/base.js';
@ -180,9 +185,15 @@ async function createProject() {
);
return project;
}
async function submit(projectId: string, goal: string, key: string, extra: Record<string, unknown> = {}) {
async function submit(
projectId: string,
goal: string,
key: string,
extra: Record<string, unknown> = {},
by: Actor = owner,
) {
const { run_id } = await services.control.submit(
owner,
by,
projectId,
{ goal, acceptanceCriteria: ['check.mjs passes'], provider: 'codex', budget: { maxRepairRounds: 2 }, ...extra },
key,
@ -289,6 +300,34 @@ const checkWith = (rule: string) =>
rule,
"console.log('greeting ok');",
].join('\n');
/** Someone the role alone decides for, in the project, as a sign-in from an identity provider is. */
async function join(projectId: string, userId: string, role: Role): Promise<Actor> {
await store.transaction(TENANT, async tx => {
await tx.putMembership({ userId, role, active: true });
const project = (await tx.get<Project>('project', projectId))!;
await tx.put('project', { ...project, memberIds: [...project.memberIds, userId] });
});
return { tenantId: TENANT, userId, role, kind: 'human' };
}
/** Someone with an account of their own and its permissions, as the local console signs them in. */
async function person(projectId: string, name: string, type: AccountType | Permissions) {
const permissions = { ...(typeof type === 'string' ? accountTypes[type] : type) };
const actor = await join(projectId, `local:${name}`, roleFor(permissions));
const time = new Date().toISOString();
await store.transaction(TENANT, tx =>
tx.put('local_account', {
id: actor.userId,
tenantId: TENANT,
version: 1,
createdAt: time,
updatedAt: time,
username: name,
displayName: name,
permissions,
}),
);
return { ...actor, permissions };
}
/** The project's policy: changes to these paths wait for a person's review before integration. */
async function holdForReview(projectId: string, paths: string[]) {
await store.transaction(TENANT, async tx => {
@ -1099,7 +1138,8 @@ describe('local main loop', () => {
it('holds a change to reviewed paths until a person approves it, then integrates it without repeating the checks', async () => {
const project = await createProject();
await holdForReview(project.id, ['greeting.txt']);
const runId = await submit(project.id, 'Make the greeting say hello world', 'wish-review-0001');
const developer = await person(project.id, 'li', 'reviewed');
const runId = await submit(project.id, 'Make the greeting say hello world', 'wish-review-0001', {}, developer);
const session = await provision(runId, writeGreeting('hello world', 'Updated the greeting.'));
expect(await drive(session)).toMatchObject({ status: 'waiting', reason: 'code_review' });
const held = await services.control.run(owner, runId);
@ -1143,23 +1183,24 @@ describe('local main loop', () => {
expect(await services.control.codeReview(owner, runId)).toMatchObject({ status: 'approved', decidedBy: 'owner' });
});
it('lets someone who may change backend code merge without a review', async () => {
it('lets a developer the project trusts merge backend changes without a review', async () => {
const project = await createProject();
const developer = await join(project.id, 'developer', 'developer');
await store.transaction(TENANT, async tx => {
const current = (await tx.get<Project>('project', project.id))!;
await tx.put('project', {
...current,
codeReview: { paths: ['**'], exceptPaths: ['docs/'], trustedMembers: [owner.userId] },
codeReview: { paths: ['**'], exceptPaths: ['docs/'], trustedMembers: [developer.userId] },
});
});
const runId = await submit(project.id, 'Make the greeting say hello world', 'wish-review-trusted');
const runId = await submit(project.id, 'Make the greeting say hello world', 'wish-review-trusted', {}, developer);
const session = await provision(runId, writeGreeting('hello world', 'Updated the greeting.'));
expect(await drive(session)).toEqual({ status: 'complete' });
expect(await git(remote, 'show', 'main:greeting.txt')).toBe('hello world');
expect(await services.control.codeReview(owner, runId)).toBeNull();
const events = await services.control.events(owner, runId);
expect(events.find(event => event.type === 'code_review.skipped')).toMatchObject({
data: { requestedBy: owner.userId, paths: ['greeting.txt'] },
data: { requestedBy: developer.userId, paths: ['greeting.txt'] },
});
});
@ -1246,10 +1287,115 @@ describe('local main loop', () => {
expect(await services.control.codeReview(owner, runId)).toBeNull();
});
it('keeps an account that may only wish for frontend changes to frontend code', async () => {
const project = await createProject();
await store.transaction(TENANT, async tx => {
const current = (await tx.get<Project>('project', project.id))!;
await tx.put('project', { ...current, codeReview: { paths: ['**'], exceptPaths: ['greeting.txt'] } });
});
const frontend = await person(project.id, 'wang', 'frontend');
// Its wishes are frontend-only whether it says so or not, and it cannot ask for more.
const own = await submit(project.id, 'Make the greeting say hello world', 'wish-scope-0001', {}, frontend);
expect(await services.control.run(owner, own)).toMatchObject({ frontendOnly: true, requestedBy: 'local:wang' });
await expect(
submit(project.id, 'Log greetings on the server', 'wish-scope-0002', { frontendOnly: false }, frontend),
).rejects.toMatchObject({ code: 'FRONTEND_ONLY_ACCOUNT' });
await expect(
services.control.command(frontend, own, { action: 'answer', allowBackend: true }, 'scope-widen-0001'),
).rejects.toMatchObject({ code: 'FRONTEND_ONLY_ACCOUNT' });
// Accounts that may not wish at all cannot submit.
const releaser = await person(project.id, 'zhao', 'releaser');
await expect(submit(project.id, 'Anything at all', 'wish-scope-0003', {}, releaser)).rejects.toMatchObject({
code: 'FORBIDDEN',
});
const done = await provision(own, writeGreeting('hello world', 'Updated the greeting.'));
expect(await drive(done)).toEqual({ status: 'complete' });
await release(own, done.generation);
// It can take back a frontend-only change, as a frontend-only run.
const { run_id: undo } = await services.control.revert(frontend, own, 'revert-scope-0001');
expect(await services.control.run(owner, undo)).toMatchObject({ frontendOnly: true, requestedBy: 'local:wang' });
await services.control.command(owner, undo, { action: 'cancel' }, 'cancel-scope-0001');
// Neither adding to, nor taking back, what may change backend code.
const wide = await submit(project.id, 'Greet louder', 'wish-scope-0004', { frontendOnly: false });
await expect(
services.control.command(frontend, wide, { action: 'answer', message: 'Also log it' }, 'scope-answer-0001'),
).rejects.toMatchObject({ code: 'FRONTEND_ONLY_ACCOUNT' });
const louder = await provision(wide, writeGreeting('hello world!', 'Greeted louder.'));
expect(await drive(louder)).toEqual({ status: 'complete' });
await release(wide, louder.generation);
await expect(services.control.revert(frontend, wide, 'revert-scope-0002')).rejects.toMatchObject({
code: 'FRONTEND_ONLY_ACCOUNT',
message: expect.stringContaining('to take it back'),
});
// Where the project does not say which code is backend, everything is frontend code.
await store.transaction(TENANT, async tx => {
const current = (await tx.get<Project>('project', project.id))!;
await tx.put('project', { ...current, codeReview: undefined });
});
const open = await submit(project.id, 'Greet in French', 'wish-scope-0005', { frontendOnly: false }, frontend);
expect((await services.control.run(owner, open)).frontendOnly).toBe(false);
});
it('merges a backend change directly only when everyone who asked for it may', async () => {
const project = await createProject();
await holdForReview(project.id, ['greeting.txt']);
const fullstack = await person(project.id, 'chen', 'fullstack');
const reviewed = await person(project.id, 'li', 'reviewed');
const own = await submit(project.id, 'Make the greeting say hello world', 'wish-trust-0001', {}, fullstack);
const first = await provision(own, writeGreeting('hello world', 'Updated the greeting.'));
expect(await drive(first)).toEqual({ status: 'complete' });
await release(own, first.generation);
// Someone whose backend changes are reviewed adds to the requirement: the change waits for a review.
const asked = await submit(project.id, 'Greet more warmly', 'wish-trust-0002', {}, fullstack);
const question = await provision(
asked,
async () => 'The wording is open.\n\nQUESTIONS:\n- Which greeting should it show?',
);
expect(await drive(question)).toMatchObject({ reason: 'clarification' });
await services.control.command(
reviewed,
asked,
{ action: 'answer', message: 'Show "hello world!"' },
'trust-answer-0001',
);
expect(await services.control.run(owner, asked)).toMatchObject({ contributors: ['local:li'] });
await release(asked, question.generation);
const answered = await provision(asked, writeGreeting('hello world!', 'Greeted as answered.'));
expect(await drive(answered)).toMatchObject({ status: 'waiting', reason: 'code_review' });
expect(await git(remote, 'show', 'main:greeting.txt')).toBe('hello world');
});
it('lets whoever may review code decide, but not on a change they could not merge themselves', async () => {
const project = await createProject();
await holdForReview(project.id, ['greeting.txt']);
const lead = await person(project.id, 'zhou', { ...accountTypes.reviewed, reviewCode: true });
const fullstack = await person(project.id, 'chen', 'fullstack');
const reviewer = await person(project.id, 'wu', { ...accountTypes.frontend, reviewCode: true });
const runId = await submit(project.id, 'Make the greeting say hello world', 'wish-reviewer-0001', {}, lead);
const session = await provision(runId, writeGreeting('hello world', 'Updated the greeting.'));
expect(await drive(session)).toMatchObject({ status: 'waiting', reason: 'code_review' });
const { sourceCommit } = (await services.control.codeReview(owner, runId))!;
const approve = (by: Actor, key: string) =>
services.control.decideCodeReview(by, runId, { decision: 'approve', sourceCommit }, key);
await expect(approve(fullstack, 'approve-reviewer-0001')).rejects.toMatchObject({ code: 'FORBIDDEN' });
await expect(approve(lead, 'approve-reviewer-0002')).rejects.toMatchObject({ code: 'SELF_REVIEW' });
await approve(reviewer, 'approve-reviewer-0003');
await release(runId, session.generation);
const approved = await provision(runId, async () => {
throw new Error('The agent does not run again');
});
expect(await drive(approved)).toEqual({ status: 'complete' });
expect(await services.control.codeReview(owner, runId)).toMatchObject({
status: 'approved',
decidedBy: 'local:wu',
});
});
it('hands a rejected change back to the agent with the reviewer’s comment', async () => {
const project = await createProject();
await holdForReview(project.id, ['*.txt']);
const runId = await submit(project.id, 'Make the greeting say hello world', 'wish-review-0002');
const developer = await person(project.id, 'li', 'reviewed');
const runId = await submit(project.id, 'Make the greeting say hello world', 'wish-review-0002', {}, developer);
const session = await provision(runId, writeGreeting('hello world', 'Updated the greeting.'));
expect(await drive(session)).toMatchObject({ reason: 'code_review' });
const first = (await services.control.codeReview(owner, runId))!;

38
tests/permissions.test.ts Normal file
View File

@ -0,0 +1,38 @@
import { describe, expect, it } from 'vitest';
import {
accountTypeNames,
accountTypeOf,
accountTypes,
normalizePermissions,
roleFor,
rolePermissions,
wishScopeIn,
} from '@wishforge/contracts/permissions';
describe('permissions', () => {
it('names every ready-made set, and nothing else', () => {
for (const type of accountTypeNames) expect(accountTypeOf(accountTypes[type])).toBe(type);
expect(accountTypeOf({ ...accountTypes.frontend, reviewCode: true })).toBeUndefined();
expect(Object.keys(accountTypes)).toEqual([...accountTypeNames]);
});
it('lets managing include everything, and keeps only the four permissions', () => {
const extra = { wish: 'none', reviewCode: false, releases: false, manage: true, role: 'owner' } as const;
expect(normalizePermissions(extra)).toEqual(accountTypes.admin);
expect(accountTypeOf(extra)).toBe('admin');
});
it('derives the role that grants the rest', () => {
expect(roleFor(accountTypes.admin)).toBe('admin');
expect(roleFor({ ...accountTypes.frontend, releases: true })).toBe('developer');
expect(roleFor(accountTypes.releaser)).toBe('deployer');
expect(roleFor({ ...accountTypes.viewer, reviewCode: true })).toBe('viewer');
expect(rolePermissions('owner')).toEqual(accountTypes.admin);
expect(rolePermissions('developer')).toEqual(accountTypes.reviewed);
expect(rolePermissions('deployer')).toEqual(accountTypes.releaser);
});
it('lets a project raise only those the role decides for', () => {
expect(wishScopeIn(accountTypes.reviewed, false, true)).toBe('full');
expect(wishScopeIn(accountTypes.reviewed, false, false)).toBe('review');
expect(wishScopeIn(accountTypes.reviewed, true, true)).toBe('review');
expect(wishScopeIn(accountTypes.frontend, false, true)).toBe('frontend');
});
});