Compare commits
101
Commits
66c17e821f
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e81bfbc98d | ||
|
|
7ed0642819 | ||
|
|
cf91155c10 | ||
|
|
32f4614251 | ||
|
|
9c9e9450bc | ||
|
|
c228b54fd7 | ||
|
|
3fb5f24208 | ||
|
|
62116225ff | ||
|
|
fdb3591cf9 | ||
|
|
e21180f2eb | ||
|
|
d81772502c | ||
|
|
46d0a42974 | ||
|
|
808e56e23d | ||
|
|
4fd4f8f1d7 | ||
|
|
fd9882104e | ||
|
|
bb32a6aafd | ||
|
|
0ee69a6c96 | ||
|
|
c23e14cf43 | ||
|
|
b82c730c82 | ||
|
|
ecec4bd7de | ||
|
|
fcc2311c6b | ||
|
|
8971a35bd3 | ||
|
|
083ccfcfa0 | ||
|
|
ae16ff8fcb | ||
|
|
abba3fa08d | ||
|
|
5e7cb7a4f7 | ||
|
|
8caa7d1c0c | ||
|
|
813dc23f80 | ||
|
|
78b5fce74a | ||
|
|
aa466ffcfd | ||
|
|
d624842842 | ||
|
|
75ad21d52b | ||
|
|
8d47081d8d | ||
|
|
94fc2082b9 | ||
|
|
ab7a27fa1a | ||
|
|
5f005dac17 | ||
|
|
755329388a | ||
|
|
c4274be0a1 | ||
|
|
648d65e354 | ||
|
|
eaaccf693e | ||
|
|
43a6a8dcc3 | ||
|
|
1c37b2061d | ||
|
|
8ee8a5bb93 | ||
|
|
94687cae5f | ||
|
|
51a7ce10ce | ||
|
|
55204aa5ec | ||
|
|
e14ad62535 | ||
|
|
924f2df1ca | ||
|
|
825aa5aa45 | ||
|
|
d0b39131c9 | ||
|
|
8ff8d77582 | ||
|
|
2b9b72b08d | ||
|
|
d805975a8d | ||
|
|
ee63e0e948 | ||
|
|
a1a672e804 | ||
|
|
208d22a777 | ||
|
|
7764987775 | ||
|
|
b59eb1bc96 | ||
|
|
823c83dfd0 | ||
|
|
046e4d8133 | ||
|
|
f6060da309 | ||
|
|
618ec3bafe | ||
|
|
198b25e828 | ||
|
|
573f583a2e | ||
|
|
415c7f0239 | ||
|
|
29d20034f2 | ||
|
|
576e4dd257 | ||
|
|
a342cb02f1 | ||
|
|
4425a29d0f | ||
|
|
37ef33084e | ||
|
|
33104af8a8 | ||
|
|
a707e2f23f | ||
|
|
956152f74f | ||
|
|
911c77a144 | ||
|
|
f14af1a61d | ||
|
|
04b0657498 | ||
|
|
463ddf1f2a | ||
|
|
28b3e2c37a | ||
|
|
54f4cba45f | ||
|
|
d2345b1eba | ||
|
|
9364b68f66 | ||
|
|
1b3e2f9789 | ||
|
|
71ceb5cdc6 | ||
|
|
27ed8a9675 | ||
|
|
62b14a9ee2 | ||
|
|
b664c3ce40 | ||
|
|
af41f1477b | ||
|
|
2dd57da647 | ||
|
|
f8a733ef87 | ||
|
|
be455dca7a | ||
|
|
e7ce8c61b5 | ||
|
|
4d7c1555bd | ||
|
|
9651323a19 | ||
|
|
79630e5d3c | ||
|
|
6f89eadbeb | ||
|
|
7065ee2c74 | ||
|
|
99473a0d20 | ||
|
|
bb6bfd30da | ||
|
|
5db0fc2a9f | ||
|
|
907b641f07 | ||
|
|
8eec34fbfd |
@@ -0,0 +1,11 @@
|
|||||||
|
.git
|
||||||
|
.gitignore
|
||||||
|
*.md
|
||||||
|
.env.local
|
||||||
|
.env
|
||||||
|
tests/
|
||||||
|
*.test.go
|
||||||
|
coverage/
|
||||||
|
.DS_Store
|
||||||
|
k8s/
|
||||||
|
migrations/
|
||||||
+33
-12
@@ -1,4 +1,4 @@
|
|||||||
name: ci
|
name: CI
|
||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
@@ -6,14 +6,14 @@ on:
|
|||||||
pull_request:
|
pull_request:
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
test:
|
test-build-push:
|
||||||
runs-on: golang
|
runs-on: golang
|
||||||
container:
|
container:
|
||||||
image: golang:1.25
|
image: golang:1.26
|
||||||
env:
|
env:
|
||||||
GOPRIVATE: forgejo.riotpiao.com
|
GOPRIVATE: forgejo.riotpiao.com
|
||||||
GOFLAGS: -mod=readonly
|
REGISTRY: forgejo.riotpiao.com
|
||||||
GITHUB_TOKEN: ${{ secrets.REGISTRY_PAT }}
|
IMAGE: forgejo.riotpiao.com/rock/poimen-workflows
|
||||||
steps:
|
steps:
|
||||||
- name: Configure git authentication
|
- name: Configure git authentication
|
||||||
run: |
|
run: |
|
||||||
@@ -25,17 +25,38 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
git init
|
git init
|
||||||
git remote add origin https://forgejo.riotpiao.com/rock/poimen-workflows.git
|
git remote add origin https://forgejo.riotpiao.com/rock/poimen-workflows.git
|
||||||
git fetch origin ${{ github.ref_name }} --depth=1
|
git fetch origin ${{ github.head_ref || github.ref_name }} --depth=1
|
||||||
git checkout FETCH_HEAD
|
git checkout FETCH_HEAD
|
||||||
|
|
||||||
- name: Download dependencies
|
- name: Download dependencies
|
||||||
run: go mod download
|
run: go mod download
|
||||||
|
|
||||||
- name: Test
|
|
||||||
run: go test -v ./...
|
|
||||||
|
|
||||||
- name: Build
|
|
||||||
run: go build -o /tmp/poimen-bin/ ./cmd/...
|
|
||||||
|
|
||||||
- name: Vet
|
- name: Vet
|
||||||
run: go vet ./...
|
run: go vet ./...
|
||||||
|
|
||||||
|
- name: Test
|
||||||
|
run: go test ./...
|
||||||
|
|
||||||
|
- name: Build binary
|
||||||
|
run: CGO_ENABLED=0 GOOS=linux go build -o /tmp/poimen-worker ./cmd/worker
|
||||||
|
|
||||||
|
- name: Get short SHA
|
||||||
|
id: sha
|
||||||
|
run: echo "short_sha=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT
|
||||||
|
|
||||||
|
- name: Registry login
|
||||||
|
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
|
||||||
|
run: |
|
||||||
|
echo "${{ secrets.FORGEJO_REGISTRY_TOKEN }}" | docker login "${REGISTRY}" \
|
||||||
|
--username "${{ secrets.FORGEJO_REGISTRY_USER }}" --password-stdin
|
||||||
|
|
||||||
|
- name: Build and push image
|
||||||
|
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
|
||||||
|
run: |
|
||||||
|
docker build \
|
||||||
|
-t "${IMAGE}:${{ steps.sha.outputs.short_sha }}" \
|
||||||
|
-t "${IMAGE}:latest" \
|
||||||
|
.
|
||||||
|
docker push "${IMAGE}:${{ steps.sha.outputs.short_sha }}"
|
||||||
|
docker push "${IMAGE}:latest"
|
||||||
|
echo "✓ Pushed ${IMAGE}:${{ steps.sha.outputs.short_sha }}"
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
creation_rules:
|
||||||
|
- path_regex: k8s/.*\.enc\.ya?ml
|
||||||
|
age: age1e5fq3hwxy78psus2nfvmtmua36g0u3suk78ephw6246l974d2utsvn0hla
|
||||||
+293
@@ -0,0 +1,293 @@
|
|||||||
|
# Poimen Application Deployment
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
Poimen is a unified application consisting of three services:
|
||||||
|
- **poimen-memory**: Memory/Graph RAG service
|
||||||
|
- **poimen-workflows**: Temporal orchestration + API
|
||||||
|
- **poimen-frontend**: Next.js frontend
|
||||||
|
|
||||||
|
All services are deployed together as a single application in the `poimen` namespace.
|
||||||
|
|
||||||
|
## Local Development
|
||||||
|
|
||||||
|
### Prerequisites
|
||||||
|
- Docker
|
||||||
|
- Docker Compose
|
||||||
|
- Node.js 18+
|
||||||
|
- Go 1.21+
|
||||||
|
- Python 3.11+
|
||||||
|
|
||||||
|
### Start Local Stack
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker-compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
This starts:
|
||||||
|
- PostgreSQL (memory + workflows DBs)
|
||||||
|
- Redis (cache)
|
||||||
|
- Temporal (workflow orchestration)
|
||||||
|
- poimen-memory (8000)
|
||||||
|
- poimen-workflows (8080)
|
||||||
|
- poimen-workflows-worker
|
||||||
|
- poimen-frontend (3000)
|
||||||
|
|
||||||
|
### Access Services
|
||||||
|
|
||||||
|
- Frontend: http://localhost:3000
|
||||||
|
- Workflows API: http://localhost:8080
|
||||||
|
- Memory API: http://localhost:8000
|
||||||
|
- Temporal UI: http://localhost:8233
|
||||||
|
|
||||||
|
### Stop Stack
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker-compose down
|
||||||
|
```
|
||||||
|
|
||||||
|
## Building & Pushing Images
|
||||||
|
|
||||||
|
### Build All Services
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./build-push.sh latest
|
||||||
|
```
|
||||||
|
|
||||||
|
Or specific services:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker build -t forgejo.riotpiao.com/rock/poimen-memory:v1.0.0 ./memory
|
||||||
|
docker push forgejo.riotpiao.com/rock/poimen-memory:v1.0.0
|
||||||
|
```
|
||||||
|
|
||||||
|
### Image Tagging Strategy
|
||||||
|
|
||||||
|
- `latest`: Development/staging
|
||||||
|
- `v1.0.0`, `v1.0.1`, etc.: Production releases
|
||||||
|
- `main-{commit-hash}`: CI/CD automated builds
|
||||||
|
|
||||||
|
## Kubernetes Deployment
|
||||||
|
|
||||||
|
### Prerequisites
|
||||||
|
|
||||||
|
- Kubernetes cluster (1.24+)
|
||||||
|
- kubectl configured
|
||||||
|
- Kustomize installed
|
||||||
|
- Registry credentials configured
|
||||||
|
|
||||||
|
### Deploy to Cluster
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd k8s
|
||||||
|
./deploy.sh -a
|
||||||
|
```
|
||||||
|
|
||||||
|
Or with specific tags:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./deploy.sh -m v1.0.0 -w v1.0.0 -f v1.0.0
|
||||||
|
```
|
||||||
|
|
||||||
|
### Verify Deployment
|
||||||
|
|
||||||
|
```bash
|
||||||
|
kubectl get pods -n poimen
|
||||||
|
kubectl get svc -n poimen
|
||||||
|
kubectl logs -n poimen -l app=poimen-workflows
|
||||||
|
```
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
### Environment Variables
|
||||||
|
|
||||||
|
Configure in `k8s/poimen-application.yaml` under `spec.template.spec.env`:
|
||||||
|
|
||||||
|
**Common:**
|
||||||
|
- `TEMPORAL_HOST`: Temporal server (default: temporal:7233)
|
||||||
|
- `DATABASE_URL`: PostgreSQL connection
|
||||||
|
- `JWT_SECRET`: JWT signing key
|
||||||
|
- `LOG_LEVEL`: debug|info|warn|error
|
||||||
|
|
||||||
|
**Memory Service:**
|
||||||
|
- `REDIS_URL`: Redis connection
|
||||||
|
- `ELASTICSEARCH_URL`: Optional full-text search
|
||||||
|
|
||||||
|
**Workflows Service:**
|
||||||
|
- `MEMORY_SERVICE_URL`: Internal memory service URL
|
||||||
|
|
||||||
|
**Frontend:**
|
||||||
|
- `NEXT_PUBLIC_WORKFLOWS_API`: External workflows API
|
||||||
|
- `NEXT_PUBLIC_MEMORY_API`: External memory API
|
||||||
|
- `OAUTH_CLIENT_ID`, `OAUTH_CLIENT_SECRET`: Auth provider
|
||||||
|
|
||||||
|
### Secrets
|
||||||
|
|
||||||
|
Create secrets before deployment:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
kubectl create secret generic poimen-db-credentials \
|
||||||
|
--from-literal=memory-url="postgresql://..." \
|
||||||
|
--from-literal=workflows-url="postgresql://..." \
|
||||||
|
-n poimen
|
||||||
|
|
||||||
|
kubectl create secret generic poimen-secrets \
|
||||||
|
--from-literal=jwt-secret="..." \
|
||||||
|
--from-literal=oauth-client-id="..." \
|
||||||
|
--from-literal=oauth-client-secret="..." \
|
||||||
|
-n poimen
|
||||||
|
```
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────────┐
|
||||||
|
│ LoadBalancer Service │
|
||||||
|
│ poimen-frontend:80→3000 │
|
||||||
|
└─────────────────┬───────────────────────────┘
|
||||||
|
│
|
||||||
|
┌───────┴────────┐
|
||||||
|
▼ ▼
|
||||||
|
┌──────────────┐ ┌──────────────┐
|
||||||
|
│ Frontend │ │ Workflows │
|
||||||
|
│ (3000) │ │ API (8080) │
|
||||||
|
│ 2 replicas │ │ 2 replicas │
|
||||||
|
└──────────────┘ └──────┬───────┘
|
||||||
|
│ │
|
||||||
|
│ ┌─────┴─────┐
|
||||||
|
│ ▼ ▼
|
||||||
|
│ ┌─────────────────────┐
|
||||||
|
│ │ Temporal Cluster │
|
||||||
|
│ │ (External) │
|
||||||
|
│ └─────────────────────┘
|
||||||
|
│
|
||||||
|
└──────────────────┬──────────────┐
|
||||||
|
▼ ▼
|
||||||
|
┌──────────────┐ ┌──────────────┐
|
||||||
|
│ Memory │ │ PostgreSQL │
|
||||||
|
│ (8000) │ │ (5432) │
|
||||||
|
│ 1 replica │ │ │
|
||||||
|
└──────────────┘ └──────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
## Scaling
|
||||||
|
|
||||||
|
### Horizontal Scaling
|
||||||
|
|
||||||
|
Adjust replicas in `k8s/poimen-application.yaml`:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
spec:
|
||||||
|
replicas: 3 # Increase this
|
||||||
|
```
|
||||||
|
|
||||||
|
Or patch:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
kubectl patch deployment poimen-workflows -p '{"spec":{"replicas":3}}' -n poimen
|
||||||
|
```
|
||||||
|
|
||||||
|
### Resource Requests/Limits
|
||||||
|
|
||||||
|
Add to container spec:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
resources:
|
||||||
|
requests:
|
||||||
|
cpu: 100m
|
||||||
|
memory: 256Mi
|
||||||
|
limits:
|
||||||
|
cpu: 500m
|
||||||
|
memory: 512Mi
|
||||||
|
```
|
||||||
|
|
||||||
|
## Monitoring & Logging
|
||||||
|
|
||||||
|
### Check Status
|
||||||
|
|
||||||
|
```bash
|
||||||
|
kubectl get pods -n poimen -w
|
||||||
|
kubectl describe pod <pod-name> -n poimen
|
||||||
|
kubectl logs -n poimen -f -l app=poimen-workflows --all-containers=true
|
||||||
|
```
|
||||||
|
|
||||||
|
### Health Checks
|
||||||
|
|
||||||
|
All services expose `/health` endpoint:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl http://poimen-workflows:8080/health
|
||||||
|
curl http://poimen-memory:8000/health
|
||||||
|
curl http://poimen-frontend:3000/
|
||||||
|
```
|
||||||
|
|
||||||
|
## Updates & Rollbacks
|
||||||
|
|
||||||
|
### Rolling Update
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./deploy.sh -w v1.0.1
|
||||||
|
```
|
||||||
|
|
||||||
|
Kubernetes automatically rolls out with health checks.
|
||||||
|
|
||||||
|
### View Rollout Status
|
||||||
|
|
||||||
|
```bash
|
||||||
|
kubectl rollout status deploy/poimen-workflows -n poimen
|
||||||
|
```
|
||||||
|
|
||||||
|
### Rollback
|
||||||
|
|
||||||
|
```bash
|
||||||
|
kubectl rollout undo deploy/poimen-workflows -n poimen
|
||||||
|
```
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
### Services Can't Connect
|
||||||
|
|
||||||
|
Check service DNS:
|
||||||
|
```bash
|
||||||
|
kubectl run -it --rm debug --image=busybox --restart=Never -- nslookup poimen-workflows
|
||||||
|
```
|
||||||
|
|
||||||
|
### Database Migrations Failing
|
||||||
|
|
||||||
|
```bash
|
||||||
|
kubectl exec -it <workflows-pod> -n poimen -- \
|
||||||
|
./workflows migrate up
|
||||||
|
```
|
||||||
|
|
||||||
|
### Temporal Worker Not Picking Up Activities
|
||||||
|
|
||||||
|
Check worker logs:
|
||||||
|
```bash
|
||||||
|
kubectl logs -n poimen -l app=poimen-workflows --all-containers=true | grep -i activity
|
||||||
|
```
|
||||||
|
|
||||||
|
Verify activities registered in `cmd/worker/main.go`
|
||||||
|
|
||||||
|
## CI/CD Integration
|
||||||
|
|
||||||
|
### GitHub Actions Example
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
name: Build & Push Poimen
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
- name: Build & Push
|
||||||
|
run: ./build-push.sh main-${{ github.sha }}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Automatic Deployment
|
||||||
|
|
||||||
|
Configure ArgoCD to watch `k8s/` directory for updates.
|
||||||
+15
-380
@@ -1,385 +1,20 @@
|
|||||||
# Multi-stage build for Poimen Temporal Worker
|
FROM golang:1.26-alpine AS builder
|
||||||
# Stage 1: Builder - Compile Go binary and set up tools
|
|
||||||
FROM golang:1.25-alpine AS builder
|
|
||||||
|
|
||||||
WORKDIR /build
|
|
||||||
|
|
||||||
# Install system dependencies (ast-grep, git, build essentials)
|
|
||||||
RUN apk add --no-cache \
|
|
||||||
git \
|
|
||||||
curl \
|
|
||||||
wget \
|
|
||||||
ca-certificates \
|
|
||||||
gcc \
|
|
||||||
musl-dev \
|
|
||||||
bash \
|
|
||||||
&& echo "[builder] System dependencies installed"
|
|
||||||
|
|
||||||
# Install ast-grep CLI tool
|
|
||||||
RUN curl -fsSL https://github.com/ast-grep/ast-grep/releases/download/0.24.0/sg-x86_64-unknown-linux-musl.tar.gz \
|
|
||||||
| tar xzf - -C /usr/local/bin \
|
|
||||||
&& chmod +x /usr/local/bin/sg \
|
|
||||||
&& sg --version \
|
|
||||||
&& echo "[builder] ast-grep installed"
|
|
||||||
|
|
||||||
# Install Node.js for pi CLI and browser-use
|
|
||||||
RUN apk add --no-cache nodejs npm \
|
|
||||||
&& echo "[builder] Node.js installed"
|
|
||||||
|
|
||||||
# Install pi CLI globally
|
|
||||||
RUN npm install -g @earendil-works/pi-coding-agent --unsafe-perm \
|
|
||||||
&& pi --version \
|
|
||||||
&& echo "[builder] pi CLI installed"
|
|
||||||
|
|
||||||
# Install browser-use CLI for browser automation
|
|
||||||
RUN npm install -g browser-use --unsafe-perm \
|
|
||||||
&& browser-use --version \
|
|
||||||
&& echo "[builder] browser-use CLI installed"
|
|
||||||
|
|
||||||
# Set up pi home directory and skills
|
|
||||||
RUN mkdir -p ~/.pi/agent/skills ~/.pi/agent/agents \
|
|
||||||
&& echo "[builder] pi directories created"
|
|
||||||
|
|
||||||
# Stage 2: Download pi skills (caveman & andrej karpathy)
|
|
||||||
# Clone caveman skill from pi-agent repo
|
|
||||||
RUN cd /tmp && git clone https://github.com/earendil-works/pi-agent.git pi-repo \
|
|
||||||
&& mkdir -p ~/.pi/agent/skills/caveman \
|
|
||||||
&& cp -r pi-repo/examples/skills/caveman/* ~/.pi/agent/skills/caveman/ 2>/dev/null || true \
|
|
||||||
&& echo "[builder] caveman skill installed"
|
|
||||||
|
|
||||||
# Create andrej karpathy skill manually (reference/training patterns)
|
|
||||||
RUN mkdir -p ~/.pi/agent/skills/andrej-karpathy && cat > ~/.pi/agent/skills/andrej-karpathy/SKILL.md << 'EOF'
|
|
||||||
# Andrej Karpathy LLM & AI Principles Skill
|
|
||||||
|
|
||||||
Build neural networks and LLM systems with proven patterns from Andrej Karpathy.
|
|
||||||
Topics: attention mechanisms, transformer training, inference optimization, edge cases.
|
|
||||||
|
|
||||||
## Key Principles
|
|
||||||
|
|
||||||
### 1. Simplicity First
|
|
||||||
- Start with minimal implementation
|
|
||||||
- Add complexity only when justified
|
|
||||||
- Test each component independently
|
|
||||||
- Use debugging tools effectively
|
|
||||||
|
|
||||||
### 2. Neural Network Architecture
|
|
||||||
- Understand backward pass deeply
|
|
||||||
- Implement from scratch when possible
|
|
||||||
- Use visualization for debugging
|
|
||||||
- Profile before optimizing
|
|
||||||
|
|
||||||
### 3. LLM Training Patterns
|
|
||||||
- Quality data > quantity
|
|
||||||
- Curriculum learning for complex tasks
|
|
||||||
- Loss landscape visualization
|
|
||||||
- Checkpoint strategy matters
|
|
||||||
|
|
||||||
### 4. Inference Optimization
|
|
||||||
- Quantization without quality loss
|
|
||||||
- KV cache management
|
|
||||||
- Batch processing strategies
|
|
||||||
- Latency profiling
|
|
||||||
|
|
||||||
### 5. Failure Analysis
|
|
||||||
- Log intermediate activations
|
|
||||||
- Check gradient flow
|
|
||||||
- Validate data pipeline
|
|
||||||
- Test edge cases explicitly
|
|
||||||
|
|
||||||
## Usage in Poimen
|
|
||||||
|
|
||||||
Apply when:
|
|
||||||
- Designing workflow stages (like training curricula)
|
|
||||||
- Optimizing inference (planner/judge/implementer prompts)
|
|
||||||
- Debugging convergence issues (retry patterns)
|
|
||||||
- Scaling to production (quantization patterns)
|
|
||||||
|
|
||||||
## Resources
|
|
||||||
- github.com/karpathy/minGPT - Minimal GPT implementation
|
|
||||||
- youtube: "Neural Networks: Zero to Hero" series
|
|
||||||
- Papers: Attention Is All You Need, GPT series whitepapers
|
|
||||||
EOF
|
|
||||||
&& echo "[builder] andrej-karpathy skill created"
|
|
||||||
|
|
||||||
# Create browser-use skill for web testing & automation
|
|
||||||
RUN mkdir -p ~/.pi/agent/skills/browser-use && cat > ~/.pi/agent/skills/browser-use/SKILL.md << 'EOF'
|
|
||||||
# browser-use: Browser Automation Skill
|
|
||||||
|
|
||||||
Automate web browser interactions for testing, verification, and UI validation.
|
|
||||||
Topics: headless browser control, visual testing, form automation, screenshot capture.
|
|
||||||
|
|
||||||
## Key Capabilities
|
|
||||||
|
|
||||||
### 1. Browser Control
|
|
||||||
- Launch headless Chrome/Firefox
|
|
||||||
- Navigate to URLs
|
|
||||||
- Wait for elements/navigation
|
|
||||||
- Handle popups/dialogs
|
|
||||||
|
|
||||||
### 2. Interaction Patterns
|
|
||||||
- Click buttons/links
|
|
||||||
- Fill forms (text, dropdown, checkbox)
|
|
||||||
- Drag & drop
|
|
||||||
- Keyboard input
|
|
||||||
|
|
||||||
### 3. Verification & Capture
|
|
||||||
- Screenshot capture
|
|
||||||
- Element inspection
|
|
||||||
- Accessibility checks
|
|
||||||
- Network monitoring
|
|
||||||
|
|
||||||
### 4. Wait Strategies
|
|
||||||
- Wait for element visible
|
|
||||||
- Wait for navigation
|
|
||||||
- Wait for condition (custom JS)
|
|
||||||
- Timeout handling
|
|
||||||
|
|
||||||
### 5. Error Recovery
|
|
||||||
- Retry failed actions
|
|
||||||
- Handle stale elements
|
|
||||||
- Browser crash recovery
|
|
||||||
- Memory leak prevention
|
|
||||||
|
|
||||||
## Usage in Poimen Phases
|
|
||||||
|
|
||||||
### Phase T2 (Implementation)
|
|
||||||
- Test generated UI code in real browser
|
|
||||||
- Verify visual layout matches spec
|
|
||||||
- Validate form inputs work correctly
|
|
||||||
|
|
||||||
### Phase T3 (Verification)
|
|
||||||
- Visual regression testing
|
|
||||||
- Accessibility validation (ARIA, keyboard nav)
|
|
||||||
- Cross-browser verification
|
|
||||||
|
|
||||||
### Phase T6 (Integration)
|
|
||||||
- End-to-end workflow testing
|
|
||||||
- External service integration testing
|
|
||||||
- User journey verification
|
|
||||||
|
|
||||||
### Phase T9 (Release)
|
|
||||||
- Pre-release smoke tests
|
|
||||||
- Deployment verification
|
|
||||||
- Production canary testing
|
|
||||||
|
|
||||||
## Example Workflows
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Launch browser and take screenshot
|
|
||||||
browser-use screenshot "https://example.com" --file output.png
|
|
||||||
|
|
||||||
# Fill form and submit
|
|
||||||
browser-use interact "https://example.com" \
|
|
||||||
--click "#submit-btn" \
|
|
||||||
--type "#email" "[email protected]" \
|
|
||||||
--type "#password" "secretpass" \
|
|
||||||
--click ".submit"
|
|
||||||
|
|
||||||
# Wait for dynamic content and extract data
|
|
||||||
browser-use extract "https://example.com" \
|
|
||||||
--wait ".dynamic-content" \
|
|
||||||
--selector ".data-row" \
|
|
||||||
--output json
|
|
||||||
|
|
||||||
# Accessibility audit
|
|
||||||
browser-use audit "https://example.com" \
|
|
||||||
--check wcag2a \
|
|
||||||
--report a11y-report.html
|
|
||||||
```
|
|
||||||
|
|
||||||
## Integration with Poimen
|
|
||||||
|
|
||||||
Pre-generated code can be tested:
|
|
||||||
```bash
|
|
||||||
# Generate code (T2)
|
|
||||||
implementer_output = "function handleClick() { ... }"
|
|
||||||
|
|
||||||
# Verify in browser (T3)
|
|
||||||
browser-use interact "http://localhost:3000" \
|
|
||||||
--click ".test-button" \
|
|
||||||
--screenshot result.png
|
|
||||||
|
|
||||||
# Compare with expected
|
|
||||||
verify_visual_match(result.png, expected.png)
|
|
||||||
```
|
|
||||||
|
|
||||||
## Performance Notes
|
|
||||||
|
|
||||||
- Startup: ~2-5s per browser
|
|
||||||
- Action latency: 100-500ms per interaction
|
|
||||||
- Screenshot: 500ms-2s (depends on page size)
|
|
||||||
- Keep browser alive for batch operations (pool management)
|
|
||||||
|
|
||||||
## Error Handling
|
|
||||||
|
|
||||||
- Transient: Network timeout → retry with backoff
|
|
||||||
- Permanent: Element not found → fail and log
|
|
||||||
- Flaky: Wait strategies → increase timeout gradually
|
|
||||||
- Memory: Reuse browser instances → kill after 10 uses
|
|
||||||
|
|
||||||
## Resources
|
|
||||||
- docs.browseruse.com - Official documentation
|
|
||||||
- github.com/browser-use/browser-use - Source code
|
|
||||||
- Chrome DevTools Protocol - Advanced browser control
|
|
||||||
EOF
|
|
||||||
&& echo "[builder] browser-use skill created"
|
|
||||||
|
|
||||||
# Copy Go source code
|
|
||||||
COPY . /build/
|
|
||||||
|
|
||||||
# Download Go dependencies
|
|
||||||
RUN go mod download \
|
|
||||||
&& echo "[builder] Go dependencies downloaded"
|
|
||||||
|
|
||||||
# Build worker binary
|
|
||||||
RUN CGO_ENABLED=1 GOOS=linux go build -o /build/worker ./cmd/worker \
|
|
||||||
&& echo "[builder] Worker binary built"
|
|
||||||
|
|
||||||
# Verify binary
|
|
||||||
RUN file /build/worker && ls -lh /build/worker
|
|
||||||
|
|
||||||
# Stage 3: Runtime - Minimal base image with runtime dependencies
|
|
||||||
FROM alpine:3.20
|
|
||||||
|
|
||||||
LABEL maintainer="Poimen Team"
|
|
||||||
LABEL description="Poimen Temporal Worker with memory service, ast-grep, and browser automation"
|
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
COPY go.mod go.sum ./
|
||||||
|
RUN go mod download
|
||||||
|
COPY . .
|
||||||
|
|
||||||
# Install runtime dependencies (including Chromium for browser-use)
|
# Re-use CI-built binary if present, otherwise build
|
||||||
RUN apk add --no-cache \
|
ARG BINARY_PATH=
|
||||||
ca-certificates \
|
RUN if [ -n "$BINARY_PATH" ] && [ -f "$BINARY_PATH" ]; then \
|
||||||
git \
|
cp "$BINARY_PATH" worker; \
|
||||||
bash \
|
else \
|
||||||
curl \
|
CGO_ENABLED=0 GOOS=linux go build -o worker ./cmd/worker; \
|
||||||
jq \
|
|
||||||
chromium \
|
|
||||||
chromium-chromedriver \
|
|
||||||
&& echo "[runtime] Runtime dependencies installed"
|
|
||||||
|
|
||||||
# Install Node.js for pi CLI and browser-use
|
|
||||||
RUN apk add --no-cache nodejs npm \
|
|
||||||
&& echo "[runtime] Node.js installed"
|
|
||||||
|
|
||||||
# Install pi CLI in runtime image
|
|
||||||
RUN npm install -g @earendil-works/pi-coding-agent --unsafe-perm \
|
|
||||||
&& pi --version \
|
|
||||||
&& echo "[runtime] pi CLI installed"
|
|
||||||
|
|
||||||
# Install browser-use CLI in runtime image
|
|
||||||
RUN npm install -g browser-use --unsafe-perm \
|
|
||||||
&& browser-use --version \
|
|
||||||
&& echo "[runtime] browser-use CLI installed"
|
|
||||||
|
|
||||||
# Copy ast-grep binary from builder
|
|
||||||
COPY --from=builder /usr/local/bin/sg /usr/local/bin/sg
|
|
||||||
RUN chmod +x /usr/local/bin/sg && sg --version \
|
|
||||||
&& echo "[runtime] ast-grep copied"
|
|
||||||
|
|
||||||
# Copy pi skills from builder
|
|
||||||
COPY --from=builder /root/.pi /root/.pi
|
|
||||||
RUN ls -la /root/.pi/agent/skills/ \
|
|
||||||
&& echo "[runtime] pi skills configured"
|
|
||||||
|
|
||||||
# Copy worker binary from builder
|
|
||||||
COPY --from=builder /build/worker /app/worker
|
|
||||||
RUN chmod +x /app/worker && file /app/worker \
|
|
||||||
&& echo "[runtime] Worker binary copied"
|
|
||||||
|
|
||||||
# Create app directory structure
|
|
||||||
RUN mkdir -p /app/work /app/logs /app/screenshots \
|
|
||||||
&& chmod 755 /app/work /app/logs /app/screenshots \
|
|
||||||
&& echo "[runtime] App directories created"
|
|
||||||
|
|
||||||
# Health check endpoint
|
|
||||||
EXPOSE 8081
|
|
||||||
|
|
||||||
# Worker task queue listener
|
|
||||||
ENV TEMPORAL_NAMESPACE=poimen-harness \
|
|
||||||
TEMPORAL_HOSTPORT=temporal-frontend.temporal:7233 \
|
|
||||||
MEMORY_SERVICE_URL=http://memory-service.poimen:5000 \
|
|
||||||
MEMORY_SERVICE_TOKEN= \
|
|
||||||
ANTHROPIC_API_KEY= \
|
|
||||||
PI_SKILLS_PATH=/root/.pi/agent/skills \
|
|
||||||
AST_GREP_BIN=/usr/local/bin/sg \
|
|
||||||
BROWSER_USE_BIN=/usr/local/bin/browser-use \
|
|
||||||
CHROMIUM_BIN=/usr/bin/chromium-browser \
|
|
||||||
SCREENSHOTS_DIR=/app/screenshots
|
|
||||||
|
|
||||||
# Entrypoint script with startup diagnostics
|
|
||||||
COPY --chmod=755 << 'EOF' /app/entrypoint.sh
|
|
||||||
#!/bin/bash
|
|
||||||
set -e
|
|
||||||
|
|
||||||
echo "[$(date)] ========== POIMEN WORKER STARTUP =========="
|
|
||||||
echo "[$(date)] Container: $HOSTNAME"
|
|
||||||
echo "[$(date)] Image: $(cat /etc/os-release | grep PRETTY_NAME | cut -d= -f2)"
|
|
||||||
|
|
||||||
# Verify CLI tools
|
|
||||||
echo "[$(date)] ✓ Checking CLI tools..."
|
|
||||||
echo " - Go version: $(go version 2>/dev/null || echo 'N/A')"
|
|
||||||
echo " - ast-grep: $(sg --version 2>&1 | head -1)"
|
|
||||||
echo " - pi: $(pi --version 2>&1 | head -1)"
|
|
||||||
echo " - browser-use: $(browser-use --version 2>&1 | head -1)"
|
|
||||||
echo " - chromium: $(chromium-browser --version 2>&1 || echo 'Not found')"
|
|
||||||
echo " - git: $(git --version)"
|
|
||||||
echo " - node: $(node --version)"
|
|
||||||
echo " - npm: $(npm --version)"
|
|
||||||
|
|
||||||
# Verify pi skills
|
|
||||||
echo "[$(date)] ✓ Checking pi skills..."
|
|
||||||
if [ -d "$PI_SKILLS_PATH" ]; then
|
|
||||||
echo " - Skills path: $PI_SKILLS_PATH"
|
|
||||||
ls -1 "$PI_SKILLS_PATH" | sed 's/^/ ✓ /'
|
|
||||||
else
|
|
||||||
echo " - WARNING: Skills path not found: $PI_SKILLS_PATH"
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Verify browser tools
|
|
||||||
echo "[$(date)] ✓ Checking browser automation tools..."
|
|
||||||
echo " - Chromium binary: $CHROMIUM_BIN"
|
|
||||||
echo " - Screenshots directory: $SCREENSHOTS_DIR"
|
|
||||||
if [ -d "$SCREENSHOTS_DIR" ]; then
|
|
||||||
echo " - Screenshots dir ready ($(du -sh $SCREENSHOTS_DIR 2>/dev/null | cut -f1 || echo '0B'))"
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Check environment variables
|
|
||||||
echo "[$(date)] ✓ Configuration loaded:"
|
|
||||||
echo " - TEMPORAL_NAMESPACE: $TEMPORAL_NAMESPACE"
|
|
||||||
echo " - TEMPORAL_HOSTPORT: $TEMPORAL_HOSTPORT"
|
|
||||||
echo " - MEMORY_SERVICE_URL: ${MEMORY_SERVICE_URL:-(not set)}"
|
|
||||||
echo " - PI_SKILLS_PATH: $PI_SKILLS_PATH"
|
|
||||||
echo " - CHROMIUM_BIN: $CHROMIUM_BIN"
|
|
||||||
|
|
||||||
# Verify memory service connectivity (optional, non-blocking)
|
|
||||||
if [ ! -z "$MEMORY_SERVICE_URL" ]; then
|
|
||||||
echo "[$(date)] ✓ Testing memory service connectivity..."
|
|
||||||
if curl -sf "$MEMORY_SERVICE_URL/health" > /dev/null 2>&1; then
|
|
||||||
echo " - Memory service: HEALTHY"
|
|
||||||
else
|
|
||||||
echo " - Memory service: UNREACHABLE (will retry in worker)"
|
|
||||||
fi
|
fi
|
||||||
fi
|
|
||||||
|
|
||||||
# Test browser automation (optional, non-blocking)
|
FROM alpine:3.20
|
||||||
echo "[$(date)] ✓ Testing browser automation..."
|
RUN apk --no-cache add ca-certificates
|
||||||
if command -v chromium-browser &> /dev/null && command -v browser-use &> /dev/null; then
|
WORKDIR /app
|
||||||
echo " - Chromium available: YES"
|
COPY --from=builder /app/worker .
|
||||||
echo " - browser-use available: YES"
|
ENTRYPOINT ["./worker"]
|
||||||
echo " - Browser automation: READY"
|
|
||||||
else
|
|
||||||
echo " - Browser automation: WARNING - missing dependencies"
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "[$(date)] ========== STARTING WORKER =========="
|
|
||||||
exec /app/worker
|
|
||||||
EOF
|
|
||||||
|
|
||||||
RUN chmod +x /app/entrypoint.sh
|
|
||||||
|
|
||||||
# Run worker with diagnostics
|
|
||||||
ENTRYPOINT ["/app/entrypoint.sh"]
|
|
||||||
|
|
||||||
# Health check
|
|
||||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
|
|
||||||
CMD curl -f http://localhost:8081/health || exit 1
|
|
||||||
|
|||||||
@@ -120,6 +120,7 @@ Poimen embodies three core principles:
|
|||||||
|
|
||||||
| Activity | Purpose | Timeout | Retry |
|
| Activity | Purpose | Timeout | Retry |
|
||||||
|----------|---------|---------|-------|
|
|----------|---------|---------|-------|
|
||||||
|
| **AssumeRoleActivity** | Request temporary JWT token (like AWS AssumeRole) | 30s | 2x |
|
||||||
| **CloneRepo** | Clone git repository | 30s | 3x |
|
| **CloneRepo** | Clone git repository | 30s | 3x |
|
||||||
| **AnalyzeCode** | Static analysis (SAST) | 120s | 2x |
|
| **AnalyzeCode** | Static analysis (SAST) | 120s | 2x |
|
||||||
| **SecurityScan** | Dependency & vulnerability scan | 60s | 2x |
|
| **SecurityScan** | Dependency & vulnerability scan | 60s | 2x |
|
||||||
@@ -548,8 +549,6 @@ Poimen supports multiple authentication methods to federate LLM access across cu
|
|||||||
auth := &routing.LLMAuth{
|
auth := &routing.LLMAuth{
|
||||||
Type: routing.AuthTypeBearer,
|
Type: routing.AuthTypeBearer,
|
||||||
Token: "eyJhbGciOiJIUzI1NiIs...", // JWT token from your auth provider
|
Token: "eyJhbGciOiJIUzI1NiIs...", // JWT token from your auth provider
|
||||||
TenantID: "customer-123", // Optional: tenant isolation
|
|
||||||
Scopes: "llm:read llm:write", // Optional: OAuth2 scopes
|
|
||||||
}
|
}
|
||||||
client := routing.NewLLMClientWithAuth(auth)
|
client := routing.NewLLMClientWithAuth(auth)
|
||||||
```
|
```
|
||||||
@@ -559,7 +558,6 @@ client := routing.NewLLMClientWithAuth(auth)
|
|||||||
auth := &routing.LLMAuth{
|
auth := &routing.LLMAuth{
|
||||||
Type: routing.AuthTypeAPIKey,
|
Type: routing.AuthTypeAPIKey,
|
||||||
APIKey: "sk-xxx-yyy-zzz", // API key from provider
|
APIKey: "sk-xxx-yyy-zzz", // API key from provider
|
||||||
TenantID: "customer-456",
|
|
||||||
}
|
}
|
||||||
client := routing.NewLLMClientWithAuth(auth)
|
client := routing.NewLLMClientWithAuth(auth)
|
||||||
```
|
```
|
||||||
@@ -570,7 +568,6 @@ auth := &routing.LLMAuth{
|
|||||||
Type: routing.AuthTypeCustom,
|
Type: routing.AuthTypeCustom,
|
||||||
HeaderName: "X-Custom-Auth",
|
HeaderName: "X-Custom-Auth",
|
||||||
HeaderValue: "custom-token-value",
|
HeaderValue: "custom-token-value",
|
||||||
TenantID: "customer-789",
|
|
||||||
}
|
}
|
||||||
client := routing.NewLLMClientWithAuth(auth)
|
client := routing.NewLLMClientWithAuth(auth)
|
||||||
```
|
```
|
||||||
@@ -583,47 +580,39 @@ config := &routing.LLMRouterConfig{
|
|||||||
Auth: &routing.LLMAuth{
|
Auth: &routing.LLMAuth{
|
||||||
Type: routing.AuthTypeBearer,
|
Type: routing.AuthTypeBearer,
|
||||||
Token: jwtToken,
|
Token: jwtToken,
|
||||||
TenantID: customerID, // Tenant isolation in multi-tenant deployments
|
|
||||||
},
|
},
|
||||||
TenantID: customerID, // Additional tenant tracking
|
|
||||||
}
|
}
|
||||||
router := routing.NewLLMRouter(config)
|
router := routing.NewLLMRouter(config)
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Multi-Tenant Federated Access
|
#### Per-Deployment Auth
|
||||||
|
|
||||||
For multi-tenant deployments:
|
Each Poimen deployment gets its own LLM token:
|
||||||
|
|
||||||
```go
|
```go
|
||||||
// Per-customer isolated routers
|
// In K8s secret/vault
|
||||||
func CreateCustomerRouter(customerID, jwtToken string) (*routing.LLMRouter, error) {
|
LLM_AUTH_TOKEN="eyJhbGciOiJIUzI1NiIs..."
|
||||||
|
|
||||||
|
// In code
|
||||||
|
func InitializeRouter() (*routing.LLMRouter, error) {
|
||||||
|
token := os.Getenv("LLM_AUTH_TOKEN")
|
||||||
|
if token == "" {
|
||||||
|
return nil, fmt.Errorf("LLM_AUTH_TOKEN not set")
|
||||||
|
}
|
||||||
|
|
||||||
auth := &routing.LLMAuth{
|
auth := &routing.LLMAuth{
|
||||||
Type: routing.AuthTypeBearer,
|
Type: routing.AuthTypeBearer,
|
||||||
Token: jwtToken,
|
Token: token,
|
||||||
TenantID: customerID, // Passed to LLM API in X-Tenant-ID header
|
|
||||||
Scopes: "llm:read", // Restrict scopes per customer
|
|
||||||
}
|
}
|
||||||
|
|
||||||
config := &routing.LLMRouterConfig{
|
config := &routing.LLMRouterConfig{
|
||||||
Provider: &routing.LLMClient{},
|
Provider: &routing.LLMClient{},
|
||||||
KnowledgeBase: globalKB,
|
KnowledgeBase: kb,
|
||||||
Auth: auth,
|
Auth: auth,
|
||||||
TenantID: customerID,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return routing.NewLLMRouter(config)
|
return routing.NewLLMRouter(config)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Usage in activity
|
|
||||||
input := &routing.LLMRouterInput{
|
|
||||||
Message: "Analyze code",
|
|
||||||
MemoryContext: memCtx,
|
|
||||||
}
|
|
||||||
output, err := router.Route(ctx, input)
|
|
||||||
// Headers sent to LLM API:
|
|
||||||
// Authorization: Bearer <jwtToken>
|
|
||||||
// X-Tenant-ID: <customerID>
|
|
||||||
// X-OAuth-Scopes: llm:read
|
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Token Refresh & Rotation
|
#### Token Refresh & Rotation
|
||||||
@@ -649,10 +638,8 @@ result, err := client.Chat(ctx, systemPrompt, userMsg)
|
|||||||
|
|
||||||
| Header | Set When | Value | Purpose |
|
| Header | Set When | Value | Purpose |
|
||||||
|--------|----------|-------|---------|
|
|--------|----------|-------|---------|
|
||||||
| `Authorization` | Bearer auth | `Bearer {token}` | OAuth2/JWT authentication |
|
| `Authorization` | Bearer auth | `Bearer {token}` | JWT/OAuth2 authentication |
|
||||||
| `X-API-Key` | API Key auth | `{api-key}` | API key authentication |
|
| `X-API-Key` | API Key auth | `{api-key}` | API key authentication |
|
||||||
| `X-Tenant-ID` | Any auth type | `{tenantID}` | Tenant/customer isolation |
|
|
||||||
| `X-OAuth-Scopes` | Bearer with scopes | Space-separated scopes | OAuth2 scope enforcement |
|
|
||||||
| Custom header | Custom auth | `{headerValue}` | Custom authentication scheme |
|
| Custom header | Custom auth | `{headerValue}` | Custom authentication scheme |
|
||||||
|
|
||||||
### LLMRouter Configuration (Programmatic)
|
### LLMRouter Configuration (Programmatic)
|
||||||
@@ -780,95 +767,171 @@ kubectl apply -f k8s/worker-deployment.yaml
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Security & Multi-Tenancy
|
## Security & Token Management
|
||||||
|
|
||||||
### Token Management
|
### Never Hardcode Tokens
|
||||||
|
|
||||||
**Never hardcode tokens!** Use secure secret management:
|
**Use secure secret management:**
|
||||||
|
|
||||||
```go
|
```go
|
||||||
// ❌ DON'T DO THIS
|
// ❌ DON'T DO THIS
|
||||||
auth := &routing.LLMAuth{
|
auth := &routing.LLMAuth{
|
||||||
|
Type: routing.AuthTypeBearer,
|
||||||
Token: "eyJhbGciOiJIUzI1NiIs...", // Hardcoded!
|
Token: "eyJhbGciOiJIUzI1NiIs...", // Hardcoded!
|
||||||
}
|
}
|
||||||
|
|
||||||
// ✅ DO THIS
|
// ✅ DO THIS
|
||||||
tokenFromVault, _ := vaultClient.GetSecret("llm-token-" + customerID)
|
token := os.Getenv("LLM_AUTH_TOKEN")
|
||||||
auth := &routing.LLMAuth{
|
auth := &routing.LLMAuth{
|
||||||
Type: routing.AuthTypeBearer,
|
Type: routing.AuthTypeBearer,
|
||||||
Token: tokenFromVault,
|
Token: token,
|
||||||
TenantID: customerID,
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
**Recommended secret management:**
|
**Recommended secret management:**
|
||||||
- Kubernetes Secrets (development)
|
- **Kubernetes Secrets** (development) — stored in etcd
|
||||||
- HashiCorp Vault (production)
|
- **HashiCorp Vault** (production) — centralized secret management
|
||||||
- AWS Secrets Manager / GCP Secret Manager (cloud)
|
- **AWS Secrets Manager** (cloud) — managed service
|
||||||
- Sealed Secrets / Sealed Policies
|
- **GCP Secret Manager** (cloud) — managed service
|
||||||
|
- **Sealed Secrets** or **Sealed Policies** — encrypted in git
|
||||||
|
|
||||||
### Tenant Isolation
|
### Token Rotation & Refresh
|
||||||
|
|
||||||
The `TenantID` header enforces tenant isolation on the LLM API side:
|
For long-running Temporal workflows, refresh tokens before they expire:
|
||||||
|
|
||||||
```go
|
```go
|
||||||
// Customer A's workflow
|
client := routing.NewLLMClientWithAuth(auth)
|
||||||
authA := &routing.LLMAuth{
|
|
||||||
Type: routing.AuthTypeBearer,
|
|
||||||
Token: tokenA,
|
|
||||||
TenantID: "customer-A", // ← Isolates this customer
|
|
||||||
}
|
|
||||||
|
|
||||||
// Customer B's workflow
|
// Later: token expires
|
||||||
authB := &routing.LLMAuth{
|
newToken := os.Getenv("LLM_AUTH_TOKEN_REFRESHED")
|
||||||
|
newAuth := &routing.LLMAuth{
|
||||||
Type: routing.AuthTypeBearer,
|
Type: routing.AuthTypeBearer,
|
||||||
Token: tokenB,
|
Token: newToken,
|
||||||
TenantID: "customer-B", // ← Isolates this customer
|
|
||||||
}
|
}
|
||||||
|
client.UpdateAuth(newAuth)
|
||||||
```
|
```
|
||||||
|
|
||||||
The LLM API server should:
|
### Authorization: LLM API Side
|
||||||
- Validate tenant ownership of tokens
|
|
||||||
- Enforce data boundaries per tenant
|
|
||||||
- Log access per tenant ID
|
|
||||||
- Rate-limit per tenant
|
|
||||||
|
|
||||||
### Scope-Based Access Control
|
The LLM provider (api.riotpiao.com) should:
|
||||||
|
- Validate JWT signature & expiration
|
||||||
|
- Enforce API rate limits per token
|
||||||
|
- Log all requests with token identity
|
||||||
|
- Support token revocation / blacklisting
|
||||||
|
|
||||||
Use OAuth2 scopes to limit capabilities:
|
---
|
||||||
|
|
||||||
|
## AssumeRoleActivity: Temporary LLM Token Grants
|
||||||
|
|
||||||
|
**Like AWS AssumeRole**, AssumeRoleActivity requests temporary credentials for accessing LLM APIs:
|
||||||
|
|
||||||
```go
|
```go
|
||||||
// Analytics-only customer
|
// 1. User requests temporary token
|
||||||
analytics := &routing.LLMAuth{
|
assumeRoleInput := &routing.AssumeRoleInput{
|
||||||
Type: routing.AuthTypeBearer,
|
Identity: "[email protected]", // Who is accessing
|
||||||
Token: token,
|
Scope: "llm:read llm:write", // What permissions
|
||||||
Scopes: "llm:read", // Read-only
|
DurationSeconds: 1800, // 30 minutes
|
||||||
}
|
}
|
||||||
|
|
||||||
// Full-access customer
|
// 2. Activity exchanges with auth server → returns JWT
|
||||||
admin := &routing.LLMAuth{
|
output, err := temporalClient.ExecuteActivity(ctx,
|
||||||
|
routing.AssumeRoleActivity,
|
||||||
|
assumeRoleInput)
|
||||||
|
|
||||||
|
// 3. Extract token from result
|
||||||
|
var tokenOutput *routing.AssumeRoleOutput
|
||||||
|
output.Get(&tokenOutput)
|
||||||
|
|
||||||
|
// 4. Use token in LLM Router
|
||||||
|
auth := &routing.LLMAuth{
|
||||||
Type: routing.AuthTypeBearer,
|
Type: routing.AuthTypeBearer,
|
||||||
Token: token,
|
Token: tokenOutput.Token, // ← JWT valid for 30 minutes
|
||||||
Scopes: "llm:read llm:write llm:admin", // Full access
|
|
||||||
}
|
}
|
||||||
|
router := routing.NewLLMRouter(config)
|
||||||
```
|
```
|
||||||
|
|
||||||
The LLM API server should validate scopes before executing requests.
|
### Workflow Pattern: AssumeRole → LLM Router → Activities
|
||||||
|
|
||||||
### Audit & Compliance
|
```go
|
||||||
|
// Step 1: Get temporary credentials
|
||||||
|
assumeRoleResult := workflow.ExecuteActivity(ctx, routing.AssumeRoleActivity, &routing.AssumeRoleInput{
|
||||||
|
Identity: workflowInput.UserID,
|
||||||
|
Scope: "llm:read llm:write",
|
||||||
|
DurationSeconds: 1800,
|
||||||
|
})
|
||||||
|
var token *routing.AssumeRoleOutput
|
||||||
|
assumeRoleResult.Get(&token)
|
||||||
|
|
||||||
All requests include identifying headers for audit trails:
|
// Step 2: Use token for all LLM router calls
|
||||||
|
routerInput := &routing.LLMRouterInput{
|
||||||
|
Message: "Analyze code for security",
|
||||||
|
Context: map[string]interface{}{"repo": "myrepo"},
|
||||||
|
}
|
||||||
|
|
||||||
|
routerOutput := workflow.ExecuteActivity(ctx, routing.LLMRouterActivity, routerInput)
|
||||||
|
// LLMRouter automatically uses the token from LLMRouterConfig
|
||||||
|
|
||||||
|
// Step 3: Execute generated workflow with same token
|
||||||
|
// (token baked into all activity calls)
|
||||||
```
|
```
|
||||||
POST /v1/chat/completions
|
|
||||||
Authorization: Bearer eyJhbGc...
|
|
||||||
X-Tenant-ID: customer-A
|
|
||||||
X-OAuth-Scopes: llm:read
|
|
||||||
|
|
||||||
# Server logs:
|
### Configuration: Credentials from Vault
|
||||||
# timestamp=2024-01-15T10:30:00Z tenant=customer-A scope=llm:read status=200 tokens=1500
|
|
||||||
|
Never hardcode credentials. Use Kubernetes Secrets or Hashicorp Vault:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# In K8s secret
|
||||||
|
kubectl create secret generic llm-oauth-creds \
|
||||||
|
--from-literal=OAUTH_CLIENT_ID="client-xxx" \
|
||||||
|
--from-literal=OAUTH_CLIENT_SECRET="secret-yyy" \
|
||||||
|
--from-literal=AUTH_SERVER_URL="https://auth.company.com"
|
||||||
|
|
||||||
|
# Pod reads from secret
|
||||||
|
env:
|
||||||
|
- name: OAUTH_CLIENT_ID
|
||||||
|
valueFrom:
|
||||||
|
secretKeyRef:
|
||||||
|
name: llm-oauth-creds
|
||||||
|
key: OAUTH_CLIENT_ID
|
||||||
```
|
```
|
||||||
|
|
||||||
|
In code, AssumeRoleActivity reads from environment:
|
||||||
|
```go
|
||||||
|
input := &routing.AssumeRoleInput{
|
||||||
|
Identity: "[email protected]",
|
||||||
|
Scope: "llm:read",
|
||||||
|
// clientId, clientSecret, authServerUrl read from env automatically
|
||||||
|
}
|
||||||
|
result, _ := AssumeRoleActivity(ctx, input)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Token Lifecycle
|
||||||
|
|
||||||
|
| Stage | Duration | Action |
|
||||||
|
|-------|----------|--------|
|
||||||
|
| **Request** | T+0s | User calls AssumeRoleActivity with identity + scope |
|
||||||
|
| **Grant** | T+1s | Auth server validates, issues JWT (default: 1hr validity) |
|
||||||
|
| **Use** | T+1s to T+3600s | LLMRouter uses token for all api.riotpiao.com calls |
|
||||||
|
| **Refresh** | Before expiry | If workflow > 1hr, request new token via AssumeRole again |
|
||||||
|
| **Revoke** | On demand | Auth server can immediately revoke token if needed |
|
||||||
|
|
||||||
|
### Scopes & Access Control
|
||||||
|
|
||||||
|
Scopes define granular permissions:
|
||||||
|
|
||||||
|
```go
|
||||||
|
// Read-only access (safe for analytics)
|
||||||
|
asScope: "llm:read"
|
||||||
|
|
||||||
|
// Full access (for agent workflows)
|
||||||
|
scope: "llm:read llm:write"
|
||||||
|
|
||||||
|
// Admin access (for operator/setup)
|
||||||
|
scope: "llm:admin"
|
||||||
|
```
|
||||||
|
|
||||||
|
The LLM API validates scopes on every request. AssumeRoleActivity can't escalate privileges—scopes returned by auth server are trusted.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
|
|||||||
@@ -1,93 +0,0 @@
|
|||||||
package action
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/rockliang/poimen/workflows/action/llm"
|
|
||||||
"github.com/rockliang/poimen/workflows/prompts"
|
|
||||||
"github.com/rockliang/poimen/workflows/statemachine"
|
|
||||||
"go.temporal.io/sdk/activity"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ImplementerInput is input to ImplementerActivity.
|
|
||||||
type ImplementerInput struct {
|
|
||||||
Config statemachine.OrchestratorConfig
|
|
||||||
TaskID string
|
|
||||||
WorktreePath string
|
|
||||||
Lessons string // "known errors — do not repeat" section
|
|
||||||
}
|
|
||||||
|
|
||||||
// ImplementerOutput is the output of ImplementerActivity.
|
|
||||||
type ImplementerOutput struct {
|
|
||||||
Success bool
|
|
||||||
Changes string // summary of changes made
|
|
||||||
}
|
|
||||||
|
|
||||||
// ImplementerActivity calls the Implementer LLM to implement the task.
|
|
||||||
func ImplementerActivity(ctx context.Context, in ImplementerInput) (ImplementerOutput, error) {
|
|
||||||
// Record heartbeat
|
|
||||||
activity.RecordHeartbeat(ctx, "starting implementer for "+in.TaskID)
|
|
||||||
|
|
||||||
// Get LLM client
|
|
||||||
client, err := llm.NewClient()
|
|
||||||
if err != nil {
|
|
||||||
return ImplementerOutput{}, fmt.Errorf("failed to create LLM client: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get implementer spec
|
|
||||||
implementerSpec, exists := in.Config.RolePrompts["implementer"]
|
|
||||||
if !exists {
|
|
||||||
return ImplementerOutput{}, fmt.Errorf("implementer role prompt not configured")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Build variables for template
|
|
||||||
templateVars := map[string]any{
|
|
||||||
"SystemPrompt": in.Config.SystemPrompt,
|
|
||||||
"Task": in.TaskID,
|
|
||||||
"WorktreePath": in.WorktreePath,
|
|
||||||
}
|
|
||||||
|
|
||||||
// Inject lessons if provided
|
|
||||||
if in.Lessons != "" {
|
|
||||||
templateVars["Lessons"] = in.Lessons
|
|
||||||
}
|
|
||||||
|
|
||||||
// Render template
|
|
||||||
var templateContent string
|
|
||||||
if implementerSpec.RawTemplate != "" {
|
|
||||||
templateContent = implementerSpec.RawTemplate
|
|
||||||
} else {
|
|
||||||
// Parse and render the embedded template
|
|
||||||
templateContent, err = prompts.Render(implementerSpec.TemplateRef, templateVars)
|
|
||||||
if err != nil {
|
|
||||||
return ImplementerOutput{}, fmt.Errorf("failed to render implementer template: %w", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Call LLM
|
|
||||||
messages := []llm.MessageParam{
|
|
||||||
{
|
|
||||||
Role: "user",
|
|
||||||
Content: templateContent,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
response, err := client.CreateMessage(ctx, llm.MessageInput{
|
|
||||||
Model: implementerSpec.Model,
|
|
||||||
SystemPrompt: in.Config.SystemPrompt,
|
|
||||||
Messages: messages,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return ImplementerOutput{}, fmt.Errorf("implementer LLM call failed: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Record progress
|
|
||||||
activity.RecordHeartbeat(ctx, "implementer completed for "+in.TaskID)
|
|
||||||
|
|
||||||
// Return success (in full implementation would parse response and execute tool calls)
|
|
||||||
return ImplementerOutput{
|
|
||||||
Success: true,
|
|
||||||
Changes: response,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
@@ -1,78 +0,0 @@
|
|||||||
package action
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/rockliang/poimen/workflows/action/llm"
|
|
||||||
"github.com/rockliang/poimen/workflows/prompts"
|
|
||||||
"github.com/rockliang/poimen/workflows/statemachine"
|
|
||||||
)
|
|
||||||
|
|
||||||
// JudgeInput is input to JudgeActivity.
|
|
||||||
type JudgeInput struct {
|
|
||||||
Config statemachine.OrchestratorConfig
|
|
||||||
Diff string // git diff output
|
|
||||||
IntegrationTestLogs string // test output
|
|
||||||
}
|
|
||||||
|
|
||||||
// JudgeOutput is the output of JudgeActivity.
|
|
||||||
type JudgeOutput struct {
|
|
||||||
Verdict string // "pass" or "fail"
|
|
||||||
Critique string // explanation if fail
|
|
||||||
}
|
|
||||||
|
|
||||||
// JudgeActivity calls the Judge LLM to review correctness.
|
|
||||||
func JudgeActivity(ctx context.Context, in JudgeInput) (JudgeOutput, error) {
|
|
||||||
// Get LLM client
|
|
||||||
client, err := llm.NewClient()
|
|
||||||
if err != nil {
|
|
||||||
return JudgeOutput{}, fmt.Errorf("failed to create LLM client: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get judge spec
|
|
||||||
judgeSpec, exists := in.Config.RolePrompts["judge"]
|
|
||||||
if !exists {
|
|
||||||
return JudgeOutput{}, fmt.Errorf("judge role prompt not configured")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Render template
|
|
||||||
var templateContent string
|
|
||||||
if judgeSpec.RawTemplate != "" {
|
|
||||||
templateContent = judgeSpec.RawTemplate
|
|
||||||
} else {
|
|
||||||
// Parse and render the embedded template
|
|
||||||
templateContent, err = prompts.Render(judgeSpec.TemplateRef, map[string]any{
|
|
||||||
"SystemPrompt": in.Config.SystemPrompt,
|
|
||||||
"Diff": in.Diff,
|
|
||||||
"TestResult": in.IntegrationTestLogs,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return JudgeOutput{}, fmt.Errorf("failed to render judge template: %w", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Call LLM
|
|
||||||
messages := []llm.MessageParam{
|
|
||||||
{
|
|
||||||
Role: "user",
|
|
||||||
Content: templateContent,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
response, err := client.CreateMessage(ctx, llm.MessageInput{
|
|
||||||
Model: judgeSpec.Model,
|
|
||||||
SystemPrompt: in.Config.SystemPrompt,
|
|
||||||
Messages: messages,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return JudgeOutput{}, fmt.Errorf("judge LLM call failed: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// For now, return a default pass verdict
|
|
||||||
// In full implementation, would parse LLM response
|
|
||||||
return JudgeOutput{
|
|
||||||
Verdict: "pass",
|
|
||||||
Critique: response,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
@@ -1,91 +0,0 @@
|
|||||||
package action
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/rockliang/poimen/workflows/action/llm"
|
|
||||||
"github.com/rockliang/poimen/workflows/prompts"
|
|
||||||
"github.com/rockliang/poimen/workflows/statemachine"
|
|
||||||
)
|
|
||||||
|
|
||||||
// PlanningInput is input to PlanningActivity.
|
|
||||||
type PlanningInput struct {
|
|
||||||
Config statemachine.OrchestratorConfig
|
|
||||||
BoardState string // JSON or markdown of task board
|
|
||||||
RepoPath string // Path to target repository
|
|
||||||
Milestone string // e.g., "T0"
|
|
||||||
TaskResults []statemachine.TaskUnitOutput // Results from completed tasks
|
|
||||||
}
|
|
||||||
|
|
||||||
// TaskDispatch represents a dispatched task.
|
|
||||||
type TaskDispatch struct {
|
|
||||||
TaskID string
|
|
||||||
PromptSpec statemachine.PromptSpec
|
|
||||||
BaseTimeout *int64 // optional override in milliseconds
|
|
||||||
}
|
|
||||||
|
|
||||||
// PlanningOutput is the output of PlanningActivity.
|
|
||||||
type PlanningOutput struct {
|
|
||||||
TasksToDispatch []string // Task IDs to dispatch in this cycle
|
|
||||||
CompletedBranches []string // Branches to squash merge (when milestone complete)
|
|
||||||
SubmilestoneComplete bool // Whether the milestone is complete
|
|
||||||
}
|
|
||||||
|
|
||||||
// PlanningActivity calls the Planner LLM to decide which tasks to dispatch.
|
|
||||||
func PlanningActivity(ctx context.Context, in PlanningInput) (PlanningOutput, error) {
|
|
||||||
// Get LLM client
|
|
||||||
client, err := llm.NewClient()
|
|
||||||
if err != nil {
|
|
||||||
return PlanningOutput{}, fmt.Errorf("failed to create LLM client: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get planner spec
|
|
||||||
plannerSpec, exists := in.Config.RolePrompts["planner"]
|
|
||||||
if !exists {
|
|
||||||
return PlanningOutput{}, fmt.Errorf("planner role prompt not configured")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Render template
|
|
||||||
var templateContent string
|
|
||||||
if plannerSpec.RawTemplate != "" {
|
|
||||||
templateContent = plannerSpec.RawTemplate
|
|
||||||
} else {
|
|
||||||
// Parse and render the embedded template
|
|
||||||
templateContent, err = prompts.Render(plannerSpec.TemplateRef, map[string]any{
|
|
||||||
"SystemPrompt": in.Config.SystemPrompt,
|
|
||||||
"BoardState": in.BoardState,
|
|
||||||
"Milestone": in.Milestone,
|
|
||||||
"Config": in.Config,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return PlanningOutput{}, fmt.Errorf("failed to render planner template: %w", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Call LLM
|
|
||||||
messages := []llm.MessageParam{
|
|
||||||
{
|
|
||||||
Role: "user",
|
|
||||||
Content: templateContent,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
response, err := client.CreateMessage(ctx, llm.MessageInput{
|
|
||||||
Model: plannerSpec.Model,
|
|
||||||
SystemPrompt: in.Config.SystemPrompt,
|
|
||||||
Messages: messages,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return PlanningOutput{}, fmt.Errorf("planner LLM call failed: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// For now, return empty dispatch (will be parsed from LLM response in full implementation)
|
|
||||||
// This is a stub that allows the test to verify the activity is called
|
|
||||||
_ = response
|
|
||||||
return PlanningOutput{
|
|
||||||
TasksToDispatch: []string{},
|
|
||||||
CompletedBranches: []string{},
|
|
||||||
SubmilestoneComplete: false,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package action
|
package activity
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package action
|
package activity
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
@@ -0,0 +1,216 @@
|
|||||||
|
package activity
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// AssumeRoleInput is the input to AssumeRoleActivity
|
||||||
|
type AssumeRoleInput struct {
|
||||||
|
// Identity is the user/service identity requesting access
|
||||||
|
Identity string `json:"identity"`
|
||||||
|
|
||||||
|
// ClientID is the OAuth2/OIDC client ID (from vault or env)
|
||||||
|
ClientID string `json:"clientId,omitempty"`
|
||||||
|
|
||||||
|
// ClientSecret is the OAuth2/OIDC client secret (from vault or env)
|
||||||
|
ClientSecret string `json:"clientSecret,omitempty"`
|
||||||
|
|
||||||
|
// Scope defines what APIs this token can access (e.g., "llm:read llm:write")
|
||||||
|
Scope string `json:"scope"`
|
||||||
|
|
||||||
|
// DurationSeconds is how long the token is valid (default: 3600 = 1 hour)
|
||||||
|
DurationSeconds int `json:"durationSeconds,omitempty"`
|
||||||
|
|
||||||
|
// AuthServerURL is the auth server endpoint (from env if not provided)
|
||||||
|
AuthServerURL string `json:"authServerUrl,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// AssumeRoleOutput is the output from AssumeRoleActivity
|
||||||
|
type AssumeRoleOutput struct {
|
||||||
|
// Token is the JWT token for calling api.riotpiao.com
|
||||||
|
Token string `json:"token"`
|
||||||
|
|
||||||
|
// ExpiresAt is when the token expires (Unix timestamp)
|
||||||
|
ExpiresAt int64 `json:"expiresAt"`
|
||||||
|
|
||||||
|
// ExpiresIn is the duration in seconds until expiration
|
||||||
|
ExpiresIn int `json:"expiresIn"`
|
||||||
|
|
||||||
|
// TokenType is typically "Bearer"
|
||||||
|
TokenType string `json:"tokenType"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// oauthTokenRequest is sent to the auth server
|
||||||
|
type oauthTokenRequest struct {
|
||||||
|
GrantType string `json:"grant_type"`
|
||||||
|
ClientID string `json:"client_id"`
|
||||||
|
ClientSecret string `json:"client_secret"`
|
||||||
|
Scope string `json:"scope"`
|
||||||
|
Subject string `json:"subject,omitempty"` // The identity being assumed
|
||||||
|
}
|
||||||
|
|
||||||
|
// oauthTokenResponse is returned from the auth server
|
||||||
|
type oauthTokenResponse struct {
|
||||||
|
AccessToken string `json:"access_token"`
|
||||||
|
TokenType string `json:"token_type"`
|
||||||
|
ExpiresIn int `json:"expires_in"`
|
||||||
|
Scope string `json:"scope"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// AssumeRoleActivity requests a temporary JWT token for accessing LLM APIs
|
||||||
|
//
|
||||||
|
// This activity works like AWS AssumeRole:
|
||||||
|
// 1. User provides identity + scope of access needed
|
||||||
|
// 2. Activity exchanges credentials with auth server
|
||||||
|
// 3. Returns JWT token valid for a limited time
|
||||||
|
// 4. Caller uses token in subsequent LLM API calls
|
||||||
|
//
|
||||||
|
// Security: Credentials should come from vault/secrets, never hardcoded
|
||||||
|
func AssumeRoleActivity(ctx context.Context, input *AssumeRoleInput) (*AssumeRoleOutput, error) {
|
||||||
|
// Validate inputs
|
||||||
|
if err := validateAssumeRoleInput(input); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolve configuration from input + environment
|
||||||
|
config, err := resolveAssumeRoleConfig(input)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request token from auth server
|
||||||
|
tokenResp, err := requestAuthToken(ctx, config, input)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build output
|
||||||
|
return buildAssumeRoleOutput(tokenResp), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// validateAssumeRoleInput checks required fields
|
||||||
|
func validateAssumeRoleInput(input *AssumeRoleInput) error {
|
||||||
|
if input.Identity == "" {
|
||||||
|
return fmt.Errorf("identity is required")
|
||||||
|
}
|
||||||
|
if input.Scope == "" {
|
||||||
|
return fmt.Errorf("scope is required (e.g., 'llm:read' or 'llm:read llm:write')")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// assumeRoleConfig holds resolved configuration
|
||||||
|
type assumeRoleConfig struct {
|
||||||
|
authServerURL string
|
||||||
|
clientID string
|
||||||
|
clientSecret string
|
||||||
|
duration int
|
||||||
|
}
|
||||||
|
|
||||||
|
// resolveAssumeRoleConfig gets config from input or environment
|
||||||
|
func resolveAssumeRoleConfig(input *AssumeRoleInput) (*assumeRoleConfig, error) {
|
||||||
|
cfg := &assumeRoleConfig{}
|
||||||
|
|
||||||
|
// Helper function to avoid DRY violation
|
||||||
|
getOrEnv := func(val, envKey, fieldName string) (string, error) {
|
||||||
|
if val != "" {
|
||||||
|
return val, nil
|
||||||
|
}
|
||||||
|
if val = os.Getenv(envKey); val != "" {
|
||||||
|
return val, nil
|
||||||
|
}
|
||||||
|
return "", fmt.Errorf("%s not provided and %s not set", fieldName, envKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
var err error
|
||||||
|
if cfg.authServerURL, err = getOrEnv(input.AuthServerURL, "AUTH_SERVER_URL", "authServerUrl"); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if cfg.clientID, err = getOrEnv(input.ClientID, "OAUTH_CLIENT_ID", "clientId"); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if cfg.clientSecret, err = getOrEnv(input.ClientSecret, "OAUTH_CLIENT_SECRET", "clientSecret"); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate and set duration
|
||||||
|
cfg.duration = input.DurationSeconds
|
||||||
|
if cfg.duration == 0 {
|
||||||
|
cfg.duration = 3600 // 1 hour default
|
||||||
|
}
|
||||||
|
if cfg.duration > 86400 {
|
||||||
|
cfg.duration = 86400 // Max 24 hours
|
||||||
|
}
|
||||||
|
|
||||||
|
return cfg, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// requestAuthToken calls the auth server and returns the token response
|
||||||
|
func requestAuthToken(ctx context.Context, config *assumeRoleConfig, input *AssumeRoleInput) (*oauthTokenResponse, error) {
|
||||||
|
tokenReq := oauthTokenRequest{
|
||||||
|
GrantType: "client_credentials",
|
||||||
|
ClientID: config.clientID,
|
||||||
|
ClientSecret: config.clientSecret,
|
||||||
|
Scope: input.Scope,
|
||||||
|
Subject: input.Identity,
|
||||||
|
}
|
||||||
|
|
||||||
|
reqBody, err := json.Marshal(tokenReq)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to marshal token request: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
httpReq, err := http.NewRequestWithContext(ctx, "POST",
|
||||||
|
fmt.Sprintf("%s/oauth/token", config.authServerURL),
|
||||||
|
bytes.NewReader(reqBody))
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to create request: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
httpReq.Header.Set("Content-Type", "application/json")
|
||||||
|
|
||||||
|
client := &http.Client{Timeout: 10 * time.Second}
|
||||||
|
resp, err := client.Do(httpReq)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to call auth server: %w", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
respBody, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to read response: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
return nil, fmt.Errorf("auth server returned status %d: %s", resp.StatusCode, string(respBody))
|
||||||
|
}
|
||||||
|
|
||||||
|
var tokenResp oauthTokenResponse
|
||||||
|
if err := json.Unmarshal(respBody, &tokenResp); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to unmarshal token response: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if tokenResp.AccessToken == "" {
|
||||||
|
return nil, fmt.Errorf("auth server returned empty access token")
|
||||||
|
}
|
||||||
|
|
||||||
|
return &tokenResp, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// buildAssumeRoleOutput constructs the output from token response
|
||||||
|
func buildAssumeRoleOutput(tokenResp *oauthTokenResponse) *AssumeRoleOutput {
|
||||||
|
expiresAt := time.Now().Add(time.Duration(tokenResp.ExpiresIn) * time.Second).Unix()
|
||||||
|
return &AssumeRoleOutput{
|
||||||
|
Token: tokenResp.AccessToken,
|
||||||
|
ExpiresAt: expiresAt,
|
||||||
|
ExpiresIn: tokenResp.ExpiresIn,
|
||||||
|
TokenType: tokenResp.TokenType,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,359 @@
|
|||||||
|
package activity
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/rockliang/poimen/workflows/pkg/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CanvasCompatibilityOutput validation results
|
||||||
|
type CanvasCompatibilityOutput struct {
|
||||||
|
IsValid bool `json:"is_valid"`
|
||||||
|
Incompatibilities []IncompatibilityWarning `json:"incompatibilities"`
|
||||||
|
DisconnectedNodes []string `json:"disconnected_nodes"`
|
||||||
|
Warnings []string `json:"warnings"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// IncompatibilityWarning explains why two activities can't be connected
|
||||||
|
type IncompatibilityWarning struct {
|
||||||
|
Source string `json:"source"` // Source node ID
|
||||||
|
Target string `json:"target"` // Target node ID
|
||||||
|
Reason string `json:"reason"` // Why they can't connect
|
||||||
|
SourceNeeds string `json:"source_needs"` // What source would need to output
|
||||||
|
TargetNeeds string `json:"target_needs"` // What target requires as input
|
||||||
|
Suggestion string `json:"suggestion"` // Suggestion to make it work
|
||||||
|
}
|
||||||
|
|
||||||
|
// ActivitySchema describes what an activity needs/provides
|
||||||
|
type ActivitySchema struct {
|
||||||
|
ActivityType string `json:"activity_type"`
|
||||||
|
Inputs map[string]InputField `json:"inputs"`
|
||||||
|
Outputs map[string]OutputField `json:"outputs"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type InputField struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
Description string `json:"description"`
|
||||||
|
Required bool `json:"required"`
|
||||||
|
Enum []string `json:"enum,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type OutputField struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
Description string `json:"description"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// getActivitySchema returns schema from knowledge base
|
||||||
|
func getActivitySchema(activityType string) (*ActivitySchema, error) {
|
||||||
|
kb := knowledgeBaseData()
|
||||||
|
if kb == "" {
|
||||||
|
return nil, fmt.Errorf("knowledge base not loaded")
|
||||||
|
}
|
||||||
|
|
||||||
|
var activities []map[string]interface{}
|
||||||
|
if err := json.Unmarshal([]byte(kb), &activities); err != nil {
|
||||||
|
// Try to extract activities from full KB structure
|
||||||
|
var fullKB map[string]interface{}
|
||||||
|
if err := json.Unmarshal([]byte(kb), &fullKB); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to parse knowledge base")
|
||||||
|
}
|
||||||
|
if activitiesRaw, ok := fullKB["activities"]; ok {
|
||||||
|
if b, err := json.Marshal(activitiesRaw); err == nil {
|
||||||
|
if err := json.Unmarshal(b, &activities); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to extract activities from KB")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find matching activity
|
||||||
|
for _, act := range activities {
|
||||||
|
if name, ok := act["name"].(string); ok {
|
||||||
|
if toActivityName(activityType) == name {
|
||||||
|
// Convert to ActivitySchema
|
||||||
|
schema := &ActivitySchema{
|
||||||
|
ActivityType: activityType,
|
||||||
|
Inputs: make(map[string]InputField),
|
||||||
|
Outputs: make(map[string]OutputField),
|
||||||
|
}
|
||||||
|
|
||||||
|
if inputs, ok := act["inputs"].(map[string]interface{}); ok {
|
||||||
|
for key, val := range inputs {
|
||||||
|
if field, ok := val.(map[string]interface{}); ok {
|
||||||
|
schema.Inputs[key] = parseInputField(field)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if outputs, ok := act["outputs"].(map[string]interface{}); ok {
|
||||||
|
for key, val := range outputs {
|
||||||
|
if field, ok := val.(map[string]interface{}); ok {
|
||||||
|
schema.Outputs[key] = parseOutputField(field)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return schema, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, fmt.Errorf("activity %s not found in knowledge base", activityType)
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseInputField(data map[string]interface{}) InputField {
|
||||||
|
field := InputField{}
|
||||||
|
if t, ok := data["type"].(string); ok {
|
||||||
|
field.Type = t
|
||||||
|
}
|
||||||
|
if d, ok := data["description"].(string); ok {
|
||||||
|
field.Description = d
|
||||||
|
}
|
||||||
|
if r, ok := data["required"].(bool); ok {
|
||||||
|
field.Required = r
|
||||||
|
}
|
||||||
|
return field
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseOutputField(data map[string]interface{}) OutputField {
|
||||||
|
field := OutputField{}
|
||||||
|
if t, ok := data["type"].(string); ok {
|
||||||
|
field.Type = t
|
||||||
|
}
|
||||||
|
if d, ok := data["description"].(string); ok {
|
||||||
|
field.Description = d
|
||||||
|
}
|
||||||
|
return field
|
||||||
|
}
|
||||||
|
|
||||||
|
// CheckConnectionCompatibility validates if source can connect to target
|
||||||
|
func CheckConnectionCompatibility(sourceNode, targetNode db.WorkflowNode) []IncompatibilityWarning {
|
||||||
|
warnings := []IncompatibilityWarning{}
|
||||||
|
|
||||||
|
sourceSchema, err := getActivitySchema(sourceNode.Type)
|
||||||
|
if err != nil {
|
||||||
|
warnings = append(warnings, IncompatibilityWarning{
|
||||||
|
Source: sourceNode.ID,
|
||||||
|
Target: targetNode.ID,
|
||||||
|
Reason: fmt.Sprintf("Source activity schema not found: %v", err),
|
||||||
|
Suggestion: "Ensure source activity type is registered in knowledge base",
|
||||||
|
})
|
||||||
|
return warnings
|
||||||
|
}
|
||||||
|
|
||||||
|
targetSchema, err := getActivitySchema(targetNode.Type)
|
||||||
|
if err != nil {
|
||||||
|
warnings = append(warnings, IncompatibilityWarning{
|
||||||
|
Source: sourceNode.ID,
|
||||||
|
Target: targetNode.ID,
|
||||||
|
Reason: fmt.Sprintf("Target activity schema not found: %v", err),
|
||||||
|
Suggestion: "Ensure target activity type is registered in knowledge base",
|
||||||
|
})
|
||||||
|
return warnings
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if source produces outputs that target can consume
|
||||||
|
if len(sourceSchema.Outputs) == 0 {
|
||||||
|
warnings = append(warnings, IncompatibilityWarning{
|
||||||
|
Source: sourceNode.ID,
|
||||||
|
Target: targetNode.ID,
|
||||||
|
Reason: fmt.Sprintf("%s produces no outputs", sourceNode.Type),
|
||||||
|
SourceNeeds: "any output",
|
||||||
|
Suggestion: "Source activity must produce outputs",
|
||||||
|
})
|
||||||
|
return warnings
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(targetSchema.Inputs) == 0 {
|
||||||
|
warnings = append(warnings, IncompatibilityWarning{
|
||||||
|
Source: sourceNode.ID,
|
||||||
|
Target: targetNode.ID,
|
||||||
|
Reason: fmt.Sprintf("%s accepts no inputs", targetNode.Type),
|
||||||
|
TargetNeeds: "no input",
|
||||||
|
Suggestion: "Target activity must accept inputs. Check if it's a terminal activity.",
|
||||||
|
})
|
||||||
|
return warnings
|
||||||
|
}
|
||||||
|
|
||||||
|
// Match outputs to inputs
|
||||||
|
sourceOutputs := getOutputNames(sourceSchema.Outputs)
|
||||||
|
targetInputs := getInputNames(targetSchema.Inputs)
|
||||||
|
|
||||||
|
if len(sourceOutputs) == 0 || len(targetInputs) == 0 {
|
||||||
|
warnings = append(warnings, IncompatibilityWarning{
|
||||||
|
Source: sourceNode.ID,
|
||||||
|
Target: targetNode.ID,
|
||||||
|
Reason: "No compatible output/input fields found",
|
||||||
|
SourceNeeds: strings.Join(sourceOutputs, ", "),
|
||||||
|
TargetNeeds: strings.Join(targetInputs, ", "),
|
||||||
|
Suggestion: "Use LLM transformation to map outputs to inputs",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return warnings
|
||||||
|
}
|
||||||
|
|
||||||
|
// CheckCanvasConnectivity analyzes all suggested edges for compatibility
|
||||||
|
func CheckCanvasConnectivity(nodes []db.WorkflowNode, suggestedEdges []EdgeWithWording) []IncompatibilityWarning {
|
||||||
|
warnings := []IncompatibilityWarning{}
|
||||||
|
nodeMap := make(map[string]db.WorkflowNode)
|
||||||
|
for _, n := range nodes {
|
||||||
|
nodeMap[n.ID] = n
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, edge := range suggestedEdges {
|
||||||
|
sourceNode, ok := nodeMap[edge.Source]
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
targetNode, ok := nodeMap[edge.Target]
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
edgeWarnings := CheckConnectionCompatibility(sourceNode, targetNode)
|
||||||
|
warnings = append(warnings, edgeWarnings...)
|
||||||
|
}
|
||||||
|
|
||||||
|
return warnings
|
||||||
|
}
|
||||||
|
|
||||||
|
// IdentifyDisconnectedNodes finds nodes that can't connect to anything
|
||||||
|
func IdentifyDisconnectedNodes(nodes []db.WorkflowNode, suggestedEdges []EdgeWithWording) []string {
|
||||||
|
edgeMap := make(map[string]bool)
|
||||||
|
for _, edge := range suggestedEdges {
|
||||||
|
edgeMap[edge.Source] = true
|
||||||
|
edgeMap[edge.Target] = true
|
||||||
|
}
|
||||||
|
|
||||||
|
var disconnected []string
|
||||||
|
for _, node := range nodes {
|
||||||
|
if !edgeMap[node.ID] {
|
||||||
|
disconnected = append(disconnected, node.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return disconnected
|
||||||
|
}
|
||||||
|
|
||||||
|
// toActivityName converts canvas type to activity name (e.g., "clone-repo" -> "CloneRepoActivity")
|
||||||
|
func toActivityName(canvasType string) string {
|
||||||
|
parts := strings.Split(canvasType, "-")
|
||||||
|
var result string
|
||||||
|
for _, part := range parts {
|
||||||
|
if part != "" {
|
||||||
|
result += strings.ToUpper(part[:1]) + strings.ToLower(part[1:])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result + "Activity"
|
||||||
|
}
|
||||||
|
|
||||||
|
// getOutputNames extracts output field names
|
||||||
|
func getOutputNames(outputs map[string]OutputField) []string {
|
||||||
|
var names []string
|
||||||
|
for name := range outputs {
|
||||||
|
names = append(names, name)
|
||||||
|
}
|
||||||
|
return names
|
||||||
|
}
|
||||||
|
|
||||||
|
// getInputNames extracts input field names (required ones highlighted)
|
||||||
|
func getInputNames(inputs map[string]InputField) []string {
|
||||||
|
var names []string
|
||||||
|
for name, field := range inputs {
|
||||||
|
if field.Required {
|
||||||
|
names = append(names, name+"*")
|
||||||
|
} else {
|
||||||
|
names = append(names, name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return names
|
||||||
|
}
|
||||||
|
|
||||||
|
// SuggestDataTransformation proposes how to connect incompatible activities
|
||||||
|
func SuggestDataTransformation(sourceNode, targetNode db.WorkflowNode) string {
|
||||||
|
sourceSchema, _ := getActivitySchema(sourceNode.Type)
|
||||||
|
targetSchema, _ := getActivitySchema(targetNode.Type)
|
||||||
|
|
||||||
|
if sourceSchema == nil || targetSchema == nil {
|
||||||
|
return "Cannot analyze compatibility without schemas"
|
||||||
|
}
|
||||||
|
|
||||||
|
sourceOuts := getOutputNames(sourceSchema.Outputs)
|
||||||
|
targetIns := getInputNames(targetSchema.Inputs)
|
||||||
|
|
||||||
|
return fmt.Sprintf(
|
||||||
|
"To connect %s → %s:\n"+
|
||||||
|
" %s outputs: %s\n"+
|
||||||
|
" %s needs: %s\n"+
|
||||||
|
" Solution: Use LLM transformation node to map outputs to inputs",
|
||||||
|
sourceNode.Label, targetNode.Label,
|
||||||
|
sourceNode.Type, strings.Join(sourceOuts, ", "),
|
||||||
|
targetNode.Type, strings.Join(targetIns, ", "),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// knowledgeBaseData returns raw KB JSON (stub - implement with actual KB loading)
|
||||||
|
func knowledgeBaseData() string {
|
||||||
|
// This would load from activity_knowledge_base.json
|
||||||
|
// For now, return empty - real implementation loads from file
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// CanvasCompatibilityActivity validates workflow canvas for type mismatches and isolation
|
||||||
|
func CanvasCompatibilityActivity(ctx interface{}, input CanvasCompatibilityInput) (CanvasCompatibilityOutput, error) {
|
||||||
|
output := CanvasCompatibilityOutput{
|
||||||
|
IsValid: true,
|
||||||
|
Incompatibilities: []IncompatibilityWarning{},
|
||||||
|
DisconnectedNodes: []string{},
|
||||||
|
Warnings: []string{},
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check all edges for compatibility
|
||||||
|
for _, edge := range input.Edges {
|
||||||
|
var sourceNode, targetNode *db.WorkflowNode
|
||||||
|
for i := range input.Nodes {
|
||||||
|
if input.Nodes[i].ID == edge.Source {
|
||||||
|
sourceNode = &input.Nodes[i]
|
||||||
|
}
|
||||||
|
if input.Nodes[i].ID == edge.Target {
|
||||||
|
targetNode = &input.Nodes[i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if sourceNode != nil && targetNode != nil {
|
||||||
|
if warning, err := ValidateConnection(sourceNode, targetNode); err != nil {
|
||||||
|
output.IsValid = false
|
||||||
|
output.Incompatibilities = append(output.Incompatibilities, warning)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find disconnected nodes
|
||||||
|
connected := make(map[string]bool)
|
||||||
|
for _, edge := range input.Edges {
|
||||||
|
connected[edge.Source] = true
|
||||||
|
connected[edge.Target] = true
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, node := range input.Nodes {
|
||||||
|
if node.Type == "activity" && !connected[node.ID] {
|
||||||
|
output.DisconnectedNodes = append(output.DisconnectedNodes, node.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return output, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidateConnection checks if two nodes can be connected based on their types.
|
||||||
|
func ValidateConnection(source, target *db.WorkflowNode) (IncompatibilityWarning, error) {
|
||||||
|
if source.Type != "activity" || target.Type != "activity" {
|
||||||
|
return IncompatibilityWarning{
|
||||||
|
Source: source.ID,
|
||||||
|
Target: target.ID,
|
||||||
|
Reason: fmt.Sprintf("Cannot connect %s to %s: both must be activity type", source.Type, target.Type),
|
||||||
|
}, fmt.Errorf("type mismatch")
|
||||||
|
}
|
||||||
|
return IncompatibilityWarning{}, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,253 @@
|
|||||||
|
package activity
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/rockliang/poimen/workflows/activity/llm"
|
||||||
|
"github.com/rockliang/poimen/workflows/pkg/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CanvasReasonerOutput returns suggested edges and reasoning
|
||||||
|
type CanvasReasonerOutput struct {
|
||||||
|
SuggestedEdges []EdgeWithWording `json:"suggested_edges"` // Edges with wording
|
||||||
|
RemovedEdges []db.WorkflowEdge `json:"removed_edges,omitempty"` // Edges to remove
|
||||||
|
Reasoning string `json:"reasoning"` // LLM explanation
|
||||||
|
Confidence float64 `json:"confidence"` // 0.0-1.0
|
||||||
|
IncompatibleEdges []IncompatibilityWarning `json:"incompatible_edges,omitempty"` // Can't connect
|
||||||
|
DisconnectedNodes []string `json:"disconnected_nodes,omitempty"` // No connections
|
||||||
|
UserAlerts []string `json:"user_alerts,omitempty"` // Human-readable warnings
|
||||||
|
}
|
||||||
|
|
||||||
|
// CanvasReasonerActivity uses LLM to infer connections between workflow activities
|
||||||
|
func CanvasReasonerActivity(ctx context.Context, in CanvasReasonerInput) (CanvasReasonerOutput, error) {
|
||||||
|
logger := newActivityLogger(ctx)
|
||||||
|
|
||||||
|
output := CanvasReasonerOutput{
|
||||||
|
SuggestedEdges: []EdgeWithWording{},
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(in.Nodes) == 0 {
|
||||||
|
return output, fmt.Errorf("no nodes provided")
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.Info("Analyzing canvas with %d nodes, %d edges", len(in.Nodes), len(in.Edges))
|
||||||
|
|
||||||
|
// Build activity descriptions for LLM context
|
||||||
|
nodeDesc := buildNodeDescriptions(in.Nodes)
|
||||||
|
edgeDesc := buildEdgeDescriptions(in.Edges)
|
||||||
|
|
||||||
|
// Create prompt for LLM reasoning with relation wording
|
||||||
|
systemPrompt := `You are a workflow automation expert. Analyze activities and suggest logical connections with semantic descriptions.
|
||||||
|
|
||||||
|
CRITICAL RULES:
|
||||||
|
1. Only suggest edges where outputs→inputs match
|
||||||
|
2. Provide relation wording: verb, source_output, target_input
|
||||||
|
3. Assess connection confidence (0.0-1.0)
|
||||||
|
4. Flag type mismatches that need transformers
|
||||||
|
|
||||||
|
Respond with JSON:
|
||||||
|
{
|
||||||
|
"edges": [
|
||||||
|
{
|
||||||
|
"source": "node-1",
|
||||||
|
"target": "node-2",
|
||||||
|
"relation_type": "data-flow|dependency|conditional|parallel",
|
||||||
|
"relation_label": "Node1 outputs X → Node2 requires X",
|
||||||
|
"relation_wording": {
|
||||||
|
"verb": "outputs|depends-on|triggers|etc",
|
||||||
|
"source_output": "field_name (type): description",
|
||||||
|
"target_input": "field_name (type, required?): description",
|
||||||
|
"connection_type": "direct-map|requires-transformer|conditional",
|
||||||
|
"confidence": 0.95,
|
||||||
|
"semantic_match": "Explanation of why this makes sense"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"reasoning": "Overall workflow structure explanation",
|
||||||
|
"confidence": 0.85
|
||||||
|
}`
|
||||||
|
|
||||||
|
userPrompt := fmt.Sprintf(`Canvas Analysis:
|
||||||
|
|
||||||
|
Nodes (including inputs/outputs):
|
||||||
|
%s
|
||||||
|
|
||||||
|
Current Edges:
|
||||||
|
%s
|
||||||
|
|
||||||
|
Task: %s
|
||||||
|
|
||||||
|
KEY RULES:
|
||||||
|
- Preserve existing edges and suggest only NEW edges to add
|
||||||
|
- SKIP any connections where input/output types don't match
|
||||||
|
- If an activity has no outputs, it cannot be a source
|
||||||
|
- If an activity has no inputs, it cannot be a target
|
||||||
|
- Note any activities that are hard to connect (terminal activities, generators, etc)
|
||||||
|
|
||||||
|
Return ONLY valid JSON, no markdown code blocks.`, nodeDesc, edgeDesc, getReasoningTask(in.PreserveExisting))
|
||||||
|
|
||||||
|
logger.Info("Calling LLM reasoning (preserve_existing=%v)", in.PreserveExisting)
|
||||||
|
|
||||||
|
// Call LLM
|
||||||
|
client, err := llm.NewClient()
|
||||||
|
if err != nil {
|
||||||
|
return output, fmt.Errorf("failed to create LLM client: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := client.CreateMessage(ctx, llm.MessageInput{
|
||||||
|
Model: ModelSpec{
|
||||||
|
ModelID: "reasoning", // Use reasoning model for complex analysis
|
||||||
|
},
|
||||||
|
SystemPrompt: systemPrompt,
|
||||||
|
Messages: []llm.MessageParam{
|
||||||
|
{
|
||||||
|
Role: "user",
|
||||||
|
Content: userPrompt,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
AuthToken: in.AuthToken,
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return output, fmt.Errorf("LLM reasoning failed: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse LLM response
|
||||||
|
var reasonerResp struct {
|
||||||
|
Edges []EdgeWithWording `json:"edges"`
|
||||||
|
Reasoning string `json:"reasoning"`
|
||||||
|
Confidence float64 `json:"confidence"`
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := json.Unmarshal([]byte(response), &reasonerResp); err != nil {
|
||||||
|
logger.Warn("Failed to parse LLM response as JSON: %v", err)
|
||||||
|
// Try to extract from response text
|
||||||
|
output.Reasoning = response
|
||||||
|
output.Confidence = 0.5
|
||||||
|
return output, fmt.Errorf("failed to parse LLM response: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate suggested edges
|
||||||
|
nodeMap := make(map[string]bool)
|
||||||
|
for _, n := range in.Nodes {
|
||||||
|
nodeMap[n.ID] = true
|
||||||
|
}
|
||||||
|
|
||||||
|
validEdges := []EdgeWithWording{}
|
||||||
|
for _, edge := range reasonerResp.Edges {
|
||||||
|
if !nodeMap[edge.Source] {
|
||||||
|
logger.Warn("Suggested edge references unknown source: %s", edge.Source)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !nodeMap[edge.Target] {
|
||||||
|
logger.Warn("Suggested edge references unknown target: %s", edge.Target)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// Don't suggest self-loops
|
||||||
|
if edge.Source == edge.Target {
|
||||||
|
logger.Warn("Skipping self-loop: %s", edge.Source)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
validEdges = append(validEdges, edge)
|
||||||
|
}
|
||||||
|
|
||||||
|
output.SuggestedEdges = validEdges
|
||||||
|
output.Reasoning = reasonerResp.Reasoning
|
||||||
|
output.Confidence = reasonerResp.Confidence
|
||||||
|
|
||||||
|
// Check compatibility of suggested edges
|
||||||
|
incompatibilities := CheckCanvasConnectivity(in.Nodes, validEdges)
|
||||||
|
if len(incompatibilities) > 0 {
|
||||||
|
output.IncompatibleEdges = incompatibilities
|
||||||
|
logger.Warn("Found %d incompatible edge connections", len(incompatibilities))
|
||||||
|
|
||||||
|
// Generate user-friendly alerts
|
||||||
|
for i, incompat := range incompatibilities {
|
||||||
|
if i < 5 { // Limit to 5 alerts to avoid spam
|
||||||
|
alert := fmt.Sprintf(
|
||||||
|
"⚠️ %s → %s: %s. %s",
|
||||||
|
incompat.Source, incompat.Target, incompat.Reason, incompat.Suggestion,
|
||||||
|
)
|
||||||
|
output.UserAlerts = append(output.UserAlerts, alert)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Identify disconnected nodes
|
||||||
|
disconnected := IdentifyDisconnectedNodes(in.Nodes, validEdges)
|
||||||
|
if len(disconnected) > 0 {
|
||||||
|
output.DisconnectedNodes = disconnected
|
||||||
|
logger.Warn("Found %d disconnected nodes", len(disconnected))
|
||||||
|
|
||||||
|
for _, nodeID := range disconnected {
|
||||||
|
var label string
|
||||||
|
for _, node := range in.Nodes {
|
||||||
|
if node.ID == nodeID {
|
||||||
|
label = node.Label
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
alert := fmt.Sprintf(
|
||||||
|
"🔌 Node '%s' has no connections. Consider adding edges or removing it.",
|
||||||
|
label,
|
||||||
|
)
|
||||||
|
output.UserAlerts = append(output.UserAlerts, alert)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.Info("LLM suggested %d edges with confidence %.2f | %d incompatibilities | %d disconnected",
|
||||||
|
len(validEdges), output.Confidence, len(incompatibilities), len(disconnected))
|
||||||
|
|
||||||
|
return output, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// buildNodeDescriptions creates readable node descriptions for LLM (including schemas)
|
||||||
|
func buildNodeDescriptions(nodes []db.WorkflowNode) string {
|
||||||
|
var desc string
|
||||||
|
for i, node := range nodes {
|
||||||
|
desc += fmt.Sprintf("%d. [%s] %s (type: %s)\n", i+1, node.ID, node.Label, node.Type)
|
||||||
|
|
||||||
|
// Add input/output schema info
|
||||||
|
if schema, err := getActivitySchema(node.Type); err == nil {
|
||||||
|
if len(schema.Inputs) > 0 {
|
||||||
|
desc += fmt.Sprintf(" INPUTS: %v\n", getInputNames(schema.Inputs))
|
||||||
|
} else {
|
||||||
|
desc += fmt.Sprintf(" INPUTS: none (generator/trigger)\n")
|
||||||
|
}
|
||||||
|
if len(schema.Outputs) > 0 {
|
||||||
|
desc += fmt.Sprintf(" OUTPUTS: %v\n", getOutputNames(schema.Outputs))
|
||||||
|
} else {
|
||||||
|
desc += fmt.Sprintf(" OUTPUTS: none (terminal/sink)\n")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if node.Data != nil {
|
||||||
|
if b, err := json.MarshalIndent(node.Data, " ", " "); err == nil {
|
||||||
|
desc += fmt.Sprintf(" CONFIG: %s\n", string(b))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return desc
|
||||||
|
}
|
||||||
|
|
||||||
|
// buildEdgeDescriptions creates readable edge descriptions for LLM
|
||||||
|
func buildEdgeDescriptions(edges []db.WorkflowEdge) string {
|
||||||
|
if len(edges) == 0 {
|
||||||
|
return "None"
|
||||||
|
}
|
||||||
|
var desc string
|
||||||
|
for i, edge := range edges {
|
||||||
|
desc += fmt.Sprintf("%d. %s → %s\n", i+1, edge.Source, edge.Target)
|
||||||
|
}
|
||||||
|
return desc
|
||||||
|
}
|
||||||
|
|
||||||
|
// getReasoningTask returns task description based on preservation mode
|
||||||
|
func getReasoningTask(preserveExisting bool) string {
|
||||||
|
if preserveExisting {
|
||||||
|
return "Keep all existing edges and suggest ONLY NEW edges to improve workflow"
|
||||||
|
}
|
||||||
|
return "Design optimal workflow by suggesting all connections and noting any redundant edges"
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
package activity
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/rockliang/poimen/workflows/pkg/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
// FetchCanvasRelationsActivity fetches canvas + relations from DB
|
||||||
|
func FetchCanvasRelationsActivity(ctx context.Context, input FetchCanvasRelationsInput) (CanvasWithRelationsData, error) {
|
||||||
|
logger := newActivityLogger(ctx)
|
||||||
|
output := CanvasWithRelationsData{
|
||||||
|
WorkflowID: input.WorkflowID,
|
||||||
|
Version: input.Version,
|
||||||
|
Nodes: []db.WorkflowNode{},
|
||||||
|
Edges: []db.WorkflowEdge{},
|
||||||
|
Relations: []EdgeWithWording{},
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.Info("Fetching canvas relations: %s v%d", input.WorkflowID, input.Version)
|
||||||
|
|
||||||
|
// Get database client from context or activity manager
|
||||||
|
dbClient, ok := ctx.Value("db_client").(*db.DB)
|
||||||
|
if !ok {
|
||||||
|
return output, fmt.Errorf("database client not in context")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fetch workflow
|
||||||
|
workflow, err := dbClient.FetchWorkflow(ctx, input.WorkflowID, "")
|
||||||
|
if err != nil {
|
||||||
|
return output, fmt.Errorf("failed to get workflow: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse canvas nodes and edges
|
||||||
|
var nodes []db.WorkflowNode
|
||||||
|
if err := json.Unmarshal([]byte(workflow.Nodes), &nodes); err != nil {
|
||||||
|
return output, fmt.Errorf("failed to parse nodes: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var edges []db.WorkflowEdge
|
||||||
|
if err := json.Unmarshal([]byte(workflow.Edges), &edges); err != nil {
|
||||||
|
return output, fmt.Errorf("failed to parse edges: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
output.Nodes = nodes
|
||||||
|
output.Edges = edges
|
||||||
|
output.UpdatedAt = workflow.UpdatedAt.String()
|
||||||
|
|
||||||
|
// Fetch workflow relations
|
||||||
|
relations, err := dbClient.GetWorkflowRelations(ctx, input.WorkflowID, input.Version)
|
||||||
|
if err != nil {
|
||||||
|
// Relations may not exist for old canvases - this is OK
|
||||||
|
logger.Warn("Failed to fetch relations: %v", err)
|
||||||
|
return output, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Map to EdgeWithWording
|
||||||
|
for _, rel := range relations {
|
||||||
|
edge := EdgeWithWording{
|
||||||
|
ID: rel.ID,
|
||||||
|
Source: rel.SourceNodeID,
|
||||||
|
Target: rel.TargetNodeID,
|
||||||
|
RelationType: rel.RelationType,
|
||||||
|
RelationLabel: rel.Label,
|
||||||
|
CreatedAt: rel.CreatedAt.String(),
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse relation wording JSON
|
||||||
|
if err := json.Unmarshal(rel.RelationWording, &edge.RelationWording); err != nil {
|
||||||
|
logger.Warn("Failed to parse relation wording: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
output.Relations = append(output.Relations, edge)
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.Info("Fetched %d nodes, %d edges, %d relations", len(output.Nodes), len(output.Edges), len(output.Relations))
|
||||||
|
return output, nil
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package action
|
package activity
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
package activity
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"github.com/rockliang/poimen/workflows/pkg/types"
|
||||||
|
"go.temporal.io/sdk/activity"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ImplementerInput struct {
|
||||||
|
Config types.OrchestratorConfig
|
||||||
|
TaskID string
|
||||||
|
WorktreePath string
|
||||||
|
Lessons string
|
||||||
|
}
|
||||||
|
|
||||||
|
type ImplementerOutput struct {
|
||||||
|
Success bool
|
||||||
|
Changes string
|
||||||
|
}
|
||||||
|
|
||||||
|
func ImplementerActivity(ctx context.Context, in ImplementerInput) (ImplementerOutput, error) {
|
||||||
|
activity.RecordHeartbeat(ctx, "starting implementer for "+in.TaskID)
|
||||||
|
|
||||||
|
vars := map[string]any{
|
||||||
|
"SystemPrompt": in.Config.SystemPrompt,
|
||||||
|
"Task": in.TaskID,
|
||||||
|
"WorktreePath": in.WorktreePath,
|
||||||
|
}
|
||||||
|
if in.Lessons != "" {
|
||||||
|
vars["Lessons"] = in.Lessons
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := CallRoleLLM(ctx, in.Config, "implementer", vars)
|
||||||
|
if err != nil {
|
||||||
|
return ImplementerOutput{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
activity.RecordHeartbeat(ctx, "implementer completed for "+in.TaskID)
|
||||||
|
return ImplementerOutput{Success: true, Changes: response}, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package activity
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// IndexGraphRAGActivity indexes workflow canvas to GraphRAG (stub for now)
|
||||||
|
func IndexGraphRAGActivity(ctx context.Context, input IndexGraphRAGInput) (IndexGraphRAGOutput, error) {
|
||||||
|
output := IndexGraphRAGOutput{
|
||||||
|
WorkflowID: input.WorkflowID,
|
||||||
|
Version: input.Version,
|
||||||
|
Status: "indexed",
|
||||||
|
IndexedEntities: len(input.Nodes),
|
||||||
|
IndexedEdges: len(input.Relations),
|
||||||
|
IndexedAt: time.Now().UTC().Format(time.RFC3339),
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stub implementation - actual GraphRAG indexing would happen here
|
||||||
|
// For now, just return success
|
||||||
|
return output, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// QueryGraphRAGRelationsInput for direct relation discovery
|
||||||
|
type QueryGraphRAGRelationsInput struct {
|
||||||
|
WorkflowID string `json:"workflow_id"`
|
||||||
|
Version int `json:"version"`
|
||||||
|
Query string `json:"query"`
|
||||||
|
TopK int `json:"top_k"`
|
||||||
|
Filters map[string]interface{} `json:"filters,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// QueryGraphRAGRelationsOutput returns discovered relations
|
||||||
|
type QueryGraphRAGRelationsOutput struct {
|
||||||
|
Query string `json:"query"`
|
||||||
|
Results []EdgeWithWording `json:"results"`
|
||||||
|
TotalCount int `json:"total_count"`
|
||||||
|
ExecutionMs int64 `json:"execution_time_ms"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// QueryGraphRAGRelationsActivity queries GraphRAG for relation patterns (stub)
|
||||||
|
func QueryGraphRAGRelationsActivity(ctx context.Context, input QueryGraphRAGRelationsInput) (QueryGraphRAGRelationsOutput, error) {
|
||||||
|
output := QueryGraphRAGRelationsOutput{
|
||||||
|
Query: input.Query,
|
||||||
|
Results: []EdgeWithWording{},
|
||||||
|
TotalCount: 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stub implementation - actual GraphRAG querying would happen here
|
||||||
|
return output, nil
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package action
|
package activity
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package activity
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"github.com/rockliang/poimen/workflows/pkg/types"
|
||||||
|
)
|
||||||
|
|
||||||
|
type JudgeInput struct {
|
||||||
|
Config types.OrchestratorConfig
|
||||||
|
Diff string
|
||||||
|
IntegrationTestLogs string
|
||||||
|
}
|
||||||
|
|
||||||
|
type JudgeOutput struct {
|
||||||
|
Verdict string
|
||||||
|
Critique string
|
||||||
|
}
|
||||||
|
|
||||||
|
func JudgeActivity(ctx context.Context, in JudgeInput) (JudgeOutput, error) {
|
||||||
|
response, err := CallRoleLLM(ctx, in.Config, "judge", map[string]any{
|
||||||
|
"SystemPrompt": in.Config.SystemPrompt,
|
||||||
|
"Diff": in.Diff,
|
||||||
|
"TestResult": in.IntegrationTestLogs,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return JudgeOutput{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: parse LLM response for verdict
|
||||||
|
return JudgeOutput{Verdict: "pass", Critique: response}, nil
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package action
|
package activity
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
@@ -9,7 +9,7 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
|
|
||||||
"github.com/rockliang/poimen/workflows/statemachine"
|
"github.com/rockliang/poimen/workflows/pkg/types"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -54,9 +54,10 @@ func NewClient() (*OpenAIClient, error) {
|
|||||||
|
|
||||||
// MessageInput is the input to CreateMessage.
|
// MessageInput is the input to CreateMessage.
|
||||||
type MessageInput struct {
|
type MessageInput struct {
|
||||||
Model statemachine.ModelSpec
|
Model types.ModelSpec
|
||||||
SystemPrompt string
|
SystemPrompt string
|
||||||
Messages []MessageParam
|
Messages []MessageParam
|
||||||
|
AuthToken string // Optional JWT token for authenticated endpoints
|
||||||
}
|
}
|
||||||
|
|
||||||
// MessageParam represents a message parameter.
|
// MessageParam represents a message parameter.
|
||||||
@@ -136,6 +137,11 @@ func (c *OpenAIClient) CreateMessage(ctx context.Context, in MessageInput) (stri
|
|||||||
|
|
||||||
httpReq.Header.Set("Content-Type", "application/json")
|
httpReq.Header.Set("Content-Type", "application/json")
|
||||||
|
|
||||||
|
// Add authentication header if token provided
|
||||||
|
if in.AuthToken != "" {
|
||||||
|
httpReq.Header.Set("Authorization", fmt.Sprintf("Bearer %s", in.AuthToken))
|
||||||
|
}
|
||||||
|
|
||||||
// Send request
|
// Send request
|
||||||
resp, err := c.httpClient.Do(httpReq)
|
resp, err := c.httpClient.Do(httpReq)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -4,7 +4,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/rockliang/poimen/workflows/statemachine"
|
"github.com/rockliang/poimen/workflows/pkg/types"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestNewClient(t *testing.T) {
|
func TestNewClient(t *testing.T) {
|
||||||
@@ -70,7 +70,7 @@ func TestCreateMessageValidation(t *testing.T) {
|
|||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
in := MessageInput{
|
in := MessageInput{
|
||||||
Model: statemachine.ModelSpec{
|
Model: types.ModelSpec{
|
||||||
ModelID: tt.modelID,
|
ModelID: tt.modelID,
|
||||||
},
|
},
|
||||||
SystemPrompt: "test",
|
SystemPrompt: "test",
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package activity
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/rockliang/poimen/workflows/activity/llm"
|
||||||
|
"github.com/rockliang/poimen/workflows/pkg/types"
|
||||||
|
"github.com/rockliang/poimen/workflows/prompts"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CallRoleLLM is the shared pattern for calling an LLM with a role-based prompt.
|
||||||
|
// Used by planner, implementer, and judge activities (DRY extraction).
|
||||||
|
func CallRoleLLM(ctx context.Context, config types.OrchestratorConfig, role string, vars map[string]any) (string, error) {
|
||||||
|
client, err := llm.NewClient()
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("failed to create LLM client: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
spec, exists := config.RolePrompts[role]
|
||||||
|
if !exists {
|
||||||
|
return "", fmt.Errorf("%s role prompt not configured", role)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Render template
|
||||||
|
var content string
|
||||||
|
if spec.RawTemplate != "" {
|
||||||
|
content = spec.RawTemplate
|
||||||
|
} else {
|
||||||
|
content, err = prompts.Render(spec.TemplateRef, vars)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("failed to render %s template: %w", role, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Call LLM
|
||||||
|
response, err := client.CreateMessage(ctx, llm.MessageInput{
|
||||||
|
Model: spec.Model,
|
||||||
|
SystemPrompt: config.SystemPrompt,
|
||||||
|
Messages: []llm.MessageParam{{Role: "user", Content: content}},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("%s LLM call failed: %w", role, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return response, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
package activity
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/rockliang/poimen/workflows/activity/llm"
|
||||||
|
"github.com/rockliang/poimen/workflows/pkg/types"
|
||||||
|
)
|
||||||
|
|
||||||
|
type LLMInferenceInput struct {
|
||||||
|
Model string `json:"model"`
|
||||||
|
SystemPrompt string `json:"system_prompt"`
|
||||||
|
UserPrompt string `json:"user_prompt"`
|
||||||
|
Temperature float64 `json:"temperature,omitempty"`
|
||||||
|
MaxTokens int `json:"max_tokens,omitempty"`
|
||||||
|
AuthToken string `json:"auth_token,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type LLMInferenceOutput struct {
|
||||||
|
Response string `json:"response"`
|
||||||
|
Model string `json:"model"`
|
||||||
|
StopReason string `json:"stop_reason"`
|
||||||
|
TokensUsed int `json:"tokens_used"`
|
||||||
|
ErrorMessage string `json:"error,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func LLMInferenceActivity(ctx context.Context, in LLMInferenceInput) (LLMInferenceOutput, error) {
|
||||||
|
logger := newActivityLogger(ctx)
|
||||||
|
output := LLMInferenceOutput{Model: in.Model}
|
||||||
|
|
||||||
|
if in.Model == "" {
|
||||||
|
return output, fmt.Errorf("model not specified")
|
||||||
|
}
|
||||||
|
if in.UserPrompt == "" {
|
||||||
|
return output, fmt.Errorf("user_prompt not specified")
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.Info("Starting LLM inference", "model", in.Model)
|
||||||
|
|
||||||
|
client, err := llm.NewClient()
|
||||||
|
if err != nil {
|
||||||
|
output.ErrorMessage = err.Error()
|
||||||
|
return output, fmt.Errorf("failed to create LLM client: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := client.CreateMessage(ctx, llm.MessageInput{
|
||||||
|
Model: types.ModelSpec{ModelID: in.Model},
|
||||||
|
SystemPrompt: in.SystemPrompt,
|
||||||
|
Messages: []llm.MessageParam{{Role: "user", Content: in.UserPrompt}},
|
||||||
|
AuthToken: in.AuthToken,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
output.ErrorMessage = err.Error()
|
||||||
|
logger.Warn("LLM API call failed", "error", err)
|
||||||
|
return output, fmt.Errorf("LLM inference failed: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
output.Response = response
|
||||||
|
output.StopReason = "stop_sequence"
|
||||||
|
logger.Info("LLM inference completed", "response_len", len(response))
|
||||||
|
return output, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type LLMBatchInferenceInput struct {
|
||||||
|
Model string `json:"model"`
|
||||||
|
SystemPrompt string `json:"system_prompt"`
|
||||||
|
Prompts []string `json:"prompts"`
|
||||||
|
Temperature float64 `json:"temperature,omitempty"`
|
||||||
|
AuthToken string `json:"auth_token,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type LLMBatchInferenceOutput struct {
|
||||||
|
Responses []string `json:"responses"`
|
||||||
|
Model string `json:"model"`
|
||||||
|
Errors []string `json:"errors,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func LLMBatchInferenceActivity(ctx context.Context, in LLMBatchInferenceInput) (LLMBatchInferenceOutput, error) {
|
||||||
|
logger := newActivityLogger(ctx)
|
||||||
|
output := LLMBatchInferenceOutput{Model: in.Model, Responses: []string{}, Errors: []string{}}
|
||||||
|
|
||||||
|
if in.Model == "" {
|
||||||
|
return output, fmt.Errorf("model not specified")
|
||||||
|
}
|
||||||
|
if len(in.Prompts) == 0 {
|
||||||
|
return output, fmt.Errorf("no prompts provided")
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.Info("Starting batch inference", "model", in.Model, "count", len(in.Prompts))
|
||||||
|
|
||||||
|
client, err := llm.NewClient()
|
||||||
|
if err != nil {
|
||||||
|
return output, fmt.Errorf("failed to create LLM client: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for i, prompt := range in.Prompts {
|
||||||
|
response, err := client.CreateMessage(ctx, llm.MessageInput{
|
||||||
|
Model: types.ModelSpec{ModelID: in.Model},
|
||||||
|
SystemPrompt: in.SystemPrompt,
|
||||||
|
Messages: []llm.MessageParam{{Role: "user", Content: prompt}},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
output.Errors = append(output.Errors, fmt.Sprintf("prompt %d: %v", i, err))
|
||||||
|
output.Responses = append(output.Responses, "")
|
||||||
|
logger.Warn("Failed prompt", "index", i, "error", err)
|
||||||
|
} else {
|
||||||
|
output.Responses = append(output.Responses, response)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.Info("Batch inference completed", "responses", len(output.Responses), "errors", len(output.Errors))
|
||||||
|
return output, nil
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package action
|
package activity
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package action
|
package activity
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
@@ -92,9 +92,9 @@ func RetrieveMemoryActivity(ctx context.Context, in RetrieveMemoryInput) (Retrie
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Get memory service URL and token
|
// Get memory service URL and token
|
||||||
baseURL := os.Getenv("POIMEN_MEMORY_URL")
|
baseURL := os.Getenv("MEMORY_SERVICE_URL")
|
||||||
if baseURL == "" {
|
if baseURL == "" {
|
||||||
baseURL = "http://poimen-memory.poimen.svc.cluster.local:8080"
|
baseURL = "http://localhost:8080"
|
||||||
}
|
}
|
||||||
|
|
||||||
token := os.Getenv("POIMEN_MEMORY_TOKEN")
|
token := os.Getenv("POIMEN_MEMORY_TOKEN")
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package action
|
package activity
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
@@ -39,7 +39,7 @@ func TestRetrieveMemoryActivity_Query(t *testing.T) {
|
|||||||
defer server.Close()
|
defer server.Close()
|
||||||
|
|
||||||
// Set env for test
|
// Set env for test
|
||||||
t.Setenv("POIMEN_MEMORY_URL", server.URL)
|
t.Setenv("MEMORY_SERVICE_URL", server.URL)
|
||||||
|
|
||||||
output, err := RetrieveMemoryActivity(context.Background(), RetrieveMemoryInput{
|
output, err := RetrieveMemoryActivity(context.Background(), RetrieveMemoryInput{
|
||||||
Query: "security scanning",
|
Query: "security scanning",
|
||||||
@@ -93,7 +93,7 @@ func TestRetrieveMemoryActivity_Context(t *testing.T) {
|
|||||||
}))
|
}))
|
||||||
defer server.Close()
|
defer server.Close()
|
||||||
|
|
||||||
t.Setenv("POIMEN_MEMORY_URL", server.URL)
|
t.Setenv("MEMORY_SERVICE_URL", server.URL)
|
||||||
|
|
||||||
output, err := RetrieveMemoryActivity(context.Background(), RetrieveMemoryInput{
|
output, err := RetrieveMemoryActivity(context.Background(), RetrieveMemoryInput{
|
||||||
Query: "security scan repo",
|
Query: "security scan repo",
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package action
|
package activity
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package action
|
package activity
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package activity
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"github.com/rockliang/poimen/workflows/pkg/types"
|
||||||
|
)
|
||||||
|
|
||||||
|
type PlanningInput struct {
|
||||||
|
Config types.OrchestratorConfig
|
||||||
|
BoardState string
|
||||||
|
RepoPath string
|
||||||
|
Milestone string
|
||||||
|
TaskResults []types.TaskUnitOutput
|
||||||
|
}
|
||||||
|
|
||||||
|
type TaskDispatch struct {
|
||||||
|
TaskID string
|
||||||
|
PromptSpec types.PromptSpec
|
||||||
|
BaseTimeout *int64
|
||||||
|
}
|
||||||
|
|
||||||
|
type PlanningOutput struct {
|
||||||
|
TasksToDispatch []string
|
||||||
|
CompletedBranches []string
|
||||||
|
SubmilestoneComplete bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func PlanningActivity(ctx context.Context, in PlanningInput) (PlanningOutput, error) {
|
||||||
|
response, err := CallRoleLLM(ctx, in.Config, "planner", map[string]any{
|
||||||
|
"SystemPrompt": in.Config.SystemPrompt,
|
||||||
|
"BoardState": in.BoardState,
|
||||||
|
"Milestone": in.Milestone,
|
||||||
|
"Config": in.Config,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return PlanningOutput{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: parse LLM response into task dispatch list
|
||||||
|
_ = response
|
||||||
|
return PlanningOutput{
|
||||||
|
TasksToDispatch: []string{},
|
||||||
|
CompletedBranches: []string{},
|
||||||
|
SubmilestoneComplete: false,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
package activity
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// QueryGraphRAGActivity queries Memory System for semantic relations
|
||||||
|
func QueryGraphRAGActivity(ctx context.Context, input GraphRAGQueryInput) (GraphRAGQueryOutput, error) {
|
||||||
|
logger := newActivityLogger(ctx)
|
||||||
|
output := GraphRAGQueryOutput{
|
||||||
|
WorkflowID: input.WorkflowID,
|
||||||
|
Query: input.Query,
|
||||||
|
Edges: []EdgeWithWording{},
|
||||||
|
Paths: []QueryPathData{},
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.Info("Querying GraphRAG: %s", input.Query)
|
||||||
|
|
||||||
|
// Get Memory Service URL from env
|
||||||
|
memoryURL := os.Getenv("MEMORY_SERVICE_URL")
|
||||||
|
if memoryURL == "" {
|
||||||
|
memoryURL = "http://localhost:8000"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build payload for Memory System
|
||||||
|
payload := map[string]interface{}{
|
||||||
|
"workflow_id": input.WorkflowID,
|
||||||
|
"query": input.Query,
|
||||||
|
"search_type": input.SearchType,
|
||||||
|
"relation_type": input.RelationType,
|
||||||
|
"confidence_floor": input.ConfidenceFloor,
|
||||||
|
"top_k": input.TopK,
|
||||||
|
"ranking_profile": input.RankingProfile,
|
||||||
|
"canvas_nodes": input.Canvas.Nodes,
|
||||||
|
"canvas_edges": input.Canvas.Edges,
|
||||||
|
"relations": input.Canvas.Relations,
|
||||||
|
}
|
||||||
|
|
||||||
|
reqBody, err := json.Marshal(payload)
|
||||||
|
if err != nil {
|
||||||
|
return output, fmt.Errorf("failed to marshal payload: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Call Memory System unified query endpoint
|
||||||
|
req, err := http.NewRequestWithContext(
|
||||||
|
ctx,
|
||||||
|
"POST",
|
||||||
|
memoryURL+"/workflows/query",
|
||||||
|
bytes.NewReader(reqBody),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return output, fmt.Errorf("failed to create request: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
if token := ctx.Value("jwt_token"); token != nil {
|
||||||
|
req.Header.Set("Authorization", fmt.Sprintf("Bearer %v", token))
|
||||||
|
}
|
||||||
|
|
||||||
|
startTime := time.Now()
|
||||||
|
client := &http.Client{Timeout: 30 * time.Second}
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return output, fmt.Errorf("failed to call Memory Service: %w", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode != 200 {
|
||||||
|
body, _ := io.ReadAll(resp.Body)
|
||||||
|
return output, fmt.Errorf("Memory Service returned %d: %s", resp.StatusCode, string(body))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse response
|
||||||
|
var graphResp struct {
|
||||||
|
Edges []EdgeWithWording `json:"edges"`
|
||||||
|
Paths []QueryPathData `json:"paths"`
|
||||||
|
TotalCount int `json:"total_count"`
|
||||||
|
HasMore bool `json:"has_more"`
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&graphResp); err != nil {
|
||||||
|
return output, fmt.Errorf("failed to decode response: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
output.Edges = graphResp.Edges
|
||||||
|
output.Paths = graphResp.Paths
|
||||||
|
output.TotalCount = graphResp.TotalCount
|
||||||
|
output.HasMore = graphResp.HasMore
|
||||||
|
output.ExecutionMs = time.Since(startTime).Milliseconds()
|
||||||
|
|
||||||
|
logger.Info("GraphRAG returned %d edges, %d paths in %dms",
|
||||||
|
len(output.Edges), len(output.Paths), output.ExecutionMs)
|
||||||
|
return output, nil
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package action
|
package activity
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package action
|
package activity
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
@@ -10,12 +10,11 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"go.temporal.io/sdk/activity"
|
"go.temporal.io/sdk/activity"
|
||||||
"github.com/rockliang/poimen/workflows/statemachine"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// PrepareSkillsInput is input to PrepareSkillsActivity.
|
// PrepareSkillsInput is input to PrepareSkillsActivity.
|
||||||
type PrepareSkillsInput struct {
|
type PrepareSkillsInput struct {
|
||||||
Skills []statemachine.SkillRef
|
Skills []SkillRef
|
||||||
StreamTimeout time.Duration
|
StreamTimeout time.Duration
|
||||||
Provider string // pi provider name (e.g. "homelab-reasoning"); required, pi has no usable default provider
|
Provider string // pi provider name (e.g. "homelab-reasoning"); required, pi has no usable default provider
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package activity
|
||||||
|
|
||||||
|
import "github.com/rockliang/poimen/workflows/pkg/types"
|
||||||
|
|
||||||
|
// Re-export from pkg/types for convenience within activity package.
|
||||||
|
type ModelSpec = types.ModelSpec
|
||||||
|
type PromptSpec = types.PromptSpec
|
||||||
|
type SkillRef = types.SkillRef
|
||||||
|
type OrchestratorConfig = types.OrchestratorConfig
|
||||||
|
type TaskUnitOutput = types.TaskUnitOutput
|
||||||
|
type EdgeWithWording = types.EdgeWithWording
|
||||||
|
type RelationWording = types.RelationWording
|
||||||
|
type CanvasWithRelationsData = types.CanvasWithRelationsData
|
||||||
|
type FetchCanvasRelationsInput = types.FetchCanvasRelationsInput
|
||||||
|
type CanvasReasonerInput = types.CanvasReasonerInput
|
||||||
|
type GraphRAGQueryInput = types.GraphRAGQueryInput
|
||||||
|
type GraphRAGQueryOutput = types.GraphRAGQueryOutput
|
||||||
|
type QueryPathData = types.QueryPathData
|
||||||
|
type CanvasCompatibilityInput = types.CanvasCompatibilityInput
|
||||||
|
type IndexGraphRAGInput = types.IndexGraphRAGInput
|
||||||
|
type IndexGraphRAGOutput = types.IndexGraphRAGOutput
|
||||||
+15
-15
@@ -11,12 +11,12 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"go.temporal.io/sdk/client"
|
"go.temporal.io/sdk/client"
|
||||||
"github.com/rockliang/poimen/workflows/action/llm"
|
"github.com/rockliang/poimen/workflows/activity/llm"
|
||||||
"github.com/rockliang/poimen/workflows/internal/config"
|
"github.com/rockliang/poimen/workflows/internal/config"
|
||||||
"github.com/rockliang/poimen/workflows/internal/health"
|
"github.com/rockliang/poimen/workflows/internal/health"
|
||||||
"github.com/rockliang/poimen/workflows/internal/logging"
|
"github.com/rockliang/poimen/workflows/internal/logging"
|
||||||
"github.com/rockliang/poimen/workflows/internal/routing"
|
"github.com/rockliang/poimen/workflows/internal/routing"
|
||||||
"github.com/rockliang/poimen/workflows/statemachine"
|
"github.com/rockliang/poimen/workflows/workflow"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -89,20 +89,20 @@ func main() {
|
|||||||
|
|
||||||
|
|
||||||
// Build OrchestratorInput
|
// Build OrchestratorInput
|
||||||
input := statemachine.OrchestratorInput{
|
input := workflow.OrchestratorInput{
|
||||||
TargetRepoPath: *repoPath,
|
TargetRepoPath: *repoPath,
|
||||||
RemoteURL: *remoteURL,
|
RemoteURL: *remoteURL,
|
||||||
Milestone: *milestone,
|
Milestone: *milestone,
|
||||||
DryRun: *dryRun,
|
DryRun: *dryRun,
|
||||||
MaxCyclesBeforeCAN: 100,
|
MaxCyclesBeforeCAN: 100,
|
||||||
PiProvider: *piProvider,
|
PiProvider: *piProvider,
|
||||||
Config: statemachine.OrchestratorConfig{
|
Config: workflow.OrchestratorConfig{
|
||||||
SystemPrompt: "You are an expert software developer orchestrating multi-agent work.",
|
SystemPrompt: "You are an expert software developer orchestrating multi-agent work.",
|
||||||
Skills: []statemachine.SkillRef{},
|
Skills: []workflow.SkillRef{},
|
||||||
RolePrompts: map[string]statemachine.PromptSpec{
|
RolePrompts: map[string]workflow.PromptSpec{
|
||||||
"planner": {
|
"planner": {
|
||||||
TemplateRef: "planner/default.tmpl",
|
TemplateRef: "planner/default.tmpl",
|
||||||
Model: statemachine.ModelSpec{
|
Model: workflow.ModelSpec{
|
||||||
ModelID: *plannerModel,
|
ModelID: *plannerModel,
|
||||||
Thinking: "adaptive",
|
Thinking: "adaptive",
|
||||||
Effort: "high",
|
Effort: "high",
|
||||||
@@ -110,7 +110,7 @@ func main() {
|
|||||||
},
|
},
|
||||||
"judge": {
|
"judge": {
|
||||||
TemplateRef: "judge/default.tmpl",
|
TemplateRef: "judge/default.tmpl",
|
||||||
Model: statemachine.ModelSpec{
|
Model: workflow.ModelSpec{
|
||||||
ModelID: *judgeModel,
|
ModelID: *judgeModel,
|
||||||
Thinking: "adaptive",
|
Thinking: "adaptive",
|
||||||
Effort: "high",
|
Effort: "high",
|
||||||
@@ -118,12 +118,12 @@ func main() {
|
|||||||
},
|
},
|
||||||
"implementer": {
|
"implementer": {
|
||||||
TemplateRef: "implementer/default.tmpl",
|
TemplateRef: "implementer/default.tmpl",
|
||||||
Model: statemachine.ModelSpec{
|
Model: workflow.ModelSpec{
|
||||||
ModelID: *implementerModel,
|
ModelID: *implementerModel,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
Tuning: statemachine.NewActivityTuning(),
|
Tuning: workflow.NewActivityTuning(),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -144,7 +144,7 @@ func main() {
|
|||||||
run, err := c.ExecuteWorkflow(context.Background(), client.StartWorkflowOptions{
|
run, err := c.ExecuteWorkflow(context.Background(), client.StartWorkflowOptions{
|
||||||
ID: workflowID,
|
ID: workflowID,
|
||||||
TaskQueue: "poimen-taskqueue",
|
TaskQueue: "poimen-taskqueue",
|
||||||
}, statemachine.OrchestratorWorkflow, input)
|
}, workflow.OrchestratorWorkflow, input)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logging.Fatal("failed to start workflow", logging.Err(err))
|
logging.Fatal("failed to start workflow", logging.Err(err))
|
||||||
}
|
}
|
||||||
@@ -164,7 +164,7 @@ func main() {
|
|||||||
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute)
|
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
var result statemachine.OrchestratorOutput
|
var result workflow.OrchestratorOutput
|
||||||
if err := run.Get(ctx, &result); err != nil {
|
if err := run.Get(ctx, &result); err != nil {
|
||||||
fmt.Printf("\nWorkflow initiated (execution in progress).\n")
|
fmt.Printf("\nWorkflow initiated (execution in progress).\n")
|
||||||
fmt.Printf("Check the Web UI for real-time status updates.\n")
|
fmt.Printf("Check the Web UI for real-time status updates.\n")
|
||||||
@@ -267,12 +267,12 @@ func runRoutingWorkflow(c client.Client, routeMsg, specFile string, isCron, dryR
|
|||||||
}
|
}
|
||||||
|
|
||||||
workflowID := "routing-" + spec.Name + "-" + time.Now().Format("20060102-150405")
|
workflowID := "routing-" + spec.Name + "-" + time.Now().Format("20060102-150405")
|
||||||
input := statemachine.RoutingWorkflowInput{Spec: spec}
|
input := workflow.RoutingWorkflowInput{Spec: spec}
|
||||||
|
|
||||||
run, err := c.ExecuteWorkflow(ctx, client.StartWorkflowOptions{
|
run, err := c.ExecuteWorkflow(ctx, client.StartWorkflowOptions{
|
||||||
ID: workflowID,
|
ID: workflowID,
|
||||||
TaskQueue: "poimen-taskqueue",
|
TaskQueue: "poimen-taskqueue",
|
||||||
}, statemachine.RoutingWorkflow, input)
|
}, workflow.RoutingWorkflow, input)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logging.Fatal("failed to start routing workflow", logging.Err(err))
|
logging.Fatal("failed to start routing workflow", logging.Err(err))
|
||||||
}
|
}
|
||||||
@@ -285,7 +285,7 @@ func runRoutingWorkflow(c client.Client, routeMsg, specFile string, isCron, dryR
|
|||||||
waitCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
waitCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
var result statemachine.RoutingWorkflowOutput
|
var result workflow.RoutingWorkflowOutput
|
||||||
if err := run.Get(waitCtx, &result); err != nil {
|
if err := run.Get(waitCtx, &result); err != nil {
|
||||||
fmt.Printf("\nWorkflow running (check Temporal UI for status)\n")
|
fmt.Printf("\nWorkflow running (check Temporal UI for status)\n")
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
+42
-31
@@ -11,11 +11,11 @@ import (
|
|||||||
|
|
||||||
"go.temporal.io/sdk/client"
|
"go.temporal.io/sdk/client"
|
||||||
"go.temporal.io/sdk/worker"
|
"go.temporal.io/sdk/worker"
|
||||||
"github.com/rockliang/poimen/workflows/action"
|
"github.com/rockliang/poimen/workflows/activity"
|
||||||
"github.com/rockliang/poimen/workflows/internal/config"
|
"github.com/rockliang/poimen/workflows/internal/config"
|
||||||
"github.com/rockliang/poimen/workflows/internal/health"
|
"github.com/rockliang/poimen/workflows/internal/health"
|
||||||
"github.com/rockliang/poimen/workflows/internal/logging"
|
"github.com/rockliang/poimen/workflows/internal/logging"
|
||||||
"github.com/rockliang/poimen/workflows/statemachine"
|
"github.com/rockliang/poimen/workflows/workflow"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -48,45 +48,56 @@ func main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Register all workflows
|
// Register all workflows
|
||||||
w.RegisterWorkflow(statemachine.OrchestratorWorkflow)
|
w.RegisterWorkflow(workflow.OrchestratorWorkflow)
|
||||||
w.RegisterWorkflow(statemachine.TaskUnitWorkflow)
|
w.RegisterWorkflow(workflow.TaskUnitWorkflow)
|
||||||
w.RegisterWorkflow(statemachine.TestWorkflow)
|
w.RegisterWorkflow(workflow.TestWorkflow)
|
||||||
w.RegisterWorkflow(statemachine.RoutingWorkflow)
|
w.RegisterWorkflow(workflow.RoutingWorkflow)
|
||||||
|
w.RegisterWorkflow(workflow.WorkflowGraphQuery)
|
||||||
|
|
||||||
// Register all activities
|
// Register all activities
|
||||||
w.RegisterActivity(action.CloneRepoActivity)
|
w.RegisterActivity(activity.CloneRepoActivity)
|
||||||
w.RegisterActivity(action.GitWorktreeAddActivity)
|
w.RegisterActivity(activity.GitWorktreeAddActivity)
|
||||||
w.RegisterActivity(action.GitCommitActivity)
|
w.RegisterActivity(activity.GitCommitActivity)
|
||||||
w.RegisterActivity(action.GitPushActivity)
|
w.RegisterActivity(activity.GitPushActivity)
|
||||||
w.RegisterActivity(action.GitSquashMergeActivity)
|
w.RegisterActivity(activity.GitSquashMergeActivity)
|
||||||
w.RegisterActivity(action.GitDiffActivity)
|
w.RegisterActivity(activity.GitDiffActivity)
|
||||||
w.RegisterActivity(action.PrepareSkillsActivity)
|
w.RegisterActivity(activity.PrepareSkillsActivity)
|
||||||
w.RegisterActivity(action.PlanningActivity)
|
w.RegisterActivity(activity.PlanningActivity)
|
||||||
w.RegisterActivity(action.ImplementerActivity)
|
w.RegisterActivity(activity.ImplementerActivity)
|
||||||
w.RegisterActivity(action.JudgeActivity)
|
w.RegisterActivity(activity.JudgeActivity)
|
||||||
// Integration and lessons activities - register when fully tested
|
// Integration and lessons activities - register when fully tested
|
||||||
w.RegisterActivity(action.RunIntegrationTestActivity)
|
w.RegisterActivity(activity.RunIntegrationTestActivity)
|
||||||
// w.RegisterActivity(action.UpdateLessonsActivity)
|
// w.RegisterActivity(activity.UpdateLessonsActivity)
|
||||||
// w.RegisterActivity(action.ReadLessonsActivity)
|
// w.RegisterActivity(activity.ReadLessonsActivity)
|
||||||
|
|
||||||
// Routing workflow activities
|
// Routing workflow activities
|
||||||
w.RegisterActivity(action.LLMRouterActivity)
|
w.RegisterActivity(activity.LLMRouterActivity)
|
||||||
w.RegisterActivity(action.ValidateWorkflowSpecActivity)
|
w.RegisterActivity(activity.ValidateWorkflowSpecActivity)
|
||||||
w.RegisterActivity(action.ValidateCronWorkflowSpecActivity)
|
w.RegisterActivity(activity.ValidateCronWorkflowSpecActivity)
|
||||||
|
|
||||||
// Analysis activities
|
// Analysis activities
|
||||||
w.RegisterActivity(action.AnalyzeCodeActivity)
|
w.RegisterActivity(activity.AnalyzeCodeActivity)
|
||||||
w.RegisterActivity(action.SecurityScanActivity)
|
w.RegisterActivity(activity.SecurityScanActivity)
|
||||||
w.RegisterActivity(action.GenerateReportActivity)
|
w.RegisterActivity(activity.GenerateReportActivity)
|
||||||
|
|
||||||
// Notification and utility activities
|
// Notification and utility activities
|
||||||
w.RegisterActivity(action.NotifyStatusActivity)
|
w.RegisterActivity(activity.NotifyStatusActivity)
|
||||||
w.RegisterActivity(action.ArchiveResultsActivity)
|
w.RegisterActivity(activity.ArchiveResultsActivity)
|
||||||
w.RegisterActivity(action.DeploymentPreCheckActivity)
|
w.RegisterActivity(activity.DeploymentPreCheckActivity)
|
||||||
w.RegisterActivity(action.ApproveWorkflowActivity)
|
w.RegisterActivity(activity.ApproveWorkflowActivity)
|
||||||
|
|
||||||
|
// Authentication activities
|
||||||
|
w.RegisterActivity(activity.AssumeRoleActivity)
|
||||||
|
|
||||||
// Memory activities
|
// Memory activities
|
||||||
w.RegisterActivity(action.RetrieveMemoryActivity)
|
w.RegisterActivity(activity.RetrieveMemoryActivity)
|
||||||
|
|
||||||
|
// GraphRAG activities
|
||||||
|
w.RegisterActivity(activity.FetchCanvasRelationsActivity)
|
||||||
|
w.RegisterActivity(activity.QueryGraphRAGActivity)
|
||||||
|
w.RegisterActivity(activity.CanvasReasonerActivity)
|
||||||
|
w.RegisterActivity(activity.IndexGraphRAGActivity)
|
||||||
|
w.RegisterActivity(activity.CanvasCompatibilityActivity)
|
||||||
|
|
||||||
// Initialize health checker
|
// Initialize health checker
|
||||||
healthChecker := health.NewChecker(c)
|
healthChecker := health.NewChecker(c)
|
||||||
@@ -116,7 +127,7 @@ func main() {
|
|||||||
// Run worker in a goroutine
|
// Run worker in a goroutine
|
||||||
workerErrChan := make(chan error, 1)
|
workerErrChan := make(chan error, 1)
|
||||||
go func() {
|
go func() {
|
||||||
logging.Info("starting worker on queue", logging.String("queue", "poimen-taskqueue"))
|
logging.Info("starting worker", logging.String("queue", "poimen"))
|
||||||
if err := w.Run(worker.InterruptCh()); err != nil {
|
if err := w.Run(worker.InterruptCh()); err != nil {
|
||||||
workerErrChan <- err
|
workerErrChan <- err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
module github.com/rockliang/poimen/workflows
|
module github.com/rockliang/poimen/workflows
|
||||||
|
|
||||||
go 1.25.4
|
go 1.26.0
|
||||||
|
|
||||||
require (
|
require (
|
||||||
|
github.com/google/uuid v1.6.0
|
||||||
|
github.com/lib/pq v1.12.3
|
||||||
github.com/prometheus/client_golang v1.24.1
|
github.com/prometheus/client_golang v1.24.1
|
||||||
github.com/stretchr/testify v1.12.1
|
github.com/stretchr/testify v1.12.1
|
||||||
go.temporal.io/sdk v1.48.0
|
go.temporal.io/sdk v1.48.0
|
||||||
@@ -16,10 +18,8 @@ require (
|
|||||||
github.com/facebookgo/clock v0.0.0-20150410010913-600d898af40a // indirect
|
github.com/facebookgo/clock v0.0.0-20150410010913-600d898af40a // indirect
|
||||||
github.com/gogo/protobuf v1.3.2 // indirect
|
github.com/gogo/protobuf v1.3.2 // indirect
|
||||||
github.com/golang/mock v1.6.0 // indirect
|
github.com/golang/mock v1.6.0 // indirect
|
||||||
github.com/google/uuid v1.6.0 // indirect
|
|
||||||
github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.2 // indirect
|
github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.2 // indirect
|
||||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.22.0 // indirect
|
github.com/grpc-ecosystem/grpc-gateway/v2 v2.22.0 // indirect
|
||||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
|
||||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||||
github.com/nexus-rpc/nexus-proto-annotations v0.1.0 // indirect
|
github.com/nexus-rpc/nexus-proto-annotations v0.1.0 // indirect
|
||||||
github.com/nexus-rpc/sdk-go v0.7.0 // indirect
|
github.com/nexus-rpc/sdk-go v0.7.0 // indirect
|
||||||
@@ -27,8 +27,6 @@ require (
|
|||||||
github.com/prometheus/common v0.70.1 // indirect
|
github.com/prometheus/common v0.70.1 // indirect
|
||||||
github.com/prometheus/procfs v0.21.1 // indirect
|
github.com/prometheus/procfs v0.21.1 // indirect
|
||||||
github.com/robfig/cron v1.2.0 // indirect
|
github.com/robfig/cron v1.2.0 // indirect
|
||||||
github.com/spf13/cobra v1.10.2 // indirect
|
|
||||||
github.com/spf13/pflag v1.0.9 // indirect
|
|
||||||
github.com/stretchr/objx v0.5.3 // indirect
|
github.com/stretchr/objx v0.5.3 // indirect
|
||||||
go.temporal.io/api v1.63.4 // indirect
|
go.temporal.io/api v1.63.4 // indirect
|
||||||
go.uber.org/multierr v1.11.0 // indirect
|
go.uber.org/multierr v1.11.0 // indirect
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
|||||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||||
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
|
|
||||||
github.com/facebookgo/clock v0.0.0-20150410010913-600d898af40a h1:yDWHCSQ40h88yih2JAcL6Ls/kVkSE8GFACTGVnMPruw=
|
github.com/facebookgo/clock v0.0.0-20150410010913-600d898af40a h1:yDWHCSQ40h88yih2JAcL6Ls/kVkSE8GFACTGVnMPruw=
|
||||||
github.com/facebookgo/clock v0.0.0-20150410010913-600d898af40a/go.mod h1:7Ga40egUymuWXxAe151lTNnCv97MddSOVsjpPPkityA=
|
github.com/facebookgo/clock v0.0.0-20150410010913-600d898af40a/go.mod h1:7Ga40egUymuWXxAe151lTNnCv97MddSOVsjpPPkityA=
|
||||||
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||||
@@ -23,8 +22,6 @@ github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.2 h1:sGm2vDRFUrQJO/Veii4h4z
|
|||||||
github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.2/go.mod h1:wd1YpapPLivG6nQgbf7ZkG1hhSOXDhhn4MLTknx2aAc=
|
github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.2/go.mod h1:wd1YpapPLivG6nQgbf7ZkG1hhSOXDhhn4MLTknx2aAc=
|
||||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.22.0 h1:asbCHRVmodnJTuQ3qamDwqVOIjwqUPTYmYuemVOx+Ys=
|
github.com/grpc-ecosystem/grpc-gateway/v2 v2.22.0 h1:asbCHRVmodnJTuQ3qamDwqVOIjwqUPTYmYuemVOx+Ys=
|
||||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.22.0/go.mod h1:ggCgvZ2r7uOoQjOyu2Y1NhHmEPPzzuhWgcza5M1Ji1I=
|
github.com/grpc-ecosystem/grpc-gateway/v2 v2.22.0/go.mod h1:ggCgvZ2r7uOoQjOyu2Y1NhHmEPPzzuhWgcza5M1Ji1I=
|
||||||
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
|
||||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
|
||||||
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
|
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
|
||||||
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
|
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
|
||||||
github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk=
|
github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk=
|
||||||
@@ -35,6 +32,8 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
|||||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||||
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
|
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
|
||||||
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
|
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
|
||||||
|
github.com/lib/pq v1.12.3 h1:tTWxr2YLKwIvK90ZXEw8GP7UFHtcbTtty8zsI+YjrfQ=
|
||||||
|
github.com/lib/pq v1.12.3/go.mod h1:/p+8NSbOcwzAEI7wiMXFlgydTwcgTr3OSKMsD2BitpA=
|
||||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
|
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
|
||||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
||||||
github.com/nexus-rpc/nexus-proto-annotations v0.1.0 h1:2fELd+9sqUtNu6Fg//pw8YFsxOvp8vZ8hfP0nHhNI80=
|
github.com/nexus-rpc/nexus-proto-annotations v0.1.0 h1:2fELd+9sqUtNu6Fg//pw8YFsxOvp8vZ8hfP0nHhNI80=
|
||||||
@@ -53,11 +52,6 @@ github.com/robfig/cron v1.2.0 h1:ZjScXvvxeQ63Dbyxy76Fj3AT3Ut0aKsyd2/tl3DTMuQ=
|
|||||||
github.com/robfig/cron v1.2.0/go.mod h1:JGuDeoQd7Z6yL4zQhZ3OPEVHB7fL6Ka6skscFHfmt2k=
|
github.com/robfig/cron v1.2.0/go.mod h1:JGuDeoQd7Z6yL4zQhZ3OPEVHB7fL6Ka6skscFHfmt2k=
|
||||||
github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M=
|
github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M=
|
||||||
github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA=
|
github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA=
|
||||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
|
||||||
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
|
|
||||||
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
|
|
||||||
github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
|
|
||||||
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
|
||||||
github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4=
|
github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4=
|
||||||
github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0=
|
github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0=
|
||||||
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
||||||
@@ -89,7 +83,6 @@ go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo=
|
|||||||
go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q=
|
go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q=
|
||||||
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
|
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
|
||||||
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
|
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
|
||||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
|
||||||
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||||
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||||
|
|||||||
@@ -407,11 +407,265 @@
|
|||||||
"dependencies": [],
|
"dependencies": [],
|
||||||
"notes": "Network-dependent. First activity to run for context-aware routing. Fast timeout."
|
"notes": "Network-dependent. First activity to run for context-aware routing. Fast timeout."
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "AssumeRoleActivity",
|
||||||
|
"description": "Request temporary JWT token for accessing LLM APIs (like AWS AssumeRole)",
|
||||||
|
"category": "authentication",
|
||||||
|
"inputs": {
|
||||||
|
"identity": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "User/service identity requesting access",
|
||||||
|
"required": true,
|
||||||
|
"examples": ["[email protected]", "service:poimen-worker"]
|
||||||
|
},
|
||||||
|
"clientId": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "OAuth2 client ID (from vault if not provided)",
|
||||||
|
"required": false
|
||||||
|
},
|
||||||
|
"clientSecret": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "OAuth2 client secret (from vault if not provided)",
|
||||||
|
"required": false
|
||||||
|
},
|
||||||
|
"scope": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Scope of access (e.g., 'llm:read' or 'llm:read llm:write')",
|
||||||
|
"required": true,
|
||||||
|
"examples": ["llm:read", "llm:read llm:write", "llm:admin"]
|
||||||
|
},
|
||||||
|
"durationSeconds": {
|
||||||
|
"type": "integer",
|
||||||
|
"description": "Token validity duration in seconds (default: 3600, max: 86400)",
|
||||||
|
"required": false,
|
||||||
|
"default": 3600
|
||||||
|
},
|
||||||
|
"authServerUrl": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Auth server URL (from AUTH_SERVER_URL env if not provided)",
|
||||||
|
"required": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"outputs": {
|
||||||
|
"token": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "JWT token for calling api.riotpiao.com"
|
||||||
|
},
|
||||||
|
"expiresAt": {
|
||||||
|
"type": "integer",
|
||||||
|
"description": "Token expiration time (Unix timestamp)"
|
||||||
|
},
|
||||||
|
"expiresIn": {
|
||||||
|
"type": "integer",
|
||||||
|
"description": "Seconds until token expires"
|
||||||
|
},
|
||||||
|
"tokenType": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Token type (typically 'Bearer')"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"constraints": {
|
||||||
|
"defaultTimeout": "30s",
|
||||||
|
"isFlaky": false,
|
||||||
|
"recommendedRetries": 2,
|
||||||
|
"retryBackoff": 1.5,
|
||||||
|
"dependencies": [],
|
||||||
|
"notes": "Must run before LLM Router to provide auth token. Call early in workflow."
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "LLMInferenceActivity",
|
||||||
|
"description": "Call LLM API with custom prompt and get response text",
|
||||||
|
"category": "llm",
|
||||||
|
"inputs": {
|
||||||
|
"model": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Model ID (reasoning, ornith:35b, ornith:13b, qwen2.5:3b)",
|
||||||
|
"required": true,
|
||||||
|
"examples": ["reasoning", "ornith:35b"]
|
||||||
|
},
|
||||||
|
"system_prompt": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "System instruction for the model",
|
||||||
|
"required": false,
|
||||||
|
"default": ""
|
||||||
|
},
|
||||||
|
"user_prompt": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "User message to send to the model",
|
||||||
|
"required": true
|
||||||
|
},
|
||||||
|
"temperature": {
|
||||||
|
"type": "number",
|
||||||
|
"description": "Sampling temperature (0.0-1.0, higher=more creative)",
|
||||||
|
"required": false,
|
||||||
|
"default": 0.7
|
||||||
|
},
|
||||||
|
"max_tokens": {
|
||||||
|
"type": "integer",
|
||||||
|
"description": "Maximum tokens in response",
|
||||||
|
"required": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"outputs": {
|
||||||
|
"response": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "LLM response text"
|
||||||
|
},
|
||||||
|
"model": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Model used for inference"
|
||||||
|
},
|
||||||
|
"stop_reason": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Why inference stopped (stop_sequence, length, etc)"
|
||||||
|
},
|
||||||
|
"tokens_used": {
|
||||||
|
"type": "integer",
|
||||||
|
"description": "Total tokens consumed"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"constraints": {
|
||||||
|
"defaultTimeout": "120s",
|
||||||
|
"isFlaky": true,
|
||||||
|
"recommendedRetries": 2,
|
||||||
|
"retryBackoff": 2.0,
|
||||||
|
"dependencies": [],
|
||||||
|
"notes": "API-dependent. Network flaky. Use for single prompts. See LLMBatchInferenceActivity for multiple."
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "LLMBatchInferenceActivity",
|
||||||
|
"description": "Call LLM API multiple times sequentially with different prompts",
|
||||||
|
"category": "llm",
|
||||||
|
"inputs": {
|
||||||
|
"model": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Model ID (reasoning, ornith:35b, ornith:13b, qwen2.5:3b)",
|
||||||
|
"required": true
|
||||||
|
},
|
||||||
|
"system_prompt": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "System instruction (same for all prompts)",
|
||||||
|
"required": false
|
||||||
|
},
|
||||||
|
"prompts": {
|
||||||
|
"type": "array",
|
||||||
|
"description": "List of user prompts to process",
|
||||||
|
"required": true,
|
||||||
|
"items": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"temperature": {
|
||||||
|
"type": "number",
|
||||||
|
"description": "Sampling temperature (0.0-1.0)",
|
||||||
|
"required": false,
|
||||||
|
"default": 0.7
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"outputs": {
|
||||||
|
"responses": {
|
||||||
|
"type": "array",
|
||||||
|
"description": "List of LLM responses (parallel to input prompts)",
|
||||||
|
"items": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"model": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Model used"
|
||||||
|
},
|
||||||
|
"errors": {
|
||||||
|
"type": "array",
|
||||||
|
"description": "Error messages for failed prompts",
|
||||||
|
"items": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"constraints": {
|
||||||
|
"defaultTimeout": "600s",
|
||||||
|
"isFlaky": true,
|
||||||
|
"recommendedRetries": 1,
|
||||||
|
"retryBackoff": 2.0,
|
||||||
|
"dependencies": [],
|
||||||
|
"notes": "Sequential processing of multiple prompts. Use for batch analysis, summarization, etc."
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "CanvasReasonerActivity",
|
||||||
|
"description": "Use LLM reasoning to infer and suggest connections between workflow activities",
|
||||||
|
"category": "workflow",
|
||||||
|
"inputs": {
|
||||||
|
"nodes": {
|
||||||
|
"type": "array",
|
||||||
|
"description": "Canvas workflow nodes to analyze",
|
||||||
|
"required": true,
|
||||||
|
"items": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"id": {"type": "string"},
|
||||||
|
"type": {"type": "string"},
|
||||||
|
"label": {"type": "string"}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"edges": {
|
||||||
|
"type": "array",
|
||||||
|
"description": "Existing edges in the workflow",
|
||||||
|
"required": false,
|
||||||
|
"items": {
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"preserve_existing": {
|
||||||
|
"type": "boolean",
|
||||||
|
"description": "If true, only suggest new edges; if false, redesign entire workflow",
|
||||||
|
"required": false,
|
||||||
|
"default": true
|
||||||
|
},
|
||||||
|
"auth_token": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "JWT token for authenticated LLM calls",
|
||||||
|
"required": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"outputs": {
|
||||||
|
"suggested_edges": {
|
||||||
|
"type": "array",
|
||||||
|
"description": "Edges suggested by LLM reasoning",
|
||||||
|
"items": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"source": {"type": "string"},
|
||||||
|
"target": {"type": "string"}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"reasoning": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "LLM explanation of suggested connections"
|
||||||
|
},
|
||||||
|
"confidence": {
|
||||||
|
"type": "number",
|
||||||
|
"description": "Confidence score (0.0-1.0) of the suggestions"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"constraints": {
|
||||||
|
"defaultTimeout": "120s",
|
||||||
|
"isFlaky": true,
|
||||||
|
"recommendedRetries": 2,
|
||||||
|
"retryBackoff": 2.0,
|
||||||
|
"dependencies": [],
|
||||||
|
"notes": "Uses reasoning model to analyze workflow logic. Good for understanding data flow and connections between activities."
|
||||||
|
}
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"totalActivities": 9,
|
"totalActivities": 13,
|
||||||
"lastUpdated": "2025-08-31T00:00:00Z",
|
"lastUpdated": "2025-09-05T00:00:00Z",
|
||||||
"categories": {
|
"categories": {
|
||||||
"repository": 1,
|
"repository": 1,
|
||||||
"analysis": 1,
|
"analysis": 1,
|
||||||
@@ -421,7 +675,10 @@
|
|||||||
"notification": 1,
|
"notification": 1,
|
||||||
"approval": 1,
|
"approval": 1,
|
||||||
"storage": 1,
|
"storage": 1,
|
||||||
"memory": 1
|
"memory": 1,
|
||||||
|
"authentication": 1,
|
||||||
|
"llm": 2,
|
||||||
|
"workflow": 1
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,179 @@
|
|||||||
|
package routing
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/rockliang/poimen/workflows/pkg/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CanvasConverter converts visual canvas to executable WorkflowSpec
|
||||||
|
type CanvasConverter struct {
|
||||||
|
validator *CanvasValidator
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewCanvasConverter creates a converter
|
||||||
|
func NewCanvasConverter() *CanvasConverter {
|
||||||
|
return &CanvasConverter{
|
||||||
|
validator: NewCanvasValidator(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// CanvasToWorkflowSpec converts canvas to WorkflowSpec
|
||||||
|
func (cc *CanvasConverter) CanvasToWorkflowSpec(canvas *db.Canvas) (*WorkflowSpec, error) {
|
||||||
|
// Validate first
|
||||||
|
if err := cc.validator.ValidateCanvas(canvas); err != nil {
|
||||||
|
return nil, fmt.Errorf("canvas validation failed: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get topological order
|
||||||
|
sortedNodes, err := cc.validator.TopoSort(canvas.Nodes, canvas.Edges)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("topological sort failed: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build states from sorted nodes
|
||||||
|
states := []State{}
|
||||||
|
nodeToState := make(map[string]int) // node ID to state index
|
||||||
|
|
||||||
|
for i, node := range sortedNodes {
|
||||||
|
state := cc.nodeToState(node, canvas.Edges)
|
||||||
|
states = append(states, state)
|
||||||
|
nodeToState[node.ID] = i
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wire up transitions
|
||||||
|
for i, node := range sortedNodes {
|
||||||
|
outgoing := cc.getOutgoingEdges(node.ID, canvas.Edges)
|
||||||
|
|
||||||
|
if len(outgoing) == 0 {
|
||||||
|
// Last state - no transitions
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(outgoing) == 1 {
|
||||||
|
// Single outgoing edge
|
||||||
|
targetNode := outgoing[0]
|
||||||
|
targetIdx := nodeToState[targetNode]
|
||||||
|
if targetIdx > i {
|
||||||
|
states[i].Next = states[targetIdx].Name
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Multiple outgoing edges - parallel
|
||||||
|
states[i].Type = "Parallel"
|
||||||
|
branches := []interface{}{}
|
||||||
|
for _, targetNode := range outgoing {
|
||||||
|
branches = append(branches, map[string]string{
|
||||||
|
"state": states[nodeToState[targetNode]].Name,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if states[i].Branches == nil {
|
||||||
|
states[i].Branches = branches
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
spec := &WorkflowSpec{
|
||||||
|
Name: canvas.Name,
|
||||||
|
Input: map[string]interface{}{},
|
||||||
|
States: states,
|
||||||
|
}
|
||||||
|
|
||||||
|
return spec, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// nodeToState converts a canvas node to a workflow state
|
||||||
|
func (cc *CanvasConverter) nodeToState(node db.WorkflowNode, edges []db.WorkflowEdge) State {
|
||||||
|
// Map node type to activity name
|
||||||
|
activityName := cc.mapActivityType(node.Type)
|
||||||
|
|
||||||
|
state := State{
|
||||||
|
Name: node.ID,
|
||||||
|
Type: TaskActivity,
|
||||||
|
Activity: activityName,
|
||||||
|
Retry: &RetryPolicy{MaxAttempts: 3, BackoffSeconds: 2},
|
||||||
|
Timeout: "300s",
|
||||||
|
Parameters: node.Data,
|
||||||
|
}
|
||||||
|
|
||||||
|
return state
|
||||||
|
}
|
||||||
|
|
||||||
|
// mapActivityType maps canvas activity type to Poimen activity
|
||||||
|
func (cc *CanvasConverter) mapActivityType(canvasType string) string {
|
||||||
|
typeMap := map[string]string{
|
||||||
|
"clone-repo": "CloneRepoActivity",
|
||||||
|
"analyze-code": "AnalyzeCodeActivity",
|
||||||
|
"security-scan": "SecurityScanActivity",
|
||||||
|
"generate-report": "GenerateReportActivity",
|
||||||
|
"deployment-precheck": "DeploymentPreCheckActivity",
|
||||||
|
"notify-status": "NotifyStatusActivity",
|
||||||
|
"approve-workflow": "ApproveWorkflowActivity",
|
||||||
|
"archive-results": "ArchiveResultsActivity",
|
||||||
|
"retrieve-memory": "RetrieveMemoryActivity",
|
||||||
|
"assume-role": "AssumeRoleActivity",
|
||||||
|
"llm-inference": "LLMInferenceActivity",
|
||||||
|
"llm-batch-inference": "LLMBatchInferenceActivity",
|
||||||
|
"canvas-reasoner": "CanvasReasonerActivity",
|
||||||
|
}
|
||||||
|
|
||||||
|
if mapped, ok := typeMap[canvasType]; ok {
|
||||||
|
return mapped
|
||||||
|
}
|
||||||
|
|
||||||
|
return canvasType // fallback to type as-is
|
||||||
|
}
|
||||||
|
|
||||||
|
// getOutgoingEdges returns target node IDs for a given source node
|
||||||
|
func (cc *CanvasConverter) getOutgoingEdges(nodeID string, edges []db.WorkflowEdge) []string {
|
||||||
|
targets := []string{}
|
||||||
|
seen := make(map[string]bool)
|
||||||
|
|
||||||
|
for _, edge := range edges {
|
||||||
|
if edge.Source == nodeID && !seen[edge.Target] {
|
||||||
|
targets = append(targets, edge.Target)
|
||||||
|
seen[edge.Target] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return targets
|
||||||
|
}
|
||||||
|
|
||||||
|
// CanvasToExecutionPlan converts canvas to sequential activity list
|
||||||
|
func (cc *CanvasConverter) CanvasToExecutionPlan(canvas *db.Canvas) ([]ExecutionStep, error) {
|
||||||
|
// Validate first
|
||||||
|
if err := cc.validator.ValidateCanvas(canvas); err != nil {
|
||||||
|
return nil, fmt.Errorf("canvas validation failed: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get topological order
|
||||||
|
sortedNodes, err := cc.validator.TopoSort(canvas.Nodes, canvas.Edges)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("topological sort failed: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
steps := []ExecutionStep{}
|
||||||
|
for i, node := range sortedNodes {
|
||||||
|
step := ExecutionStep{
|
||||||
|
Index: i,
|
||||||
|
NodeID: node.ID,
|
||||||
|
ActivityName: cc.mapActivityType(node.Type),
|
||||||
|
Label: node.Label,
|
||||||
|
Parameters: node.Data,
|
||||||
|
Timeout: "300s",
|
||||||
|
}
|
||||||
|
steps = append(steps, step)
|
||||||
|
}
|
||||||
|
|
||||||
|
return steps, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ExecutionStep represents one activity in execution plan
|
||||||
|
type ExecutionStep struct {
|
||||||
|
Index int `json:"index"`
|
||||||
|
NodeID string `json:"node_id"`
|
||||||
|
ActivityName string `json:"activity_name"`
|
||||||
|
Label string `json:"label"`
|
||||||
|
Parameters map[string]interface{} `json:"parameters"`
|
||||||
|
Timeout string `json:"timeout"`
|
||||||
|
DependsOn []int `json:"depends_on,omitempty"` // Indices of predecessor steps
|
||||||
|
}
|
||||||
@@ -0,0 +1,317 @@
|
|||||||
|
package routing
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/rockliang/poimen/workflows/pkg/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CanvasValidator validates React Flow canvas (nodes + edges)
|
||||||
|
type CanvasValidator struct {
|
||||||
|
activityRegistry map[string]bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewCanvasValidator creates validator with activity registry
|
||||||
|
func NewCanvasValidator() *CanvasValidator {
|
||||||
|
return &CanvasValidator{
|
||||||
|
activityRegistry: map[string]bool{
|
||||||
|
"clone-repo": true,
|
||||||
|
"analyze-code": true,
|
||||||
|
"security-scan": true,
|
||||||
|
"generate-report": true,
|
||||||
|
"deployment-precheck": true,
|
||||||
|
"notify-status": true,
|
||||||
|
"approve-workflow": true,
|
||||||
|
"archive-results": true,
|
||||||
|
"retrieve-memory": true,
|
||||||
|
"assume-role": true,
|
||||||
|
"llm-inference": true,
|
||||||
|
"llm-batch-inference": true,
|
||||||
|
"canvas-reasoner": true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidateCanvas checks canvas structure, connectivity, and DAG
|
||||||
|
func (cv *CanvasValidator) ValidateCanvas(canvas *db.Canvas) error {
|
||||||
|
if canvas == nil {
|
||||||
|
return fmt.Errorf("canvas is nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(canvas.Nodes) == 0 {
|
||||||
|
return fmt.Errorf("canvas has no nodes")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 1: Validate nodes
|
||||||
|
if err := cv.validateNodes(canvas.Nodes); err != nil {
|
||||||
|
return fmt.Errorf("node validation failed: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 2: Validate edges
|
||||||
|
if err := cv.validateEdges(canvas.Nodes, canvas.Edges); err != nil {
|
||||||
|
return fmt.Errorf("edge validation failed: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 3: Check for cycles (must be DAG)
|
||||||
|
if err := cv.detectCycles(canvas.Nodes, canvas.Edges); err != nil {
|
||||||
|
return fmt.Errorf("cycle detected: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 4: Check connectivity (all nodes reachable from start)
|
||||||
|
if err := cv.validateConnectivity(canvas.Nodes, canvas.Edges); err != nil {
|
||||||
|
return fmt.Errorf("connectivity check failed: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// validateNodes checks each node has required fields and valid type
|
||||||
|
func (cv *CanvasValidator) validateNodes(nodes []db.WorkflowNode) error {
|
||||||
|
if len(nodes) == 0 {
|
||||||
|
return fmt.Errorf("no nodes in canvas")
|
||||||
|
}
|
||||||
|
|
||||||
|
nodeIds := make(map[string]bool)
|
||||||
|
|
||||||
|
for i, node := range nodes {
|
||||||
|
// Check required fields
|
||||||
|
if node.ID == "" {
|
||||||
|
return fmt.Errorf("node[%d] has empty ID", i)
|
||||||
|
}
|
||||||
|
|
||||||
|
if nodeIds[node.ID] {
|
||||||
|
return fmt.Errorf("node[%d] has duplicate ID: %s", i, node.ID)
|
||||||
|
}
|
||||||
|
nodeIds[node.ID] = true
|
||||||
|
|
||||||
|
if node.Label == "" {
|
||||||
|
return fmt.Errorf("node[%d] (%s) has empty label", i, node.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
if node.Position == nil {
|
||||||
|
return fmt.Errorf("node[%d] (%s) has no position", i, node.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check activity type (if present)
|
||||||
|
if node.Type != "" && !cv.activityRegistry[strings.ToLower(node.Type)] {
|
||||||
|
return fmt.Errorf("node[%d] (%s) has unknown activity type: %s", i, node.ID, node.Type)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check data structure
|
||||||
|
if node.Data == nil {
|
||||||
|
return fmt.Errorf("node[%d] (%s) has no data", i, node.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// validateEdges checks edges reference valid nodes
|
||||||
|
func (cv *CanvasValidator) validateEdges(nodes []db.WorkflowNode, edges []db.WorkflowEdge) error {
|
||||||
|
nodeIds := make(map[string]bool)
|
||||||
|
for _, node := range nodes {
|
||||||
|
nodeIds[node.ID] = true
|
||||||
|
}
|
||||||
|
|
||||||
|
for i, edge := range edges {
|
||||||
|
// Check required fields
|
||||||
|
if edge.Source == "" {
|
||||||
|
return fmt.Errorf("edge[%d] has empty source", i)
|
||||||
|
}
|
||||||
|
|
||||||
|
if edge.Target == "" {
|
||||||
|
return fmt.Errorf("edge[%d] has empty target", i)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check source node exists
|
||||||
|
if !nodeIds[edge.Source] {
|
||||||
|
return fmt.Errorf("edge[%d] references unknown source node: %s", i, edge.Source)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check target node exists
|
||||||
|
if !nodeIds[edge.Target] {
|
||||||
|
return fmt.Errorf("edge[%d] references unknown target node: %s", i, edge.Target)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check self-loops (discouraged but allow for now)
|
||||||
|
if edge.Source == edge.Target {
|
||||||
|
// Could warn here but not fail
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// detectCycles checks for cycles in the DAG (must be acyclic)
|
||||||
|
func (cv *CanvasValidator) detectCycles(nodes []db.WorkflowNode, edges []db.WorkflowEdge) error {
|
||||||
|
// Build adjacency list
|
||||||
|
graph := make(map[string][]string)
|
||||||
|
inDegree := make(map[string]int)
|
||||||
|
|
||||||
|
for _, node := range nodes {
|
||||||
|
graph[node.ID] = []string{}
|
||||||
|
inDegree[node.ID] = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, edge := range edges {
|
||||||
|
graph[edge.Source] = append(graph[edge.Source], edge.Target)
|
||||||
|
inDegree[edge.Target]++
|
||||||
|
}
|
||||||
|
|
||||||
|
// Kahn's algorithm: topological sort
|
||||||
|
queue := []string{}
|
||||||
|
for _, node := range nodes {
|
||||||
|
if inDegree[node.ID] == 0 {
|
||||||
|
queue = append(queue, node.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
processed := 0
|
||||||
|
for len(queue) > 0 {
|
||||||
|
// Dequeue
|
||||||
|
current := queue[0]
|
||||||
|
queue = queue[1:]
|
||||||
|
processed++
|
||||||
|
|
||||||
|
// Visit neighbors
|
||||||
|
for _, neighbor := range graph[current] {
|
||||||
|
inDegree[neighbor]--
|
||||||
|
if inDegree[neighbor] == 0 {
|
||||||
|
queue = append(queue, neighbor)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If we didn't process all nodes, there's a cycle
|
||||||
|
if processed != len(nodes) {
|
||||||
|
return fmt.Errorf("graph has cycle (processed %d/%d nodes)", processed, len(nodes))
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// validateConnectivity checks all nodes are reachable from start nodes
|
||||||
|
func (cv *CanvasValidator) validateConnectivity(nodes []db.WorkflowNode, edges []db.WorkflowEdge) error {
|
||||||
|
if len(nodes) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build adjacency list
|
||||||
|
graph := make(map[string][]string)
|
||||||
|
inDegree := make(map[string]int)
|
||||||
|
|
||||||
|
for _, node := range nodes {
|
||||||
|
graph[node.ID] = []string{}
|
||||||
|
inDegree[node.ID] = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, edge := range edges {
|
||||||
|
graph[edge.Source] = append(graph[edge.Source], edge.Target)
|
||||||
|
inDegree[edge.Target]++
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find start nodes (in-degree 0)
|
||||||
|
startNodes := []string{}
|
||||||
|
for _, node := range nodes {
|
||||||
|
if inDegree[node.ID] == 0 {
|
||||||
|
startNodes = append(startNodes, node.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(startNodes) == 0 {
|
||||||
|
return fmt.Errorf("no start nodes found (all nodes have incoming edges)")
|
||||||
|
}
|
||||||
|
|
||||||
|
// BFS from all start nodes
|
||||||
|
visited := make(map[string]bool)
|
||||||
|
queue := startNodes
|
||||||
|
|
||||||
|
for len(queue) > 0 {
|
||||||
|
// Dequeue
|
||||||
|
current := queue[0]
|
||||||
|
queue = queue[1:]
|
||||||
|
|
||||||
|
if visited[current] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
visited[current] = true
|
||||||
|
|
||||||
|
// Visit neighbors
|
||||||
|
for _, neighbor := range graph[current] {
|
||||||
|
if !visited[neighbor] {
|
||||||
|
queue = append(queue, neighbor)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check all nodes were visited
|
||||||
|
if len(visited) != len(nodes) {
|
||||||
|
unreached := []string{}
|
||||||
|
for _, node := range nodes {
|
||||||
|
if !visited[node.ID] {
|
||||||
|
unreached = append(unreached, node.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fmt.Errorf("unreachable nodes: %v", unreached)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// TopoSort returns nodes in topological order (execution order)
|
||||||
|
func (cv *CanvasValidator) TopoSort(nodes []db.WorkflowNode, edges []db.WorkflowEdge) ([]db.WorkflowNode, error) {
|
||||||
|
if len(nodes) == 0 {
|
||||||
|
return []db.WorkflowNode{}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build adjacency list and in-degree map
|
||||||
|
graph := make(map[string][]string)
|
||||||
|
inDegree := make(map[string]int)
|
||||||
|
nodeMap := make(map[string]db.WorkflowNode)
|
||||||
|
|
||||||
|
for _, node := range nodes {
|
||||||
|
graph[node.ID] = []string{}
|
||||||
|
inDegree[node.ID] = 0
|
||||||
|
nodeMap[node.ID] = node
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, edge := range edges {
|
||||||
|
graph[edge.Source] = append(graph[edge.Source], edge.Target)
|
||||||
|
inDegree[edge.Target]++
|
||||||
|
}
|
||||||
|
|
||||||
|
// Kahn's algorithm
|
||||||
|
queue := []string{}
|
||||||
|
for _, node := range nodes {
|
||||||
|
if inDegree[node.ID] == 0 {
|
||||||
|
queue = append(queue, node.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
result := []db.WorkflowNode{}
|
||||||
|
processed := make(map[string]bool)
|
||||||
|
|
||||||
|
for len(queue) > 0 {
|
||||||
|
// Dequeue
|
||||||
|
current := queue[0]
|
||||||
|
queue = queue[1:]
|
||||||
|
|
||||||
|
result = append(result, nodeMap[current])
|
||||||
|
processed[current] = true
|
||||||
|
|
||||||
|
// Visit neighbors
|
||||||
|
for _, neighbor := range graph[current] {
|
||||||
|
inDegree[neighbor]--
|
||||||
|
if inDegree[neighbor] == 0 {
|
||||||
|
queue = append(queue, neighbor)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(result) != len(nodes) {
|
||||||
|
return nil, fmt.Errorf("topological sort failed: graph has cycle")
|
||||||
|
}
|
||||||
|
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
@@ -8,7 +8,6 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"strings"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -53,12 +52,6 @@ type LLMAuth struct {
|
|||||||
|
|
||||||
// HeaderValue is the custom header value for Custom auth
|
// HeaderValue is the custom header value for Custom auth
|
||||||
HeaderValue string `json:"headerValue,omitempty"`
|
HeaderValue string `json:"headerValue,omitempty"`
|
||||||
|
|
||||||
// TenantID is the tenant/customer ID for multi-tenant federated access
|
|
||||||
TenantID string `json:"tenantId,omitempty"`
|
|
||||||
|
|
||||||
// Scopes are the OAuth2 scopes (space-separated)
|
|
||||||
Scopes string `json:"scopes,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// LLMClient is a simple LLM client for routing
|
// LLMClient is a simple LLM client for routing
|
||||||
@@ -216,16 +209,6 @@ func (c *LLMClient) applyAuth(req *http.Request) error {
|
|||||||
req.Header.Set(c.auth.HeaderName, c.auth.HeaderValue)
|
req.Header.Set(c.auth.HeaderName, c.auth.HeaderValue)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add tenant ID if specified (for multi-tenant federated access)
|
|
||||||
if c.auth.TenantID != "" {
|
|
||||||
req.Header.Set("X-Tenant-ID", c.auth.TenantID)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add scopes if specified (for OAuth2 flows)
|
|
||||||
if c.auth.Scopes != "" {
|
|
||||||
req.Header.Set("X-OAuth-Scopes", c.auth.Scopes)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -69,7 +69,6 @@ type LLMRouterConfig struct {
|
|||||||
Validators []WorkflowValidator
|
Validators []WorkflowValidator
|
||||||
ParamBinder ParameterBinder
|
ParamBinder ParameterBinder
|
||||||
Auth *LLMAuth // Authentication config for LLM API
|
Auth *LLMAuth // Authentication config for LLM API
|
||||||
TenantID string // Tenant ID for multi-tenant isolation
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewLLMRouter creates a new LLM router with custom config
|
// NewLLMRouter creates a new LLM router with custom config
|
||||||
|
|||||||
@@ -28,12 +28,16 @@ type State struct {
|
|||||||
Type StateType `json:"type"`
|
Type StateType `json:"type"`
|
||||||
|
|
||||||
// Task fields
|
// Task fields
|
||||||
|
Activity string `json:"activity,omitempty"`
|
||||||
Resource string `json:"resource,omitempty"`
|
Resource string `json:"resource,omitempty"`
|
||||||
Parameters map[string]interface{} `json:"parameters,omitempty"`
|
Parameters map[string]interface{} `json:"parameters,omitempty"`
|
||||||
Timeout string `json:"timeout,omitempty"`
|
Timeout string `json:"timeout,omitempty"`
|
||||||
Retry *RetryPolicy `json:"retry,omitempty"`
|
Retry *RetryPolicy `json:"retry,omitempty"`
|
||||||
Catch []CatchClause `json:"catch,omitempty"`
|
Catch []CatchClause `json:"catch,omitempty"`
|
||||||
|
|
||||||
|
// Parallel fields
|
||||||
|
Branches []interface{} `json:"branches,omitempty"`
|
||||||
|
|
||||||
// Pass fields
|
// Pass fields
|
||||||
Result interface{} `json:"result,omitempty"`
|
Result interface{} `json:"result,omitempty"`
|
||||||
|
|
||||||
@@ -53,11 +57,15 @@ const (
|
|||||||
StateTypeTask StateType = "Task"
|
StateTypeTask StateType = "Task"
|
||||||
StateTypePass StateType = "Pass"
|
StateTypePass StateType = "Pass"
|
||||||
StateTypeFail StateType = "Fail"
|
StateTypeFail StateType = "Fail"
|
||||||
|
StateTypeParallel StateType = "Parallel"
|
||||||
|
|
||||||
|
TaskActivity = "Task"
|
||||||
)
|
)
|
||||||
|
|
||||||
// RetryPolicy defines retry behavior for activities
|
// RetryPolicy defines retry behavior for activities
|
||||||
type RetryPolicy struct {
|
type RetryPolicy struct {
|
||||||
MaxAttempts int32 `json:"maxAttempts"`
|
MaxAttempts int32 `json:"maxAttempts"`
|
||||||
|
BackoffSeconds int32 `json:"backoffSeconds,omitempty"`
|
||||||
BackoffRate float64 `json:"backoffRate"`
|
BackoffRate float64 `json:"backoffRate"`
|
||||||
InitialInterval string `json:"initialInterval"`
|
InitialInterval string `json:"initialInterval"`
|
||||||
MaxInterval string `json:"maxInterval,omitempty"`
|
MaxInterval string `json:"maxInterval,omitempty"`
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
apiVersion: ENC[AES256_GCM,data:IxE=,iv:nh5IQck87AsRYnvxMLxn2rZFBUTHcc9obvsYoHnvC6g=,tag:ink4m5kv1NqX2TeRrpCaqg==,type:str]
|
||||||
|
kind: ENC[AES256_GCM,data:2U5oBCqywkR0,iv:EVBlp6G1SlznoP7Zx9Y0mQOnxbzcosP28+UbJUWFjHM=,tag:v1lot4q06QBqU2M5q2RJ/g==,type:str]
|
||||||
|
metadata:
|
||||||
|
name: ENC[AES256_GCM,data:pFOLyxGAW7/KqUqijkPM1mGYaKo=,iv:jttNW2Ef0itpuWupOQkGEiFaanpcd/HuvfLg9l2tSEg=,tag:6ijOdYdjnUaCOf29z8vkxg==,type:str]
|
||||||
|
namespace: ENC[AES256_GCM,data:FSZFmVEp,iv:liL0yGuEbjZjf6egh8KS9zi6H3AEF9MvynGBO+49GW0=,tag:4iJNECe8vsXqzQBV/Q7c0g==,type:str]
|
||||||
|
data:
|
||||||
|
#ENC[AES256_GCM,data:d+Z/w/n69JI5,iv:/w2xIrmNXg53kz+tfebT0P6rD3TC909YTDFXXUc/yHo=,tag:ao4yA2lW2a1/ELT8ZIBOgw==,type:comment]
|
||||||
|
TEMPORAL_NAMESPACE: ENC[AES256_GCM,data:X0D/DVfVgzhFh+oB8nU=,iv:biiLtXRALsUMNIW4qGj8JOc9C1RJK93pOw74ZmymM/g=,tag:tW5+AwUGj8jzvxPSZAf41A==,type:str]
|
||||||
|
TEMPORAL_HOSTPORT: ENC[AES256_GCM,data:OK8Cu7nA2fKhXmBko8MORoD6hvJBMFfE/dTBZ99ac420xjPBWjhrz2XR3WRiWhUIIQ==,iv:HKDNRT/30HNzN3pX91e63i/ZeIUUYkycknjjKTFlVwo=,tag:OjPle4p+nV4ZQYN/yuUFEw==,type:str]
|
||||||
|
#ENC[AES256_GCM,data:1jnEt80ScfSqnCv9Rf/XLAlYTfuZVxoRdV7Sx9EgIGmzvAM=,iv:3NKsB9ZytMxuMipSLApKX7hj2jQG+2e2Hp8+ofFin9k=,tag:s4eRatHTQJa37xBO5UYI5Q==,type:comment]
|
||||||
|
LOCAL_LLM_BASE_URL: ENC[AES256_GCM,data:rTWBhNovjp5WdFI2jMaMRRg41uhh1dOFqVnplmMADiubu/FGXCvUPD2d9IuU,iv:1RdS5UfD6aOXnaEfddRd4PxJ1+K7AwKlMUYxzUQxVJ4=,tag:K0g2KDCFLOtxDFkHxoRbMw==,type:str]
|
||||||
|
MEMORY_SERVICE_URL: ENC[AES256_GCM,data:CarE5ENFtDvBWVzB7qTZQqoL0OsN2uAO9aoPXu1LPWtdoSQ2rQsVs2scTA08jaWLD+o=,iv:e7M/aibmYdSk4NbY6fYw0UPjd/VQvWJ1tC8n0r2y6r0=,tag:bWuCTBRfKkaB2fauPR51Fg==,type:str]
|
||||||
|
sops:
|
||||||
|
age:
|
||||||
|
- enc: |
|
||||||
|
-----BEGIN AGE ENCRYPTED FILE-----
|
||||||
|
YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBBV0RJU2wzN1Bib0lZRlFl
|
||||||
|
K2UzSVBNUjNHUVVFeUFEWTJBUHNZT0l3RWprCmp2cE1HM2xOWnVjVGlqdWI0SndG
|
||||||
|
Q1VOaklVdlg4eGp6V29uVDVJRUtmKzgKLS0tIGp3MWJMdmdyZmRnWmxOWEhVZUhm
|
||||||
|
Rm5DNzBhUWt0SVBDK09mSWw2SHVRTWMKLS6Cz2nhz1RSoV+VUvFw9EsjlWbE2nEk
|
||||||
|
4P1FdNgr+v1MTNczKZGzh9HbTAmYxCRgVBszXR5ov2JfukaZAWb9mg==
|
||||||
|
-----END AGE ENCRYPTED FILE-----
|
||||||
|
recipient: age1e5fq3hwxy78psus2nfvmtmua36g0u3suk78ephw6246l974d2utsvn0hla
|
||||||
|
lastmodified: "2026-09-06T12:56:33Z"
|
||||||
|
mac: ENC[AES256_GCM,data:Ra89XdYHoJV+uFBlUMdw+I36UQfhM+r0Q4WjI3V/A7jBY2t00I0xSP+KRKPXlAA18HXpLCc5VkWklPMU4gfyYied1bPuFw6yLvvuup/ev4UAg/LofThKjtuRfXPy82Ltvro6R+ilWzJ8pRtgtk+jC4xkkMsUOACJMVwgn979D7M=,iv:UWR+CqXAreW/fx3tt1kJsOKYZkrAkxLXlU5QVy5p3gE=,tag:3t9c6631D4XrDmkR6Iv/4Q==,type:str]
|
||||||
|
unencrypted_suffix: _unencrypted
|
||||||
|
version: 3.13.2
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
apiVersion: v1
|
|
||||||
kind: ConfigMap
|
|
||||||
metadata:
|
|
||||||
name: poimen-config
|
|
||||||
namespace: poimen
|
|
||||||
data:
|
|
||||||
TEMPORAL_NAMESPACE: "poimen-harness"
|
|
||||||
TEMPORAL_HOSTPORT: "temporal-frontend.temporal:7233"
|
|
||||||
LOCAL_LLM_BASE_URL: "http://api-gateway.api:8080"
|
|
||||||
POIMEN_MEMORY_URL: "http://poimen-memory.poimen.svc.cluster.local:8080"
|
|
||||||
+2
-2
@@ -9,6 +9,6 @@ metadata:
|
|||||||
app.kubernetes.io/name: poimen
|
app.kubernetes.io/name: poimen
|
||||||
app.kubernetes.io/component: orchestrator
|
app.kubernetes.io/component: orchestrator
|
||||||
data:
|
data:
|
||||||
GIT_COMMIT: "30644a8e" # Updated automatically by CI/CD
|
GIT_COMMIT: "84b4ca120" # Updated automatically by CI/CD
|
||||||
GIT_BRANCH: "main"
|
GIT_BRANCH: "main"
|
||||||
DEPLOYMENT_DATE: "2026-09-04"
|
DEPLOYMENT_DATE: "2026-09-05"
|
||||||
|
|||||||
+11
-7
@@ -4,15 +4,19 @@ kind: Kustomization
|
|||||||
namespace: poimen
|
namespace: poimen
|
||||||
|
|
||||||
resources:
|
resources:
|
||||||
- worker-deployment.yaml
|
- poimen-application.yaml
|
||||||
- configmap.yaml
|
|
||||||
|
|
||||||
commonLabels:
|
commonLabels:
|
||||||
app.kubernetes.io/name: poimen
|
app.kubernetes.io/name: poimen
|
||||||
app.kubernetes.io/component: worker
|
app.kubernetes.io/component: worker
|
||||||
|
|
||||||
secretGenerator:
|
images:
|
||||||
- name: poimen-secrets
|
- name: forgejo.riotpiao.com/rock/poimen-memory
|
||||||
envs:
|
newName: forgejo.riotpiao.com/rock/poimen-memory
|
||||||
- secrets.env
|
newTag: latest
|
||||||
behavior: create
|
- name: forgejo.riotpiao.com/rock/poimen-workflows
|
||||||
|
newName: forgejo.riotpiao.com/rock/poimen-workflows
|
||||||
|
newTag: latest
|
||||||
|
- name: forgejo.riotpiao.com/rock/poimen-frontend
|
||||||
|
newName: forgejo.riotpiao.com/rock/poimen-frontend
|
||||||
|
newTag: latest
|
||||||
|
|||||||
@@ -1,12 +0,0 @@
|
|||||||
# NOTE: This file is for reference only.
|
|
||||||
# Kustomize will auto-generate secrets from secrets.env
|
|
||||||
# See kustomization.yaml for details
|
|
||||||
|
|
||||||
apiVersion: v1
|
|
||||||
kind: Secret
|
|
||||||
metadata:
|
|
||||||
name: poimen-secrets
|
|
||||||
namespace: poimen
|
|
||||||
type: Opaque
|
|
||||||
stringData:
|
|
||||||
ANTHROPIC_API_KEY: "" # Generated from secrets.env by Kustomize
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
ANTHROPIC_API_KEY=YOUR_ANTHROPIC_API_KEY_HERE
|
|
||||||
@@ -13,8 +13,8 @@ spec:
|
|||||||
labels:
|
labels:
|
||||||
app: poimen-worker
|
app: poimen-worker
|
||||||
annotations:
|
annotations:
|
||||||
git-commit: "30644a8e" # ✅ Updated on each push, triggers rolling restart
|
git-commit: "84b4ca120" # ✅ Updated on each push, triggers rolling restart
|
||||||
deployment-date: "2026-09-04"
|
deployment-date: "2026-09-05"
|
||||||
spec:
|
spec:
|
||||||
containers:
|
containers:
|
||||||
- name: worker
|
- name: worker
|
||||||
|
|||||||
+535
@@ -0,0 +1,535 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
_ "github.com/lib/pq"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DB wraps the database connection
|
||||||
|
type DB struct {
|
||||||
|
conn *sql.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
// New creates a new database connection to memory-db (K8s CNPG)
|
||||||
|
// Expected DSN format: postgresql://app:password@host:5432/dbname?sslmode=disable
|
||||||
|
func New(dsn string) (*DB, error) {
|
||||||
|
if dsn == "" {
|
||||||
|
// Fallback: try to construct from K8s env vars
|
||||||
|
host := os.Getenv("DATABASE_HOST")
|
||||||
|
port := os.Getenv("DATABASE_PORT")
|
||||||
|
name := os.Getenv("DATABASE_NAME")
|
||||||
|
user := os.Getenv("DATABASE_USER")
|
||||||
|
password := os.Getenv("DATABASE_PASSWORD")
|
||||||
|
|
||||||
|
if host != "" && port != "" && name != "" && user != "" && password != "" {
|
||||||
|
dsn = fmt.Sprintf("postgresql://%s:%s@%s:%s/%s?sslmode=disable",
|
||||||
|
user, password, host, port, name)
|
||||||
|
} else {
|
||||||
|
return nil, fmt.Errorf("DATABASE_URL or K8s env vars (DATABASE_HOST, DATABASE_PORT, DATABASE_NAME, DATABASE_USER, DATABASE_PASSWORD) required")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
conn, err := sql.Open("postgres", dsn)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to open database: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test connection
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
if err := conn.PingContext(ctx); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to ping database: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set connection pool settings
|
||||||
|
conn.SetMaxOpenConns(25)
|
||||||
|
conn.SetMaxIdleConns(5)
|
||||||
|
conn.SetConnMaxLifetime(5 * time.Minute)
|
||||||
|
|
||||||
|
return &DB{conn: conn}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close closes the database connection
|
||||||
|
func (db *DB) Close() error {
|
||||||
|
return db.conn.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// SaveWorkflow saves or updates a workflow with canvas
|
||||||
|
func (db *DB) SaveWorkflow(ctx context.Context, wf *Workflow) error {
|
||||||
|
query := `
|
||||||
|
INSERT INTO workflows (id, customer_id, name, description, status, version, nodes, edges, created_by, created_at, updated_at)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
|
||||||
|
ON CONFLICT (id) DO UPDATE SET
|
||||||
|
name = $3,
|
||||||
|
description = $4,
|
||||||
|
status = $5,
|
||||||
|
version = $6,
|
||||||
|
nodes = $7,
|
||||||
|
edges = $8,
|
||||||
|
updated_at = $11
|
||||||
|
`
|
||||||
|
|
||||||
|
_, err := db.conn.ExecContext(ctx, query,
|
||||||
|
wf.ID,
|
||||||
|
wf.CustomerID,
|
||||||
|
wf.Name,
|
||||||
|
wf.Description,
|
||||||
|
wf.Status,
|
||||||
|
wf.Version,
|
||||||
|
wf.Nodes,
|
||||||
|
wf.Edges,
|
||||||
|
wf.CreatedBy,
|
||||||
|
wf.CreatedAt,
|
||||||
|
wf.UpdatedAt,
|
||||||
|
)
|
||||||
|
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// SaveCanvasUpdate saves canvas (nodes + edges) for a workflow
|
||||||
|
func (db *DB) SaveCanvasUpdate(ctx context.Context, workflowID, customerID string, canvas *Canvas) error {
|
||||||
|
nodesJSON, err := json.Marshal(canvas.Nodes)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to marshal nodes: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
edgesJSON, err := json.Marshal(canvas.Edges)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to marshal edges: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
query := `
|
||||||
|
UPDATE workflows
|
||||||
|
SET nodes = $1, edges = $2, updated_at = now()
|
||||||
|
WHERE id = $3 AND customer_id = $4
|
||||||
|
`
|
||||||
|
|
||||||
|
result, err := db.conn.ExecContext(ctx, query, nodesJSON, edgesJSON, workflowID, customerID)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to update canvas: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
rows, err := result.RowsAffected()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if rows == 0 {
|
||||||
|
return fmt.Errorf("workflow not found: %s", workflowID)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// FetchWorkflow retrieves a workflow by ID
|
||||||
|
func (db *DB) FetchWorkflow(ctx context.Context, workflowID, customerID string) (*Workflow, error) {
|
||||||
|
query := `
|
||||||
|
SELECT id, customer_id, name, description, status, version, nodes, edges, created_by, created_at, updated_at, last_executed_at
|
||||||
|
FROM workflows
|
||||||
|
WHERE id = $1 AND customer_id = $2
|
||||||
|
`
|
||||||
|
|
||||||
|
wf := &Workflow{}
|
||||||
|
err := db.conn.QueryRowContext(ctx, query, workflowID, customerID).Scan(
|
||||||
|
&wf.ID,
|
||||||
|
&wf.CustomerID,
|
||||||
|
&wf.Name,
|
||||||
|
&wf.Description,
|
||||||
|
&wf.Status,
|
||||||
|
&wf.Version,
|
||||||
|
&wf.Nodes,
|
||||||
|
&wf.Edges,
|
||||||
|
&wf.CreatedBy,
|
||||||
|
&wf.CreatedAt,
|
||||||
|
&wf.UpdatedAt,
|
||||||
|
&wf.LastExecutedAt,
|
||||||
|
)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
if err == sql.ErrNoRows {
|
||||||
|
return nil, fmt.Errorf("workflow not found: %s", workflowID)
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("failed to fetch workflow: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return wf, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// FetchCanvas retrieves canvas (nodes + edges) for a workflow
|
||||||
|
func (db *DB) FetchCanvas(ctx context.Context, workflowID, customerID string) (*Canvas, error) {
|
||||||
|
query := `
|
||||||
|
SELECT nodes, edges
|
||||||
|
FROM workflows
|
||||||
|
WHERE id = $1 AND customer_id = $2
|
||||||
|
`
|
||||||
|
|
||||||
|
var nodesJSON, edgesJSON []byte
|
||||||
|
err := db.conn.QueryRowContext(ctx, query, workflowID, customerID).Scan(&nodesJSON, &edgesJSON)
|
||||||
|
if err != nil {
|
||||||
|
if err == sql.ErrNoRows {
|
||||||
|
return nil, fmt.Errorf("workflow not found: %s", workflowID)
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("failed to fetch canvas: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var nodes []WorkflowNode
|
||||||
|
var edges []WorkflowEdge
|
||||||
|
|
||||||
|
if err := json.Unmarshal(nodesJSON, &nodes); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to unmarshal nodes: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := json.Unmarshal(edgesJSON, &edges); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to unmarshal edges: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Canvas{Nodes: nodes, Edges: edges}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListWorkflows retrieves all workflows for a customer
|
||||||
|
func (db *DB) ListWorkflows(ctx context.Context, customerID string, limit, offset int) ([]Workflow, error) {
|
||||||
|
query := `
|
||||||
|
SELECT id, customer_id, name, description, status, version, nodes, edges, created_by, created_at, updated_at, last_executed_at
|
||||||
|
FROM workflows
|
||||||
|
WHERE customer_id = $1
|
||||||
|
ORDER BY created_at DESC
|
||||||
|
LIMIT $2 OFFSET $3
|
||||||
|
`
|
||||||
|
|
||||||
|
rows, err := db.conn.QueryContext(ctx, query, customerID, limit, offset)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to list workflows: %w", err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var workflows []Workflow
|
||||||
|
for rows.Next() {
|
||||||
|
wf := Workflow{}
|
||||||
|
err := rows.Scan(
|
||||||
|
&wf.ID,
|
||||||
|
&wf.CustomerID,
|
||||||
|
&wf.Name,
|
||||||
|
&wf.Description,
|
||||||
|
&wf.Status,
|
||||||
|
&wf.Version,
|
||||||
|
&wf.Nodes,
|
||||||
|
&wf.Edges,
|
||||||
|
&wf.CreatedBy,
|
||||||
|
&wf.CreatedAt,
|
||||||
|
&wf.UpdatedAt,
|
||||||
|
&wf.LastExecutedAt,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to scan workflow: %w", err)
|
||||||
|
}
|
||||||
|
workflows = append(workflows, wf)
|
||||||
|
}
|
||||||
|
|
||||||
|
return workflows, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteWorkflow deletes a workflow
|
||||||
|
func (db *DB) DeleteWorkflow(ctx context.Context, workflowID, customerID string) error {
|
||||||
|
query := `
|
||||||
|
DELETE FROM workflows
|
||||||
|
WHERE id = $1 AND customer_id = $2
|
||||||
|
`
|
||||||
|
|
||||||
|
result, err := db.conn.ExecContext(ctx, query, workflowID, customerID)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to delete workflow: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
rows, err := result.RowsAffected()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if rows == 0 {
|
||||||
|
return fmt.Errorf("workflow not found: %s", workflowID)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SaveExecution saves a workflow execution record
|
||||||
|
func (db *DB) SaveExecution(ctx context.Context, exec *WorkflowExecution) error {
|
||||||
|
query := `
|
||||||
|
INSERT INTO workflow_executions (id, workflow_id, customer_id, temporal_id, status, inputs, outputs, started_at, completed_at, duration_ms, error_message, error_count)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
|
||||||
|
ON CONFLICT (id) DO UPDATE SET
|
||||||
|
status = $5,
|
||||||
|
outputs = $7,
|
||||||
|
completed_at = $9,
|
||||||
|
duration_ms = $10,
|
||||||
|
error_message = $11,
|
||||||
|
error_count = $12
|
||||||
|
`
|
||||||
|
|
||||||
|
_, err := db.conn.ExecContext(ctx, query,
|
||||||
|
exec.ID,
|
||||||
|
exec.WorkflowID,
|
||||||
|
exec.CustomerID,
|
||||||
|
exec.TemporalID,
|
||||||
|
exec.Status,
|
||||||
|
exec.Inputs,
|
||||||
|
exec.Outputs,
|
||||||
|
exec.StartedAt,
|
||||||
|
exec.CompletedAt,
|
||||||
|
exec.DurationMs,
|
||||||
|
exec.ErrorMessage,
|
||||||
|
exec.ErrorCount,
|
||||||
|
)
|
||||||
|
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// FetchExecution retrieves a workflow execution
|
||||||
|
func (db *DB) FetchExecution(ctx context.Context, executionID string) (*WorkflowExecution, error) {
|
||||||
|
query := `
|
||||||
|
SELECT id, workflow_id, customer_id, temporal_id, status, inputs, outputs, started_at, completed_at, duration_ms, error_message, error_count
|
||||||
|
FROM workflow_executions
|
||||||
|
WHERE id = $1
|
||||||
|
`
|
||||||
|
|
||||||
|
exec := &WorkflowExecution{}
|
||||||
|
err := db.conn.QueryRowContext(ctx, query, executionID).Scan(
|
||||||
|
&exec.ID,
|
||||||
|
&exec.WorkflowID,
|
||||||
|
&exec.CustomerID,
|
||||||
|
&exec.TemporalID,
|
||||||
|
&exec.Status,
|
||||||
|
&exec.Inputs,
|
||||||
|
&exec.Outputs,
|
||||||
|
&exec.StartedAt,
|
||||||
|
&exec.CompletedAt,
|
||||||
|
&exec.DurationMs,
|
||||||
|
&exec.ErrorMessage,
|
||||||
|
&exec.ErrorCount,
|
||||||
|
)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
if err == sql.ErrNoRows {
|
||||||
|
return nil, fmt.Errorf("execution not found: %s", executionID)
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("failed to fetch execution: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return exec, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SaveExecutionLog saves an activity log entry
|
||||||
|
func (db *DB) SaveExecutionLog(ctx context.Context, log *ExecutionLog) error {
|
||||||
|
query := `
|
||||||
|
INSERT INTO execution_logs (execution_id, node_id, activity_name, level, message, metadata, logged_at)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||||
|
`
|
||||||
|
|
||||||
|
_, err := db.conn.ExecContext(ctx, query,
|
||||||
|
log.ExecutionID,
|
||||||
|
log.NodeID,
|
||||||
|
log.ActivityName,
|
||||||
|
log.Level,
|
||||||
|
log.Message,
|
||||||
|
log.Metadata,
|
||||||
|
log.LoggedAt,
|
||||||
|
)
|
||||||
|
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// FetchExecutionLogs retrieves all logs for an execution
|
||||||
|
func (db *DB) FetchExecutionLogs(ctx context.Context, executionID string) ([]ExecutionLog, error) {
|
||||||
|
query := `
|
||||||
|
SELECT id, execution_id, node_id, activity_name, level, message, metadata, logged_at
|
||||||
|
FROM execution_logs
|
||||||
|
WHERE execution_id = $1
|
||||||
|
ORDER BY logged_at ASC
|
||||||
|
`
|
||||||
|
|
||||||
|
rows, err := db.conn.QueryContext(ctx, query, executionID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to fetch execution logs: %w", err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var logs []ExecutionLog
|
||||||
|
for rows.Next() {
|
||||||
|
log := ExecutionLog{}
|
||||||
|
err := rows.Scan(
|
||||||
|
&log.ID,
|
||||||
|
&log.ExecutionID,
|
||||||
|
&log.NodeID,
|
||||||
|
&log.ActivityName,
|
||||||
|
&log.Level,
|
||||||
|
&log.Message,
|
||||||
|
&log.Metadata,
|
||||||
|
&log.LoggedAt,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to scan log: %w", err)
|
||||||
|
}
|
||||||
|
logs = append(logs, log)
|
||||||
|
}
|
||||||
|
|
||||||
|
return logs, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// SaveActivityTrace saves per-activity execution trace
|
||||||
|
func (db *DB) SaveActivityTrace(ctx context.Context, trace *ActivityTrace) error {
|
||||||
|
query := `
|
||||||
|
INSERT INTO activity_traces (execution_id, node_id, activity_name, parameters, result, started_at, completed_at, duration_ms, attempt, retry_reason, status, error_message)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
|
||||||
|
ON CONFLICT (id) DO UPDATE SET
|
||||||
|
status = $11,
|
||||||
|
result = $5,
|
||||||
|
completed_at = $7,
|
||||||
|
duration_ms = $8,
|
||||||
|
error_message = $12
|
||||||
|
`
|
||||||
|
|
||||||
|
_, err := db.conn.ExecContext(ctx, query,
|
||||||
|
trace.ExecutionID,
|
||||||
|
trace.NodeID,
|
||||||
|
trace.ActivityName,
|
||||||
|
trace.Parameters,
|
||||||
|
trace.Result,
|
||||||
|
trace.StartedAt,
|
||||||
|
trace.CompletedAt,
|
||||||
|
trace.DurationMs,
|
||||||
|
trace.Attempt,
|
||||||
|
trace.RetryReason,
|
||||||
|
trace.Status,
|
||||||
|
trace.ErrorMessage,
|
||||||
|
)
|
||||||
|
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// FetchActivityTraces retrieves all activity traces for an execution
|
||||||
|
func (db *DB) FetchActivityTraces(ctx context.Context, executionID string) ([]ActivityTrace, error) {
|
||||||
|
query := `
|
||||||
|
SELECT id, execution_id, node_id, activity_name, parameters, result, started_at, completed_at, duration_ms, attempt, retry_reason, status, error_message
|
||||||
|
FROM activity_traces
|
||||||
|
WHERE execution_id = $1
|
||||||
|
ORDER BY started_at ASC
|
||||||
|
`
|
||||||
|
|
||||||
|
rows, err := db.conn.QueryContext(ctx, query, executionID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to fetch activity traces: %w", err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var traces []ActivityTrace
|
||||||
|
for rows.Next() {
|
||||||
|
trace := ActivityTrace{}
|
||||||
|
err := rows.Scan(
|
||||||
|
&trace.ID,
|
||||||
|
&trace.ExecutionID,
|
||||||
|
&trace.NodeID,
|
||||||
|
&trace.ActivityName,
|
||||||
|
&trace.Parameters,
|
||||||
|
&trace.Result,
|
||||||
|
&trace.StartedAt,
|
||||||
|
&trace.CompletedAt,
|
||||||
|
&trace.DurationMs,
|
||||||
|
&trace.Attempt,
|
||||||
|
&trace.RetryReason,
|
||||||
|
&trace.Status,
|
||||||
|
&trace.ErrorMessage,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to scan trace: %w", err)
|
||||||
|
}
|
||||||
|
traces = append(traces, trace)
|
||||||
|
}
|
||||||
|
|
||||||
|
return traces, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetWorkflowRelations retrieves all relations for a workflow version
|
||||||
|
func (db *DB) GetWorkflowRelations(ctx context.Context, workflowID string, version int) ([]WorkflowRelation, error) {
|
||||||
|
var relations []WorkflowRelation
|
||||||
|
|
||||||
|
query := `
|
||||||
|
SELECT id, workflow_id, version, source_node_id, target_node_id,
|
||||||
|
relation_type, label, relation_wording, metadata, created_at
|
||||||
|
FROM workflow_relations
|
||||||
|
WHERE workflow_id = $1 AND version = $2
|
||||||
|
ORDER BY created_at DESC
|
||||||
|
`
|
||||||
|
|
||||||
|
rows, err := db.conn.QueryContext(ctx, query, workflowID, version)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to query relations: %w", err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
for rows.Next() {
|
||||||
|
var rel WorkflowRelation
|
||||||
|
if err := rows.Scan(
|
||||||
|
&rel.ID,
|
||||||
|
&rel.WorkflowID,
|
||||||
|
&rel.Version,
|
||||||
|
&rel.SourceNodeID,
|
||||||
|
&rel.TargetNodeID,
|
||||||
|
&rel.RelationType,
|
||||||
|
&rel.Label,
|
||||||
|
&rel.RelationWording,
|
||||||
|
&rel.Metadata,
|
||||||
|
&rel.CreatedAt,
|
||||||
|
); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to scan relation: %w", err)
|
||||||
|
}
|
||||||
|
relations = append(relations, rel)
|
||||||
|
}
|
||||||
|
|
||||||
|
return relations, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetRelationVersions retrieves version history for a specific relation
|
||||||
|
func (db *DB) GetRelationVersions(ctx context.Context, workflowID string, edgeID string) ([]WorkflowRelationVersion, error) {
|
||||||
|
var versions []WorkflowRelationVersion
|
||||||
|
|
||||||
|
query := `
|
||||||
|
SELECT id, workflow_id, edge_id, version_num, operation, snapshot,
|
||||||
|
changed_at, changed_by, fields_changed
|
||||||
|
FROM workflow_relation_versions
|
||||||
|
WHERE workflow_id = $1 AND edge_id = $2
|
||||||
|
ORDER BY version_num ASC
|
||||||
|
`
|
||||||
|
|
||||||
|
rows, err := db.conn.QueryContext(ctx, query, workflowID, edgeID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to query relation versions: %w", err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
for rows.Next() {
|
||||||
|
var v WorkflowRelationVersion
|
||||||
|
if err := rows.Scan(
|
||||||
|
&v.ID,
|
||||||
|
&v.WorkflowID,
|
||||||
|
&v.EdgeID,
|
||||||
|
&v.VersionNum,
|
||||||
|
&v.Operation,
|
||||||
|
&v.Snapshot,
|
||||||
|
&v.ChangedAt,
|
||||||
|
&v.ChangedBy,
|
||||||
|
&v.FieldsChanged,
|
||||||
|
); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to scan version: %w", err)
|
||||||
|
}
|
||||||
|
versions = append(versions, v)
|
||||||
|
}
|
||||||
|
|
||||||
|
return versions, rows.Err()
|
||||||
|
}
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// WorkflowNode represents a React Flow node in the canvas
|
||||||
|
type WorkflowNode struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Label string `json:"label"`
|
||||||
|
Type string `json:"type"` // "activity"
|
||||||
|
Position map[string]interface{} `json:"position"`
|
||||||
|
Data map[string]interface{} `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// WorkflowEdge represents a React Flow edge in the canvas
|
||||||
|
type WorkflowEdge struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Source string `json:"source"`
|
||||||
|
Target string `json:"target"`
|
||||||
|
Data map[string]interface{} `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Canvas represents the full React Flow canvas (nodes + edges)
|
||||||
|
type Canvas struct {
|
||||||
|
Name string `json:"name,omitempty"`
|
||||||
|
Nodes []WorkflowNode `json:"nodes"`
|
||||||
|
Edges []WorkflowEdge `json:"edges"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Workflow represents a workflow definition in the database
|
||||||
|
type Workflow struct {
|
||||||
|
ID string `db:"id"`
|
||||||
|
CustomerID string `db:"customer_id"`
|
||||||
|
Name string `db:"name"`
|
||||||
|
Description string `db:"description"`
|
||||||
|
Status string `db:"status"` // "draft", "active", "archived"
|
||||||
|
Version int `db:"version"`
|
||||||
|
Nodes []byte `db:"nodes"` // JSONB stored as []byte
|
||||||
|
Edges []byte `db:"edges"` // JSONB stored as []byte
|
||||||
|
CreatedBy string `db:"created_by"`
|
||||||
|
CreatedAt time.Time `db:"created_at"`
|
||||||
|
UpdatedAt time.Time `db:"updated_at"`
|
||||||
|
LastExecutedAt *time.Time `db:"last_executed_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// WorkflowExecution represents a workflow execution run
|
||||||
|
type WorkflowExecution struct {
|
||||||
|
ID string `db:"id"`
|
||||||
|
WorkflowID string `db:"workflow_id"`
|
||||||
|
CustomerID string `db:"customer_id"`
|
||||||
|
TemporalID string `db:"temporal_id"` // Temporal execution ID
|
||||||
|
Status string `db:"status"` // "pending", "running", "success", "failed", "cancelled"
|
||||||
|
Inputs []byte `db:"inputs"` // JSONB
|
||||||
|
Outputs []byte `db:"outputs"` // JSONB
|
||||||
|
StartedAt time.Time `db:"started_at"`
|
||||||
|
CompletedAt *time.Time `db:"completed_at"`
|
||||||
|
DurationMs *int `db:"duration_ms"`
|
||||||
|
ErrorMessage string `db:"error_message"`
|
||||||
|
ErrorCount int `db:"error_count"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ExecutionLog represents a detailed activity log entry
|
||||||
|
type ExecutionLog struct {
|
||||||
|
ID int64 `db:"id"`
|
||||||
|
ExecutionID string `db:"execution_id"`
|
||||||
|
NodeID string `db:"node_id"` // From canvas node ID
|
||||||
|
ActivityName string `db:"activity_name"` // "CloneRepo", "AnalyzeCode", etc
|
||||||
|
Level string `db:"level"` // "info", "warn", "error", "debug"
|
||||||
|
Message string `db:"message"`
|
||||||
|
Metadata []byte `db:"metadata"` // JSONB
|
||||||
|
LoggedAt time.Time `db:"logged_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ActivityTrace represents per-activity execution metrics
|
||||||
|
type ActivityTrace struct {
|
||||||
|
ID int64 `db:"id"`
|
||||||
|
ExecutionID string `db:"execution_id"`
|
||||||
|
NodeID string `db:"node_id"`
|
||||||
|
ActivityName string `db:"activity_name"`
|
||||||
|
Parameters []byte `db:"parameters"` // JSONB
|
||||||
|
Result []byte `db:"result"` // JSONB
|
||||||
|
StartedAt time.Time `db:"started_at"`
|
||||||
|
CompletedAt *time.Time `db:"completed_at"`
|
||||||
|
DurationMs *int `db:"duration_ms"`
|
||||||
|
Attempt int `db:"attempt"`
|
||||||
|
RetryReason string `db:"retry_reason"`
|
||||||
|
Status string `db:"status"` // "running", "success", "failed", "skipped"
|
||||||
|
ErrorMessage string `db:"error_message"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// WorkflowStats represents aggregated workflow metrics
|
||||||
|
type WorkflowStats struct {
|
||||||
|
WorkflowID string `db:"workflow_id"`
|
||||||
|
CustomerID string `db:"customer_id"`
|
||||||
|
TotalRuns int `db:"total_runs"`
|
||||||
|
SuccessfulRuns int `db:"successful_runs"`
|
||||||
|
FailedRuns int `db:"failed_runs"`
|
||||||
|
AvgDurationMs float64 `db:"avg_duration_ms"`
|
||||||
|
MinDurationMs *int `db:"min_duration_ms"`
|
||||||
|
MaxDurationMs *int `db:"max_duration_ms"`
|
||||||
|
Last30dRuns int `db:"last_30d_runs"`
|
||||||
|
Last30dSuccessRate float64 `db:"last_30d_success_rate"`
|
||||||
|
UpdatedAt time.Time `db:"updated_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// WorkflowMemoryLink represents a connection between execution and memory nodes
|
||||||
|
type WorkflowMemoryLink struct {
|
||||||
|
ExecutionID string `db:"execution_id"`
|
||||||
|
MemoryNodeSha string `db:"memory_node_sha"`
|
||||||
|
Relationship string `db:"relationship"` // "generated", "used", "learned", "failed_on"
|
||||||
|
CreatedAt time.Time `db:"created_at"`
|
||||||
|
Notes string `db:"notes"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// WorkflowRelation represents a semantic relation between two canvas nodes
|
||||||
|
type WorkflowRelation struct {
|
||||||
|
ID string `db:"id"`
|
||||||
|
WorkflowID string `db:"workflow_id"`
|
||||||
|
Version int `db:"version"`
|
||||||
|
SourceNodeID string `db:"source_node_id"`
|
||||||
|
TargetNodeID string `db:"target_node_id"`
|
||||||
|
RelationType string `db:"relation_type"` // "data-flow", "dependency", "conditional"
|
||||||
|
Label string `db:"label"` // Human-readable relation description
|
||||||
|
RelationWording []byte `db:"relation_wording"` // JSONB with verb, outputs, inputs, confidence
|
||||||
|
Metadata []byte `db:"metadata"` // JSONB for extensibility
|
||||||
|
CreatedAt time.Time `db:"created_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// WorkflowRelationVersion represents versioned history of relation changes
|
||||||
|
type WorkflowRelationVersion struct {
|
||||||
|
ID string `db:"id"`
|
||||||
|
WorkflowID string `db:"workflow_id"`
|
||||||
|
EdgeID string `db:"edge_id"`
|
||||||
|
VersionNum int `db:"version_num"`
|
||||||
|
Operation string `db:"operation"` // "CREATE", "UPDATE", "DELETE"
|
||||||
|
Snapshot []byte `db:"snapshot"` // JSONB full state at this version
|
||||||
|
ChangedAt time.Time `db:"changed_at"`
|
||||||
|
ChangedBy string `db:"changed_by"`
|
||||||
|
FieldsChanged []byte `db:"fields_changed"` // JSONB array of changed field names
|
||||||
|
}
|
||||||
@@ -0,0 +1,223 @@
|
|||||||
|
// Package types defines the shared domain model for Poimen workflows.
|
||||||
|
// Both workflow/ (orchestration) and activity/ (execution) import from here.
|
||||||
|
package types
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/rockliang/poimen/workflows/pkg/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ===== LLM Configuration =====
|
||||||
|
|
||||||
|
type ModelSpec struct {
|
||||||
|
ModelID string
|
||||||
|
Thinking string // "adaptive" or ""
|
||||||
|
Effort string // "low", "medium", "high", "xhigh", "max"
|
||||||
|
}
|
||||||
|
|
||||||
|
type PromptSpec struct {
|
||||||
|
TemplateRef string
|
||||||
|
RawTemplate string
|
||||||
|
Variables map[string]any
|
||||||
|
Model ModelSpec
|
||||||
|
LessonsRef string
|
||||||
|
}
|
||||||
|
|
||||||
|
type SkillRef struct {
|
||||||
|
Name string
|
||||||
|
URL string
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== Retry & Tuning =====
|
||||||
|
|
||||||
|
type PiRetryPolicy struct {
|
||||||
|
ScheduleToCloseTimeout time.Duration
|
||||||
|
InitialInterval time.Duration
|
||||||
|
MaximumInterval time.Duration
|
||||||
|
BackoffCoefficient float64
|
||||||
|
StreamTimeout time.Duration
|
||||||
|
StreamTimeoutMax time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
type ActivityTuning struct {
|
||||||
|
ImplementerBaseTimeout time.Duration
|
||||||
|
ImplementerMaxRetries int
|
||||||
|
JudgeTimeout time.Duration
|
||||||
|
PiRetry PiRetryPolicy
|
||||||
|
InitialRetryInterval time.Duration
|
||||||
|
MaxRetryInterval time.Duration
|
||||||
|
RetryBackoffCoefficient float64
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== Orchestrator =====
|
||||||
|
|
||||||
|
type OrchestratorConfig struct {
|
||||||
|
SystemPrompt string
|
||||||
|
Skills []SkillRef
|
||||||
|
RolePrompts map[string]PromptSpec
|
||||||
|
Tuning ActivityTuning
|
||||||
|
}
|
||||||
|
|
||||||
|
type OrchestratorInput struct {
|
||||||
|
TargetRepoPath string
|
||||||
|
RemoteURL string
|
||||||
|
Milestone string
|
||||||
|
Config OrchestratorConfig
|
||||||
|
DryRun bool
|
||||||
|
CycleCount int
|
||||||
|
MaxCyclesBeforeCAN int
|
||||||
|
PiProvider string
|
||||||
|
}
|
||||||
|
|
||||||
|
type OrchestratorOutput struct {
|
||||||
|
MilestoneComplete bool
|
||||||
|
Done bool
|
||||||
|
LastError string
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== TaskUnit =====
|
||||||
|
|
||||||
|
type TaskUnitInput struct {
|
||||||
|
TaskID string
|
||||||
|
RemoteURL string
|
||||||
|
TargetRepoPath string
|
||||||
|
Milestone string
|
||||||
|
Config OrchestratorConfig
|
||||||
|
DryRun bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type TaskUnitOutput struct {
|
||||||
|
TaskID string
|
||||||
|
Status string
|
||||||
|
Verdict string
|
||||||
|
Critique string
|
||||||
|
Branch string
|
||||||
|
Reason string
|
||||||
|
Changes string
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== Canvas & Relations =====
|
||||||
|
|
||||||
|
type RelationWording struct {
|
||||||
|
Verb string `json:"verb"`
|
||||||
|
SourceOutput string `json:"source_output"`
|
||||||
|
TargetInput string `json:"target_input"`
|
||||||
|
ConnectionType string `json:"connection_type"`
|
||||||
|
Confidence float64 `json:"confidence"`
|
||||||
|
SemanticMatch string `json:"semantic_match"`
|
||||||
|
TransformerNeeded string `json:"transformer_needed,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type EdgeWithWording struct {
|
||||||
|
ID string `json:"id,omitempty"`
|
||||||
|
Source string `json:"source"`
|
||||||
|
Target string `json:"target"`
|
||||||
|
RelationType string `json:"relation_type"`
|
||||||
|
RelationLabel string `json:"relation_label"`
|
||||||
|
RelationWording RelationWording `json:"relation_wording"`
|
||||||
|
CreatedAt string `json:"created_at,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type CanvasWithRelationsData struct {
|
||||||
|
WorkflowID string `json:"workflow_id"`
|
||||||
|
Version int `json:"version"`
|
||||||
|
Nodes []db.WorkflowNode `json:"nodes"`
|
||||||
|
Edges []db.WorkflowEdge `json:"edges"`
|
||||||
|
Relations []EdgeWithWording `json:"relations"`
|
||||||
|
UpdatedAt string `json:"updated_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== Activity I/O =====
|
||||||
|
|
||||||
|
type FetchCanvasRelationsInput struct {
|
||||||
|
WorkflowID string `json:"workflow_id"`
|
||||||
|
Version int `json:"version"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type CanvasReasonerInput struct {
|
||||||
|
Nodes []db.WorkflowNode `json:"nodes"`
|
||||||
|
Edges []db.WorkflowEdge `json:"edges"`
|
||||||
|
PreserveExisting bool `json:"preserve_existing,omitempty"`
|
||||||
|
AuthToken string `json:"auth_token,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type QueryPathData struct {
|
||||||
|
SourceID string `json:"source_id"`
|
||||||
|
TargetID string `json:"target_id"`
|
||||||
|
Distance int `json:"distance"`
|
||||||
|
PathCount int `json:"path_count"`
|
||||||
|
NodeIDs []string `json:"node_ids"`
|
||||||
|
Confidence float64 `json:"total_confidence"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type GraphRAGQueryInput struct {
|
||||||
|
WorkflowID string `json:"workflow_id"`
|
||||||
|
Query string `json:"query"`
|
||||||
|
SearchType string `json:"search_type"`
|
||||||
|
RelationType string `json:"relation_type"`
|
||||||
|
ConfidenceFloor float64 `json:"confidence_floor"`
|
||||||
|
TopK int `json:"top_k"`
|
||||||
|
RankingProfile string `json:"ranking_profile"`
|
||||||
|
Canvas CanvasWithRelationsData `json:"canvas"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type GraphRAGQueryOutput struct {
|
||||||
|
WorkflowID string `json:"workflow_id"`
|
||||||
|
Query string `json:"query"`
|
||||||
|
Edges []EdgeWithWording `json:"edges"`
|
||||||
|
Paths []QueryPathData `json:"paths"`
|
||||||
|
TotalCount int `json:"total_count"`
|
||||||
|
HasMore bool `json:"has_more"`
|
||||||
|
ExecutionMs int64 `json:"execution_time_ms"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type CanvasCompatibilityInput struct {
|
||||||
|
Nodes []db.WorkflowNode `json:"nodes"`
|
||||||
|
Edges []db.WorkflowEdge `json:"edges"`
|
||||||
|
Query string `json:"query,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type IndexGraphRAGInput struct {
|
||||||
|
WorkflowID string `json:"workflow_id"`
|
||||||
|
Version int `json:"version"`
|
||||||
|
Nodes []db.WorkflowNode `json:"nodes"`
|
||||||
|
Relations []EdgeWithWording `json:"relations"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type IndexGraphRAGOutput struct {
|
||||||
|
WorkflowID string `json:"workflow_id"`
|
||||||
|
Version int `json:"version"`
|
||||||
|
IndexedEntities int `json:"indexed_entities"`
|
||||||
|
IndexedEdges int `json:"indexed_edges"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
GraphRAGChecksum string `json:"graph_rag_checksum"`
|
||||||
|
IndexedAt string `json:"indexed_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type PromptUpdate struct {
|
||||||
|
Role string
|
||||||
|
Spec PromptSpec
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== Defaults =====
|
||||||
|
|
||||||
|
func NewPiRetryPolicy() PiRetryPolicy {
|
||||||
|
return PiRetryPolicy{
|
||||||
|
ScheduleToCloseTimeout: 5 * time.Minute,
|
||||||
|
InitialInterval: 2 * time.Second,
|
||||||
|
MaximumInterval: 30 * time.Second,
|
||||||
|
BackoffCoefficient: 2.0,
|
||||||
|
StreamTimeout: 30 * time.Second,
|
||||||
|
StreamTimeoutMax: 2 * time.Minute,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewActivityTuning() ActivityTuning {
|
||||||
|
return ActivityTuning{
|
||||||
|
ImplementerBaseTimeout: 10 * time.Minute,
|
||||||
|
ImplementerMaxRetries: 3,
|
||||||
|
JudgeTimeout: 5 * time.Minute,
|
||||||
|
PiRetry: NewPiRetryPolicy(),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,136 +0,0 @@
|
|||||||
package statemachine
|
|
||||||
|
|
||||||
import "time"
|
|
||||||
|
|
||||||
// ModelSpec defines LLM model configuration.
|
|
||||||
type ModelSpec struct {
|
|
||||||
ModelID string // e.g. "claude-opus-5", "claude-sonnet-5"
|
|
||||||
Thinking string // "adaptive" or ""
|
|
||||||
Effort string // "low", "medium", "high", "xhigh", "max"
|
|
||||||
}
|
|
||||||
|
|
||||||
// PromptSpec defines a prompt template with variables and model.
|
|
||||||
type PromptSpec struct {
|
|
||||||
TemplateRef string // e.g. "planner/default.tmpl"
|
|
||||||
RawTemplate string // overrides TemplateRef if non-empty
|
|
||||||
Variables map[string]any // template variables
|
|
||||||
Model ModelSpec // which LLM to use
|
|
||||||
LessonsRef string // key into lessons store
|
|
||||||
}
|
|
||||||
|
|
||||||
// PiRetryPolicy defines retry and timeout settings for Pi command execution.
|
|
||||||
type PiRetryPolicy struct {
|
|
||||||
ScheduleToCloseTimeout time.Duration // default: 5m
|
|
||||||
InitialInterval time.Duration // default: 2s
|
|
||||||
MaximumInterval time.Duration // default: 30s
|
|
||||||
BackoffCoefficient float64 // default: 2.0
|
|
||||||
StreamTimeout time.Duration // default: 30s
|
|
||||||
StreamTimeoutMax time.Duration // default: 2m
|
|
||||||
}
|
|
||||||
|
|
||||||
// ActivityTuning defines timeouts and retry counts for activities.
|
|
||||||
type ActivityTuning struct {
|
|
||||||
ImplementerBaseTimeout time.Duration // default: 10m
|
|
||||||
ImplementerMaxRetries int // default: 3
|
|
||||||
JudgeTimeout time.Duration // default: 5m
|
|
||||||
PiRetry PiRetryPolicy
|
|
||||||
// Retry policy settings
|
|
||||||
InitialRetryInterval time.Duration // default: 2s
|
|
||||||
MaxRetryInterval time.Duration // default: 5m
|
|
||||||
RetryBackoffCoefficient float64 // default: 2.0
|
|
||||||
}
|
|
||||||
|
|
||||||
// OrchestratorConfig holds all runtime configuration for the orchestrator.
|
|
||||||
type OrchestratorConfig struct {
|
|
||||||
SystemPrompt string // shared prompt prefix
|
|
||||||
Skills []SkillRef // required skill sources
|
|
||||||
RolePrompts map[string]PromptSpec // per-role: "planner", "judge", "implementer"
|
|
||||||
Tuning ActivityTuning
|
|
||||||
}
|
|
||||||
|
|
||||||
// OrchestratorInput is the input to the Orchestrator workflow.
|
|
||||||
type OrchestratorInput struct {
|
|
||||||
TargetRepoPath string
|
|
||||||
RemoteURL string
|
|
||||||
Milestone string // e.g. "T0"
|
|
||||||
Config OrchestratorConfig
|
|
||||||
DryRun bool
|
|
||||||
CycleCount int
|
|
||||||
MaxCyclesBeforeCAN int // default: 100
|
|
||||||
PiProvider string // pi provider name (e.g., "local-llm"); required for skill preparation
|
|
||||||
}
|
|
||||||
|
|
||||||
// OrchestratorOutput is the output of the Orchestrator workflow.
|
|
||||||
type OrchestratorOutput struct {
|
|
||||||
MilestoneComplete bool
|
|
||||||
Done bool
|
|
||||||
LastError string
|
|
||||||
}
|
|
||||||
|
|
||||||
// TaskUnitInput is the input to the TaskUnit workflow.
|
|
||||||
type TaskUnitInput struct {
|
|
||||||
TaskID string
|
|
||||||
RemoteURL string
|
|
||||||
TargetRepoPath string
|
|
||||||
Milestone string
|
|
||||||
Config OrchestratorConfig
|
|
||||||
DryRun bool
|
|
||||||
}
|
|
||||||
|
|
||||||
// TaskUnitOutput is the output of the TaskUnit workflow.
|
|
||||||
type TaskUnitOutput struct {
|
|
||||||
TaskID string
|
|
||||||
Status string // "success" or "failed"
|
|
||||||
Verdict string // "pass" or "fail" from judge
|
|
||||||
Critique string // feedback from judge
|
|
||||||
Branch string
|
|
||||||
Reason string // error reason if failed
|
|
||||||
Changes string // summary of changes
|
|
||||||
}
|
|
||||||
|
|
||||||
// SkillRef references a skill source.
|
|
||||||
type SkillRef struct {
|
|
||||||
Name string // skill identifier
|
|
||||||
URL string // source to clone
|
|
||||||
}
|
|
||||||
|
|
||||||
// Default values for types.
|
|
||||||
const (
|
|
||||||
defaultScheduleToCloseTimeout = 5 * time.Minute
|
|
||||||
defaultInitialInterval = 2 * time.Second
|
|
||||||
defaultMaximumInterval = 30 * time.Second
|
|
||||||
defaultBackoffCoefficient = 2.0
|
|
||||||
defaultStreamTimeout = 30 * time.Second
|
|
||||||
defaultStreamTimeoutMax = 2 * time.Minute
|
|
||||||
defaultImplementerBaseTimeout = 10 * time.Minute
|
|
||||||
defaultImplementerMaxRetries = 3
|
|
||||||
defaultJudgeTimeout = 5 * time.Minute
|
|
||||||
)
|
|
||||||
|
|
||||||
// NewPiRetryPolicy returns a PiRetryPolicy with defaults.
|
|
||||||
func NewPiRetryPolicy() PiRetryPolicy {
|
|
||||||
return PiRetryPolicy{
|
|
||||||
ScheduleToCloseTimeout: defaultScheduleToCloseTimeout,
|
|
||||||
InitialInterval: defaultInitialInterval,
|
|
||||||
MaximumInterval: defaultMaximumInterval,
|
|
||||||
BackoffCoefficient: defaultBackoffCoefficient,
|
|
||||||
StreamTimeout: defaultStreamTimeout,
|
|
||||||
StreamTimeoutMax: defaultStreamTimeoutMax,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewActivityTuning returns an ActivityTuning with defaults.
|
|
||||||
func NewActivityTuning() ActivityTuning {
|
|
||||||
return ActivityTuning{
|
|
||||||
ImplementerBaseTimeout: defaultImplementerBaseTimeout,
|
|
||||||
ImplementerMaxRetries: defaultImplementerMaxRetries,
|
|
||||||
JudgeTimeout: defaultJudgeTimeout,
|
|
||||||
PiRetry: NewPiRetryPolicy(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// PromptUpdate represents an update to a role prompt.
|
|
||||||
type PromptUpdate struct {
|
|
||||||
Role string
|
|
||||||
Spec PromptSpec
|
|
||||||
}
|
|
||||||
+15
-15
@@ -9,7 +9,7 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"github.com/rockliang/poimen/workflows/action"
|
"github.com/rockliang/poimen/workflows/activity"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestGitCloneAndFetch(t *testing.T) {
|
func TestGitCloneAndFetch(t *testing.T) {
|
||||||
@@ -56,7 +56,7 @@ func TestGitCloneAndFetch(t *testing.T) {
|
|||||||
|
|
||||||
// Test clone into empty path
|
// Test clone into empty path
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
err := action.CloneRepoActivity(ctx, action.CloneRepoInput{
|
err := activity.CloneRepoActivity(ctx, activity.CloneRepoInput{
|
||||||
RemoteURL: sourceDir,
|
RemoteURL: sourceDir,
|
||||||
TargetRepoPath: targetDir,
|
TargetRepoPath: targetDir,
|
||||||
})
|
})
|
||||||
@@ -89,7 +89,7 @@ func TestGitCloneAndFetch(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Test fetch on existing repo
|
// Test fetch on existing repo
|
||||||
err = action.CloneRepoActivity(ctx, action.CloneRepoInput{
|
err = activity.CloneRepoActivity(ctx, activity.CloneRepoInput{
|
||||||
RemoteURL: sourceDir,
|
RemoteURL: sourceDir,
|
||||||
TargetRepoPath: targetDir,
|
TargetRepoPath: targetDir,
|
||||||
})
|
})
|
||||||
@@ -139,14 +139,14 @@ func TestGitWorktreeAdd(t *testing.T) {
|
|||||||
|
|
||||||
// Clone the repo
|
// Clone the repo
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
err := action.CloneRepoActivity(ctx, action.CloneRepoInput{
|
err := activity.CloneRepoActivity(ctx, activity.CloneRepoInput{
|
||||||
RemoteURL: sourceDir,
|
RemoteURL: sourceDir,
|
||||||
TargetRepoPath: repoDir,
|
TargetRepoPath: repoDir,
|
||||||
})
|
})
|
||||||
assert.NoError(t, err, "clone should succeed")
|
assert.NoError(t, err, "clone should succeed")
|
||||||
|
|
||||||
// Test worktree add
|
// Test worktree add
|
||||||
worktreePath, err := action.GitWorktreeAddActivity(ctx, action.GitWorktreeAddInput{
|
worktreePath, err := activity.GitWorktreeAddActivity(ctx, activity.GitWorktreeAddInput{
|
||||||
RepoPath: repoDir,
|
RepoPath: repoDir,
|
||||||
TaskID: "T0.1",
|
TaskID: "T0.1",
|
||||||
})
|
})
|
||||||
@@ -207,14 +207,14 @@ func TestGitCommit(t *testing.T) {
|
|||||||
|
|
||||||
// Clone the repo
|
// Clone the repo
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
err := action.CloneRepoActivity(ctx, action.CloneRepoInput{
|
err := activity.CloneRepoActivity(ctx, activity.CloneRepoInput{
|
||||||
RemoteURL: sourceDir,
|
RemoteURL: sourceDir,
|
||||||
TargetRepoPath: repoDir,
|
TargetRepoPath: repoDir,
|
||||||
})
|
})
|
||||||
assert.NoError(t, err, "clone should succeed")
|
assert.NoError(t, err, "clone should succeed")
|
||||||
|
|
||||||
// Create a worktree
|
// Create a worktree
|
||||||
worktreePath, err := action.GitWorktreeAddActivity(ctx, action.GitWorktreeAddInput{
|
worktreePath, err := activity.GitWorktreeAddActivity(ctx, activity.GitWorktreeAddInput{
|
||||||
RepoPath: repoDir,
|
RepoPath: repoDir,
|
||||||
TaskID: "T0.1",
|
TaskID: "T0.1",
|
||||||
})
|
})
|
||||||
@@ -227,7 +227,7 @@ func TestGitCommit(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Commit changes
|
// Commit changes
|
||||||
err = action.GitCommitActivity(ctx, action.GitCommitInput{
|
err = activity.GitCommitActivity(ctx, activity.GitCommitInput{
|
||||||
WorktreePath: worktreePath,
|
WorktreePath: worktreePath,
|
||||||
Message: "Add new file",
|
Message: "Add new file",
|
||||||
})
|
})
|
||||||
@@ -283,14 +283,14 @@ func TestGitDiff(t *testing.T) {
|
|||||||
|
|
||||||
// Clone the repo
|
// Clone the repo
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
err := action.CloneRepoActivity(ctx, action.CloneRepoInput{
|
err := activity.CloneRepoActivity(ctx, activity.CloneRepoInput{
|
||||||
RemoteURL: sourceDir,
|
RemoteURL: sourceDir,
|
||||||
TargetRepoPath: repoDir,
|
TargetRepoPath: repoDir,
|
||||||
})
|
})
|
||||||
assert.NoError(t, err, "clone should succeed")
|
assert.NoError(t, err, "clone should succeed")
|
||||||
|
|
||||||
// Create a worktree
|
// Create a worktree
|
||||||
worktreePath, err := action.GitWorktreeAddActivity(ctx, action.GitWorktreeAddInput{
|
worktreePath, err := activity.GitWorktreeAddActivity(ctx, activity.GitWorktreeAddInput{
|
||||||
RepoPath: repoDir,
|
RepoPath: repoDir,
|
||||||
TaskID: "T0.1",
|
TaskID: "T0.1",
|
||||||
})
|
})
|
||||||
@@ -309,7 +309,7 @@ func TestGitDiff(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Get diff (should show the staged change)
|
// Get diff (should show the staged change)
|
||||||
diffOutput, err := action.GitDiffActivity(ctx, action.GitDiffInput{
|
diffOutput, err := activity.GitDiffActivity(ctx, activity.GitDiffInput{
|
||||||
WorktreePath: worktreePath,
|
WorktreePath: worktreePath,
|
||||||
})
|
})
|
||||||
assert.NoError(t, err, "diff should succeed")
|
assert.NoError(t, err, "diff should succeed")
|
||||||
@@ -378,7 +378,7 @@ func TestGitSquashMerge(t *testing.T) {
|
|||||||
|
|
||||||
// Clone for the orchestrator to use
|
// Clone for the orchestrator to use
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
err := action.CloneRepoActivity(ctx, action.CloneRepoInput{
|
err := activity.CloneRepoActivity(ctx, activity.CloneRepoInput{
|
||||||
RemoteURL: sourceDir,
|
RemoteURL: sourceDir,
|
||||||
TargetRepoPath: repoDir,
|
TargetRepoPath: repoDir,
|
||||||
})
|
})
|
||||||
@@ -387,7 +387,7 @@ func TestGitSquashMerge(t *testing.T) {
|
|||||||
// Create multiple worktrees with changes
|
// Create multiple worktrees with changes
|
||||||
for i := 1; i <= 2; i++ {
|
for i := 1; i <= 2; i++ {
|
||||||
taskID := fmt.Sprintf("T0.%d", i)
|
taskID := fmt.Sprintf("T0.%d", i)
|
||||||
worktreePath, err := action.GitWorktreeAddActivity(ctx, action.GitWorktreeAddInput{
|
worktreePath, err := activity.GitWorktreeAddActivity(ctx, activity.GitWorktreeAddInput{
|
||||||
RepoPath: repoDir,
|
RepoPath: repoDir,
|
||||||
TaskID: taskID,
|
TaskID: taskID,
|
||||||
})
|
})
|
||||||
@@ -400,7 +400,7 @@ func TestGitSquashMerge(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Commit changes
|
// Commit changes
|
||||||
err = action.GitCommitActivity(ctx, action.GitCommitInput{
|
err = activity.GitCommitActivity(ctx, activity.GitCommitInput{
|
||||||
WorktreePath: worktreePath,
|
WorktreePath: worktreePath,
|
||||||
Message: fmt.Sprintf("Task %s implementation", taskID),
|
Message: fmt.Sprintf("Task %s implementation", taskID),
|
||||||
})
|
})
|
||||||
@@ -408,7 +408,7 @@ func TestGitSquashMerge(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Perform squash merge
|
// Perform squash merge
|
||||||
err = action.GitSquashMergeActivity(ctx, action.GitSquashMergeInput{
|
err = activity.GitSquashMergeActivity(ctx, activity.GitSquashMergeInput{
|
||||||
RepoPath: repoDir,
|
RepoPath: repoDir,
|
||||||
Branches: []string{"task/T0.1", "task/T0.2"},
|
Branches: []string{"task/T0.1", "task/T0.2"},
|
||||||
Message: "Milestone T0: completed all tasks",
|
Message: "Milestone T0: completed all tasks",
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/rockliang/poimen/workflows/internal/routing"
|
"github.com/rockliang/poimen/workflows/internal/routing"
|
||||||
"github.com/rockliang/poimen/workflows/statemachine"
|
"github.com/rockliang/poimen/workflows/workflow"
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
"go.temporal.io/sdk/testsuite"
|
"go.temporal.io/sdk/testsuite"
|
||||||
)
|
)
|
||||||
@@ -45,14 +45,14 @@ func TestRoutingWorkflow_SimpleWorkflow(t *testing.T) {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
input := statemachine.RoutingWorkflowInput{Spec: spec}
|
input := workflow.RoutingWorkflowInput{Spec: spec}
|
||||||
|
|
||||||
env.ExecuteWorkflow(statemachine.RoutingWorkflow, input)
|
env.ExecuteWorkflow(workflow.RoutingWorkflow, input)
|
||||||
|
|
||||||
require.True(t, env.IsWorkflowCompleted())
|
require.True(t, env.IsWorkflowCompleted())
|
||||||
require.NoError(t, env.GetWorkflowError())
|
require.NoError(t, env.GetWorkflowError())
|
||||||
|
|
||||||
var output statemachine.RoutingWorkflowOutput
|
var output workflow.RoutingWorkflowOutput
|
||||||
require.NoError(t, env.GetWorkflowResult(&output))
|
require.NoError(t, env.GetWorkflowResult(&output))
|
||||||
require.Equal(t, "COMPLETED", output.Status)
|
require.Equal(t, "COMPLETED", output.Status)
|
||||||
require.NotNil(t, output.FinalOutput)
|
require.NotNil(t, output.FinalOutput)
|
||||||
@@ -96,14 +96,14 @@ func TestRoutingWorkflow_MultiStepWorkflow(t *testing.T) {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
input := statemachine.RoutingWorkflowInput{Spec: spec}
|
input := workflow.RoutingWorkflowInput{Spec: spec}
|
||||||
|
|
||||||
env.ExecuteWorkflow(statemachine.RoutingWorkflow, input)
|
env.ExecuteWorkflow(workflow.RoutingWorkflow, input)
|
||||||
|
|
||||||
require.True(t, env.IsWorkflowCompleted())
|
require.True(t, env.IsWorkflowCompleted())
|
||||||
require.NoError(t, env.GetWorkflowError())
|
require.NoError(t, env.GetWorkflowError())
|
||||||
|
|
||||||
var output statemachine.RoutingWorkflowOutput
|
var output workflow.RoutingWorkflowOutput
|
||||||
require.NoError(t, env.GetWorkflowResult(&output))
|
require.NoError(t, env.GetWorkflowResult(&output))
|
||||||
t.Logf("Output: %+v", output)
|
t.Logf("Output: %+v", output)
|
||||||
t.Logf("Error: %s", output.Error)
|
t.Logf("Error: %s", output.Error)
|
||||||
@@ -130,14 +130,14 @@ func TestRoutingWorkflow_PassState(t *testing.T) {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
input := statemachine.RoutingWorkflowInput{Spec: spec}
|
input := workflow.RoutingWorkflowInput{Spec: spec}
|
||||||
|
|
||||||
env.ExecuteWorkflow(statemachine.RoutingWorkflow, input)
|
env.ExecuteWorkflow(workflow.RoutingWorkflow, input)
|
||||||
|
|
||||||
require.True(t, env.IsWorkflowCompleted())
|
require.True(t, env.IsWorkflowCompleted())
|
||||||
require.NoError(t, env.GetWorkflowError())
|
require.NoError(t, env.GetWorkflowError())
|
||||||
|
|
||||||
var output statemachine.RoutingWorkflowOutput
|
var output workflow.RoutingWorkflowOutput
|
||||||
require.NoError(t, env.GetWorkflowResult(&output))
|
require.NoError(t, env.GetWorkflowResult(&output))
|
||||||
require.Equal(t, "COMPLETED", output.Status)
|
require.Equal(t, "COMPLETED", output.Status)
|
||||||
}
|
}
|
||||||
@@ -160,14 +160,14 @@ func TestRoutingWorkflow_FailState(t *testing.T) {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
input := statemachine.RoutingWorkflowInput{Spec: spec}
|
input := workflow.RoutingWorkflowInput{Spec: spec}
|
||||||
|
|
||||||
env.ExecuteWorkflow(statemachine.RoutingWorkflow, input)
|
env.ExecuteWorkflow(workflow.RoutingWorkflow, input)
|
||||||
|
|
||||||
require.True(t, env.IsWorkflowCompleted())
|
require.True(t, env.IsWorkflowCompleted())
|
||||||
require.NoError(t, env.GetWorkflowError())
|
require.NoError(t, env.GetWorkflowError())
|
||||||
|
|
||||||
var output statemachine.RoutingWorkflowOutput
|
var output workflow.RoutingWorkflowOutput
|
||||||
require.NoError(t, env.GetWorkflowResult(&output))
|
require.NoError(t, env.GetWorkflowResult(&output))
|
||||||
require.Equal(t, "FAILED", output.Status)
|
require.Equal(t, "FAILED", output.Status)
|
||||||
require.Contains(t, output.Error, "WorkflowError")
|
require.Contains(t, output.Error, "WorkflowError")
|
||||||
@@ -219,14 +219,14 @@ func TestRoutingWorkflow_ErrorCatch(t *testing.T) {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
input := statemachine.RoutingWorkflowInput{Spec: spec}
|
input := workflow.RoutingWorkflowInput{Spec: spec}
|
||||||
|
|
||||||
env.ExecuteWorkflow(statemachine.RoutingWorkflow, input)
|
env.ExecuteWorkflow(workflow.RoutingWorkflow, input)
|
||||||
|
|
||||||
require.True(t, env.IsWorkflowCompleted())
|
require.True(t, env.IsWorkflowCompleted())
|
||||||
require.NoError(t, env.GetWorkflowError())
|
require.NoError(t, env.GetWorkflowError())
|
||||||
|
|
||||||
var output statemachine.RoutingWorkflowOutput
|
var output workflow.RoutingWorkflowOutput
|
||||||
require.NoError(t, env.GetWorkflowResult(&output))
|
require.NoError(t, env.GetWorkflowResult(&output))
|
||||||
require.Equal(t, "FAILED", output.Status)
|
require.Equal(t, "FAILED", output.Status)
|
||||||
require.Contains(t, output.Error, "CaughtError")
|
require.Contains(t, output.Error, "CaughtError")
|
||||||
@@ -237,14 +237,14 @@ func TestRoutingWorkflow_EmptySpec(t *testing.T) {
|
|||||||
env := testSuite.NewTestWorkflowEnvironment()
|
env := testSuite.NewTestWorkflowEnvironment()
|
||||||
|
|
||||||
// Empty spec
|
// Empty spec
|
||||||
input := statemachine.RoutingWorkflowInput{Spec: nil}
|
input := workflow.RoutingWorkflowInput{Spec: nil}
|
||||||
|
|
||||||
env.ExecuteWorkflow(statemachine.RoutingWorkflow, input)
|
env.ExecuteWorkflow(workflow.RoutingWorkflow, input)
|
||||||
|
|
||||||
require.True(t, env.IsWorkflowCompleted())
|
require.True(t, env.IsWorkflowCompleted())
|
||||||
require.NoError(t, env.GetWorkflowError())
|
require.NoError(t, env.GetWorkflowError())
|
||||||
|
|
||||||
var output statemachine.RoutingWorkflowOutput
|
var output workflow.RoutingWorkflowOutput
|
||||||
require.NoError(t, env.GetWorkflowResult(&output))
|
require.NoError(t, env.GetWorkflowResult(&output))
|
||||||
require.Equal(t, "FAILED", output.Status)
|
require.Equal(t, "FAILED", output.Status)
|
||||||
require.Contains(t, output.Error, "empty")
|
require.Contains(t, output.Error, "empty")
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import (
|
|||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"go.temporal.io/sdk/client"
|
"go.temporal.io/sdk/client"
|
||||||
"github.com/rockliang/poimen/workflows/internal/config"
|
"github.com/rockliang/poimen/workflows/internal/config"
|
||||||
"github.com/rockliang/poimen/workflows/statemachine"
|
"github.com/rockliang/poimen/workflows/workflow"
|
||||||
)
|
)
|
||||||
|
|
||||||
// TestTemporalConnection verifies the worker is connected and healthy
|
// TestTemporalConnection verifies the worker is connected and healthy
|
||||||
@@ -67,7 +67,7 @@ func TestActivityExecution(t *testing.T) {
|
|||||||
runResp, err := c.ExecuteWorkflow(ctx, client.StartWorkflowOptions{
|
runResp, err := c.ExecuteWorkflow(ctx, client.StartWorkflowOptions{
|
||||||
ID: workflowID,
|
ID: workflowID,
|
||||||
TaskQueue: "poimen-taskqueue",
|
TaskQueue: "poimen-taskqueue",
|
||||||
}, statemachine.TestWorkflow)
|
}, workflow.TestWorkflow)
|
||||||
|
|
||||||
assert.NoError(t, err, "failed to execute test workflow")
|
assert.NoError(t, err, "failed to execute test workflow")
|
||||||
assert.NotNil(t, runResp, "workflow response should not be nil")
|
assert.NotNil(t, runResp, "workflow response should not be nil")
|
||||||
@@ -136,28 +136,28 @@ func TestOrchestratorWorkflowIntegration(t *testing.T) {
|
|||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
// Create minimal orchestrator input
|
// Create minimal orchestrator input
|
||||||
input := statemachine.OrchestratorInput{
|
input := workflow.OrchestratorInput{
|
||||||
RemoteURL: "https://forgejo.riotpiao.com/rock/poimen",
|
RemoteURL: "https://forgejo.riotpiao.com/rock/poimen",
|
||||||
TargetRepoPath: "/tmp/test-poimen-integration",
|
TargetRepoPath: "/tmp/test-poimen-integration",
|
||||||
Milestone: "T0",
|
Milestone: "T0",
|
||||||
Config: statemachine.OrchestratorConfig{
|
Config: workflow.OrchestratorConfig{
|
||||||
SystemPrompt: "You are a code generation assistant. Generate simple test code.",
|
SystemPrompt: "You are a code generation assistant. Generate simple test code.",
|
||||||
RolePrompts: map[string]statemachine.PromptSpec{
|
RolePrompts: map[string]workflow.PromptSpec{
|
||||||
"planner": {
|
"planner": {
|
||||||
TemplateRef: "planner/default.tmpl",
|
TemplateRef: "planner/default.tmpl",
|
||||||
Model: statemachine.ModelSpec{
|
Model: workflow.ModelSpec{
|
||||||
ModelID: "ornith",
|
ModelID: "ornith",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"judge": {
|
"judge": {
|
||||||
TemplateRef: "judge/default.tmpl",
|
TemplateRef: "judge/default.tmpl",
|
||||||
Model: statemachine.ModelSpec{
|
Model: workflow.ModelSpec{
|
||||||
ModelID: "ornith",
|
ModelID: "ornith",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"implementer": {
|
"implementer": {
|
||||||
TemplateRef: "implementer/default.tmpl",
|
TemplateRef: "implementer/default.tmpl",
|
||||||
Model: statemachine.ModelSpec{
|
Model: workflow.ModelSpec{
|
||||||
ModelID: "claude-sonnet-5",
|
ModelID: "claude-sonnet-5",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -170,7 +170,7 @@ func TestOrchestratorWorkflowIntegration(t *testing.T) {
|
|||||||
runResp, err := c.ExecuteWorkflow(ctx, client.StartWorkflowOptions{
|
runResp, err := c.ExecuteWorkflow(ctx, client.StartWorkflowOptions{
|
||||||
ID: workflowID,
|
ID: workflowID,
|
||||||
TaskQueue: "poimen-taskqueue",
|
TaskQueue: "poimen-taskqueue",
|
||||||
}, statemachine.OrchestratorWorkflow, input)
|
}, workflow.OrchestratorWorkflow, input)
|
||||||
|
|
||||||
assert.NoError(t, err, "failed to execute orchestrator workflow")
|
assert.NoError(t, err, "failed to execute orchestrator workflow")
|
||||||
t.Logf("✅ Orchestrator workflow started: %s", workflowID)
|
t.Logf("✅ Orchestrator workflow started: %s", workflowID)
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/rockliang/poimen/workflows/internal/routing"
|
"github.com/rockliang/poimen/workflows/internal/routing"
|
||||||
"github.com/rockliang/poimen/workflows/statemachine"
|
"github.com/rockliang/poimen/workflows/workflow"
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
"go.temporal.io/sdk/client"
|
"go.temporal.io/sdk/client"
|
||||||
)
|
)
|
||||||
@@ -69,12 +69,12 @@ func TestTemporalRoutingWorkflow(t *testing.T) {
|
|||||||
|
|
||||||
// Submit to Temporal
|
// Submit to Temporal
|
||||||
workflowID := "test-routing-" + time.Now().Format("20060102-150405")
|
workflowID := "test-routing-" + time.Now().Format("20060102-150405")
|
||||||
input := statemachine.RoutingWorkflowInput{Spec: output.Spec}
|
input := workflow.RoutingWorkflowInput{Spec: output.Spec}
|
||||||
|
|
||||||
run, err := c.ExecuteWorkflow(ctx, client.StartWorkflowOptions{
|
run, err := c.ExecuteWorkflow(ctx, client.StartWorkflowOptions{
|
||||||
ID: workflowID,
|
ID: workflowID,
|
||||||
TaskQueue: "poimen-taskqueue",
|
TaskQueue: "poimen-taskqueue",
|
||||||
}, statemachine.RoutingWorkflow, input)
|
}, workflow.RoutingWorkflow, input)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
t.Logf("Workflow submitted: ID=%s, RunID=%s", run.GetID(), run.GetRunID())
|
t.Logf("Workflow submitted: ID=%s, RunID=%s", run.GetID(), run.GetRunID())
|
||||||
@@ -118,18 +118,18 @@ func TestTemporalRoutingWorkflow(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
workflowID := "test-pass-only-" + time.Now().Format("20060102-150405")
|
workflowID := "test-pass-only-" + time.Now().Format("20060102-150405")
|
||||||
input := statemachine.RoutingWorkflowInput{Spec: spec}
|
input := workflow.RoutingWorkflowInput{Spec: spec}
|
||||||
|
|
||||||
run, err := c.ExecuteWorkflow(ctx, client.StartWorkflowOptions{
|
run, err := c.ExecuteWorkflow(ctx, client.StartWorkflowOptions{
|
||||||
ID: workflowID,
|
ID: workflowID,
|
||||||
TaskQueue: "poimen-taskqueue",
|
TaskQueue: "poimen-taskqueue",
|
||||||
}, statemachine.RoutingWorkflow, input)
|
}, workflow.RoutingWorkflow, input)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
t.Logf("Pass-only workflow submitted: ID=%s", run.GetID())
|
t.Logf("Pass-only workflow submitted: ID=%s", run.GetID())
|
||||||
|
|
||||||
// Wait for result (Pass states don't need workers)
|
// Wait for result (Pass states don't need workers)
|
||||||
var result statemachine.RoutingWorkflowOutput
|
var result workflow.RoutingWorkflowOutput
|
||||||
err = run.Get(ctx, &result)
|
err = run.Get(ctx, &result)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
|||||||
+12
-12
@@ -5,12 +5,12 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"github.com/rockliang/poimen/workflows/statemachine"
|
"github.com/rockliang/poimen/workflows/workflow"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestTypesDefaults(t *testing.T) {
|
func TestTypesDefaults(t *testing.T) {
|
||||||
// Test PiRetryPolicy defaults
|
// Test PiRetryPolicy defaults
|
||||||
pr := statemachine.NewPiRetryPolicy()
|
pr := workflow.NewPiRetryPolicy()
|
||||||
assert.Equal(t, 5*time.Minute, pr.ScheduleToCloseTimeout, "ScheduleToCloseTimeout should be 5m")
|
assert.Equal(t, 5*time.Minute, pr.ScheduleToCloseTimeout, "ScheduleToCloseTimeout should be 5m")
|
||||||
assert.Equal(t, 2*time.Second, pr.InitialInterval, "InitialInterval should be 2s")
|
assert.Equal(t, 2*time.Second, pr.InitialInterval, "InitialInterval should be 2s")
|
||||||
assert.Equal(t, 30*time.Second, pr.MaximumInterval, "MaximumInterval should be 30s")
|
assert.Equal(t, 30*time.Second, pr.MaximumInterval, "MaximumInterval should be 30s")
|
||||||
@@ -19,7 +19,7 @@ func TestTypesDefaults(t *testing.T) {
|
|||||||
assert.Equal(t, 2*time.Minute, pr.StreamTimeoutMax, "StreamTimeoutMax should be 2m")
|
assert.Equal(t, 2*time.Minute, pr.StreamTimeoutMax, "StreamTimeoutMax should be 2m")
|
||||||
|
|
||||||
// Test ActivityTuning defaults
|
// Test ActivityTuning defaults
|
||||||
at := statemachine.NewActivityTuning()
|
at := workflow.NewActivityTuning()
|
||||||
assert.Equal(t, 10*time.Minute, at.ImplementerBaseTimeout, "ImplementerBaseTimeout should be 10m")
|
assert.Equal(t, 10*time.Minute, at.ImplementerBaseTimeout, "ImplementerBaseTimeout should be 10m")
|
||||||
assert.Equal(t, 3, at.ImplementerMaxRetries, "ImplementerMaxRetries should be 3")
|
assert.Equal(t, 3, at.ImplementerMaxRetries, "ImplementerMaxRetries should be 3")
|
||||||
assert.Equal(t, 5*time.Minute, at.JudgeTimeout, "JudgeTimeout should be 5m")
|
assert.Equal(t, 5*time.Minute, at.JudgeTimeout, "JudgeTimeout should be 5m")
|
||||||
@@ -31,7 +31,7 @@ func TestTypesDefaults(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestModelSpec(t *testing.T) {
|
func TestModelSpec(t *testing.T) {
|
||||||
spec := statemachine.ModelSpec{
|
spec := workflow.ModelSpec{
|
||||||
ModelID: "claude-opus-5",
|
ModelID: "claude-opus-5",
|
||||||
Thinking: "adaptive",
|
Thinking: "adaptive",
|
||||||
Effort: "high",
|
Effort: "high",
|
||||||
@@ -42,13 +42,13 @@ func TestModelSpec(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestPromptSpec(t *testing.T) {
|
func TestPromptSpec(t *testing.T) {
|
||||||
spec := statemachine.PromptSpec{
|
spec := workflow.PromptSpec{
|
||||||
TemplateRef: "planner/default.tmpl",
|
TemplateRef: "planner/default.tmpl",
|
||||||
RawTemplate: "",
|
RawTemplate: "",
|
||||||
Variables: map[string]any{
|
Variables: map[string]any{
|
||||||
"key": "value",
|
"key": "value",
|
||||||
},
|
},
|
||||||
Model: statemachine.ModelSpec{
|
Model: workflow.ModelSpec{
|
||||||
ModelID: "claude-opus-5",
|
ModelID: "claude-opus-5",
|
||||||
},
|
},
|
||||||
LessonsRef: "T0.1",
|
LessonsRef: "T0.1",
|
||||||
@@ -61,18 +61,18 @@ func TestPromptSpec(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestOrchestratorConfig(t *testing.T) {
|
func TestOrchestratorConfig(t *testing.T) {
|
||||||
cfg := statemachine.OrchestratorConfig{
|
cfg := workflow.OrchestratorConfig{
|
||||||
SystemPrompt: "You are an expert",
|
SystemPrompt: "You are an expert",
|
||||||
Skills: []statemachine.SkillRef{
|
Skills: []workflow.SkillRef{
|
||||||
{Name: "golang-skills", URL: "https://example.com/skill1"},
|
{Name: "golang-skills", URL: "https://example.com/skill1"},
|
||||||
},
|
},
|
||||||
RolePrompts: map[string]statemachine.PromptSpec{
|
RolePrompts: map[string]workflow.PromptSpec{
|
||||||
"planner": {
|
"planner": {
|
||||||
TemplateRef: "planner/default.tmpl",
|
TemplateRef: "planner/default.tmpl",
|
||||||
Model: statemachine.ModelSpec{ModelID: "claude-opus-5"},
|
Model: workflow.ModelSpec{ModelID: "claude-opus-5"},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
Tuning: statemachine.NewActivityTuning(),
|
Tuning: workflow.NewActivityTuning(),
|
||||||
}
|
}
|
||||||
assert.Equal(t, "You are an expert", cfg.SystemPrompt)
|
assert.Equal(t, "You are an expert", cfg.SystemPrompt)
|
||||||
assert.Len(t, cfg.Skills, 1)
|
assert.Len(t, cfg.Skills, 1)
|
||||||
@@ -81,7 +81,7 @@ func TestOrchestratorConfig(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestTaskUnitInput(t *testing.T) {
|
func TestTaskUnitInput(t *testing.T) {
|
||||||
input := statemachine.TaskUnitInput{
|
input := workflow.TaskUnitInput{
|
||||||
TaskID: "T0.1",
|
TaskID: "T0.1",
|
||||||
RemoteURL: "https://github.com/example/repo",
|
RemoteURL: "https://github.com/example/repo",
|
||||||
TargetRepoPath: "/tmp/repo",
|
TargetRepoPath: "/tmp/repo",
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
package statemachine
|
package workflow
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package statemachine
|
package workflow
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package statemachine
|
package workflow
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
@@ -1,3 +1,3 @@
|
|||||||
package statemachine
|
package workflow
|
||||||
|
|
||||||
// Empty stub - will be filled in T0.7
|
// Empty stub - will be filled in T0.7
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package statemachine
|
package workflow
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package statemachine
|
package workflow
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"go.temporal.io/sdk/workflow"
|
"go.temporal.io/sdk/workflow"
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package workflow
|
||||||
|
|
||||||
|
import "github.com/rockliang/poimen/workflows/pkg/types"
|
||||||
|
|
||||||
|
// Re-export from pkg/types — single source of truth.
|
||||||
|
type ModelSpec = types.ModelSpec
|
||||||
|
type PromptSpec = types.PromptSpec
|
||||||
|
type SkillRef = types.SkillRef
|
||||||
|
type PiRetryPolicy = types.PiRetryPolicy
|
||||||
|
type ActivityTuning = types.ActivityTuning
|
||||||
|
type OrchestratorConfig = types.OrchestratorConfig
|
||||||
|
type OrchestratorInput = types.OrchestratorInput
|
||||||
|
type OrchestratorOutput = types.OrchestratorOutput
|
||||||
|
type TaskUnitInput = types.TaskUnitInput
|
||||||
|
type TaskUnitOutput = types.TaskUnitOutput
|
||||||
|
type PromptUpdate = types.PromptUpdate
|
||||||
|
type EdgeWithWording = types.EdgeWithWording
|
||||||
|
|
||||||
|
var NewPiRetryPolicy = types.NewPiRetryPolicy
|
||||||
|
var NewActivityTuning = types.NewActivityTuning
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
package workflow
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"go.temporal.io/sdk/temporal"
|
||||||
|
"go.temporal.io/sdk/workflow"
|
||||||
|
|
||||||
|
"github.com/rockliang/poimen/workflows/pkg/types"
|
||||||
|
)
|
||||||
|
|
||||||
|
type WorkflowGraphQueryInput struct {
|
||||||
|
WorkflowID string `json:"workflow_id"`
|
||||||
|
Query string `json:"query"`
|
||||||
|
SearchType string `json:"search_type"`
|
||||||
|
RelationType string `json:"relation_type"`
|
||||||
|
Version int `json:"version"`
|
||||||
|
ConfidenceFloor float64 `json:"confidence_floor"`
|
||||||
|
TopK int `json:"top_k"`
|
||||||
|
FindPaths bool `json:"find_paths"`
|
||||||
|
TargetNodeID string `json:"target_node_id"`
|
||||||
|
MaxPathDepth int `json:"max_path_depth"`
|
||||||
|
RankingProfile string `json:"ranking_profile"`
|
||||||
|
IncludeReasoning bool `json:"include_reasoning"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type WorkflowGraphQueryOutput struct {
|
||||||
|
WorkflowID string `json:"workflow_id"`
|
||||||
|
Query string `json:"query"`
|
||||||
|
Version int `json:"version"`
|
||||||
|
ExecutionTimeMs int64 `json:"execution_time_ms"`
|
||||||
|
Results []types.EdgeWithWording `json:"results"`
|
||||||
|
Paths []QueryPath `json:"paths"`
|
||||||
|
TotalCount int `json:"total_count"`
|
||||||
|
HasMore bool `json:"has_more"`
|
||||||
|
RankingProfile string `json:"ranking_profile"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type QueryPath struct {
|
||||||
|
SourceID string `json:"source_id"`
|
||||||
|
TargetID string `json:"target_id"`
|
||||||
|
Distance int `json:"distance"`
|
||||||
|
PathCount int `json:"path_count"`
|
||||||
|
NodeIDs []string `json:"node_ids"`
|
||||||
|
Confidence float64 `json:"total_confidence"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func WorkflowGraphQuery(ctx workflow.Context, input WorkflowGraphQueryInput) (WorkflowGraphQueryOutput, error) {
|
||||||
|
startTime := time.Now()
|
||||||
|
output := WorkflowGraphQueryOutput{
|
||||||
|
WorkflowID: input.WorkflowID,
|
||||||
|
Query: input.Query,
|
||||||
|
Version: input.Version,
|
||||||
|
RankingProfile: input.RankingProfile,
|
||||||
|
Results: []types.EdgeWithWording{},
|
||||||
|
Paths: []QueryPath{},
|
||||||
|
}
|
||||||
|
|
||||||
|
opts := workflow.ActivityOptions{
|
||||||
|
StartToCloseTimeout: 120 * time.Second,
|
||||||
|
RetryPolicy: &temporal.RetryPolicy{
|
||||||
|
InitialInterval: 2 * time.Second,
|
||||||
|
BackoffCoefficient: 2.0,
|
||||||
|
MaximumInterval: 10 * time.Second,
|
||||||
|
MaximumAttempts: 3,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
ctx = workflow.WithActivityOptions(ctx, opts)
|
||||||
|
|
||||||
|
var canvasData types.CanvasWithRelationsData
|
||||||
|
err := workflow.ExecuteActivity(ctx, "FetchCanvasRelationsActivity",
|
||||||
|
types.FetchCanvasRelationsInput{
|
||||||
|
WorkflowID: input.WorkflowID,
|
||||||
|
Version: input.Version,
|
||||||
|
},
|
||||||
|
).Get(ctx, &canvasData)
|
||||||
|
if err != nil {
|
||||||
|
return output, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var graphResults types.GraphRAGQueryOutput
|
||||||
|
err = workflow.ExecuteActivity(ctx, "QueryGraphRAGActivity",
|
||||||
|
types.GraphRAGQueryInput{
|
||||||
|
WorkflowID: input.WorkflowID,
|
||||||
|
Query: input.Query,
|
||||||
|
SearchType: input.SearchType,
|
||||||
|
RelationType: input.RelationType,
|
||||||
|
ConfidenceFloor: input.ConfidenceFloor,
|
||||||
|
TopK: input.TopK,
|
||||||
|
RankingProfile: input.RankingProfile,
|
||||||
|
Canvas: canvasData,
|
||||||
|
},
|
||||||
|
).Get(ctx, &graphResults)
|
||||||
|
if err != nil {
|
||||||
|
return output, err
|
||||||
|
}
|
||||||
|
|
||||||
|
output.Results = graphResults.Edges
|
||||||
|
output.TotalCount = graphResults.TotalCount
|
||||||
|
output.HasMore = graphResults.HasMore
|
||||||
|
output.ExecutionTimeMs = time.Since(startTime).Milliseconds()
|
||||||
|
return output, nil
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user