refactor: remove dead code and typecheck the test suite

- Drop the WorkBuddy Cloud executor stub: it always reported
  "unverified" and could never run. WorkBuddy remains an MCP client for
  submitting wishes. Providers are now codex and codebuddy; an unknown
  provider waits with an explicit reason instead of a fake adapter.
- Remove internal routes nobody calls (/internal/releases/:id/begin,
  /accept, /failure and /internal/workspaces/:id/provisioned) with
  their domain methods, the never-consumed release.ready and
  release.rollback outbox events, an unreachable idempotency branch,
  dead helpers in runtime/deploy.ts and an unused RunnerBroker
  dependency.
- Enable noUnusedLocals in the base and web TypeScript configs; the
  runtime package now extends the base config.
- Add tests/tsconfig.json and include it in `npm run typecheck`. This
  surfaced tests still calling the deleted begin/accept path (now
  exercised through the Runner protocol) and five latent type errors.
- Web: provider capability labels match the API's keys and the wish
  form disables unavailable providers.
- Delete the invalid example Runner Job manifest; stop tracking the
  generated apps/web/next-env.d.ts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
eust-w 2026-10-19 14:02:27 +08:00
parent 3931bf94f0
commit b90db2cc6f
31 changed files with 136 additions and 479 deletions

3
.gitignore vendored
View File

@ -13,3 +13,6 @@ playwright-report/
test-results/
.DS_Store
*.log
# Generated by Next.js
next-env.d.ts

View File

@ -1,6 +1,6 @@
import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
import { z } from 'zod';
import { DomainError, providers, type Actor, type Entity, type Run } from '@wishforge/contracts';
import { DomainError, providers, type Actor, type Run } from '@wishforge/contracts';
import type { Store } from '../db/store.js';
import { record, touch, must, executionLease } from './control-plane.js';
import { requireRole } from './policy.js';

View File

@ -188,26 +188,19 @@ export class ControlPlane {
[
['codex', 'Codex'],
['codebuddy', 'CodeBuddy'],
['workbuddy_cloud', 'WorkBuddy Cloud'],
] as const
).map(([id, name]) => {
const configured = connected(id);
const productionAllowed =
this.env.NODE_ENV !== 'production' || (id === 'codex' && providerProxyConfigured(this.env));
const enabled =
configured &&
productionAllowed &&
id !== 'workbuddy_cloud' &&
(id !== 'codebuddy' || !!this.env.WF_CODEBUDDY_BIN);
const enabled = configured && productionAllowed && (id !== 'codebuddy' || !!this.env.WF_CODEBUDDY_BIN);
const reason = !productionAllowed
? 'Production execution requires a verified credential-isolation proxy and approved model configuration; raw BYOK is never sent to a production job.'
: !configured
? 'Connect a tenant-owned provider credential to execute tasks.'
: id === 'workbuddy_cloud'
? 'Cloud coding is gated until export, recovery and cancellation contracts are verified.'
: id === 'codebuddy' && !this.env.WF_CODEBUDDY_BIN
? 'CodeBuddy executable is not configured on the worker.'
: 'Available for worker preflight; account/model access is checked when a task starts.';
: id === 'codebuddy' && !this.env.WF_CODEBUDDY_BIN
? 'CodeBuddy executable is not configured on the worker.'
: 'Available for worker preflight; account/model access is checked when a task starts.';
return {
id,
name,
@ -220,7 +213,6 @@ export class ControlPlane {
cancel: enabled,
eventReplay: false,
usage: id === 'codex' && enabled,
cloud: id === 'workbuddy_cloud',
},
};
});
@ -231,74 +223,66 @@ export class ControlPlane {
this.validateKey(key);
return this.store.transaction(actor.tenantId, async tx => {
const project = await projectAccess(tx, actor, projectId);
return idempotent(
tx,
`wish:${actor.userId}:${projectId}:${key ?? ''}`,
key ? { projectId, ...data } : await this.missingKey(),
async () => {
const tenant = await tx.tenant();
const runs = await tx.list<Run>('run');
const usage = await tx.usage(this.period());
const reserved = runs.reduce((sum, run) => sum + run.reservedTokens, 0);
if (
reserved + usage.reduce((n, x) => n + x.tokens, 0) + data.budget.maxTokens >
effectiveEntitlements(tenant).limits.monthlyModelTokens
)
throw new DomainError('QUOTA_EXCEEDED', 'Tenant token reservation limit is exhausted', 429);
const provider = (await this.providerInfo(tx)).find(p => p.id === data.provider)!;
const runnable = provider.enabled && !!project.repositoryUrl;
const wish = {
...record(actor.tenantId),
projectId,
revision: 1,
goal: data.goal,
acceptanceCriteria: data.acceptanceCriteria,
} as Wish;
const identity = record(actor.tenantId);
const bundle = await activeBundle(tx);
const run = {
...identity,
projectId,
wishId: wish.id,
revision: 1,
...data,
stage: 'clarify',
status: runnable ? 'queued' : 'waiting',
waitingReason: !provider.enabled ? 'credentials' : !project.repositoryUrl ? 'git_storage' : undefined,
pendingStartId: runnable ? randomUUID() : undefined,
repairCount: 0,
bundleVersion: bundle.version,
providerModel:
bundle.config.model ??
(data.provider === 'codex'
? (this.env.WF_CODEX_DEFAULT_MODEL ?? this.env.WF_PROVIDER_PROXY_ALLOWED_MODELS?.split(',')[0]?.trim())
: undefined),
policyVersion: 'policy-v1',
reservedTokens: data.budget.maxTokens,
usedTokens: 0,
activeMilliseconds: 0,
} as Run;
await tx.put('wish', wish);
await tx.put('run', run);
await tx.event(run.id, 'wish.submitted', 'Wish accepted and acceptance criteria recorded.', { revision: 1 });
if (runnable) await tx.enqueue('run.start', { runId: run.id, revision: 1 }, String(run.pendingStartId));
else
await tx.event(
run.id,
'run.waiting',
!provider.enabled
? provider.reason
: 'Provision durable Git storage or connect a repository before execution.',
{ reason: run.waitingReason },
);
return { wish_id: wish.id, run_id: run.id, status_url: `/runs/${run.id}` };
},
);
return idempotent(tx, `wish:${actor.userId}:${projectId}:${key ?? ''}`, { projectId, ...data }, async () => {
const tenant = await tx.tenant();
const runs = await tx.list<Run>('run');
const usage = await tx.usage(this.period());
const reserved = runs.reduce((sum, run) => sum + run.reservedTokens, 0);
if (
reserved + usage.reduce((n, x) => n + x.tokens, 0) + data.budget.maxTokens >
effectiveEntitlements(tenant).limits.monthlyModelTokens
)
throw new DomainError('QUOTA_EXCEEDED', 'Tenant token reservation limit is exhausted', 429);
const provider = (await this.providerInfo(tx)).find(p => p.id === data.provider)!;
const runnable = provider.enabled && !!project.repositoryUrl;
const wish = {
...record(actor.tenantId),
projectId,
revision: 1,
goal: data.goal,
acceptanceCriteria: data.acceptanceCriteria,
} as Wish;
const identity = record(actor.tenantId);
const bundle = await activeBundle(tx);
const run = {
...identity,
projectId,
wishId: wish.id,
revision: 1,
...data,
stage: 'clarify',
status: runnable ? 'queued' : 'waiting',
waitingReason: !provider.enabled ? 'credentials' : !project.repositoryUrl ? 'git_storage' : undefined,
pendingStartId: runnable ? randomUUID() : undefined,
repairCount: 0,
bundleVersion: bundle.version,
providerModel:
bundle.config.model ??
(data.provider === 'codex'
? (this.env.WF_CODEX_DEFAULT_MODEL ?? this.env.WF_PROVIDER_PROXY_ALLOWED_MODELS?.split(',')[0]?.trim())
: undefined),
policyVersion: 'policy-v1',
reservedTokens: data.budget.maxTokens,
usedTokens: 0,
activeMilliseconds: 0,
} as Run;
await tx.put('wish', wish);
await tx.put('run', run);
await tx.event(run.id, 'wish.submitted', 'Wish accepted and acceptance criteria recorded.', { revision: 1 });
if (runnable) await tx.enqueue('run.start', { runId: run.id, revision: 1 }, String(run.pendingStartId));
else
await tx.event(
run.id,
'run.waiting',
!provider.enabled
? provider.reason
: 'Provision durable Git storage or connect a repository before execution.',
{ reason: run.waitingReason },
);
return { wish_id: wish.id, run_id: run.id, status_url: `/runs/${run.id}` };
});
});
}
private async missingKey(): Promise<never> {
throw new DomainError('IDEMPOTENCY_REQUIRED', 'Provide Idempotency-Key', 400);
}
private validateKey(key?: string) {
if (!key || key.length < 8 || key.length > 200)
throw new DomainError('IDEMPOTENCY_REQUIRED', 'Provide an Idempotency-Key of 8–200 characters', 400);

View File

@ -1,4 +1,4 @@
import { createHmac, randomUUID } from 'node:crypto';
import { createHmac } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import { z } from 'zod';
import {
@ -10,7 +10,6 @@ import {
type ExecutionResourceGrant,
type PlanLimits,
type Run,
type TenantEntitlementSnapshot,
} from '@wishforge/contracts';
import type { Store, Tenant, Transaction } from '../db/store.js';
import { idempotent, must, record, touch } from './control-plane.js';

View File

@ -458,7 +458,6 @@ export class ProviderProxy {
'x-wishforge-request-id': requestId,
},
});
const operation = prepared.operation!;
const abort = new AbortController();
let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
let settled = false,

View File

@ -14,7 +14,7 @@ import {
} from '@wishforge/contracts';
import type { Store, Transaction } from '../db/store.js';
import { record, touch, must, projectAccess, idempotent, now, executionScope } from './control-plane.js';
import { digest, releaseRisk, requireRole, requireHuman, redact } from './policy.js';
import { digest, releaseRisk, requireRole, requireHuman } from './policy.js';
import { applicationUrlFor, assertApplicationConfigured, assertApplicationAccepted } from './application-access.js';
import { assertVerificationProfile, verificationPolicyDigest } from './verification-policy.js';
@ -268,7 +268,6 @@ export class Releases {
: 'Release passed the configured automatic policy.',
{ releaseId: release.id, bindingDigest: release.bindingDigest },
);
if (!riskReasons.length) await tx.enqueue('release.ready', { releaseId: release.id });
return release;
});
});
@ -341,28 +340,9 @@ export class Releases {
releaseId: release.id,
actorId: actor.userId,
});
if (release.status === 'ready') await tx.enqueue('release.ready', { releaseId: release.id });
return release;
});
}
async begin(actor: Actor, id: string) {
return this.store.transaction(actor.tenantId, async tx => {
const release = await must<Release>(tx, 'release', id);
deploymentIdentity(actor, release.environmentId, release.runId);
const { environment: env } = await this.assertCurrent(tx, release);
if (release.status === 'deploying' && env.activeReleaseId === id) return release;
if (release.status !== 'ready') throw new DomainError('RELEASE_NOT_READY', 'Release must pass policy/approval');
if (env.activeReleaseId) throw new DomainError('ENVIRONMENT_CONFLICT', 'Another release owns the environment');
env.activeReleaseId = release.id;
release.status = 'deploying';
await tx.put('environment', touch(env));
await tx.put('release', touch(release));
return release;
});
}
async accept(actor: Actor, id: string, input: { evidenceId: string; bindingDigest: string }) {
return this.store.transaction(actor.tenantId, tx => this.acceptInTransaction(tx, actor, id, input));
}
async acceptInTransaction(
tx: Transaction,
actor: Actor,
@ -426,22 +406,6 @@ export class Releases {
await tx.enqueue('run.signal', { runId: run.id, action: 'completed' });
return release;
}
async reportFailure(actor: Actor, id: string, status: 'failed' | 'unknown', message: string) {
return this.store.transaction(actor.tenantId, async tx => {
const release = await must<Release>(tx, 'release', id);
deploymentIdentity(actor, release.environmentId, release.runId);
const env = await must<Environment>(tx, 'environment', release.environmentId);
if (!['deploying', 'unknown'].includes(release.status) || env.activeReleaseId !== id)
throw new DomainError('RELEASE_CONFLICT', 'Failure receipt does not own the active deployment');
release.status = status;
/* Preserve the lock until live-state reconciliation, even for a reported failure. */ await tx.put(
'release',
touch(release),
);
await tx.event(release.runId, 'release.failure', redact(message), { releaseId: id, status });
return release;
});
}
async rollback(actor: Actor, id: string, key?: string) {
requireRole(actor, ['owner', 'admin', 'deployer']);
requireHuman(actor);
@ -491,7 +455,6 @@ export class Releases {
env.activeReleaseId = previous.id;
await tx.put('environment', touch(env));
await tx.put('runner_task', operation);
await tx.enqueue('release.rollback', { operationId: operation.id });
await tx.event(
release.runId,
'rollback.requested',

View File

@ -2,17 +2,9 @@ import { matchesApplicationAccess } from '@wishforge/contracts';
import { createHash, createPrivateKey, createPublicKey, randomBytes, randomUUID, sign } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import { z } from 'zod';
import {
DomainError,
type Actor,
type Entity,
type Environment,
type Release,
type Run,
type Evidence,
} from '@wishforge/contracts';
import { DomainError, type Actor, type Environment, type Release, type Evidence } from '@wishforge/contracts';
import type { Store, Transaction } from '../db/store.js';
import { ControlPlane, must, projectAccess, record, touch, now } from './control-plane.js';
import { must, projectAccess, record, touch, now } from './control-plane.js';
import { canonical, digest, requireHuman, requireRole } from './policy.js';
import { Releases, releaseBinding } from './releases.js';
@ -44,7 +36,6 @@ const receipt = z
export class RunnerBroker {
constructor(
private store: Store,
private control: ControlPlane,
private releases: Releases,
private env = process.env,
) {}

View File

@ -1,4 +1,3 @@
import { resolveGatewayTarget } from './domain/gateway-target.js';
import {
Body,
Controller,
@ -18,7 +17,7 @@ import {
} from '@nestjs/common';
import type { Request, Response } from 'express';
import { z, ZodError } from 'zod';
import { DomainError, type Actor, type Entity, type Project, type Run, type Release } from '@wishforge/contracts';
import { DomainError, type Actor, type Run } from '@wishforge/contracts';
import { Authenticator } from './auth.js';
import { ControlPlane, must, projectAccess, record, touch } from './domain/control-plane.js';
import { Releases } from './domain/releases.js';
@ -44,7 +43,7 @@ export class Services {
this.releases = new Releases(control.store, control.env);
this.bundles = new AgentBundles(control.store);
this.connections = new Connections(control.store, control.env);
this.runners = new RunnerBroker(control.store, control, this.releases, control.env);
this.runners = new RunnerBroker(control.store, this.releases, control.env);
this.github = new GitHubIntegration(control.store, control.env);
}
}
@ -583,25 +582,6 @@ export class InternalController {
if (r.actor.kind !== 'deployer') throw new DomainError('FORBIDDEN', 'Deployer required', 403);
return ok(await this.s.releases.request(r.actor, b, key(r)));
}
@Post('releases/:id/begin') async begin(@Req() r: AuthRequest, @Param('id') id: string) {
return ok(await this.s.releases.begin(r.actor, id));
}
@Post('releases/:id/accept') async accept(
@Req() r: AuthRequest,
@Param('id') id: string,
@Body() b: { evidenceId: string; bindingDigest: string },
) {
return ok(await this.s.releases.accept(r.actor, id, b));
}
@Post('releases/:id/failure') async failure(
@Req() r: AuthRequest,
@Param('id') id: string,
@Body() b: { status: 'failed' | 'unknown'; message: string },
) {
if (!['failed', 'unknown'].includes(b.status))
throw new DomainError('INVALID_STATUS', 'Failure status required', 400);
return ok(await this.s.releases.reportFailure(r.actor, id, b.status, b.message));
}
@Post('workspaces/:id/authorize') async authorizeWorkspace(
@Req() r: AuthRequest,
@Param('id') id: string,
@ -640,43 +620,4 @@ export class InternalController {
}),
);
}
@Post('workspaces/:id/provisioned') async provisioned(
@Req() r: AuthRequest,
@Param('id') id: string,
@Body() b: { upstreamUrl: string; collaborationUpstreamUrl?: string },
) {
if (r.actor.kind !== 'worker') throw new DomainError('FORBIDDEN', 'Workspace controller required', 403);
let collaboration: URL | undefined;
if (b.collaborationUpstreamUrl) {
collaboration = new URL(b.collaborationUpstreamUrl);
if (
!['http:', 'https:'].includes(collaboration.protocol) ||
collaboration.username ||
collaboration.password ||
collaboration.pathname !== '/' ||
collaboration.search ||
collaboration.hash
)
throw new DomainError('INVALID_COLLABORATION_UPSTREAM', 'Invalid workspace collaboration backend', 400);
}
const upstream = new URL(b.upstreamUrl);
if (!['http:', 'https:'].includes(upstream.protocol) || upstream.username || upstream.password)
throw new DomainError('INVALID_UPSTREAM', 'Invalid workspace backend', 400);
const base = (await resolveGatewayTarget(this.s.control.env, r.actor.tenantId))?.publicUrl;
if (!base) throw new DomainError('GATEWAY_UNCONFIGURED', 'Authenticated workspace gateway is not configured', 503);
return ok(
await this.s.control.store.transaction(r.actor.tenantId, async tx => {
const w = await must(tx, 'workspace', id);
if (w.lifecycle)
throw new DomainError('WORKSPACE_LIFECYCLE_OWNED', 'Lifecycle controller must reconcile this workspace');
w.status = 'ready';
w.upstreamUrl = upstream.toString();
if (collaboration) w.collaborationUpstreamUrl = collaboration.toString();
w.url = `${base.replace(/\/$/, '')}/workspaces/${id}/`;
w.reason = undefined;
await tx.put('workspace', touch(w));
return { id, status: w.status, url: w.url };
}),
);
}
}

View File

@ -1,7 +0,0 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
import "./.next/dev/types/routes.d.ts";
import "./.next/dev/types/root-params.d.ts";
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.

View File

@ -18,7 +18,6 @@ export const stages: Record<string, string> = {
export const providerNames: Record<string, string> = {
codex: 'Codex',
codebuddy: 'CodeBuddy',
workbuddy_cloud: 'WorkBuddy Cloud',
};
export function RunTable({
runs,

View File

@ -1,5 +1,5 @@
'use client';
import { ArrowRight, Check, CheckCircle2, Cloud, Cpu, KeyRound, Minus, Terminal } from 'lucide-react';
import { ArrowRight, Check, CheckCircle2, Cpu, KeyRound, Minus, Terminal } from 'lucide-react';
import { useState } from 'react';
import { messageOf, mutateApi, useResource } from '@/lib/api';
import type { ProviderConnection, ProviderInfo } from '@/lib/types';
@ -17,26 +17,16 @@ import {
Status,
} from '@/components/ui';
const descriptions: Record<string, string> = {
codex: '通过 Codex 在受控环境中规划、实现与验证代码。',
codebuddy: '腾讯 CodeBuddy 编程执行器,运行于隔离的任务环境。',
workbuddy_cloud: 'WorkBuddy 云端任务服务。能力以已验证的接入契约为准。',
codex: 'OpenAI Codex,在隔离的任务环境中实现与修复代码。',
codebuddy: '腾讯 CodeBuddy 命令行执行器,运行于隔离的任务环境。',
};
// Keys match ProviderInfo.capabilities returned by the control plane.
const capabilityLabels: Record<string, string> = {
streaming: '实时事件',
resume: '恢复会话',
codeExport: '代码导出',
resume: '恢复执行',
cancel: '取消运行',
artifacts: '产物导出',
workspace: '工作区访问',
sandbox: '隔离执行',
structuredOutput: '结构化输出',
headless: '无头执行',
mcp: 'MCP 工具',
supportsResume: '恢复会话',
supportsCancel: '取消运行',
supportsStreaming: '实时事件',
supportsArtifacts: '产物导出',
localExecution: '本地执行',
cloudExecution: '云端执行',
eventReplay: '事件重放',
usage: '用量计量',
};
export function ProvidersView() {
const { data, error, isLoading, mutate } = useResource<ProviderInfo[]>('/providers', 10000);
@ -45,9 +35,7 @@ export function ProvidersView() {
<>
<PageHeader title="执行器" description="连接你的执行引擎,按真实能力调度每一次任务。" />
{error ? <ErrorNotice error={error} retry={() => void mutate()} /> : null}
<Notice>
模型费用由你的服务商直接计费。WorkBuddy 入口连接器、WorkBuddy Cloud 和 CodeBuddy 是不同的接入角色。
</Notice>
<Notice>模型费用由你的服务商直接计费。WorkBuddy 通过 MCP 连接器发起愿望,不需要在这里配置。</Notice>
<Panel title="执行器连接">
{isLoading ? (
<Loading />
@ -57,13 +45,7 @@ export function ProvidersView() {
<article className="provider-item" key={provider.id}>
<div className="provider-heading">
<div className="provider-mark">
{provider.id === 'workbuddy_cloud' ? (
<Cloud size={25} />
) : provider.id === 'codebuddy' ? (
<Terminal size={25} />
) : (
<Cpu size={25} />
)}
{provider.id === 'codebuddy' ? <Terminal size={25} /> : <Cpu size={25} />}
</div>
<div>
<h2>{provider.name}</h2>
@ -145,12 +127,8 @@ function CredentialDialog({
return (
<Modal title={`连接 ${provider.name}`} description="凭据发送到你的控制面,不保存到浏览器存储。" onClose={onClose}>
<form className="form-stack" onSubmit={submit}>
<Notice>
{provider.id === 'workbuddy_cloud'
? '云端接入可能需要应用授权。请使用已获授权的凭据,并以控制面的连通性结果为准。'
: '请使用你自己的模型服务凭据。执行器不会自动共享其他执行器的登录态。'}
</Notice>
<Field label={provider.id === 'workbuddy_cloud' ? '访问令牌' : 'API Key'}>
<Notice>请使用你自己的模型服务凭据。执行器不会自动共享其他执行器的登录态。</Notice>
<Field label="API Key">
<input
type="password"
autoComplete="off"

View File

@ -205,12 +205,15 @@ export function NewWishView() {
<h2>执行与预算</h2>
<Field label="执行器">
<select value={provider} onChange={event => setProvider(event.target.value as ProviderId)}>
{(['codex', 'codebuddy', 'workbuddy_cloud'] as const).map(id => (
<option key={id} value={id}>
{providerNames[id]}
{providers.data?.find(item => item.id === id)?.configured ? '' : ' · 未配置'}
</option>
))}
{(['codex', 'codebuddy'] as const).map(id => {
const info = providers.data?.find(item => item.id === id);
return (
<option key={id} value={id} disabled={info ? !info.enabled : false}>
{providerNames[id]}
{info && !info.enabled ? ` · ${info.configured ? '不可用' : '未配置'}` : ''}
</option>
);
})}
</select>
</Field>
{selectedProvider && !selectedProvider.configured ? (

View File

@ -24,7 +24,7 @@ export type Project = {
}[];
};
};
export type ProviderId = 'codex' | 'codebuddy' | 'workbuddy_cloud';
export type ProviderId = 'codex' | 'codebuddy';
export type Run = {
id: string;
projectId: string;

View File

@ -13,8 +13,15 @@
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [{ "name": "next" }],
"paths": { "@/*": ["./src/*"] }
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"]
},
"noUnusedLocals": true
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", ".next/dev/types/**/*.ts"],
"exclude": ["node_modules"]

View File

@ -17,7 +17,6 @@ import {
validateRepositoryUrl,
verifyWorkspace,
validateVerificationProfile,
WorkBuddyCloudAdapter,
type PortableCheckpoint,
type ProviderAdapter,
type VerificationReport,
@ -227,7 +226,8 @@ export function createActivities(config: WorkerConfig) {
: undefined),
sandboxEnforced: config.sandboxEnforced,
})
: new WorkBuddyCloudAdapter());
: undefined);
if (!provider) return wait(`unsupported_provider: ${run.provider} is not available on this worker`);
if (!provider.capabilities().coding)
return wait(`${provider.capabilities().availability}: ${provider.capabilities().reason}`);
if (run.stage === 'clarify')

View File

@ -1,54 +0,0 @@
# TEMPLATE ONLY: replace the image with a verified digest and create the
# per-run capability Secret out-of-band. Do not kubectl apply without review.
apiVersion: batch/v1
kind: Job
metadata:
name: wishforge-run-example
namespace: wishforge-tenant-example
spec:
backoffLimit: 0
activeDeadlineSeconds: 1800
ttlSecondsAfterFinished: 86400
template:
metadata:
labels:
wishforge.io/component: runner
wishforge.io/tenant: example
spec:
runtimeClassName: wishforge-kata
serviceAccountName: sandbox
automountServiceAccountToken: false
restartPolicy: Never
securityContext:
runAsNonRoot: true
runAsUser: 1000
runAsGroup: 1000
fsGroup: 1000
seccompProfile: { type: RuntimeDefault }
containers:
- name: runner
image: registry.example.invalid/wishforge/runner:REPLACE_WITH_VERIFIED_DIGEST
imagePullPolicy: Always
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities: { drop: [ALL] }
resources:
requests: { cpu: '1', memory: 2Gi, ephemeral-storage: 2Gi }
limits: { cpu: '2', memory: 4Gi, ephemeral-storage: 8Gi }
env:
- name: TOOL_GATEWAY_URL
value: https://tool-gateway.wishforge-control.svc:8443
- name: RUN_CAPABILITY_TOKEN
valueFrom:
secretKeyRef:
name: wishforge-run-example-capability
key: token
volumeMounts:
- { name: workspace, mountPath: /workspace }
- { name: temporary, mountPath: /tmp }
volumes:
- name: workspace
emptyDir: { sizeLimit: 8Gi }
- name: temporary
emptyDir: { sizeLimit: 1Gi }

View File

@ -21,7 +21,7 @@
"dev:worker": "npm run dev -w @wishforge/worker",
"dev:git": "node --env-file=.env.local --import tsx apps/git-service/src/main.ts",
"build": "npm run build --workspaces --if-present",
"typecheck": "npm run typecheck --workspaces --if-present",
"typecheck": "npm run typecheck --workspaces --if-present && tsc --noEmit -p tests",
"test": "vitest run",
"test:integration": "WF_INTEGRATION=1 vitest run tests/integration",
"test:ide": "node --test apps/ide/gateway/test/*.test.mjs apps/ide/provisioner/test/*.test.mjs apps/ide/collaboration/test/*.test.mjs apps/ide/collaboration/test/*.test.cjs apps/ide/policy/test/*.test.cjs",

View File

@ -3,7 +3,7 @@ import { z } from 'zod';
export const API_VERSION = 1;
export const roles = ['owner', 'admin', 'developer', 'deployer', 'viewer'] as const;
export type Role = (typeof roles)[number];
export const providers = ['codex', 'codebuddy', 'workbuddy_cloud'] as const;
export const providers = ['codex', 'codebuddy'] as const;
export type ProviderId = (typeof providers)[number];
export const stages = [
'clarify',

View File

@ -1,10 +1,6 @@
import { normalizeApplicationUrl, type ApplicationAccessEvidence } from '@wishforge/contracts';
import { createHash } from 'node:crypto';
import { mkdir, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { executeCommand, type CommandExecutor } from './process.js';
import { requireCommit, safeIdentifier } from './git.js';
import { RuntimeError, type DeploymentAdapter, type DeploymentResult, type ReleaseManifest } from './types.js';
import { RuntimeError, type ReleaseManifest } from './types.js';
export function validateRelease(release: ReleaseManifest): void {
if (release.applicationUrl) {
@ -80,24 +76,6 @@ export function validateRelease(release: ReleaseManifest): void {
'Business smoke checks must use a same-origin path distinct from health',
);
}
function resourceName(release: ReleaseManifest) {
return `wf-${createHash('sha256').update(`${release.tenantId}/${release.environmentId}`).digest('hex').slice(0, 20)}`;
}
function labels(release: ReleaseManifest) {
return {
'wishforge.io/release': release.id,
'wishforge.io/tenant': release.tenantId,
'wishforge.io/environment': release.environmentId,
'wishforge.io/source': release.sourceCommit,
};
}
const result = (
release: ReleaseManifest,
target: DeploymentResult['target'],
status: DeploymentResult['status'],
evidence: Record<string, unknown> = {},
rendered?: string,
): DeploymentResult => ({ releaseId: release.id, status, target, evidence, ...(rendered ? { rendered } : {}) });
export function deliveryConfiguration(release: ReleaseManifest, stable: string | undefined): string | undefined {
if (!release.applicationUrl)
return release.deliveryRequired || process.env.NODE_ENV === 'production'

View File

@ -8,7 +8,6 @@ export * from './deploy.js';
export * from './runner.js';
export * from './providers/codex.js';
export * from './providers/codebuddy.js';
export * from './providers/workbuddy.js';
export * from './verification-profile.js';
export * from './project-manifest.js';

View File

@ -1,90 +0,0 @@
import { RuntimeError, type ProviderAdapter, type ProviderStart } from '../types.js';
export interface WorkBuddyCloudConfig {
tokenUrl?: string;
clientId?: string;
clientSecret?: string;
refreshToken?: string;
capabilitiesUrl?: string;
/** Set only after an audited OAuth/ACP contract PoC. No guessed Cloud API routes. */
contractEvidenceId?: string;
verifiedTransport?: ProviderAdapter;
fetcher?: typeof fetch;
}
export class WorkBuddyCloudAdapter implements ProviderAdapter {
constructor(private readonly config: WorkBuddyCloudConfig = {}) {}
capabilities() {
if (this.config.contractEvidenceId && this.config.verifiedTransport)
return { ...this.config.verifiedTransport.capabilities(), provider: 'workbuddy_cloud' };
return {
provider: 'workbuddy_cloud',
availability: 'unverified' as const,
coding: false,
streaming: false,
cancellation: false,
portableCheckpoint: false,
reason: 'OAuth/ACP contract PoC and a verified transport are required before coding is enabled',
};
}
private transport() {
if (!this.config.contractEvidenceId || !this.config.verifiedTransport)
throw new RuntimeError('UNVERIFIED', this.capabilities().reason ?? 'WorkBuddy Cloud contract is not verified');
return this.config.verifiedTransport;
}
async fetchOAuthToken(): Promise<{ accessToken: string; expiresIn?: number }> {
const { tokenUrl, clientId, clientSecret, refreshToken } = this.config;
if (!tokenUrl || !clientId || !clientSecret || !refreshToken)
throw new RuntimeError('UNCONFIGURED', 'OAuth refresh credentials are not configured');
if (new URL(tokenUrl).protocol !== 'https:')
throw new RuntimeError('INSECURE_ENDPOINT', 'OAuth token endpoint must use HTTPS');
const response = await (this.config.fetcher ?? fetch)(tokenUrl, {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'refresh_token',
client_id: clientId,
client_secret: clientSecret,
refresh_token: refreshToken,
}),
redirect: 'error',
signal: AbortSignal.timeout(15_000),
});
if (!response.ok) throw new RuntimeError('OAUTH_FAILED', `OAuth refresh returned HTTP ${response.status}`);
const data = (await response.json()) as Record<string, unknown>;
if (typeof data.access_token !== 'string' || !data.access_token)
throw new RuntimeError('INVALID_OAUTH_RESPONSE', 'OAuth response is missing access_token');
return {
accessToken: data.access_token,
...(typeof data.expires_in === 'number' ? { expiresIn: data.expires_in } : {}),
};
}
async inspectRemoteCapabilities(accessToken: string): Promise<unknown> {
if (!this.config.capabilitiesUrl)
throw new RuntimeError('UNCONFIGURED', 'An audited capabilities endpoint is required');
if (new URL(this.config.capabilitiesUrl).protocol !== 'https:')
throw new RuntimeError('INSECURE_ENDPOINT', 'Capabilities endpoint must use HTTPS');
const response = await (this.config.fetcher ?? fetch)(this.config.capabilitiesUrl, {
headers: { authorization: `Bearer ${accessToken}` },
redirect: 'error',
signal: AbortSignal.timeout(15_000),
});
if (!response.ok)
throw new RuntimeError('CAPABILITY_FETCH_FAILED', `Capabilities returned HTTP ${response.status}`);
return response.json(); // Evidence for an operator; this never enables coding automatically.
}
async start(input: ProviderStart) {
return this.transport().start(input);
}
async inspect(id: string) {
return this.transport().inspect(id);
}
events(id: string, afterSequence?: number) {
return this.transport().events(id, afterSequence);
}
async cancel(id: string) {
return this.transport().cancel(id);
}
async exportCheckpoint(id: string) {
return this.transport().exportCheckpoint(id);
}
}

View File

@ -14,7 +14,6 @@ import {
validateRelease,
verifyRunnerTask,
verifyWorkspace,
WorkBuddyCloudAdapter,
type ReleaseManifest,
type RunnerTask,
} from '../src/index.js';
@ -155,19 +154,9 @@ describe('deployments fail closed', () => {
});
describe('portable provider execution', () => {
it('never starts from ambient credentials or an unverified cloud contract', async () => {
it('never starts from ambient credentials', () => {
expect(new CodexAdapter().capabilities().availability).toBe('unconfigured');
expect(new CodeBuddyAdapter().capabilities().availability).toBe('unconfigured');
expect(new WorkBuddyCloudAdapter().capabilities().coding).toBe(false);
await expect(
new WorkBuddyCloudAdapter().start({
runId: 'r',
tenantId: 't',
workspace: '/tmp',
baseCommit: 'a'.repeat(40),
prompt: 'test',
}),
).rejects.toThrow('PoC');
});
it('requires Codex turn.completed and does not forward worker secrets or raw reasoning', async () => {
const home = await temp();

View File

@ -1,12 +1,8 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"noEmit": true,
"noUncheckedIndexedAccess": true,
"skipLibCheck": true,
"esModuleInterop": true,
"types": ["node"],
"lib": ["ES2022", "DOM"]
},

View File

@ -31,7 +31,7 @@ async function fixture() {
const env = { NODE_ENV: 'test', WF_VAULT_KEY: 'a'.repeat(64), WF_RUNNER_SIGNING_KEY_FILE: `${temp}/key.pem` };
const control = new ControlPlane(db, env),
releases = new Releases(db, env),
broker = new RunnerBroker(db, control, releases, env);
broker = new RunnerBroker(db, releases, env);
const project = await control.createProject(owner, {
name: 'Application',
repositoryUrl: 'https://example.test/repo.git',

View File

@ -42,7 +42,7 @@ beforeEach(async () => {
control = new ControlPlane(db, env);
connections = new Connections(db, env);
releases = new Releases(db);
broker = new RunnerBroker(db, control, releases, env);
broker = new RunnerBroker(db, releases, env);
await connections.create(owner, { provider: 'codex', label: 'test', apiKey: 'fixture-key-only' });
});
async function edit<T extends Entity>(kind: EntityKind, id: string, change: (value: T) => void) {
@ -232,7 +232,7 @@ describe('exact release bindings and project ACLs', () => {
it.each(['secret', 'architecture', 'revision', 'delivery-config', 'verification-policy'] as const)(
'rejects %s drift after human approval',
async change => {
const { release, environment, runId, project } = await prepared();
const { environment, runId, project, runner } = await prepared();
if (change === 'secret')
await edit<Environment>('environment', environment.id, e => {
e.secretVersionRefs = ['vault:new-version'];
@ -253,7 +253,7 @@ describe('exact release bindings and project ACLs', () => {
await edit('project', project.id, p => {
p.verificationCommands = [['node', '--test', 'new-policy']];
});
await expect(releases.begin(deployer, release.id)).rejects.toMatchObject({ code: 'RELEASE_STALE' });
await expect(broker.poll(runner, environment.id)).rejects.toMatchObject({ code: 'RELEASE_STALE' });
},
);
it('invalidates an already approved release when requirements are revised', async () => {

View File

@ -1,7 +1,7 @@
import { beforeEach, describe, expect, it } from 'vitest';
import type { Actor, Run } from '@wishforge/contracts';
import type { Actor } from '@wishforge/contracts';
import { MemoryStore } from './helpers/memory-store.js';
import { ControlPlane, record } from '../apps/api/src/domain/control-plane.js';
import { ControlPlane } from '../apps/api/src/domain/control-plane.js';
import { Connections } from '../apps/api/src/domain/connections.js';
import { Releases } from '../apps/api/src/domain/releases.js';
import { AgentBundles } from '../apps/api/src/domain/agent-bundles.js';
@ -9,8 +9,7 @@ import { digest } from '../apps/api/src/domain/policy.js';
const owner: Actor = { tenantId: 'alpha', userId: 'owner', role: 'owner', kind: 'human' };
const worker: Actor = { ...owner, kind: 'worker', userId: 'worker' },
verifier: Actor = { ...owner, kind: 'verifier', userId: 'verifier' },
deployer: Actor = { ...owner, kind: 'deployer', userId: 'deployer' };
verifier: Actor = { ...owner, kind: 'verifier', userId: 'verifier' };
let db: MemoryStore, control: ControlPlane, releases: Releases, connections: Connections;
const goal = {
goal: 'Add search to the catalog',
@ -215,40 +214,6 @@ describe('artifact-bound publication', () => {
releases.decide(owner, rel.approvalId!, { decision: 'approve', bindingDigest: rel.bindingDigest }),
).rejects.toMatchObject({ code: 'APPROVAL_EXPIRED' });
});
it('only accepts matching deployed digest with health and business evidence', async () => {
const { rel, runId, commit, image } = await prepared();
await releases.decide(owner, rel.approvalId!, { decision: 'approve', bindingDigest: rel.bindingDigest });
await releases.begin(deployer, rel.id);
const e = await control.evidence(deployer, {
releaseId: rel.id,
environmentId: rel.environmentId,
bindingDigest: rel.bindingDigest,
runId,
revision: 1,
sourceCommit: commit,
type: 'deployment',
passed: true,
imageDigest: image,
checks: ['health'],
});
await expect(
releases.accept(deployer, rel.id, { bindingDigest: rel.bindingDigest, evidenceId: e.id }),
).rejects.toMatchObject({ code: 'ACCEPTANCE_REQUIRED' });
const good = await control.evidence(deployer, {
releaseId: rel.id,
environmentId: rel.environmentId,
bindingDigest: rel.bindingDigest,
runId,
revision: 1,
sourceCommit: commit,
type: 'deployment',
passed: true,
imageDigest: image,
checks: ['health', 'business-smoke'],
});
await releases.accept(deployer, rel.id, { bindingDigest: rel.bindingDigest, evidenceId: good.id });
expect(await control.run(owner, runId)).toMatchObject({ status: 'succeeded', stage: 'accept', reservedTokens: 0 });
});
});
describe('agent configuration versions', () => {

View File

@ -4,6 +4,7 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { Client, Connection } from '@temporalio/client';
import { Context } from '@temporalio/activity';
import { ApplicationFailure } from '@temporalio/common';
import { msToTs } from '@temporalio/common/lib/time.js';
import { bundleWorkflowCode, NativeConnection, Runtime, Worker } from '@temporalio/worker';
import type { RunInput, ActivityOutcome } from '../../apps/worker/src/activities.js';
@ -95,7 +96,7 @@ describe.skipIf(!enabled)('Temporal durable runWorkflow recovery (fixture activi
await connection.workflowService.registerNamespace({
namespace,
description: 'WishForge contract-test fixtures only; no production credentials or model calls',
workflowExecutionRetentionPeriod: { seconds: 86400 },
workflowExecutionRetentionPeriod: msToTs('1 day'),
});
} catch (error) {
if (!String(error).includes('already exists')) throw error;

View File

@ -207,7 +207,10 @@ describe('run-scoped Codex credential proxy', () => {
it('rejects tampered tenant tokens, wrong audience, stale generations and rotated provider connections before upstream I/O', async () => {
const upstream = vi.fn();
const { proxy, credential, request } = await fixture(upstream);
const token = await new SignJWT({ ...decodeJwt(credential.apiKey), tenantId: 'beta' })
const token = await new SignJWT({
...decodeJwt<Record<string, unknown>>(String(credential.apiKey)),
tenantId: 'beta',
})
.setProtectedHeader({ alg: 'HS256' })
.sign(new TextEncoder().encode(env.WF_PROVIDER_PROXY_SIGNING_KEY));
await expect(

9
tests/tsconfig.json Normal file
View File

@ -0,0 +1,9 @@
{
"extends": "../tsconfig.base.json",
"compilerOptions": {
"noEmit": true,
"types": ["node"],
"allowJs": true
},
"include": ["**/*.ts"]
}

View File

@ -11,6 +11,7 @@
"sourceMap": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"noUnusedLocals": true
}
}

View File

@ -2,7 +2,7 @@ import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
include: ['packages/**/*.test.ts', 'apps/**/*.test.ts', 'tests/**/*.test.ts'],
exclude: ['**/node_modules/**', '**/dist/**', '**/apps/ide/browser/**'],
exclude: ['**/node_modules/**', '**/dist/**'],
testTimeout: 15000,
},
});