Compare commits
23 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0dfa20f1d7 | |||
| 15dcdee1cb | |||
| 53fa4d8972 | |||
| ff8542d811 | |||
| 97637ad831 | |||
| 27d699fa73 | |||
| 80bbb8b5f9 | |||
| d310d43ab8 | |||
| 7612c97ae7 | |||
| 8ffea10db0 | |||
| abe516f739 | |||
| 647f40bdd5 | |||
| 2265b32933 | |||
| 3971c26dc1 | |||
| 27d6062992 | |||
| 625d975c3d | |||
| b4919aa921 | |||
| 3a927de63f | |||
| 512a3f8653 | |||
| 0b20e88317 | |||
| abc9dcfc5a | |||
| 080b37c2be | |||
| 7935b73374 |
@@ -7,18 +7,19 @@ on:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
test:
|
||||
check:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
- uses: oven-sh/setup-bun@v2
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install
|
||||
- run: bun install
|
||||
|
||||
- name: Check
|
||||
- name: Build
|
||||
run: bun run build
|
||||
|
||||
- name: Lint
|
||||
run: bun run check
|
||||
|
||||
- name: Test
|
||||
|
||||
@@ -61,6 +61,17 @@ roles:
|
||||
9. Implement the code to make tests pass
|
||||
10. Ensure `bun run build` passes with no errors
|
||||
11. Run `bun test` to verify all tests pass
|
||||
- If tests fail on first run:
|
||||
* Read the test output carefully for missing imports or setup issues
|
||||
* Check if you're running tests from the correct working directory (package root vs workspace root)
|
||||
* Fix the immediate issue and rerun ONCE
|
||||
* If tests still fail after 2 attempts: check the test spec for ambiguities
|
||||
* If stuck after 3 test cycles: set $status=failed with detailed error report rather than continuing blind retries
|
||||
12. MANDATORY VERIFICATION before reporting done:
|
||||
- Run `git branch --show-current` and confirm branch name matches expected
|
||||
- Run `git status` and verify changed files exist
|
||||
- Run `ls -la <key-implementation-files>` to verify they exist on disk
|
||||
- If ANY verification fails: retry the implementation, do NOT report done
|
||||
|
||||
If you cannot complete the implementation (e.g. the issue is too complex, blocked by external factors,
|
||||
or repeated attempts fail), set $status=failed with a reason.
|
||||
@@ -85,7 +96,12 @@ roles:
|
||||
procedure: |
|
||||
The worktree path is provided in your task prompt. cd into it first.
|
||||
|
||||
Before reviewing, verify the git branch:
|
||||
CRITICAL: You MUST execute every verification command below. Do NOT report results without running the actual commands. Do NOT rely on prior context or assumptions.
|
||||
|
||||
Before reviewing, verify the worktree and branch exist:
|
||||
0. Run `cd <worktree-path> && pwd` to confirm the path is accessible
|
||||
- If the cd fails: the worktree truly doesn't exist, reject with that reason
|
||||
- If the cd succeeds: proceed with step 1 below
|
||||
1. Run `git branch --show-current` — confirm the branch name references the issue number being worked on
|
||||
2. If the branch doesn't correspond to the issue, flag it in your output and reject
|
||||
|
||||
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
# UWF Bootstrap Guide
|
||||
|
||||
This guide helps any AI agent set up `uwf` (Uncaged Workflow) from scratch — or self-check and upgrade an existing installation.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- **bun** — `uwf` is built with bun. Install: `curl -fsSL https://bun.sh/install | bash`
|
||||
- **Network access** — to install npm packages
|
||||
|
||||
> **Already have uwf?** Jump to [Self-Check & Upgrade](#self-check--upgrade).
|
||||
|
||||
---
|
||||
|
||||
## Fresh Install
|
||||
|
||||
### 1. Install uwf CLI
|
||||
|
||||
```bash
|
||||
bun install -g @uncaged/cli-workflow
|
||||
```
|
||||
|
||||
✅ **Check:** `uwf --version` prints a version number (e.g. `0.5.1`).
|
||||
|
||||
### 2. Install Agent Adapter
|
||||
|
||||
Install the adapter that matches your agent runtime. Pick **one**:
|
||||
|
||||
| Agent | Package | Binary |
|
||||
|-------|---------|--------|
|
||||
| Hermes | `@uncaged/workflow-agent-hermes` | `uwf-hermes` |
|
||||
|
||||
```bash
|
||||
# Example: Hermes agent
|
||||
bun install -g @uncaged/workflow-agent-hermes
|
||||
```
|
||||
|
||||
✅ **Check:** `uwf-hermes --version` prints a version number.
|
||||
|
||||
### 3. Setup
|
||||
|
||||
Run the interactive wizard:
|
||||
|
||||
```bash
|
||||
uwf setup
|
||||
```
|
||||
|
||||
Or configure non-interactively:
|
||||
|
||||
```bash
|
||||
uwf setup \
|
||||
--provider <name> \
|
||||
--base-url <url> \
|
||||
--api-key <key> \
|
||||
--model <model-name> \
|
||||
--agent hermes
|
||||
```
|
||||
|
||||
This creates `~/.uncaged/workflow/config.yaml` with your provider, model, and default agent.
|
||||
|
||||
#### Config Structure
|
||||
|
||||
```yaml
|
||||
providers:
|
||||
my-provider:
|
||||
baseUrl: https://api.example.com/v1
|
||||
apiKey: sk-xxx
|
||||
models:
|
||||
default:
|
||||
provider: my-provider
|
||||
name: my-model
|
||||
agents:
|
||||
hermes:
|
||||
command: uwf-hermes
|
||||
args: []
|
||||
defaultAgent: hermes
|
||||
defaultModel: default
|
||||
```
|
||||
|
||||
✅ **Check:** `cat ~/.uncaged/workflow/config.yaml` shows valid provider, model, and agent config.
|
||||
|
||||
### 4. Verify Installation
|
||||
|
||||
```bash
|
||||
uwf workflow list # should return empty array or existing workflows
|
||||
uwf skill user # prints usage guide
|
||||
uwf skill author # prints workflow authoring guide
|
||||
```
|
||||
|
||||
✅ **Check:** All three commands run without errors.
|
||||
|
||||
### 5. Add the uwf Skill
|
||||
|
||||
```bash
|
||||
mkdir -p ~/.hermes/skills/devops/uwf
|
||||
uwf skill bootstrap > ~/.hermes/skills/devops/uwf/SKILL.md
|
||||
```
|
||||
|
||||
✅ **Check:** `cat ~/.hermes/skills/devops/uwf/SKILL.md` shows the skill content with triggers `uwf`, `workflow`, `工作流`.
|
||||
|
||||
### 6. Smoke Test
|
||||
|
||||
```bash
|
||||
# Register an example workflow
|
||||
uwf workflow add examples/analyze-topic.yaml
|
||||
|
||||
# Start a thread
|
||||
uwf thread start analyze-topic -p "Analyze the concept of technical debt"
|
||||
|
||||
# Execute it (one moderator → agent → extract cycle)
|
||||
uwf thread exec <thread-id>
|
||||
```
|
||||
|
||||
✅ **Check:** Thread reaches `completed` status. Verify with `uwf thread list`.
|
||||
|
||||
---
|
||||
|
||||
## Self-Check & Upgrade
|
||||
|
||||
Already have uwf installed? Run through this checklist to verify and upgrade.
|
||||
|
||||
### Version Check
|
||||
|
||||
```bash
|
||||
uwf --version
|
||||
uwf-hermes --version # or your agent adapter
|
||||
```
|
||||
|
||||
Compare with latest published versions:
|
||||
|
||||
```bash
|
||||
bun pm ls -g | grep -E "cli-workflow|workflow-agent"
|
||||
npm info @uncaged/cli-workflow version
|
||||
npm info @uncaged/workflow-agent-hermes version
|
||||
```
|
||||
|
||||
If local version < published version, upgrade:
|
||||
|
||||
```bash
|
||||
bun install -g @uncaged/cli-workflow@latest
|
||||
bun install -g @uncaged/workflow-agent-hermes@latest
|
||||
```
|
||||
|
||||
✅ **Check:** `uwf --version` matches `npm info @uncaged/cli-workflow version`.
|
||||
|
||||
### Config Check
|
||||
|
||||
```bash
|
||||
cat ~/.uncaged/workflow/config.yaml
|
||||
```
|
||||
|
||||
Verify:
|
||||
- [ ] `providers` has at least one entry with valid `baseUrl` and `apiKey`
|
||||
- [ ] `models.default` references an existing provider
|
||||
- [ ] `agents` has your adapter configured
|
||||
- [ ] `defaultAgent` and `defaultModel` are set
|
||||
|
||||
### Skill Check
|
||||
|
||||
```bash
|
||||
cat ~/.hermes/skills/devops/uwf/SKILL.md
|
||||
```
|
||||
|
||||
Verify the skill is up to date:
|
||||
|
||||
```bash
|
||||
uwf skill bootstrap | diff - ~/.hermes/skills/devops/uwf/SKILL.md
|
||||
```
|
||||
|
||||
If `diff` produces any output, the local skill is outdated. Update:
|
||||
|
||||
```bash
|
||||
uwf skill bootstrap > ~/.hermes/skills/devops/uwf/SKILL.md
|
||||
```
|
||||
|
||||
### Functional Check
|
||||
|
||||
```bash
|
||||
uwf workflow list # should not error
|
||||
uwf skill user # should print usage guide
|
||||
uwf skill author # should print authoring guide
|
||||
```
|
||||
|
||||
✅ All green? You're good to go.
|
||||
@@ -270,7 +270,7 @@ node scripts/publish-all.mjs --dry-run # preview without publishing
|
||||
examples/solve-issue.yaml — write a workflow YAML definition
|
||||
│ uwf workflow put
|
||||
▼
|
||||
~/.uncaged/workflow/cas/ — Workflow stored as CAS node
|
||||
~/.uncaged/json-cas/ — Workflow stored as CAS node (unified CAS store)
|
||||
~/.uncaged/workflow/registry.yaml — name → hash mapping updated
|
||||
│ uwf thread start <name> -p "..."
|
||||
▼
|
||||
|
||||
+2
-1
@@ -39,7 +39,8 @@
|
||||
"linter": {
|
||||
"rules": {
|
||||
"suspicious": {
|
||||
"noExplicitAny": "off"
|
||||
"noExplicitAny": "off",
|
||||
"noConsole": "off"
|
||||
},
|
||||
"style": {
|
||||
"noNonNullAssertion": "off"
|
||||
|
||||
+7
-1
@@ -1,11 +1,14 @@
|
||||
{
|
||||
"name": "@uncaged/workflow-monorepo",
|
||||
"private": true,
|
||||
"packageManager": "bun@1.3.14",
|
||||
"workspaces": [
|
||||
"packages/*"
|
||||
],
|
||||
"scripts": {
|
||||
"uwf": "bun packages/cli-workflow/src/cli.ts",
|
||||
"preinstall": "npx only-allow bun",
|
||||
"prepublishOnly": "echo 'Use bun run release instead' && exit 1",
|
||||
"build": "bunx tsc --build",
|
||||
"check": "bunx tsc --build && biome check . && bash scripts/lint-log-tags.sh",
|
||||
"typecheck": "bunx tsc --build",
|
||||
@@ -23,7 +26,10 @@
|
||||
"@types/node": "^25.7.0",
|
||||
"@types/xxhashjs": "^0.2.4",
|
||||
"@uncaged/workflow-agent-hermes": "workspace:*",
|
||||
"bun-types": "^1.3.13"
|
||||
"bun-types": "^1.3.13",
|
||||
"typescript": "^5.8.3",
|
||||
"vitest": "^4.1.7",
|
||||
"yaml": "^2.9.0"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -209,4 +209,13 @@ src/
|
||||
| `~/.uncaged/workflow/.env` | API keys (referenced by `apiKeyEnv` in config) |
|
||||
| `~/.uncaged/workflow/registry.yaml` | Workflow name → CAS hash |
|
||||
| `~/.uncaged/workflow/threads.yaml` | Active thread head pointers |
|
||||
| `~/.uncaged/workflow/cas/` | Content-addressed node storage |
|
||||
| `~/.uncaged/json-cas/` | Content-addressed node storage (unified CAS store, shared with `json-cas` CLI) |
|
||||
|
||||
### Environment Variables
|
||||
|
||||
| Variable | Purpose | Default |
|
||||
|----------|---------|---------|
|
||||
| `UNCAGED_CAS_DIR` | Override the global CAS directory location | `~/.uncaged/json-cas` |
|
||||
| `UNCAGED_WORKFLOW_STORAGE_ROOT` | Internal override for workflow metadata storage | `~/.uncaged/workflow` |
|
||||
| `WORKFLOW_STORAGE_ROOT` | User override for workflow metadata storage | `~/.uncaged/workflow` |
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
"yaml": "^2.8.4"
|
||||
},
|
||||
"scripts": {
|
||||
"prepublishOnly": "echo 'Use bun run release from repo root' && exit 1",
|
||||
"test": "vitest run",
|
||||
"test:ci": "vitest run"
|
||||
},
|
||||
@@ -34,12 +35,12 @@
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/shazhou-ww/uncaged-workflow.git",
|
||||
"url": "https://git.shazhou.work/uncaged/workflow.git",
|
||||
"directory": "packages/cli-workflow"
|
||||
},
|
||||
"homepage": "https://github.com/shazhou-ww/uncaged-workflow#readme",
|
||||
"homepage": "https://git.shazhou.work/uncaged/workflow#readme",
|
||||
"bugs": {
|
||||
"url": "https://github.com/shazhou-ww/uncaged-workflow/issues"
|
||||
"url": "https://git.shazhou.work/uncaged/workflow/issues"
|
||||
},
|
||||
"license": "MIT"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { putSchema } from "@uncaged/json-cas";
|
||||
import { createFsStore } from "@uncaged/json-cas-fs";
|
||||
import type { CasRef, StepNodePayload, ThreadId } from "@uncaged/workflow-protocol";
|
||||
import { afterEach, beforeEach, describe, expect, test } from "vitest";
|
||||
import { registerUwfSchemas } from "../schemas.js";
|
||||
import { saveThreadsIndex } from "../store.js";
|
||||
|
||||
// ── schemas ──────────────────────────────────────────────────────────────────
|
||||
|
||||
const OUTPUT_SCHEMA = {
|
||||
type: "object" as const,
|
||||
properties: {
|
||||
$status: { type: "string" as const, enum: ["done", "failed"] },
|
||||
result: { type: "string" as const },
|
||||
},
|
||||
required: ["$status"],
|
||||
additionalProperties: false,
|
||||
};
|
||||
|
||||
// ── fixture ──────────────────────────────────────────────────────────────────
|
||||
|
||||
let tmpDir: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
tmpDir = await mkdtemp(join(tmpdir(), "cli-uwf-roundtrip-test-"));
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(tmpDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("C1: adapter JSON round-trip integration", () => {
|
||||
test("mock agent outputs JSON, CLI parses it and updates thread head in CAS", async () => {
|
||||
// 1. Set up CAS store with workflow, start node, and output schema
|
||||
const casDir = join(tmpDir, "cas");
|
||||
await mkdir(casDir, { recursive: true });
|
||||
const store = createFsStore(casDir);
|
||||
const schemas = await registerUwfSchemas(store);
|
||||
|
||||
const outputSchemaHash = await putSchema(store, OUTPUT_SCHEMA);
|
||||
|
||||
const workflowHash = await store.put(schemas.workflow, {
|
||||
name: "test-roundtrip",
|
||||
description: "roundtrip integration test",
|
||||
roles: {
|
||||
worker: {
|
||||
description: "Worker role",
|
||||
goal: "Do work",
|
||||
capabilities: [],
|
||||
procedure: "work",
|
||||
output: "result",
|
||||
frontmatter: outputSchemaHash,
|
||||
},
|
||||
},
|
||||
graph: {
|
||||
$START: { _: { role: "worker", prompt: "Do the work", location: null } },
|
||||
worker: { done: { role: "$END", prompt: "completed", location: null } },
|
||||
},
|
||||
});
|
||||
|
||||
const startHash = await store.put(schemas.startNode, {
|
||||
workflow: workflowHash,
|
||||
prompt: "Test round-trip task",
|
||||
});
|
||||
|
||||
const threadId = "01ROUNDTRIPTEST0000000000" as ThreadId;
|
||||
await saveThreadsIndex(tmpDir, { [threadId]: startHash });
|
||||
|
||||
// 2. Pre-create CAS nodes that the mock agent would produce
|
||||
const outputHash = await store.put(outputSchemaHash, {
|
||||
$status: "done",
|
||||
result: "test-ok",
|
||||
});
|
||||
|
||||
// Use text schema for detail (simple placeholder)
|
||||
const detailHash = await store.put(schemas.text, "mock detail");
|
||||
|
||||
const startedAtMs = 1716600000000;
|
||||
const completedAtMs = 1716600001500;
|
||||
|
||||
const stepHash = await store.put(schemas.stepNode, {
|
||||
start: startHash,
|
||||
prev: null,
|
||||
role: "worker",
|
||||
output: outputHash,
|
||||
detail: detailHash,
|
||||
agent: "uwf-mock",
|
||||
edgePrompt: "Do the work",
|
||||
startedAtMs,
|
||||
completedAtMs,
|
||||
cwd: tmpDir,
|
||||
});
|
||||
|
||||
// 3. Create a minimal mock agent shell script that just outputs JSON
|
||||
// The step node is already in CAS — the agent just needs to print the JSON line
|
||||
const mockAgentPath = join(tmpDir, "mock-agent.sh");
|
||||
const adapterJson = JSON.stringify({
|
||||
stepHash,
|
||||
detailHash,
|
||||
role: "worker",
|
||||
frontmatter: { $status: "done", result: "test-ok" },
|
||||
body: "",
|
||||
startedAtMs,
|
||||
completedAtMs,
|
||||
});
|
||||
await writeFile(mockAgentPath, `#!/bin/sh\necho '${adapterJson}'\n`, { mode: 0o755 });
|
||||
|
||||
// 4. Write config.yaml
|
||||
const configPath = join(tmpDir, "config.yaml");
|
||||
await writeFile(
|
||||
configPath,
|
||||
`defaultAgent: uwf-hermes\ndefaultModel: test-model\nagentOverrides: null\nagents: {}\nproviders: {}\nmodels: {}\n`,
|
||||
);
|
||||
|
||||
// 5. Run CLI with agent override pointing to our mock
|
||||
const cliPath = join(import.meta.dirname, "..", "cli.js");
|
||||
let stdout: string;
|
||||
let stderr: string;
|
||||
let exitCode: number;
|
||||
|
||||
try {
|
||||
stdout = execFileSync(
|
||||
"bun",
|
||||
["run", cliPath, "thread", "exec", threadId, "--agent", mockAgentPath],
|
||||
{
|
||||
encoding: "utf8",
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
env: {
|
||||
...process.env,
|
||||
WORKFLOW_STORAGE_ROOT: tmpDir,
|
||||
UNCAGED_CAS_DIR: casDir,
|
||||
},
|
||||
cwd: tmpDir,
|
||||
timeout: 30000,
|
||||
},
|
||||
);
|
||||
stderr = "";
|
||||
exitCode = 0;
|
||||
} catch (e: unknown) {
|
||||
const err = e as NodeJS.ErrnoException & {
|
||||
stdout?: string;
|
||||
stderr?: string;
|
||||
status?: number;
|
||||
};
|
||||
stdout = err.stdout ?? "";
|
||||
stderr = err.stderr ?? "";
|
||||
exitCode = err.status ?? 1;
|
||||
}
|
||||
|
||||
// 6. Verify
|
||||
if (exitCode !== 0) {
|
||||
throw new Error(`CLI exited with code ${exitCode}\nstdout: ${stdout}\nstderr: ${stderr}`);
|
||||
}
|
||||
|
||||
// Parse CLI output
|
||||
const cliOutput = JSON.parse(stdout.trim());
|
||||
expect(cliOutput).toHaveProperty("thread", threadId);
|
||||
expect(cliOutput).toHaveProperty("head", stepHash);
|
||||
expect(cliOutput.head).toMatch(/^[0-9A-HJ-NP-TV-Z]{13}$/);
|
||||
|
||||
// Verify the CAS step node exists and has correct metadata
|
||||
const storeAfter = createFsStore(casDir);
|
||||
const stepNode = storeAfter.get(cliOutput.head as CasRef);
|
||||
expect(stepNode).not.toBeNull();
|
||||
|
||||
const payload = stepNode!.payload as StepNodePayload;
|
||||
expect(payload.role).toBe("worker");
|
||||
expect(payload.agent).toBe("uwf-mock");
|
||||
expect(payload.startedAtMs).toBe(1716600000000);
|
||||
expect(payload.completedAtMs).toBe(1716600001500);
|
||||
expect(payload.output).toBe(outputHash);
|
||||
expect(payload.detail).toBe(detailHash);
|
||||
});
|
||||
});
|
||||
@@ -6,14 +6,22 @@ import { afterEach, beforeEach, describe, expect, test } from "vitest";
|
||||
import { cmdCasPutText } from "../commands/cas.js";
|
||||
|
||||
let storageRoot: string;
|
||||
let casDir: string;
|
||||
let uwfPath: string;
|
||||
let originalEnv: string | undefined;
|
||||
|
||||
beforeEach(async () => {
|
||||
storageRoot = join(
|
||||
tmpdir(),
|
||||
`uwf-cas-exit-test-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
||||
);
|
||||
casDir = join(storageRoot, "cas");
|
||||
await mkdir(storageRoot, { recursive: true });
|
||||
await mkdir(casDir, { recursive: true });
|
||||
|
||||
// Set UNCAGED_CAS_DIR for this test
|
||||
originalEnv = process.env.UNCAGED_CAS_DIR;
|
||||
process.env.UNCAGED_CAS_DIR = casDir;
|
||||
|
||||
// Find the uwf CLI path
|
||||
uwfPath = join(__dirname, "../../src/cli.ts");
|
||||
@@ -21,6 +29,13 @@ beforeEach(async () => {
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(storageRoot, { recursive: true, force: true });
|
||||
|
||||
// Restore original environment
|
||||
if (originalEnv === undefined) {
|
||||
delete process.env.UNCAGED_CAS_DIR;
|
||||
} else {
|
||||
process.env.UNCAGED_CAS_DIR = originalEnv;
|
||||
}
|
||||
});
|
||||
|
||||
type ExecResult = {
|
||||
@@ -32,7 +47,11 @@ type ExecResult = {
|
||||
function execUwf(args: string[]): ExecResult {
|
||||
try {
|
||||
const stdout = execSync(`bun ${uwfPath} ${args.join(" ")}`, {
|
||||
env: { ...process.env, WORKFLOW_STORAGE_ROOT: storageRoot },
|
||||
env: {
|
||||
...process.env,
|
||||
WORKFLOW_STORAGE_ROOT: storageRoot,
|
||||
UNCAGED_CAS_DIR: casDir,
|
||||
},
|
||||
encoding: "utf-8",
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
});
|
||||
|
||||
@@ -0,0 +1,456 @@
|
||||
import { mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { putSchema } from "@uncaged/json-cas";
|
||||
import type { CasRef, ThreadId } from "@uncaged/workflow-protocol";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { createMarker, deleteMarker } from "../background/index.js";
|
||||
import { cmdThreadList, cmdThreadShow, cmdThreadStart } from "../commands/thread.js";
|
||||
import {
|
||||
appendThreadHistory,
|
||||
createUwfStore,
|
||||
loadThreadsIndex,
|
||||
saveThreadsIndex,
|
||||
} from "../store.js";
|
||||
|
||||
const OUTPUT_SCHEMA = {
|
||||
type: "object" as const,
|
||||
properties: {
|
||||
$status: { type: "string" as const },
|
||||
},
|
||||
};
|
||||
|
||||
const SIMPLE_WORKFLOW_YAML = `
|
||||
name: test-current-role
|
||||
description: Test workflow for currentRole
|
||||
roles:
|
||||
roleA:
|
||||
description: First role
|
||||
goal: Do A
|
||||
capabilities: ["coding"]
|
||||
procedure: Do A
|
||||
output: |
|
||||
$status: "ready"
|
||||
frontmatter:
|
||||
type: object
|
||||
required: ["$status"]
|
||||
properties:
|
||||
$status: { type: string, enum: ["ready", "not-ready"] }
|
||||
roleB:
|
||||
description: Second role
|
||||
goal: Do B
|
||||
capabilities: ["coding"]
|
||||
procedure: Do B
|
||||
output: |
|
||||
$status: "done"
|
||||
frontmatter:
|
||||
type: object
|
||||
required: ["$status"]
|
||||
properties:
|
||||
$status: { type: string }
|
||||
graph:
|
||||
$START:
|
||||
_:
|
||||
role: roleA
|
||||
prompt: "Do A"
|
||||
location: null
|
||||
roleA:
|
||||
ready:
|
||||
role: roleB
|
||||
prompt: "Do B"
|
||||
location: null
|
||||
not-ready:
|
||||
role: roleA
|
||||
prompt: "Try again"
|
||||
location: null
|
||||
roleB:
|
||||
_:
|
||||
role: $END
|
||||
prompt: "Done"
|
||||
location: null
|
||||
`;
|
||||
|
||||
const CONDITIONAL_WORKFLOW_YAML = `
|
||||
name: test-conditional-role
|
||||
description: Conditional routing workflow
|
||||
roles:
|
||||
roleA:
|
||||
description: First role
|
||||
goal: Do A
|
||||
capabilities: ["coding"]
|
||||
procedure: Do A
|
||||
output: |
|
||||
$status: "pass"
|
||||
frontmatter:
|
||||
type: object
|
||||
required: ["$status"]
|
||||
properties:
|
||||
$status: { type: string, enum: ["pass", "fail"] }
|
||||
roleB:
|
||||
description: Pass role
|
||||
goal: Do B
|
||||
capabilities: ["coding"]
|
||||
procedure: Do B
|
||||
output: |
|
||||
$status: "done"
|
||||
frontmatter:
|
||||
type: object
|
||||
required: ["$status"]
|
||||
properties:
|
||||
$status: { type: string }
|
||||
roleC:
|
||||
description: Fail role
|
||||
goal: Do C
|
||||
capabilities: ["coding"]
|
||||
procedure: Do C
|
||||
output: |
|
||||
$status: "done"
|
||||
frontmatter:
|
||||
type: object
|
||||
required: ["$status"]
|
||||
properties:
|
||||
$status: { type: string }
|
||||
graph:
|
||||
$START:
|
||||
_:
|
||||
role: roleA
|
||||
prompt: "Do A"
|
||||
location: null
|
||||
roleA:
|
||||
pass:
|
||||
role: roleB
|
||||
prompt: "Do B (pass)"
|
||||
location: null
|
||||
fail:
|
||||
role: roleC
|
||||
prompt: "Do C (fail)"
|
||||
location: null
|
||||
roleB:
|
||||
_:
|
||||
role: $END
|
||||
prompt: "Done"
|
||||
location: null
|
||||
roleC:
|
||||
_:
|
||||
role: $END
|
||||
prompt: "Done"
|
||||
location: null
|
||||
`;
|
||||
|
||||
const SINGLE_ROLE_WORKFLOW_YAML = `
|
||||
name: test-single-role
|
||||
description: Single role that goes to END
|
||||
roles:
|
||||
worker:
|
||||
description: Worker
|
||||
goal: Work
|
||||
capabilities: ["coding"]
|
||||
procedure: Work
|
||||
output: |
|
||||
$status: "done"
|
||||
frontmatter:
|
||||
type: object
|
||||
required: ["$status"]
|
||||
properties:
|
||||
$status: { type: string }
|
||||
graph:
|
||||
$START:
|
||||
_:
|
||||
role: worker
|
||||
prompt: "Work"
|
||||
location: null
|
||||
worker:
|
||||
_:
|
||||
role: $END
|
||||
prompt: "Done"
|
||||
location: null
|
||||
`;
|
||||
|
||||
/** Helper: insert a completed step node after the current head. */
|
||||
async function insertStepNode(
|
||||
storageRoot: string,
|
||||
threadId: ThreadId,
|
||||
role: string,
|
||||
outputPayload: Record<string, unknown>,
|
||||
): Promise<void> {
|
||||
const uwf = await createUwfStore(storageRoot);
|
||||
const index = await loadThreadsIndex(storageRoot);
|
||||
const head = index[threadId];
|
||||
if (head === undefined) throw new Error(`thread ${threadId} not in index`);
|
||||
|
||||
const outputSchemaHash = await putSchema(uwf.store, OUTPUT_SCHEMA);
|
||||
const outputHash = await uwf.store.put(outputSchemaHash, outputPayload);
|
||||
|
||||
// Use text schema for detail (simple placeholder)
|
||||
const detailHash = await uwf.store.put(uwf.schemas.text, "detail-placeholder");
|
||||
|
||||
// Resolve start hash from head
|
||||
const headNode = uwf.store.get(head);
|
||||
if (headNode === null) throw new Error(`head ${head} not found`);
|
||||
const isStart = headNode.type === uwf.schemas.startNode;
|
||||
const startHash = isStart ? head : (headNode.payload as { start: CasRef }).start;
|
||||
|
||||
const stepHash = (await uwf.store.put(uwf.schemas.stepNode, {
|
||||
start: startHash,
|
||||
prev: isStart ? null : head,
|
||||
role,
|
||||
prompt: `Do ${role}`,
|
||||
output: outputHash,
|
||||
detail: detailHash,
|
||||
})) as CasRef;
|
||||
|
||||
index[threadId] = stepHash;
|
||||
await saveThreadsIndex(storageRoot, index);
|
||||
}
|
||||
|
||||
describe("currentRole field", () => {
|
||||
let tmpDir: string;
|
||||
let storageRoot: string;
|
||||
let casDir: string;
|
||||
let originalEnv: string | undefined;
|
||||
|
||||
async function setup() {
|
||||
tmpDir = join(
|
||||
tmpdir(),
|
||||
`uwf-test-current-role-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
||||
);
|
||||
storageRoot = join(tmpDir, "storage");
|
||||
casDir = join(tmpDir, "cas");
|
||||
await mkdir(storageRoot, { recursive: true });
|
||||
await mkdir(casDir, { recursive: true });
|
||||
|
||||
// Set UNCAGED_CAS_DIR for this test
|
||||
originalEnv = process.env.UNCAGED_CAS_DIR;
|
||||
process.env.UNCAGED_CAS_DIR = casDir;
|
||||
}
|
||||
|
||||
async function teardown() {
|
||||
if (tmpDir) {
|
||||
await rm(tmpDir, { recursive: true, force: true });
|
||||
}
|
||||
// Restore original environment
|
||||
if (originalEnv === undefined) {
|
||||
delete process.env.UNCAGED_CAS_DIR;
|
||||
} else {
|
||||
process.env.UNCAGED_CAS_DIR = originalEnv;
|
||||
}
|
||||
}
|
||||
|
||||
// T1: idle at start — currentRole = first role from graph
|
||||
test("thread show — idle at start returns first role as currentRole", async () => {
|
||||
await setup();
|
||||
try {
|
||||
const wf = join(tmpDir, "test-current-role.yaml");
|
||||
await writeFile(wf, SIMPLE_WORKFLOW_YAML, "utf8");
|
||||
const { thread } = await cmdThreadStart(storageRoot, wf, "test", tmpDir);
|
||||
|
||||
const result = await cmdThreadShow(storageRoot, thread as ThreadId);
|
||||
expect(result.status).toBe("idle");
|
||||
expect(result.currentRole).toBe("roleA");
|
||||
} finally {
|
||||
await teardown();
|
||||
}
|
||||
});
|
||||
|
||||
// T2: idle after one step — currentRole = next role
|
||||
test("thread show — idle after step returns next role as currentRole", async () => {
|
||||
await setup();
|
||||
try {
|
||||
const wf = join(tmpDir, "test-current-role.yaml");
|
||||
await writeFile(wf, SIMPLE_WORKFLOW_YAML, "utf8");
|
||||
const { thread } = await cmdThreadStart(storageRoot, wf, "test", tmpDir);
|
||||
|
||||
await insertStepNode(storageRoot, thread as ThreadId, "roleA", { $status: "ready" });
|
||||
|
||||
const result = await cmdThreadShow(storageRoot, thread as ThreadId);
|
||||
expect(result.status).toBe("idle");
|
||||
expect(result.currentRole).toBe("roleB");
|
||||
} finally {
|
||||
await teardown();
|
||||
}
|
||||
});
|
||||
|
||||
// T3: completed → currentRole = null
|
||||
test("thread show — completed thread returns null currentRole", async () => {
|
||||
await setup();
|
||||
try {
|
||||
const wf = join(tmpDir, "test-current-role.yaml");
|
||||
await writeFile(wf, SIMPLE_WORKFLOW_YAML, "utf8");
|
||||
const { thread, workflow } = await cmdThreadStart(storageRoot, wf, "test", tmpDir);
|
||||
const tid = thread as ThreadId;
|
||||
|
||||
const index = await loadThreadsIndex(storageRoot);
|
||||
const head = index[tid]!;
|
||||
delete index[tid];
|
||||
await saveThreadsIndex(storageRoot, index);
|
||||
await appendThreadHistory(storageRoot, {
|
||||
thread: tid,
|
||||
workflow,
|
||||
head,
|
||||
completedAt: Date.now(),
|
||||
reason: "completed",
|
||||
});
|
||||
|
||||
const result = await cmdThreadShow(storageRoot, tid);
|
||||
expect(result.status).toBe("completed");
|
||||
expect(result.currentRole).toBe(null);
|
||||
} finally {
|
||||
await teardown();
|
||||
}
|
||||
});
|
||||
|
||||
// T4: cancelled → currentRole = null
|
||||
test("thread show — cancelled thread returns null currentRole", async () => {
|
||||
await setup();
|
||||
try {
|
||||
const wf = join(tmpDir, "test-current-role.yaml");
|
||||
await writeFile(wf, SIMPLE_WORKFLOW_YAML, "utf8");
|
||||
const { thread, workflow } = await cmdThreadStart(storageRoot, wf, "test", tmpDir);
|
||||
const tid = thread as ThreadId;
|
||||
|
||||
const index = await loadThreadsIndex(storageRoot);
|
||||
const head = index[tid]!;
|
||||
delete index[tid];
|
||||
await saveThreadsIndex(storageRoot, index);
|
||||
await appendThreadHistory(storageRoot, {
|
||||
thread: tid,
|
||||
workflow,
|
||||
head,
|
||||
completedAt: Date.now(),
|
||||
reason: "cancelled",
|
||||
});
|
||||
|
||||
const result = await cmdThreadShow(storageRoot, tid);
|
||||
expect(result.status).toBe("cancelled");
|
||||
expect(result.currentRole).toBe(null);
|
||||
} finally {
|
||||
await teardown();
|
||||
}
|
||||
});
|
||||
|
||||
// T5: running → currentRole = role being executed
|
||||
test("thread show — running thread returns current role", async () => {
|
||||
await setup();
|
||||
try {
|
||||
const wf = join(tmpDir, "test-current-role.yaml");
|
||||
await writeFile(wf, SIMPLE_WORKFLOW_YAML, "utf8");
|
||||
const { thread, workflow } = await cmdThreadStart(storageRoot, wf, "test", tmpDir);
|
||||
const tid = thread as ThreadId;
|
||||
|
||||
await createMarker(storageRoot, {
|
||||
thread: tid,
|
||||
workflow,
|
||||
pid: process.pid,
|
||||
startedAt: Date.now(),
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await cmdThreadShow(storageRoot, tid);
|
||||
expect(result.status).toBe("running");
|
||||
expect(result.currentRole).toBe("roleA");
|
||||
} finally {
|
||||
await deleteMarker(storageRoot, tid);
|
||||
}
|
||||
} finally {
|
||||
await teardown();
|
||||
}
|
||||
});
|
||||
|
||||
// T6: thread list — mixed statuses with correct currentRole
|
||||
test("thread list — returns correct currentRole for each status", async () => {
|
||||
await setup();
|
||||
try {
|
||||
const wf = join(tmpDir, "test-current-role.yaml");
|
||||
await writeFile(wf, SIMPLE_WORKFLOW_YAML, "utf8");
|
||||
|
||||
// idle thread
|
||||
const idle = await cmdThreadStart(storageRoot, wf, "idle", tmpDir);
|
||||
const idleId = idle.thread as ThreadId;
|
||||
|
||||
// completed thread
|
||||
const comp = await cmdThreadStart(storageRoot, wf, "completed", tmpDir);
|
||||
const compId = comp.thread as ThreadId;
|
||||
const index = await loadThreadsIndex(storageRoot);
|
||||
const compHead = index[compId]!;
|
||||
delete index[compId];
|
||||
await saveThreadsIndex(storageRoot, index);
|
||||
await appendThreadHistory(storageRoot, {
|
||||
thread: compId,
|
||||
workflow: comp.workflow,
|
||||
head: compHead,
|
||||
completedAt: Date.now(),
|
||||
reason: "completed",
|
||||
});
|
||||
|
||||
const list = await cmdThreadList(storageRoot, null, null, null, 0, 100);
|
||||
|
||||
const idleItem = list.find((i) => i.thread === idleId);
|
||||
expect(idleItem).toBeDefined();
|
||||
expect(idleItem!.currentRole).toBe("roleA");
|
||||
|
||||
const compItem = list.find((i) => i.thread === compId);
|
||||
expect(compItem).toBeDefined();
|
||||
expect(compItem!.currentRole).toBe(null);
|
||||
} finally {
|
||||
await teardown();
|
||||
}
|
||||
});
|
||||
|
||||
// T7: thread list — idle at start has correct currentRole
|
||||
test("thread list — idle thread at start has correct currentRole", async () => {
|
||||
await setup();
|
||||
try {
|
||||
const wf = join(tmpDir, "test-current-role.yaml");
|
||||
await writeFile(wf, SIMPLE_WORKFLOW_YAML, "utf8");
|
||||
const { thread } = await cmdThreadStart(storageRoot, wf, "test", tmpDir);
|
||||
|
||||
const list = await cmdThreadList(storageRoot, null, null, null, 0, 100);
|
||||
const item = list.find((i) => i.thread === (thread as ThreadId));
|
||||
expect(item).toBeDefined();
|
||||
expect(item!.currentRole).toBe("roleA");
|
||||
} finally {
|
||||
await teardown();
|
||||
}
|
||||
});
|
||||
|
||||
// T8: conditional routing — $status=pass vs fail
|
||||
test("thread show — conditional routing selects correct next role", async () => {
|
||||
await setup();
|
||||
try {
|
||||
const wf = join(tmpDir, "test-conditional-role.yaml");
|
||||
await writeFile(wf, CONDITIONAL_WORKFLOW_YAML, "utf8");
|
||||
|
||||
// pass path
|
||||
const t1 = await cmdThreadStart(storageRoot, wf, "pass test", tmpDir);
|
||||
await insertStepNode(storageRoot, t1.thread as ThreadId, "roleA", { $status: "pass" });
|
||||
const r1 = await cmdThreadShow(storageRoot, t1.thread as ThreadId);
|
||||
expect(r1.currentRole).toBe("roleB");
|
||||
|
||||
// fail path
|
||||
const t2 = await cmdThreadStart(storageRoot, wf, "fail test", tmpDir);
|
||||
await insertStepNode(storageRoot, t2.thread as ThreadId, "roleA", { $status: "fail" });
|
||||
const r2 = await cmdThreadShow(storageRoot, t2.thread as ThreadId);
|
||||
expect(r2.currentRole).toBe("roleC");
|
||||
} finally {
|
||||
await teardown();
|
||||
}
|
||||
});
|
||||
|
||||
// T9: next role is $END → currentRole = null
|
||||
test("thread show — when next is $END, currentRole is null", async () => {
|
||||
await setup();
|
||||
try {
|
||||
const wf = join(tmpDir, "test-single-role.yaml");
|
||||
await writeFile(wf, SINGLE_ROLE_WORKFLOW_YAML, "utf8");
|
||||
|
||||
const { thread } = await cmdThreadStart(storageRoot, wf, "test", tmpDir);
|
||||
// worker → _ maps to $END
|
||||
await insertStepNode(storageRoot, thread as ThreadId, "worker", {});
|
||||
|
||||
const result = await cmdThreadShow(storageRoot, thread as ThreadId);
|
||||
expect(result.currentRole).toBe(null);
|
||||
} finally {
|
||||
await teardown();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -6,27 +6,17 @@ import { describe, expect, test } from "vitest";
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
import {
|
||||
cmdSkillActor,
|
||||
cmdSkillAdapter,
|
||||
cmdSkillArchitecture,
|
||||
cmdSkillAuthor,
|
||||
cmdSkillCli,
|
||||
cmdSkillDeveloper,
|
||||
cmdSkillList,
|
||||
cmdSkillModerator,
|
||||
cmdSkillUser,
|
||||
cmdSkillYaml,
|
||||
} from "../commands/skill.js";
|
||||
|
||||
describe("skill commands", () => {
|
||||
test("skill list returns all skill names", () => {
|
||||
const result = cmdSkillList();
|
||||
expect(result).toBeInstanceOf(Array);
|
||||
expect(result).toContain("cli");
|
||||
expect(result).toContain("architecture");
|
||||
expect(result).toContain("yaml");
|
||||
expect(result).toContain("moderator");
|
||||
expect(result).toContain("actor");
|
||||
expect(result).toContain("user");
|
||||
expect(result).toContain("author");
|
||||
expect(result).toContain("developer");
|
||||
@@ -36,50 +26,6 @@ describe("skill commands", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("skill architecture returns non-empty markdown string", () => {
|
||||
const result = cmdSkillArchitecture();
|
||||
expect(typeof result).toBe("string");
|
||||
expect(result).toContain("CAS");
|
||||
expect(result).toContain("Thread");
|
||||
expect(result).toContain("Workflow");
|
||||
expect(result).toContain("Step");
|
||||
expect(result.length).toBeGreaterThan(200);
|
||||
});
|
||||
|
||||
test("skill yaml returns non-empty markdown string", () => {
|
||||
const result = cmdSkillYaml();
|
||||
expect(typeof result).toBe("string");
|
||||
expect(result).toContain("roles");
|
||||
expect(result).toContain("graph");
|
||||
expect(result).toContain("frontmatter");
|
||||
expect(result.length).toBeGreaterThan(200);
|
||||
});
|
||||
|
||||
test("skill moderator returns non-empty markdown string", () => {
|
||||
const result = cmdSkillModerator();
|
||||
expect(typeof result).toBe("string");
|
||||
expect(result).toContain("routing");
|
||||
expect(result).toContain("status");
|
||||
expect(result.length).toBeGreaterThan(200);
|
||||
// Check for edge or graph
|
||||
expect(result).toMatch(/edge|graph/i);
|
||||
});
|
||||
|
||||
test("skill cli returns CLI reference markdown", () => {
|
||||
const result = cmdSkillCli();
|
||||
expect(typeof result).toBe("string");
|
||||
expect(result).toContain("uwf");
|
||||
});
|
||||
|
||||
test("skill actor returns non-empty markdown string", () => {
|
||||
const result = cmdSkillActor();
|
||||
expect(typeof result).toBe("string");
|
||||
expect(result).toContain("frontmatter");
|
||||
expect(result).toContain("CAS");
|
||||
expect(result).toContain("status");
|
||||
expect(result.length).toBeGreaterThan(200);
|
||||
});
|
||||
|
||||
test("skill user returns non-empty markdown string", () => {
|
||||
const result = cmdSkillUser();
|
||||
expect(typeof result).toBe("string");
|
||||
@@ -126,11 +72,6 @@ describe("skill commands", () => {
|
||||
env: { ...process.env, PATH: `/opt/homebrew/bin:${process.env.PATH}` },
|
||||
});
|
||||
expect(output).not.toMatch(/help\s+\[command\]/i);
|
||||
expect(output).toContain("cli");
|
||||
expect(output).toContain("architecture");
|
||||
expect(output).toContain("yaml");
|
||||
expect(output).toContain("moderator");
|
||||
expect(output).toContain("actor");
|
||||
expect(output).toContain("user");
|
||||
expect(output).toContain("author");
|
||||
expect(output).toContain("developer");
|
||||
|
||||
@@ -98,9 +98,51 @@ describe("solve-issue workflow: tea pr create worktree fix", () => {
|
||||
expect(frontmatter).toBeDefined();
|
||||
expect(frontmatter?.oneOf).toBeDefined();
|
||||
const committedVariant = frontmatter.oneOf.find(
|
||||
(v: any) => v.properties?.["$status"]?.const === "committed",
|
||||
(v: any) => v.properties?.$status?.const === "committed",
|
||||
);
|
||||
expect(committedVariant).toBeDefined();
|
||||
expect(committedVariant.required).toContain("$status");
|
||||
});
|
||||
|
||||
test("developer procedure should include mandatory verification step", async () => {
|
||||
const yamlContent = await readFile(workflowPath, "utf-8");
|
||||
const workflow = parse(yamlContent) as WorkflowPayload;
|
||||
|
||||
const developerProcedure = workflow.roles.developer?.procedure;
|
||||
expect(developerProcedure).toBeDefined();
|
||||
|
||||
// Verify the procedure includes mandatory verification step
|
||||
expect(developerProcedure).toContain("MANDATORY VERIFICATION");
|
||||
expect(developerProcedure).toContain("git branch --show-current");
|
||||
expect(developerProcedure).toContain("git status");
|
||||
expect(developerProcedure).toMatch(/ls -la|verify.*exist/i);
|
||||
});
|
||||
|
||||
test("reviewer procedure should enforce worktree path verification", async () => {
|
||||
const yamlContent = await readFile(workflowPath, "utf-8");
|
||||
const workflow = parse(yamlContent) as WorkflowPayload;
|
||||
|
||||
const reviewerProcedure = workflow.roles.reviewer?.procedure;
|
||||
expect(reviewerProcedure).toBeDefined();
|
||||
|
||||
// Verify the procedure includes critical enforcement
|
||||
expect(reviewerProcedure).toContain("CRITICAL");
|
||||
expect(reviewerProcedure).toMatch(/cd.*pwd/);
|
||||
expect(reviewerProcedure).toContain(
|
||||
"Do NOT report results without running the actual commands",
|
||||
);
|
||||
});
|
||||
|
||||
test("developer procedure should include test debugging escalation", async () => {
|
||||
const yamlContent = await readFile(workflowPath, "utf-8");
|
||||
const workflow = parse(yamlContent) as WorkflowPayload;
|
||||
|
||||
const developerProcedure = workflow.roles.developer?.procedure;
|
||||
expect(developerProcedure).toBeDefined();
|
||||
|
||||
// Verify the procedure includes test failure guidance
|
||||
expect(developerProcedure).toMatch(/tests fail.*first run/i);
|
||||
expect(developerProcedure).toMatch(/3 test cycles|after 3 attempts/i);
|
||||
expect(developerProcedure).toContain("$status=failed");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
/**
|
||||
* B-group tests: validate JSON parsing logic used by spawnAgent.
|
||||
*
|
||||
* We test the parsing logic inline since spawnAgent is a private function.
|
||||
* These tests verify the contract: last line of stdout must be valid JSON
|
||||
* with a valid stepHash CasRef.
|
||||
*/
|
||||
|
||||
const CASREF_PATTERN = /^[0-9A-HJ-NP-TV-Z]{13}$/;
|
||||
|
||||
function isCasRef(s: string): boolean {
|
||||
return CASREF_PATTERN.test(s);
|
||||
}
|
||||
|
||||
type AdapterOutput = {
|
||||
stepHash: string;
|
||||
detailHash: string;
|
||||
role: string;
|
||||
frontmatter: Record<string, unknown>;
|
||||
body: string;
|
||||
startedAtMs: number;
|
||||
completedAtMs: number;
|
||||
};
|
||||
|
||||
function parseAgentStdout(stdout: string): AdapterOutput {
|
||||
const line = stdout.trim().split("\n").pop()?.trim() ?? "";
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(line);
|
||||
} catch {
|
||||
throw new Error(`agent stdout last line is not valid JSON: ${line || "(empty)"}`);
|
||||
}
|
||||
const obj = parsed as Record<string, unknown>;
|
||||
if (
|
||||
typeof obj !== "object" ||
|
||||
obj === null ||
|
||||
typeof obj.stepHash !== "string" ||
|
||||
!isCasRef(obj.stepHash as string)
|
||||
) {
|
||||
throw new Error(`agent stdout JSON missing valid stepHash: ${line}`);
|
||||
}
|
||||
return obj as unknown as AdapterOutput;
|
||||
}
|
||||
|
||||
const VALID_OUTPUT: AdapterOutput = {
|
||||
stepHash: "0123456789ABC",
|
||||
detailHash: "DEFGH12345678",
|
||||
role: "planner",
|
||||
frontmatter: { $status: "ready", plan: "somehash" },
|
||||
body: "Plan body",
|
||||
startedAtMs: 1000,
|
||||
completedAtMs: 2000,
|
||||
};
|
||||
|
||||
describe("spawnAgent JSON parsing", () => {
|
||||
test("B1. parses valid JSON from agent stdout", () => {
|
||||
const stdout = `${JSON.stringify(VALID_OUTPUT)}\n`;
|
||||
const result = parseAgentStdout(stdout);
|
||||
expect(result.stepHash).toBe("0123456789ABC");
|
||||
expect(result.detailHash).toBe("DEFGH12345678");
|
||||
expect(result.role).toBe("planner");
|
||||
expect(result.frontmatter).toEqual({ $status: "ready", plan: "somehash" });
|
||||
expect(result.body).toBe("Plan body");
|
||||
expect(result.startedAtMs).toBe(1000);
|
||||
expect(result.completedAtMs).toBe(2000);
|
||||
});
|
||||
|
||||
test("B2. extracts stepHash for head pointer", () => {
|
||||
const stdout = `${JSON.stringify(VALID_OUTPUT)}\n`;
|
||||
const result = parseAgentStdout(stdout);
|
||||
expect(result.stepHash).toBe("0123456789ABC");
|
||||
expect(isCasRef(result.stepHash)).toBe(true);
|
||||
});
|
||||
|
||||
test("B3. handles debug lines before JSON", () => {
|
||||
const debugLines = "[debug] loading context...\n[debug] running agent...\n";
|
||||
const stdout = `${debugLines + JSON.stringify(VALID_OUTPUT)}\n`;
|
||||
const result = parseAgentStdout(stdout);
|
||||
expect(result.stepHash).toBe("0123456789ABC");
|
||||
});
|
||||
|
||||
test("B4. rejects non-JSON last line", () => {
|
||||
const stdout = "not-json-at-all\n";
|
||||
expect(() => parseAgentStdout(stdout)).toThrow("not valid JSON");
|
||||
});
|
||||
|
||||
test("B5. rejects JSON missing stepHash", () => {
|
||||
const incomplete = { detailHash: "DEFGH12345678", role: "planner" };
|
||||
const stdout = `${JSON.stringify(incomplete)}\n`;
|
||||
expect(() => parseAgentStdout(stdout)).toThrow("missing valid stepHash");
|
||||
});
|
||||
|
||||
test("B6. rejects JSON with invalid stepHash", () => {
|
||||
const bad = { ...VALID_OUTPUT, stepHash: "not-a-hash" };
|
||||
const stdout = `${JSON.stringify(bad)}\n`;
|
||||
expect(() => parseAgentStdout(stdout)).toThrow("missing valid stepHash");
|
||||
});
|
||||
});
|
||||
@@ -66,13 +66,21 @@ function generateContent(size: number, prefix = "Content"): string {
|
||||
// ── fixture ───────────────────────────────────────────────────────────────────
|
||||
|
||||
let tmpDir: string;
|
||||
let originalEnv: string | undefined;
|
||||
|
||||
beforeEach(async () => {
|
||||
tmpDir = await mkdtemp(join(tmpdir(), "cli-uwf-step-read-test-"));
|
||||
originalEnv = process.env.UNCAGED_CAS_DIR;
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(tmpDir, { recursive: true, force: true });
|
||||
// Restore original environment
|
||||
if (originalEnv === undefined) {
|
||||
delete process.env.UNCAGED_CAS_DIR;
|
||||
} else {
|
||||
process.env.UNCAGED_CAS_DIR = originalEnv;
|
||||
}
|
||||
});
|
||||
|
||||
// ── step read tests ───────────────────────────────────────────────────────────
|
||||
@@ -80,7 +88,10 @@ afterEach(async () => {
|
||||
describe("step read", () => {
|
||||
test("test 1: basic single-step read with 3 turns", async () => {
|
||||
const casDir = join(tmpDir, "cas");
|
||||
process.env.UNCAGED_CAS_DIR = casDir;
|
||||
await mkdir(casDir, { recursive: true });
|
||||
process.env.UNCAGED_CAS_DIR = casDir;
|
||||
process.env.UNCAGED_CAS_DIR = casDir;
|
||||
const store = createFsStore(casDir);
|
||||
const schemas = await registerUwfSchemas(store);
|
||||
const detailSchemas = await registerDetailSchemas(store);
|
||||
@@ -146,10 +157,11 @@ describe("step read", () => {
|
||||
agent: "uwf-test",
|
||||
startedAtMs: 1000000000000,
|
||||
completedAtMs: 1000000005000,
|
||||
assembledPrompt: null,
|
||||
});
|
||||
|
||||
// Read step with large quota
|
||||
const markdown = await cmdStepRead(tmpDir, stepHash, 10000);
|
||||
const markdown = await cmdStepRead(tmpDir, stepHash, 10000, false);
|
||||
|
||||
// Assert structure
|
||||
expect(markdown).toContain(`# Step ${stepHash}`);
|
||||
@@ -165,7 +177,9 @@ describe("step read", () => {
|
||||
|
||||
test("test 2: quota enforcement - multiple turns", async () => {
|
||||
const casDir = join(tmpDir, "cas");
|
||||
process.env.UNCAGED_CAS_DIR = casDir;
|
||||
await mkdir(casDir, { recursive: true });
|
||||
process.env.UNCAGED_CAS_DIR = casDir;
|
||||
const store = createFsStore(casDir);
|
||||
const schemas = await registerUwfSchemas(store);
|
||||
const detailSchemas = await registerDetailSchemas(store);
|
||||
@@ -231,10 +245,11 @@ describe("step read", () => {
|
||||
agent: "uwf-test",
|
||||
startedAtMs: 1000000000000,
|
||||
completedAtMs: 1000000005000,
|
||||
assembledPrompt: null,
|
||||
});
|
||||
|
||||
// Read step with limited quota (700 chars)
|
||||
const markdown = await cmdStepRead(tmpDir, stepHash, 700);
|
||||
const markdown = await cmdStepRead(tmpDir, stepHash, 700, false);
|
||||
|
||||
// Assert only most recent turns fit
|
||||
expect(markdown).toContain(`# Step ${stepHash}`);
|
||||
@@ -248,7 +263,9 @@ describe("step read", () => {
|
||||
|
||||
test("test 3: minimal quota edge case - always show at least one turn", async () => {
|
||||
const casDir = join(tmpDir, "cas");
|
||||
process.env.UNCAGED_CAS_DIR = casDir;
|
||||
await mkdir(casDir, { recursive: true });
|
||||
process.env.UNCAGED_CAS_DIR = casDir;
|
||||
const store = createFsStore(casDir);
|
||||
const schemas = await registerUwfSchemas(store);
|
||||
const detailSchemas = await registerDetailSchemas(store);
|
||||
@@ -310,10 +327,11 @@ describe("step read", () => {
|
||||
agent: "uwf-test",
|
||||
startedAtMs: 1000000000000,
|
||||
completedAtMs: 1000000005000,
|
||||
assembledPrompt: null,
|
||||
});
|
||||
|
||||
// Read step with minimal quota (1 char)
|
||||
const markdown = await cmdStepRead(tmpDir, stepHash, 1);
|
||||
const markdown = await cmdStepRead(tmpDir, stepHash, 1, false);
|
||||
|
||||
// Assert at least one turn is always shown
|
||||
expect(markdown).toContain("LongTurn");
|
||||
@@ -322,7 +340,9 @@ describe("step read", () => {
|
||||
|
||||
test("test 4: step with no detail field", async () => {
|
||||
const casDir = join(tmpDir, "cas");
|
||||
process.env.UNCAGED_CAS_DIR = casDir;
|
||||
await mkdir(casDir, { recursive: true });
|
||||
process.env.UNCAGED_CAS_DIR = casDir;
|
||||
const store = createFsStore(casDir);
|
||||
const schemas = await registerUwfSchemas(store);
|
||||
|
||||
@@ -365,10 +385,11 @@ describe("step read", () => {
|
||||
agent: "uwf-test",
|
||||
startedAtMs: 1000000000000,
|
||||
completedAtMs: 1000000005000,
|
||||
assembledPrompt: null,
|
||||
});
|
||||
|
||||
// Read step - should return metadata only (no error)
|
||||
const markdown = await cmdStepRead(tmpDir, stepHash, 4000);
|
||||
const markdown = await cmdStepRead(tmpDir, stepHash, 4000, false);
|
||||
|
||||
// Assert metadata is present
|
||||
expect(markdown).toContain(`# Step ${stepHash}`);
|
||||
@@ -380,7 +401,9 @@ describe("step read", () => {
|
||||
|
||||
test("test 5: step with detail but no turns array", async () => {
|
||||
const casDir = join(tmpDir, "cas");
|
||||
process.env.UNCAGED_CAS_DIR = casDir;
|
||||
await mkdir(casDir, { recursive: true });
|
||||
process.env.UNCAGED_CAS_DIR = casDir;
|
||||
const store = createFsStore(casDir);
|
||||
const schemas = await registerUwfSchemas(store);
|
||||
await registerDetailSchemas(store);
|
||||
@@ -441,10 +464,11 @@ describe("step read", () => {
|
||||
agent: "uwf-test",
|
||||
startedAtMs: 1000000000000,
|
||||
completedAtMs: 1000000005000,
|
||||
assembledPrompt: null,
|
||||
});
|
||||
|
||||
// Read step - should return metadata only (no error)
|
||||
const markdown = await cmdStepRead(tmpDir, stepHash, 4000);
|
||||
const markdown = await cmdStepRead(tmpDir, stepHash, 4000, false);
|
||||
|
||||
// Assert metadata is present
|
||||
expect(markdown).toContain(`# Step ${stepHash}`);
|
||||
@@ -455,7 +479,9 @@ describe("step read", () => {
|
||||
|
||||
test("test 6: displays role and tool calls in turn body", async () => {
|
||||
const casDir = join(tmpDir, "cas");
|
||||
process.env.UNCAGED_CAS_DIR = casDir;
|
||||
await mkdir(casDir, { recursive: true });
|
||||
process.env.UNCAGED_CAS_DIR = casDir;
|
||||
const store = createFsStore(casDir);
|
||||
const schemas = await registerUwfSchemas(store);
|
||||
const detailSchemas = await registerDetailSchemas(store);
|
||||
@@ -515,9 +541,10 @@ describe("step read", () => {
|
||||
agent: "uwf-hermes",
|
||||
startedAtMs: 1000000000000,
|
||||
completedAtMs: 1000000005000,
|
||||
assembledPrompt: null,
|
||||
});
|
||||
|
||||
const markdown = await cmdStepRead(tmpDir, stepHash, 4000);
|
||||
const markdown = await cmdStepRead(tmpDir, stepHash, 4000, false);
|
||||
|
||||
expect(markdown).toContain("**Turn role:** assistant");
|
||||
expect(markdown).toContain("**terminal**");
|
||||
@@ -526,7 +553,9 @@ describe("step read", () => {
|
||||
|
||||
test("test 7: turn content with special characters", async () => {
|
||||
const casDir = join(tmpDir, "cas");
|
||||
process.env.UNCAGED_CAS_DIR = casDir;
|
||||
await mkdir(casDir, { recursive: true });
|
||||
process.env.UNCAGED_CAS_DIR = casDir;
|
||||
const store = createFsStore(casDir);
|
||||
const schemas = await registerUwfSchemas(store);
|
||||
const detailSchemas = await registerDetailSchemas(store);
|
||||
@@ -588,10 +617,11 @@ describe("step read", () => {
|
||||
agent: "uwf-test",
|
||||
startedAtMs: 1000000000000,
|
||||
completedAtMs: 1000000005000,
|
||||
assembledPrompt: null,
|
||||
});
|
||||
|
||||
// Read step
|
||||
const markdown = await cmdStepRead(tmpDir, stepHash, 4000);
|
||||
const markdown = await cmdStepRead(tmpDir, stepHash, 4000, false);
|
||||
|
||||
// Assert content is rendered correctly without corruption
|
||||
expect(markdown).toContain("`backticks`");
|
||||
|
||||
@@ -116,6 +116,7 @@ async function createTestStep(
|
||||
edgePrompt: "",
|
||||
startedAtMs: Date.now(),
|
||||
completedAtMs: Date.now() + 1000,
|
||||
assembledPrompt: null,
|
||||
cwd: "/tmp",
|
||||
};
|
||||
return store.put(schemas.stepNode, stepPayload);
|
||||
@@ -124,15 +125,23 @@ async function createTestStep(
|
||||
describe("cmdStepShow JSON serialization", () => {
|
||||
let testDir: string;
|
||||
let casDir: string;
|
||||
let originalEnv: string | undefined;
|
||||
|
||||
beforeEach(async () => {
|
||||
testDir = await mkdtemp(join(tmpdir(), "uwf-test-"));
|
||||
casDir = join(testDir, "cas");
|
||||
await mkdir(casDir, { recursive: true });
|
||||
originalEnv = process.env.UNCAGED_CAS_DIR;
|
||||
process.env.UNCAGED_CAS_DIR = casDir;
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(testDir, { recursive: true, force: true });
|
||||
if (originalEnv === undefined) {
|
||||
delete process.env.UNCAGED_CAS_DIR;
|
||||
} else {
|
||||
process.env.UNCAGED_CAS_DIR = originalEnv;
|
||||
}
|
||||
});
|
||||
|
||||
test("escapes newlines in tool call args", async () => {
|
||||
|
||||
@@ -63,13 +63,22 @@ async function registerDetailSchemas(store: ReturnType<typeof createFsStore>) {
|
||||
// ── fixture ──────────────────────────────────────────────────────────────────
|
||||
|
||||
let tmpDir: string;
|
||||
let originalEnv: string | undefined;
|
||||
|
||||
beforeEach(async () => {
|
||||
tmpDir = await mkdtemp(join(tmpdir(), "cli-uwf-step-timing-test-"));
|
||||
originalEnv = process.env.UNCAGED_CAS_DIR;
|
||||
process.env.UNCAGED_CAS_DIR = join(tmpDir, "cas");
|
||||
await mkdir(process.env.UNCAGED_CAS_DIR, { recursive: true });
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(tmpDir, { recursive: true, force: true });
|
||||
if (originalEnv === undefined) {
|
||||
delete process.env.UNCAGED_CAS_DIR;
|
||||
} else {
|
||||
process.env.UNCAGED_CAS_DIR = originalEnv;
|
||||
}
|
||||
});
|
||||
|
||||
// ── 1. Protocol types (compile-time) ─────────────────────────────────────────
|
||||
@@ -85,6 +94,7 @@ describe("protocol types", () => {
|
||||
edgePrompt: "",
|
||||
startedAtMs: 1000,
|
||||
completedAtMs: 2000,
|
||||
assembledPrompt: null,
|
||||
cwd: "/test/path",
|
||||
};
|
||||
expect(record.startedAtMs).toBe(1000);
|
||||
@@ -153,6 +163,7 @@ describe("StepNode JSON schema", () => {
|
||||
edgePrompt: "",
|
||||
startedAtMs: 1000000000000,
|
||||
completedAtMs: 1000000005000,
|
||||
assembledPrompt: null,
|
||||
});
|
||||
expect(hash).toBeTruthy();
|
||||
});
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
import { mkdir, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, test } from "vitest";
|
||||
import { createUwfStore, getCasDir, getGlobalCasDir } from "../store.js";
|
||||
|
||||
describe("Global CAS directory", () => {
|
||||
let tmpDir: string;
|
||||
let originalEnv: string | undefined;
|
||||
|
||||
beforeEach(async () => {
|
||||
tmpDir = join(tmpdir(), `uwf-test-global-cas-${Date.now()}`);
|
||||
await mkdir(tmpDir, { recursive: true });
|
||||
originalEnv = process.env.UNCAGED_CAS_DIR;
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
if (tmpDir) {
|
||||
await rm(tmpDir, { recursive: true, force: true });
|
||||
}
|
||||
if (originalEnv === undefined) {
|
||||
delete process.env.UNCAGED_CAS_DIR;
|
||||
} else {
|
||||
process.env.UNCAGED_CAS_DIR = originalEnv;
|
||||
}
|
||||
});
|
||||
|
||||
test("getGlobalCasDir returns default path when no env var set", () => {
|
||||
delete process.env.UNCAGED_CAS_DIR;
|
||||
const casDir = getGlobalCasDir();
|
||||
// Should return ~/.uncaged/json-cas
|
||||
expect(casDir).toContain(".uncaged");
|
||||
expect(casDir).toContain("json-cas");
|
||||
});
|
||||
|
||||
test("getGlobalCasDir respects UNCAGED_CAS_DIR environment variable", () => {
|
||||
const customPath = join(tmpDir, "custom-cas");
|
||||
process.env.UNCAGED_CAS_DIR = customPath;
|
||||
const casDir = getGlobalCasDir();
|
||||
expect(casDir).toBe(customPath);
|
||||
});
|
||||
|
||||
test("getGlobalCasDir ignores empty UNCAGED_CAS_DIR", () => {
|
||||
process.env.UNCAGED_CAS_DIR = "";
|
||||
const casDir = getGlobalCasDir();
|
||||
expect(casDir).toContain(".uncaged");
|
||||
expect(casDir).toContain("json-cas");
|
||||
});
|
||||
|
||||
test("getCasDir is deprecated but still works for backward compatibility", () => {
|
||||
const storageRoot = join(tmpDir, "storage");
|
||||
const casDir = getCasDir(storageRoot);
|
||||
expect(casDir).toBe(join(storageRoot, "cas"));
|
||||
});
|
||||
|
||||
test("createUwfStore uses global CAS directory", async () => {
|
||||
const globalCasDir = join(tmpDir, "global-cas");
|
||||
process.env.UNCAGED_CAS_DIR = globalCasDir;
|
||||
|
||||
const storageRoot = join(tmpDir, "storage");
|
||||
await mkdir(storageRoot, { recursive: true });
|
||||
|
||||
const uwf = await createUwfStore(storageRoot);
|
||||
|
||||
// Verify the store was created in the global CAS directory
|
||||
expect(uwf.storageRoot).toBe(storageRoot);
|
||||
expect(uwf.store).toBeDefined();
|
||||
expect(uwf.schemas).toBeDefined();
|
||||
|
||||
// The global CAS directory should be created
|
||||
const { stat } = await import("node:fs/promises");
|
||||
const stats = await stat(globalCasDir);
|
||||
expect(stats.isDirectory()).toBe(true);
|
||||
});
|
||||
|
||||
test("createUwfStore creates global CAS directory if it does not exist", async () => {
|
||||
const globalCasDir = join(tmpDir, "new-global-cas");
|
||||
process.env.UNCAGED_CAS_DIR = globalCasDir;
|
||||
|
||||
const storageRoot = join(tmpDir, "storage");
|
||||
await mkdir(storageRoot, { recursive: true });
|
||||
|
||||
await createUwfStore(storageRoot);
|
||||
|
||||
// Verify the directory was created
|
||||
const { stat } = await import("node:fs/promises");
|
||||
const stats = await stat(globalCasDir);
|
||||
expect(stats.isDirectory()).toBe(true);
|
||||
});
|
||||
|
||||
test("multiple uwfStore instances share the same global CAS filesystem", async () => {
|
||||
const globalCasDir = join(tmpDir, "shared-cas");
|
||||
process.env.UNCAGED_CAS_DIR = globalCasDir;
|
||||
|
||||
const storageRoot1 = join(tmpDir, "storage1");
|
||||
const storageRoot2 = join(tmpDir, "storage2");
|
||||
await mkdir(storageRoot1, { recursive: true });
|
||||
await mkdir(storageRoot2, { recursive: true });
|
||||
|
||||
const uwf1 = await createUwfStore(storageRoot1);
|
||||
const uwf2 = await createUwfStore(storageRoot2);
|
||||
|
||||
// Both should use the same global CAS directory
|
||||
expect(uwf1.store).toBeDefined();
|
||||
expect(uwf2.store).toBeDefined();
|
||||
|
||||
// Store a node in the first store
|
||||
const testData = { test: "data" };
|
||||
const _hash = uwf1.store.put(uwf1.schemas.text, JSON.stringify(testData));
|
||||
|
||||
// Both stores share the same CAS filesystem directory
|
||||
// Since schemas are registered idempotently, they should have the same hash
|
||||
expect(uwf2.schemas.text).toBe(uwf1.schemas.text);
|
||||
|
||||
// Verify the CAS files are written to the shared directory
|
||||
const { readdir } = await import("node:fs/promises");
|
||||
const files = await readdir(globalCasDir);
|
||||
expect(files.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test("workflow metadata remains in storageRoot, not global CAS", async () => {
|
||||
const globalCasDir = join(tmpDir, "global-cas");
|
||||
process.env.UNCAGED_CAS_DIR = globalCasDir;
|
||||
|
||||
const storageRoot = join(tmpDir, "storage");
|
||||
await mkdir(storageRoot, { recursive: true });
|
||||
|
||||
const _uwf = await createUwfStore(storageRoot);
|
||||
|
||||
// Write workflow registry file
|
||||
const { saveWorkflowRegistry } = await import("../store.js");
|
||||
await saveWorkflowRegistry(storageRoot, { "test-workflow": "ABC123" });
|
||||
|
||||
// Verify registry is in storageRoot, not global CAS
|
||||
const { readFile } = await import("node:fs/promises");
|
||||
const registryPath = join(storageRoot, "workflows.yaml");
|
||||
const content = await readFile(registryPath, "utf8");
|
||||
expect(content).toContain("test-workflow");
|
||||
expect(content).toContain("ABC123");
|
||||
|
||||
// Verify registry is NOT in global CAS directory
|
||||
const globalRegistryPath = join(globalCasDir, "workflows.yaml");
|
||||
await expect(readFile(globalRegistryPath, "utf8")).rejects.toThrow();
|
||||
});
|
||||
|
||||
test("thread metadata remains in storageRoot", async () => {
|
||||
const globalCasDir = join(tmpDir, "global-cas");
|
||||
process.env.UNCAGED_CAS_DIR = globalCasDir;
|
||||
|
||||
const storageRoot = join(tmpDir, "storage");
|
||||
await mkdir(storageRoot, { recursive: true });
|
||||
|
||||
await createUwfStore(storageRoot);
|
||||
|
||||
// Write threads index
|
||||
const { saveThreadsIndex } = await import("../store.js");
|
||||
await saveThreadsIndex(storageRoot, { "thread-123": "hash-456" });
|
||||
|
||||
// Verify threads.yaml is in storageRoot, not global CAS
|
||||
const { readFile } = await import("node:fs/promises");
|
||||
const threadsPath = join(storageRoot, "threads.yaml");
|
||||
const content = await readFile(threadsPath, "utf8");
|
||||
expect(content).toContain("thread-123");
|
||||
expect(content).toContain("hash-456");
|
||||
|
||||
// Verify threads.yaml is NOT in global CAS directory
|
||||
const globalThreadsPath = join(globalCasDir, "threads.yaml");
|
||||
await expect(readFile(globalThreadsPath, "utf8")).rejects.toThrow();
|
||||
});
|
||||
|
||||
test("history remains in storageRoot", async () => {
|
||||
const globalCasDir = join(tmpDir, "global-cas");
|
||||
process.env.UNCAGED_CAS_DIR = globalCasDir;
|
||||
|
||||
const storageRoot = join(tmpDir, "storage");
|
||||
await mkdir(storageRoot, { recursive: true });
|
||||
|
||||
await createUwfStore(storageRoot);
|
||||
|
||||
// Write history
|
||||
const { appendThreadHistory } = await import("../store.js");
|
||||
await appendThreadHistory(storageRoot, {
|
||||
thread: "thread-123" as any,
|
||||
workflow: "workflow-456",
|
||||
head: "hash-789",
|
||||
completedAt: Date.now(),
|
||||
reason: "completed",
|
||||
});
|
||||
|
||||
// Verify history.jsonl is in storageRoot, not global CAS
|
||||
const { readFile } = await import("node:fs/promises");
|
||||
const historyPath = join(storageRoot, "history.jsonl");
|
||||
const content = await readFile(historyPath, "utf8");
|
||||
expect(content).toContain("thread-123");
|
||||
expect(content).toContain("workflow-456");
|
||||
|
||||
// Verify history.jsonl is NOT in global CAS directory
|
||||
const globalHistoryPath = join(globalCasDir, "history.jsonl");
|
||||
await expect(readFile(globalHistoryPath, "utf8")).rejects.toThrow();
|
||||
});
|
||||
|
||||
test("CAS nodes are stored in global directory", async () => {
|
||||
const globalCasDir = join(tmpDir, "global-cas");
|
||||
process.env.UNCAGED_CAS_DIR = globalCasDir;
|
||||
|
||||
const storageRoot = join(tmpDir, "storage");
|
||||
await mkdir(storageRoot, { recursive: true });
|
||||
|
||||
const uwf = await createUwfStore(storageRoot);
|
||||
|
||||
// Store a CAS node
|
||||
const testPayload = JSON.stringify({ test: "node" });
|
||||
const _hash = uwf.store.put(uwf.schemas.text, testPayload);
|
||||
|
||||
// Verify the node is in global CAS directory
|
||||
const { readdir } = await import("node:fs/promises");
|
||||
const files = await readdir(globalCasDir);
|
||||
expect(files.length).toBeGreaterThan(0);
|
||||
|
||||
// Verify the node is NOT in the old storageRoot/cas location
|
||||
const oldCasDir = join(storageRoot, "cas");
|
||||
await expect(readdir(oldCasDir)).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -15,6 +15,8 @@ import { appendThreadHistory, createUwfStore, saveThreadsIndex } from "../store.
|
||||
async function makeUwfStore(storageRoot: string): Promise<UwfStore> {
|
||||
const casDir = join(storageRoot, "cas");
|
||||
await mkdir(casDir, { recursive: true });
|
||||
// Set UNCAGED_CAS_DIR to use the test's CAS directory
|
||||
process.env.UNCAGED_CAS_DIR = casDir;
|
||||
return createUwfStore(storageRoot);
|
||||
}
|
||||
|
||||
|
||||
@@ -9,17 +9,31 @@ import { createUwfStore } from "../store.js";
|
||||
describe("Thread and edge location integration", () => {
|
||||
let tmpDir: string;
|
||||
let storageRoot: string;
|
||||
let casDir: string;
|
||||
let originalEnv: string | undefined;
|
||||
|
||||
async function setupTestEnv() {
|
||||
tmpDir = join(tmpdir(), `uwf-test-location-${Date.now()}`);
|
||||
storageRoot = join(tmpDir, "storage");
|
||||
casDir = join(tmpDir, "cas");
|
||||
await mkdir(storageRoot, { recursive: true });
|
||||
await mkdir(casDir, { recursive: true });
|
||||
|
||||
// Set UNCAGED_CAS_DIR for this test
|
||||
originalEnv = process.env.UNCAGED_CAS_DIR;
|
||||
process.env.UNCAGED_CAS_DIR = casDir;
|
||||
}
|
||||
|
||||
async function teardown() {
|
||||
if (tmpDir) {
|
||||
await rm(tmpDir, { recursive: true, force: true });
|
||||
}
|
||||
// Restore original environment
|
||||
if (originalEnv === undefined) {
|
||||
delete process.env.UNCAGED_CAS_DIR;
|
||||
} else {
|
||||
process.env.UNCAGED_CAS_DIR = originalEnv;
|
||||
}
|
||||
}
|
||||
|
||||
test("thread start captures cwd in StartNode", async () => {
|
||||
|
||||
@@ -67,13 +67,22 @@ function generateContent(size: number, prefix = "Content"): string {
|
||||
// ── fixture ───────────────────────────────────────────────────────────────────
|
||||
|
||||
let tmpDir: string;
|
||||
let originalEnv: string | undefined;
|
||||
|
||||
beforeEach(async () => {
|
||||
tmpDir = await mkdtemp(join(tmpdir(), "cli-uwf-quota-test-"));
|
||||
originalEnv = process.env.UNCAGED_CAS_DIR;
|
||||
process.env.UNCAGED_CAS_DIR = join(tmpDir, "cas");
|
||||
await mkdir(process.env.UNCAGED_CAS_DIR, { recursive: true });
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(tmpDir, { recursive: true, force: true });
|
||||
if (originalEnv === undefined) {
|
||||
delete process.env.UNCAGED_CAS_DIR;
|
||||
} else {
|
||||
process.env.UNCAGED_CAS_DIR = originalEnv;
|
||||
}
|
||||
});
|
||||
|
||||
// ── thread read quota enforcement ─────────────────────────────────────────────
|
||||
@@ -143,6 +152,7 @@ describe("thread read --quota flag", () => {
|
||||
agent: "uwf-test",
|
||||
startedAtMs: 1000000000000,
|
||||
completedAtMs: 1000000005000,
|
||||
assembledPrompt: null,
|
||||
});
|
||||
steps.push(stepHash);
|
||||
}
|
||||
@@ -225,6 +235,7 @@ describe("thread read --quota flag", () => {
|
||||
agent: "uwf-test",
|
||||
startedAtMs: 1000000000000,
|
||||
completedAtMs: 1000000005000,
|
||||
assembledPrompt: null,
|
||||
});
|
||||
|
||||
const step2Content = generateContent(600, "Second");
|
||||
@@ -251,6 +262,7 @@ describe("thread read --quota flag", () => {
|
||||
agent: "uwf-test",
|
||||
startedAtMs: 1000000000000,
|
||||
completedAtMs: 1000000005000,
|
||||
assembledPrompt: null,
|
||||
});
|
||||
|
||||
const threadId = "01HX2Q3R4S5T6V7W8X9YZ1" as ThreadId;
|
||||
@@ -336,6 +348,7 @@ describe("thread read --quota flag", () => {
|
||||
agent: "uwf-test",
|
||||
startedAtMs: 1000000000000,
|
||||
completedAtMs: 1000000005000,
|
||||
assembledPrompt: null,
|
||||
});
|
||||
steps.push(stepHash);
|
||||
}
|
||||
@@ -415,6 +428,7 @@ describe("thread read --quota flag", () => {
|
||||
agent: "uwf-test",
|
||||
startedAtMs: 1000000000000,
|
||||
completedAtMs: 1000000005000,
|
||||
assembledPrompt: null,
|
||||
});
|
||||
|
||||
const threadId = "01HX2Q3R4S5T6V7W8X9YZ4" as ThreadId;
|
||||
@@ -492,6 +506,7 @@ describe("thread read --quota flag", () => {
|
||||
agent: "uwf-test",
|
||||
startedAtMs: 1000000000000,
|
||||
completedAtMs: 1000000005000,
|
||||
assembledPrompt: null,
|
||||
});
|
||||
steps.push(stepHash);
|
||||
}
|
||||
@@ -573,6 +588,7 @@ describe("thread read --quota flag", () => {
|
||||
agent: "uwf-test",
|
||||
startedAtMs: 1000000000000,
|
||||
completedAtMs: 1000000005000,
|
||||
assembledPrompt: null,
|
||||
});
|
||||
steps.push(stepHash);
|
||||
}
|
||||
|
||||
@@ -53,6 +53,8 @@ const DETAIL_SCHEMA = {
|
||||
async function makeUwfStore(storageRoot: string): Promise<UwfStore> {
|
||||
const casDir = join(storageRoot, "cas");
|
||||
await mkdir(casDir, { recursive: true });
|
||||
// Set UNCAGED_CAS_DIR to use the test's CAS directory
|
||||
process.env.UNCAGED_CAS_DIR = casDir;
|
||||
const store = createFsStore(casDir);
|
||||
const schemas = await registerUwfSchemas(store);
|
||||
return { storageRoot, store, schemas };
|
||||
@@ -141,6 +143,7 @@ describe("thread read XML tag isolation", () => {
|
||||
agent: "uwf-claude-code",
|
||||
startedAtMs: 1000000000000,
|
||||
completedAtMs: 1000000005000,
|
||||
assembledPrompt: null,
|
||||
});
|
||||
|
||||
const threadId = "01JTEST0000000000000001" as ThreadId;
|
||||
@@ -218,6 +221,7 @@ describe("thread read XML tag isolation", () => {
|
||||
agent: "uwf-claude-code",
|
||||
startedAtMs: 1000000000000,
|
||||
completedAtMs: 1000000005000,
|
||||
assembledPrompt: null,
|
||||
});
|
||||
|
||||
const threadId = "01JTEST0000000000000002" as ThreadId;
|
||||
@@ -280,6 +284,7 @@ describe("thread read XML tag isolation", () => {
|
||||
agent: "uwf-test",
|
||||
startedAtMs: 1000000000000,
|
||||
completedAtMs: 1000000005000,
|
||||
assembledPrompt: null,
|
||||
});
|
||||
|
||||
const step2 = await uwf.store.put(uwf.schemas.stepNode, {
|
||||
@@ -291,6 +296,7 @@ describe("thread read XML tag isolation", () => {
|
||||
agent: "uwf-test",
|
||||
startedAtMs: 1000000000000,
|
||||
completedAtMs: 1000000005000,
|
||||
assembledPrompt: null,
|
||||
});
|
||||
|
||||
const threadId = "01JTEST0000000000000003" as ThreadId;
|
||||
@@ -345,6 +351,7 @@ describe("thread read XML tag isolation", () => {
|
||||
agent: "uwf-test",
|
||||
startedAtMs: 1000000000000,
|
||||
completedAtMs: 1000000005000,
|
||||
assembledPrompt: null,
|
||||
});
|
||||
|
||||
const threadId = "01JTEST0000000000000004" as ThreadId;
|
||||
@@ -399,6 +406,7 @@ describe("thread read XML tag isolation", () => {
|
||||
agent: "uwf-test",
|
||||
startedAtMs: 1000000000000,
|
||||
completedAtMs: 1000000005000,
|
||||
assembledPrompt: null,
|
||||
});
|
||||
|
||||
const threadId = "01JTEST0000000000000005" as ThreadId;
|
||||
@@ -453,6 +461,7 @@ describe("thread read XML tag isolation", () => {
|
||||
agent: "uwf-test",
|
||||
startedAtMs: 1000000000000,
|
||||
completedAtMs: 1000000005000,
|
||||
assembledPrompt: null,
|
||||
});
|
||||
|
||||
const threadId = "01JTEST0000000000000006" as ThreadId;
|
||||
@@ -527,6 +536,7 @@ describe("thread read XML tag isolation", () => {
|
||||
agent: "uwf-test",
|
||||
startedAtMs: 1000000000000,
|
||||
completedAtMs: 1000000005000,
|
||||
assembledPrompt: null,
|
||||
});
|
||||
|
||||
const step2 = await uwf.store.put(uwf.schemas.stepNode, {
|
||||
@@ -538,6 +548,7 @@ describe("thread read XML tag isolation", () => {
|
||||
agent: "uwf-test",
|
||||
startedAtMs: 1000000000000,
|
||||
completedAtMs: 1000000005000,
|
||||
assembledPrompt: null,
|
||||
});
|
||||
|
||||
const step3 = await uwf.store.put(uwf.schemas.stepNode, {
|
||||
@@ -549,6 +560,7 @@ describe("thread read XML tag isolation", () => {
|
||||
agent: "uwf-test",
|
||||
startedAtMs: 1000000000000,
|
||||
completedAtMs: 1000000005000,
|
||||
assembledPrompt: null,
|
||||
});
|
||||
|
||||
const threadId = "01JTEST0000000000000007" as ThreadId;
|
||||
@@ -629,6 +641,7 @@ describe("thread read XML tag isolation", () => {
|
||||
agent: "uwf-test",
|
||||
startedAtMs: 1000000000000,
|
||||
completedAtMs: 1000000005000,
|
||||
assembledPrompt: null,
|
||||
});
|
||||
|
||||
const threadId = "01JTEST0000000000000008" as ThreadId;
|
||||
@@ -685,6 +698,7 @@ describe("thread read XML tag isolation", () => {
|
||||
agent: "uwf-test",
|
||||
startedAtMs: 1000000000000,
|
||||
completedAtMs: 1000000005000,
|
||||
assembledPrompt: null,
|
||||
})) as CasRef;
|
||||
steps.push(step);
|
||||
prev = step;
|
||||
|
||||
@@ -10,17 +10,31 @@ import { createUwfStore, loadThreadsIndex } from "../store.js";
|
||||
describe("thread start --cwd CLI option", () => {
|
||||
let tmpDir: string;
|
||||
let storageRoot: string;
|
||||
let casDir: string;
|
||||
let originalEnv: string | undefined;
|
||||
|
||||
async function setupTestEnv() {
|
||||
tmpDir = join(tmpdir(), `uwf-test-cwd-cli-${Date.now()}`);
|
||||
storageRoot = join(tmpDir, "storage");
|
||||
casDir = join(tmpDir, "cas");
|
||||
await mkdir(storageRoot, { recursive: true });
|
||||
await mkdir(casDir, { recursive: true });
|
||||
|
||||
// Set UNCAGED_CAS_DIR for this test
|
||||
originalEnv = process.env.UNCAGED_CAS_DIR;
|
||||
process.env.UNCAGED_CAS_DIR = casDir;
|
||||
}
|
||||
|
||||
async function teardown() {
|
||||
if (tmpDir) {
|
||||
await rm(tmpDir, { recursive: true, force: true });
|
||||
}
|
||||
// Restore original environment
|
||||
if (originalEnv === undefined) {
|
||||
delete process.env.UNCAGED_CAS_DIR;
|
||||
} else {
|
||||
process.env.UNCAGED_CAS_DIR = originalEnv;
|
||||
}
|
||||
}
|
||||
|
||||
async function createTestWorkflow(): Promise<string> {
|
||||
@@ -123,7 +137,7 @@ graph:
|
||||
|
||||
// Register the workflow
|
||||
execFileSync("node", [uwfBin, "workflow", "add", workflowPath], {
|
||||
env: { ...process.env, UWF_STORAGE_ROOT: storageRoot },
|
||||
env: { ...process.env, UWF_STORAGE_ROOT: storageRoot, UNCAGED_CAS_DIR: casDir },
|
||||
encoding: "utf8",
|
||||
});
|
||||
|
||||
@@ -132,7 +146,7 @@ graph:
|
||||
"node",
|
||||
[uwfBin, "thread", "start", "test-cwd-cli", "-p", "test prompt", "--cwd", testCwd],
|
||||
{
|
||||
env: { ...process.env, UWF_STORAGE_ROOT: storageRoot },
|
||||
env: { ...process.env, UWF_STORAGE_ROOT: storageRoot, UNCAGED_CAS_DIR: casDir },
|
||||
encoding: "utf8",
|
||||
},
|
||||
);
|
||||
|
||||
@@ -58,6 +58,8 @@ const DETAIL_SCHEMA = {
|
||||
async function makeUwfStore(storageRoot: string): Promise<UwfStore> {
|
||||
const casDir = join(storageRoot, "cas");
|
||||
await mkdir(casDir, { recursive: true });
|
||||
// Set UNCAGED_CAS_DIR to use the test's CAS directory
|
||||
process.env.UNCAGED_CAS_DIR = casDir;
|
||||
const store = createFsStore(casDir);
|
||||
const schemas = await registerUwfSchemas(store);
|
||||
return { storageRoot, store, schemas };
|
||||
|
||||
@@ -15,6 +15,8 @@ import { loadWorkflowRegistry, saveWorkflowRegistry } from "../store.js";
|
||||
async function makeUwfStore(storageRoot: string): Promise<UwfStore> {
|
||||
const casDir = join(storageRoot, "cas");
|
||||
await mkdir(casDir, { recursive: true });
|
||||
// Set UNCAGED_CAS_DIR to use the test's CAS directory
|
||||
process.env.UNCAGED_CAS_DIR = casDir;
|
||||
const store = createFsStore(casDir);
|
||||
const schemas = await registerUwfSchemas(store);
|
||||
return { storageRoot, store, schemas };
|
||||
|
||||
@@ -17,16 +17,12 @@ import { cmdConfigGet, cmdConfigList, cmdConfigSet } from "./commands/config.js"
|
||||
import { cmdLogClean, cmdLogList, cmdLogShow } from "./commands/log.js";
|
||||
import { cmdSetup, cmdSetupInteractive } from "./commands/setup.js";
|
||||
import {
|
||||
cmdSkillActor,
|
||||
cmdSkillAdapter,
|
||||
cmdSkillArchitecture,
|
||||
cmdSkillAuthor,
|
||||
cmdSkillCli,
|
||||
cmdSkillBootstrap,
|
||||
cmdSkillDeveloper,
|
||||
cmdSkillList,
|
||||
cmdSkillModerator,
|
||||
cmdSkillUser,
|
||||
cmdSkillYaml,
|
||||
} from "./commands/skill.js";
|
||||
import { cmdStepFork, cmdStepList, cmdStepRead, cmdStepShow } from "./commands/step.js";
|
||||
import {
|
||||
@@ -368,7 +364,8 @@ step
|
||||
.description("Read a step's turns as human-readable markdown")
|
||||
.argument("<step-hash>", "CAS hash of the StepNode")
|
||||
.option("--quota <chars>", "Max output characters", "4000")
|
||||
.action((stepHash: string, opts: { quota: string }) => {
|
||||
.option("--prompt", "Show the assembled prompt sent to the agent instead of turns")
|
||||
.action((stepHash: string, opts: { quota: string; prompt: boolean }) => {
|
||||
const storageRoot = resolveStorageRoot();
|
||||
runAction(async () => {
|
||||
const quota = Number.parseInt(opts.quota, 10);
|
||||
@@ -376,7 +373,12 @@ step
|
||||
process.stderr.write("invalid --quota: must be a positive integer\n");
|
||||
process.exit(1);
|
||||
}
|
||||
const markdown = await cmdStepRead(storageRoot, stepHash as CasRef, quota);
|
||||
const markdown = await cmdStepRead(
|
||||
storageRoot,
|
||||
stepHash as CasRef,
|
||||
quota,
|
||||
opts.prompt === true,
|
||||
);
|
||||
process.stdout.write(markdown.endsWith("\n") ? markdown : `${markdown}\n`);
|
||||
});
|
||||
});
|
||||
@@ -493,34 +495,6 @@ For more information, see: uwf help thread list
|
||||
const skill = program.command("skill").description("Built-in skill references for agents");
|
||||
skill.addHelpCommand(false);
|
||||
|
||||
skill
|
||||
.command("cli")
|
||||
.description("Print a markdown reference of all uwf commands")
|
||||
.action(() => {
|
||||
console.log(cmdSkillCli());
|
||||
});
|
||||
|
||||
skill
|
||||
.command("architecture")
|
||||
.description("Print the architecture reference")
|
||||
.action(() => {
|
||||
console.log(cmdSkillArchitecture());
|
||||
});
|
||||
|
||||
skill
|
||||
.command("yaml")
|
||||
.description("Print the workflow YAML schema reference")
|
||||
.action(() => {
|
||||
console.log(cmdSkillYaml());
|
||||
});
|
||||
|
||||
skill
|
||||
.command("actor")
|
||||
.description("Print the actor reference (frontmatter protocol + CAS)")
|
||||
.action(() => {
|
||||
console.log(cmdSkillActor());
|
||||
});
|
||||
|
||||
skill
|
||||
.command("adapter")
|
||||
.description("Print the adapter reference (building agent adapters)")
|
||||
@@ -542,13 +516,6 @@ skill
|
||||
console.log(cmdSkillDeveloper());
|
||||
});
|
||||
|
||||
skill
|
||||
.command("moderator")
|
||||
.description("Print the moderator reference")
|
||||
.action(() => {
|
||||
console.log(cmdSkillModerator());
|
||||
});
|
||||
|
||||
skill
|
||||
.command("user")
|
||||
.description("Print the user reference (CLI guide + typical workflows)")
|
||||
@@ -556,6 +523,13 @@ skill
|
||||
console.log(cmdSkillUser());
|
||||
});
|
||||
|
||||
skill
|
||||
.command("bootstrap")
|
||||
.description("Print the bootstrap skill YAML for Hermes agents")
|
||||
.action(() => {
|
||||
console.log(cmdSkillBootstrap());
|
||||
});
|
||||
|
||||
skill
|
||||
.command("list")
|
||||
.description("List all available skill names")
|
||||
|
||||
@@ -1,26 +1,12 @@
|
||||
export {
|
||||
generateActorReference as cmdSkillActor,
|
||||
generateAdapterReference as cmdSkillAdapter,
|
||||
generateArchitectureReference as cmdSkillArchitecture,
|
||||
generateAuthorReference as cmdSkillAuthor,
|
||||
generateCliReference as cmdSkillCli,
|
||||
generateBootstrapReference as cmdSkillBootstrap,
|
||||
generateDeveloperReference as cmdSkillDeveloper,
|
||||
generateModeratorReference as cmdSkillModerator,
|
||||
generateUserReference as cmdSkillUser,
|
||||
generateYamlReference as cmdSkillYaml,
|
||||
} from "@uncaged/workflow-util";
|
||||
|
||||
const SKILL_NAMES = [
|
||||
"cli",
|
||||
"architecture",
|
||||
"yaml",
|
||||
"moderator",
|
||||
"actor",
|
||||
"user",
|
||||
"author",
|
||||
"developer",
|
||||
"adapter",
|
||||
] as const;
|
||||
const SKILL_NAMES = ["user", "author", "developer", "adapter", "bootstrap"] as const;
|
||||
|
||||
export function cmdSkillList(): ReadonlyArray<string> {
|
||||
return [...SKILL_NAMES];
|
||||
|
||||
@@ -289,6 +289,7 @@ export async function cmdStepRead(
|
||||
storageRoot: string,
|
||||
stepHash: CasRef,
|
||||
quota: number,
|
||||
showPrompt: boolean,
|
||||
): Promise<string> {
|
||||
const uwf = await createUwfStore(storageRoot);
|
||||
const node = uwf.store.get(stepHash);
|
||||
@@ -300,6 +301,23 @@ export async function cmdStepRead(
|
||||
}
|
||||
const payload = node.payload as StepNodePayload;
|
||||
|
||||
// --prompt mode: show the assembled prompt that was sent to the agent
|
||||
if (showPrompt) {
|
||||
const promptRef = (payload as Record<string, unknown>).assembledPrompt;
|
||||
if (typeof promptRef !== "string") {
|
||||
return `# Step ${stepHash}\n\n_Prompt not recorded (legacy step)._`;
|
||||
}
|
||||
const promptNode = uwf.store.get(promptRef as CasRef);
|
||||
if (promptNode === null) {
|
||||
return `# Step ${stepHash}\n\n_Prompt CAS node not found: ${promptRef}_`;
|
||||
}
|
||||
const promptText =
|
||||
typeof promptNode.payload === "string"
|
||||
? promptNode.payload
|
||||
: JSON.stringify(promptNode.payload);
|
||||
return `# Step ${stepHash}\n\n**Role:** ${payload.role}\n**Agent:** ${payload.agent}\n\n## Prompt\n\n${promptText}`;
|
||||
}
|
||||
|
||||
if (payload.detail === null) {
|
||||
return formatStepMarkdown(stepHash, payload.role, payload.agent, [], []);
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
generateUlid,
|
||||
type ProcessLogger,
|
||||
} from "@uncaged/workflow-util";
|
||||
import type { AdapterOutput } from "@uncaged/workflow-util-agent";
|
||||
import { getEnvPath, loadWorkflowConfig } from "@uncaged/workflow-util-agent";
|
||||
import { config as loadDotenv } from "dotenv";
|
||||
import { parse } from "yaml";
|
||||
@@ -56,6 +57,21 @@ const END_ROLE = "$END";
|
||||
const START_ROLE = "$START";
|
||||
export const THREAD_READ_DEFAULT_QUOTA = 4000;
|
||||
|
||||
/**
|
||||
* Derive the current/next role from the workflow graph and chain state.
|
||||
* Returns null when the next role is $END or evaluation fails.
|
||||
*/
|
||||
function resolveCurrentRole(uwf: UwfStore, head: CasRef, workflowRef: CasRef): string | null {
|
||||
const chain = walkChain(uwf, head);
|
||||
const { lastRole, lastOutput } = resolveEvaluateArgs(uwf, chain);
|
||||
const workflow = loadWorkflowPayload(uwf, workflowRef);
|
||||
const result = evaluate(workflow.graph, lastRole, lastOutput);
|
||||
if (!result.ok) {
|
||||
return null;
|
||||
}
|
||||
return result.value.role === END_ROLE ? null : result.value.role;
|
||||
}
|
||||
|
||||
const PL_THREAD_START = "7HNQ4B2X";
|
||||
const PL_MODERATOR = "M3K8V9T1";
|
||||
const PL_AGENT_SPAWN = "R5J2W8N4";
|
||||
@@ -320,12 +336,14 @@ export async function cmdThreadShow(storageRoot: string, threadId: ThreadId): Pr
|
||||
// Check if thread is running
|
||||
const runningMarker = await isThreadRunning(storageRoot, threadId);
|
||||
const status: ThreadStatus = runningMarker !== null ? "running" : "idle";
|
||||
const currentRole = resolveCurrentRole(uwf, activeHead, workflow);
|
||||
|
||||
return {
|
||||
workflow,
|
||||
thread: threadId,
|
||||
head: activeHead,
|
||||
status,
|
||||
currentRole,
|
||||
done: false,
|
||||
background: null,
|
||||
};
|
||||
@@ -340,6 +358,7 @@ export async function cmdThreadShow(storageRoot: string, threadId: ThreadId): Pr
|
||||
thread: threadId,
|
||||
head: hist.head,
|
||||
status,
|
||||
currentRole: null,
|
||||
done: true,
|
||||
background: null,
|
||||
};
|
||||
@@ -350,6 +369,7 @@ export async function cmdThreadShow(storageRoot: string, threadId: ThreadId): Pr
|
||||
|
||||
export type ThreadListItemWithStatus = ThreadListItem & {
|
||||
status: ThreadStatus;
|
||||
currentRole: string | null;
|
||||
};
|
||||
|
||||
async function threadListItemFromActive(
|
||||
@@ -367,7 +387,13 @@ async function threadListItemFromActive(
|
||||
const runningMarker = await isThreadRunning(storageRoot, threadId);
|
||||
const status: ThreadStatus = runningMarker !== null ? "running" : "idle";
|
||||
|
||||
return { thread: threadId, workflow, head, status };
|
||||
return {
|
||||
thread: threadId,
|
||||
workflow,
|
||||
head,
|
||||
status,
|
||||
currentRole: resolveCurrentRole(uwf, head, workflow),
|
||||
};
|
||||
}
|
||||
|
||||
async function collectActiveThreads(
|
||||
@@ -405,6 +431,7 @@ async function collectCompletedThreads(
|
||||
workflow: entry.workflow,
|
||||
head: entry.head,
|
||||
status: entry.reason === "cancelled" ? "cancelled" : "completed",
|
||||
currentRole: null,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -788,7 +815,7 @@ function spawnAgent(
|
||||
role: string,
|
||||
edgePrompt: string,
|
||||
cwd: string,
|
||||
): CasRef {
|
||||
): AdapterOutput {
|
||||
const argv = [...agent.args, "--thread", threadId, "--role", role, "--prompt", edgePrompt];
|
||||
let stdout: string;
|
||||
try {
|
||||
@@ -811,10 +838,22 @@ function spawnAgent(
|
||||
}
|
||||
|
||||
const line = stdout.trim().split("\n").pop()?.trim() ?? "";
|
||||
if (!isCasRef(line)) {
|
||||
failStep(plog, `agent stdout is not a valid CAS hash: ${line || "(empty)"}`);
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(line);
|
||||
} catch {
|
||||
failStep(plog, `agent stdout last line is not valid JSON: ${line || "(empty)"}`);
|
||||
}
|
||||
return line;
|
||||
const obj = parsed as Record<string, unknown>;
|
||||
if (
|
||||
typeof obj !== "object" ||
|
||||
obj === null ||
|
||||
typeof obj.stepHash !== "string" ||
|
||||
!isCasRef(obj.stepHash as string)
|
||||
) {
|
||||
failStep(plog, `agent stdout JSON missing valid stepHash: ${line}`);
|
||||
}
|
||||
return obj as unknown as AdapterOutput;
|
||||
}
|
||||
|
||||
async function archiveThread(
|
||||
@@ -925,6 +964,8 @@ async function cmdThreadStepBackground(
|
||||
failStep(plog, `thread not active: ${threadId}`);
|
||||
}
|
||||
|
||||
const uwf = await createUwfStore(storageRoot);
|
||||
|
||||
// Spawn detached background process
|
||||
const scriptPath = process.argv[1];
|
||||
if (scriptPath === undefined) {
|
||||
@@ -956,6 +997,7 @@ async function cmdThreadStepBackground(
|
||||
thread: threadId,
|
||||
head: headHash,
|
||||
status: "running",
|
||||
currentRole: resolveCurrentRole(uwf, headHash, workflowHash),
|
||||
done: false,
|
||||
background: true,
|
||||
},
|
||||
@@ -999,6 +1041,7 @@ async function cmdThreadStepOnce(
|
||||
thread: threadId,
|
||||
head: headHash,
|
||||
status: "completed",
|
||||
currentRole: null,
|
||||
done: true,
|
||||
background: null,
|
||||
};
|
||||
@@ -1019,7 +1062,8 @@ async function cmdThreadStepOnce(
|
||||
});
|
||||
|
||||
loadDotenv({ path: getEnvPath(storageRoot) });
|
||||
const newHead = spawnAgent(plog, agent, threadId, role, edgePrompt, effectiveCwd);
|
||||
const agentResult = spawnAgent(plog, agent, threadId, role, edgePrompt, effectiveCwd);
|
||||
const newHead = agentResult.stepHash as CasRef;
|
||||
|
||||
plog.log(PL_AGENT_DONE, `agent returned head=${newHead}`, null);
|
||||
|
||||
@@ -1053,12 +1097,14 @@ async function cmdThreadStepOnce(
|
||||
|
||||
// Determine status based on whether thread is done and running state
|
||||
const status: ThreadStatus = done ? "completed" : "idle";
|
||||
const currentRole = done ? null : afterResult.value.role;
|
||||
|
||||
return {
|
||||
workflow: workflowHash,
|
||||
thread: threadId,
|
||||
head: newHead,
|
||||
status,
|
||||
currentRole,
|
||||
done,
|
||||
background: null,
|
||||
};
|
||||
|
||||
@@ -70,10 +70,26 @@ export function resolveStorageRoot(): string {
|
||||
return getDefaultStorageRoot();
|
||||
}
|
||||
|
||||
/**
|
||||
* Deprecated: Use `getGlobalCasDir()` instead.
|
||||
* Returns the old CAS directory for backward compatibility.
|
||||
*/
|
||||
export function getCasDir(storageRoot: string): string {
|
||||
return join(storageRoot, "cas");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the global CAS directory shared by all uwf and json-cas tools.
|
||||
* Priority: UNCAGED_CAS_DIR environment variable → default ~/.uncaged/json-cas
|
||||
*/
|
||||
export function getGlobalCasDir(): string {
|
||||
const envPath = process.env.UNCAGED_CAS_DIR;
|
||||
if (envPath !== undefined && envPath !== "") {
|
||||
return envPath;
|
||||
}
|
||||
return join(homedir(), ".uncaged", "json-cas");
|
||||
}
|
||||
|
||||
export function getRegistryPath(storageRoot: string): string {
|
||||
return join(storageRoot, "workflows.yaml");
|
||||
}
|
||||
@@ -98,7 +114,7 @@ export type UwfStore = {
|
||||
};
|
||||
|
||||
export async function createUwfStore(storageRoot: string): Promise<UwfStore> {
|
||||
const casDir = getCasDir(storageRoot);
|
||||
const casDir = getGlobalCasDir();
|
||||
await mkdir(casDir, { recursive: true });
|
||||
const store = createFsStore(casDir);
|
||||
const schemas = await registerUwfSchemas(store);
|
||||
|
||||
@@ -3,5 +3,6 @@ import { defineConfig } from "vitest/config";
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ["src/__tests__/**/*.test.ts"],
|
||||
passWithNoTests: true,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -18,8 +18,9 @@
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"test": "bun test",
|
||||
"test:ci": "bun test"
|
||||
"prepublishOnly": "echo 'Use bun run release from repo root' && exit 1",
|
||||
"test": "vitest run",
|
||||
"test:ci": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@uncaged/json-cas": "^0.5.3",
|
||||
@@ -34,12 +35,12 @@
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/shazhou-ww/uncaged-workflow.git",
|
||||
"url": "https://git.shazhou.work/uncaged/workflow.git",
|
||||
"directory": "packages/workflow-agent-builtin"
|
||||
},
|
||||
"homepage": "https://github.com/shazhou-ww/uncaged-workflow#readme",
|
||||
"homepage": "https://git.shazhou.work/uncaged/workflow#readme",
|
||||
"bugs": {
|
||||
"url": "https://github.com/shazhou-ww/uncaged-workflow/issues"
|
||||
"url": "https://git.shazhou.work/uncaged/workflow/issues"
|
||||
},
|
||||
"license": "MIT"
|
||||
}
|
||||
|
||||
@@ -82,7 +82,7 @@ async function runBuiltinWithMessages(
|
||||
|
||||
if (loopResult.turnCount === 0) {
|
||||
log("5RWTK9NB", "no turns produced, returning empty output");
|
||||
return { output: "", detailHash: "", sessionId: session.sessionId };
|
||||
return { output: "", detailHash: "", sessionId: session.sessionId, assembledPrompt: "" };
|
||||
}
|
||||
|
||||
// Read jsonl → persist turns to CAS → store detail
|
||||
@@ -94,7 +94,12 @@ async function runBuiltinWithMessages(
|
||||
session.startedAtMs,
|
||||
);
|
||||
|
||||
return { output: stripPreamble(loopResult.finalText), detailHash, sessionId: session.sessionId };
|
||||
return {
|
||||
output: stripPreamble(loopResult.finalText),
|
||||
detailHash,
|
||||
sessionId: session.sessionId,
|
||||
assembledPrompt: "",
|
||||
};
|
||||
}
|
||||
|
||||
async function runBuiltin(ctx: AgentContext): Promise<AgentRunResult> {
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { defineConfig } from "vitest/config";
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ["src/__tests__/**/*.test.ts"],
|
||||
passWithNoTests: true,
|
||||
},
|
||||
});
|
||||
@@ -301,6 +301,179 @@ describe("storeClaudeCodeDetail", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseClaudeCodeStreamOutput — incomplete output (no result line)", () => {
|
||||
test("Test 1.1: parses stream with turns but no result line", () => {
|
||||
const lines = [
|
||||
JSON.stringify({
|
||||
type: "system",
|
||||
subtype: "init",
|
||||
session_id: "sess-incomplete-1",
|
||||
model: "claude-sonnet-4.5",
|
||||
}),
|
||||
JSON.stringify({
|
||||
type: "assistant",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: [{ type: "text", text: "Starting work..." }],
|
||||
},
|
||||
}),
|
||||
JSON.stringify({
|
||||
type: "assistant",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: [{ type: "text", text: "This is the last assistant message." }],
|
||||
},
|
||||
}),
|
||||
];
|
||||
const stdout = lines.join("\n");
|
||||
const parsed = parseClaudeCodeStreamOutput(stdout);
|
||||
|
||||
expect(parsed).not.toBeNull();
|
||||
expect(parsed!.subtype).toBe("incomplete");
|
||||
expect(parsed!.result).toBe("This is the last assistant message.");
|
||||
expect(parsed!.sessionId).toBe("sess-incomplete-1");
|
||||
expect(parsed!.model).toBe("claude-sonnet-4.5");
|
||||
expect(parsed!.turns).toHaveLength(2);
|
||||
expect(parsed!.stopReason).toBe("incomplete_no_result_line");
|
||||
expect(parsed!.numTurns).toBe(2);
|
||||
expect(parsed!.durationMs).toBe(0);
|
||||
expect(parsed!.totalCostUsd).toBe(0);
|
||||
});
|
||||
|
||||
test("Test 1.2: parses stream with no turns and no result line", () => {
|
||||
const lines = [
|
||||
JSON.stringify({
|
||||
type: "system",
|
||||
session_id: "sess-no-turns",
|
||||
model: "claude-opus-4",
|
||||
}),
|
||||
];
|
||||
const stdout = lines.join("\n");
|
||||
const parsed = parseClaudeCodeStreamOutput(stdout);
|
||||
|
||||
expect(parsed).not.toBeNull();
|
||||
expect(parsed!.subtype).toBe("incomplete");
|
||||
expect(parsed!.result).toBe("");
|
||||
expect(parsed!.sessionId).toBe("sess-no-turns");
|
||||
expect(parsed!.model).toBe("claude-opus-4");
|
||||
expect(parsed!.turns).toHaveLength(0);
|
||||
expect(parsed!.stopReason).toBe("incomplete_no_result_line");
|
||||
});
|
||||
|
||||
test("Test 1.3: returns null for completely empty output", () => {
|
||||
const parsed1 = parseClaudeCodeStreamOutput("");
|
||||
expect(parsed1).toBeNull();
|
||||
|
||||
const parsed2 = parseClaudeCodeStreamOutput(" \n \n ");
|
||||
expect(parsed2).toBeNull();
|
||||
});
|
||||
|
||||
test("Test 1.4: returns null for malformed JSON lines only", () => {
|
||||
const stdout = "not json\n{broken json\n[invalid";
|
||||
const parsed = parseClaudeCodeStreamOutput(stdout);
|
||||
expect(parsed).toBeNull();
|
||||
});
|
||||
|
||||
test("Test 6.1: extracts from last assistant text-only turn", () => {
|
||||
const lines = [
|
||||
JSON.stringify({ type: "system", session_id: "s1", model: "test" }),
|
||||
JSON.stringify({
|
||||
type: "assistant",
|
||||
message: { role: "assistant", content: [{ type: "text", text: "First message" }] },
|
||||
}),
|
||||
JSON.stringify({
|
||||
type: "assistant",
|
||||
message: { role: "assistant", content: [{ type: "text", text: "Last message" }] },
|
||||
}),
|
||||
];
|
||||
const parsed = parseClaudeCodeStreamOutput(lines.join("\n"));
|
||||
expect(parsed).not.toBeNull();
|
||||
expect(parsed!.result).toBe("Last message");
|
||||
});
|
||||
|
||||
test("Test 6.2: extracts from last assistant turn with tool calls", () => {
|
||||
const lines = [
|
||||
JSON.stringify({ type: "system", session_id: "s1", model: "test" }),
|
||||
JSON.stringify({
|
||||
type: "assistant",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: [
|
||||
{ type: "text", text: "Text with tools" },
|
||||
{ type: "tool_use", name: "Bash", input: { command: "ls" } },
|
||||
],
|
||||
},
|
||||
}),
|
||||
];
|
||||
const parsed = parseClaudeCodeStreamOutput(lines.join("\n"));
|
||||
expect(parsed).not.toBeNull();
|
||||
expect(parsed!.result).toBe("Text with tools");
|
||||
});
|
||||
|
||||
test("Test 6.3: returns empty string when no assistant turns", () => {
|
||||
const lines = [JSON.stringify({ type: "system", session_id: "s1", model: "test" })];
|
||||
const parsed = parseClaudeCodeStreamOutput(lines.join("\n"));
|
||||
expect(parsed).not.toBeNull();
|
||||
expect(parsed!.result).toBe("");
|
||||
});
|
||||
|
||||
test("Test 6.4: extracts from most recent assistant turn before tool_result", () => {
|
||||
const lines = [
|
||||
JSON.stringify({ type: "system", session_id: "s1", model: "test" }),
|
||||
JSON.stringify({
|
||||
type: "assistant",
|
||||
message: { role: "assistant", content: [{ type: "text", text: "Before tool call" }] },
|
||||
}),
|
||||
JSON.stringify({
|
||||
type: "user",
|
||||
message: { role: "user", content: [{ type: "tool_result", content: "tool output" }] },
|
||||
}),
|
||||
];
|
||||
const parsed = parseClaudeCodeStreamOutput(lines.join("\n"));
|
||||
expect(parsed).not.toBeNull();
|
||||
expect(parsed!.result).toBe("Before tool call");
|
||||
});
|
||||
});
|
||||
|
||||
describe("storeClaudeCodeDetail — incomplete results", () => {
|
||||
test("Test 4.1: stores incomplete result as detail", async () => {
|
||||
const store = createMemoryStore();
|
||||
const incompleteParsed: ClaudeCodeParsedResult = {
|
||||
type: "result",
|
||||
subtype: "incomplete",
|
||||
result: "Partial output",
|
||||
sessionId: "sess-incomplete",
|
||||
numTurns: 2,
|
||||
totalCostUsd: 0,
|
||||
durationMs: 0,
|
||||
model: "claude-sonnet-4.5",
|
||||
stopReason: "incomplete_no_result_line",
|
||||
usage: {
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
cacheReadInputTokens: 0,
|
||||
cacheCreationInputTokens: 0,
|
||||
},
|
||||
turns: [
|
||||
{ index: 0, role: "assistant", content: "Turn 1", toolCalls: null },
|
||||
{ index: 1, role: "assistant", content: "Partial output", toolCalls: null },
|
||||
],
|
||||
};
|
||||
|
||||
const { detailHash, output, sessionId } = await storeClaudeCodeDetail(store, incompleteParsed);
|
||||
|
||||
expect(detailHash).toHaveLength(13);
|
||||
expect(output).toBe("Partial output");
|
||||
expect(sessionId).toBe("sess-incomplete");
|
||||
|
||||
const node = await store.get(detailHash);
|
||||
expect(node).not.toBeNull();
|
||||
expect(node!.payload.subtype).toBe("incomplete");
|
||||
expect(node!.payload.stopReason).toBe("incomplete_no_result_line");
|
||||
expect(node!.payload.turns).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("storeClaudeCodeRawOutput", () => {
|
||||
test("stores raw text when JSON parsing fails", async () => {
|
||||
const store = createMemoryStore();
|
||||
|
||||
@@ -18,8 +18,9 @@
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"test": "bun test",
|
||||
"test:ci": "bun test"
|
||||
"prepublishOnly": "echo 'Use bun run release from repo root' && exit 1",
|
||||
"test": "vitest run",
|
||||
"test:ci": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@uncaged/json-cas": "^0.5.3",
|
||||
@@ -34,12 +35,12 @@
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/shazhou-ww/uncaged-workflow.git",
|
||||
"url": "https://git.shazhou.work/uncaged/workflow.git",
|
||||
"directory": "packages/workflow-agent-claude-code"
|
||||
},
|
||||
"homepage": "https://github.com/shazhou-ww/uncaged-workflow#readme",
|
||||
"homepage": "https://git.shazhou.work/uncaged/workflow#readme",
|
||||
"bugs": {
|
||||
"url": "https://github.com/shazhou-ww/uncaged-workflow/issues"
|
||||
"url": "https://git.shazhou.work/uncaged/workflow/issues"
|
||||
},
|
||||
"license": "MIT"
|
||||
}
|
||||
|
||||
@@ -48,7 +48,9 @@ export function buildClaudeCodePrompt(ctx: AgentContext): string {
|
||||
return parts.join("\n");
|
||||
}
|
||||
|
||||
function spawnClaude(args: string[]): Promise<{ stdout: string; stderr: string }> {
|
||||
function spawnClaude(
|
||||
args: string[],
|
||||
): Promise<{ stdout: string; stderr: string; exitCode: number | null }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn(CLAUDE_COMMAND, args, {
|
||||
env: process.env,
|
||||
@@ -72,7 +74,7 @@ function spawnClaude(args: string[]): Promise<{ stdout: string; stderr: string }
|
||||
|
||||
child.on("close", (code) => {
|
||||
if (code === 0) {
|
||||
resolve({ stdout, stderr });
|
||||
resolve({ stdout, stderr, exitCode: code });
|
||||
return;
|
||||
}
|
||||
const detail = stderr.trim() !== "" ? ` stderr=${stderr.trim()}` : "";
|
||||
@@ -81,7 +83,9 @@ function spawnClaude(args: string[]): Promise<{ stdout: string; stderr: string }
|
||||
});
|
||||
}
|
||||
|
||||
function spawnClaudeRun(prompt: string): Promise<{ stdout: string; stderr: string }> {
|
||||
function spawnClaudeRun(
|
||||
prompt: string,
|
||||
): Promise<{ stdout: string; stderr: string; exitCode: number | null }> {
|
||||
const args = [
|
||||
"-p",
|
||||
prompt,
|
||||
@@ -101,7 +105,7 @@ function spawnClaudeRun(prompt: string): Promise<{ stdout: string; stderr: strin
|
||||
function spawnClaudeResume(
|
||||
sessionId: string,
|
||||
message: string,
|
||||
): Promise<{ stdout: string; stderr: string }> {
|
||||
): Promise<{ stdout: string; stderr: string; exitCode: number | null }> {
|
||||
const args = [
|
||||
"-p",
|
||||
message,
|
||||
@@ -120,16 +124,36 @@ function spawnClaudeResume(
|
||||
return spawnClaude(args);
|
||||
}
|
||||
|
||||
async function processClaudeOutput(stdout: string, store: Store): Promise<AgentRunResult> {
|
||||
async function processClaudeOutput(
|
||||
stdout: string,
|
||||
stderr: string,
|
||||
exitCode: number | null,
|
||||
store: Store,
|
||||
assembledPrompt: string,
|
||||
): Promise<AgentRunResult> {
|
||||
const parsed = parseClaudeCodeStreamOutput(stdout);
|
||||
|
||||
if (parsed !== null) {
|
||||
const { detailHash, output, sessionId } = await storeClaudeCodeDetail(store, parsed);
|
||||
return { output, detailHash, sessionId };
|
||||
|
||||
// Log incomplete results for visibility
|
||||
if (parsed.subtype === "incomplete") {
|
||||
log(
|
||||
"7NQW8R4P",
|
||||
`Claude Code exited with incomplete output (no result line). Exit code: ${exitCode ?? "null"}, stderr: ${stderr.slice(0, 200)}`,
|
||||
);
|
||||
}
|
||||
|
||||
return { output, detailHash, sessionId, assembledPrompt };
|
||||
}
|
||||
|
||||
// Truly unparseable output - provide enhanced error message
|
||||
const exitInfo = exitCode !== null && exitCode !== 0 ? `Exit code: ${exitCode}\n` : "";
|
||||
const stderrInfo = stderr.trim() !== "" ? `Stderr: ${stderr.slice(0, 200)}\n` : "";
|
||||
const stdoutSnippet = stdout.slice(0, 200);
|
||||
|
||||
throw new Error(
|
||||
`Claude Code returned unparseable output (first 200 chars): ${stdout.slice(0, 200)}`,
|
||||
`Claude Code exited without producing parseable output.\n${exitInfo}${stderrInfo}Stdout (first 200 chars): ${stdoutSnippet}`,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -143,8 +167,8 @@ async function runClaudeCode(ctx: AgentContext): Promise<AgentRunResult> {
|
||||
const cachedSessionId = await getCachedSessionId("claude-code", ctx.threadId, ctx.role);
|
||||
if (cachedSessionId !== null) {
|
||||
try {
|
||||
const { stdout } = await spawnClaudeResume(cachedSessionId, fullPrompt);
|
||||
const result = await processClaudeOutput(stdout, ctx.store);
|
||||
const { stdout, stderr, exitCode } = await spawnClaudeResume(cachedSessionId, fullPrompt);
|
||||
const result = await processClaudeOutput(stdout, stderr, exitCode, ctx.store, fullPrompt);
|
||||
if (result.sessionId !== undefined && result.sessionId !== "") {
|
||||
await setCachedSessionId("claude-code", ctx.threadId, ctx.role, result.sessionId);
|
||||
}
|
||||
@@ -152,16 +176,14 @@ async function runClaudeCode(ctx: AgentContext): Promise<AgentRunResult> {
|
||||
} catch (err) {
|
||||
log(
|
||||
"5VKR8N3Q",
|
||||
"resume failed for session %s, falling back to fresh run: %s",
|
||||
cachedSessionId,
|
||||
err,
|
||||
`resume failed for session ${cachedSessionId}, falling back to fresh run: ${err}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const { stdout } = await spawnClaudeRun(fullPrompt);
|
||||
const result = await processClaudeOutput(stdout, ctx.store);
|
||||
const { stdout, stderr, exitCode } = await spawnClaudeRun(fullPrompt);
|
||||
const result = await processClaudeOutput(stdout, stderr, exitCode, ctx.store, fullPrompt);
|
||||
if (result.sessionId !== undefined && result.sessionId !== "") {
|
||||
await setCachedSessionId("claude-code", ctx.threadId, ctx.role, result.sessionId);
|
||||
}
|
||||
@@ -173,8 +195,8 @@ async function continueClaudeCode(
|
||||
message: string,
|
||||
store: Store,
|
||||
): Promise<AgentRunResult> {
|
||||
const { stdout } = await spawnClaudeResume(sessionId, message);
|
||||
return processClaudeOutput(stdout, store);
|
||||
const { stdout, stderr, exitCode } = await spawnClaudeResume(sessionId, message);
|
||||
return processClaudeOutput(stdout, stderr, exitCode, store, "");
|
||||
}
|
||||
|
||||
/** Agent CLI factory: parses argv, runs Claude Code, extracts output, writes StepNode. */
|
||||
|
||||
@@ -71,6 +71,7 @@ type ParseState = {
|
||||
turns: ClaudeCodeTurnPayload[];
|
||||
resultLine: Record<string, unknown> | null;
|
||||
model: string;
|
||||
sessionId: string;
|
||||
turnIndex: number;
|
||||
};
|
||||
|
||||
@@ -78,6 +79,9 @@ function processSystemLine(parsed: Record<string, unknown>, state: ParseState):
|
||||
if (typeof parsed.model === "string") {
|
||||
state.model = parsed.model;
|
||||
}
|
||||
if (typeof parsed.session_id === "string") {
|
||||
state.sessionId = parsed.session_id;
|
||||
}
|
||||
}
|
||||
|
||||
function processAssistantLine(parsed: Record<string, unknown>, state: ParseState): void {
|
||||
@@ -124,8 +128,52 @@ function processLine(line: string, state: ParseState): void {
|
||||
else if (type === "result") state.resultLine = parsed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract output text from the last assistant turn.
|
||||
* Used for best-effort extraction when no result line is present.
|
||||
*/
|
||||
function extractLastAssistantContent(turns: ClaudeCodeTurnPayload[]): string {
|
||||
for (let i = turns.length - 1; i >= 0; i--) {
|
||||
const turn = turns[i];
|
||||
if (turn !== undefined && turn.role === "assistant" && turn.content !== "") {
|
||||
return turn.content;
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function assembleResult(state: ParseState): ClaudeCodeParsedResult | null {
|
||||
if (state.resultLine === null) return null;
|
||||
// Handle incomplete result (no result line)
|
||||
if (state.resultLine === null) {
|
||||
// Need at least a session_id from system line to be parseable
|
||||
if (state.sessionId === "") {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Best-effort extraction: get output from last assistant turn
|
||||
const result = extractLastAssistantContent(state.turns);
|
||||
|
||||
return {
|
||||
type: "result",
|
||||
subtype: "incomplete",
|
||||
result,
|
||||
sessionId: state.sessionId,
|
||||
numTurns: state.turns.length,
|
||||
totalCostUsd: 0,
|
||||
durationMs: 0,
|
||||
model: state.model,
|
||||
stopReason: "incomplete_no_result_line",
|
||||
usage: {
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
cacheReadInputTokens: 0,
|
||||
cacheCreationInputTokens: 0,
|
||||
},
|
||||
turns: state.turns,
|
||||
};
|
||||
}
|
||||
|
||||
// Handle complete result (has result line)
|
||||
const sessionId = state.resultLine.session_id;
|
||||
const result = state.resultLine.result;
|
||||
const subtype = state.resultLine.subtype;
|
||||
@@ -159,7 +207,13 @@ function assembleResult(state: ParseState): ClaudeCodeParsedResult | null {
|
||||
*/
|
||||
export function parseClaudeCodeStreamOutput(stdout: string): ClaudeCodeParsedResult | null {
|
||||
const lines = stdout.trim().split("\n");
|
||||
const state: ParseState = { turns: [], resultLine: null, model: "", turnIndex: 0 };
|
||||
const state: ParseState = {
|
||||
turns: [],
|
||||
resultLine: null,
|
||||
model: "",
|
||||
sessionId: "",
|
||||
turnIndex: 0,
|
||||
};
|
||||
for (const line of lines) {
|
||||
processLine(line, state);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export type ClaudeCodeResultSubtype = "success" | "error_max_turns" | "error_budget";
|
||||
export type ClaudeCodeResultSubtype = "success" | "error_max_turns" | "error_budget" | "incomplete";
|
||||
|
||||
/** A single tool call within an assistant turn. */
|
||||
export type ClaudeCodeToolCall = {
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { defineConfig } from "vitest/config";
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ["src/__tests__/**/*.test.ts"],
|
||||
passWithNoTests: true,
|
||||
},
|
||||
});
|
||||
@@ -18,8 +18,9 @@
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"test": "bun test",
|
||||
"test:ci": "bun test __tests__/*.test.ts"
|
||||
"prepublishOnly": "echo 'Use bun run release from repo root' && exit 1",
|
||||
"test": "vitest run",
|
||||
"test:ci": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@uncaged/json-cas": "^0.5.3",
|
||||
@@ -35,12 +36,12 @@
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/shazhou-ww/uncaged-workflow.git",
|
||||
"url": "https://git.shazhou.work/uncaged/workflow.git",
|
||||
"directory": "packages/workflow-agent-hermes"
|
||||
},
|
||||
"homepage": "https://github.com/shazhou-ww/uncaged-workflow#readme",
|
||||
"homepage": "https://git.shazhou.work/uncaged/workflow#readme",
|
||||
"bugs": {
|
||||
"url": "https://github.com/shazhou-ww/uncaged-workflow/issues"
|
||||
"url": "https://git.shazhou.work/uncaged/workflow/issues"
|
||||
},
|
||||
"engines": {
|
||||
"bun": ">= 1.0.0"
|
||||
|
||||
@@ -117,7 +117,7 @@ export function createHermesAgent(): () => Promise<void> {
|
||||
await setCachedSessionId(ctx.threadId, ctx.role, sessionId);
|
||||
}
|
||||
|
||||
return { output: text, detailHash, sessionId };
|
||||
return { output: text, detailHash, sessionId, assembledPrompt: fullPrompt };
|
||||
}
|
||||
|
||||
async function runHermes(ctx: AgentContext): Promise<AgentRunResult> {
|
||||
@@ -148,7 +148,7 @@ export function createHermesAgent(): () => Promise<void> {
|
||||
// so the agent sees the full conversation history (crucial for retries).
|
||||
const { text, sessionId } = await client.prompt(message);
|
||||
const { detailHash } = await storePromptResult(store, sessionId);
|
||||
return { output: text, detailHash, sessionId };
|
||||
return { output: text, detailHash, sessionId, assembledPrompt: "" };
|
||||
}
|
||||
|
||||
const agentMain = createAgent({
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { defineConfig } from "vitest/config";
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ["src/__tests__/**/*.test.ts"],
|
||||
passWithNoTests: true,
|
||||
},
|
||||
});
|
||||
@@ -5,7 +5,9 @@
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "bun server.ts",
|
||||
"build": "vite build"
|
||||
"build": "vite build",
|
||||
"test": "vitest run",
|
||||
"test:ci": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.5.0",
|
||||
|
||||
@@ -14,7 +14,7 @@ export const editNodeViewModel = define.view("editNodeView", editNodeView, (set,
|
||||
function start(nodeId: string) {
|
||||
const [nodes] = model.use(nodesModel);
|
||||
const node = nodes.find((n) => n.id === nodeId);
|
||||
if (!node || node.type !== "role") return;
|
||||
if (node?.type !== "role") return;
|
||||
set({ node: node as WorkNode<"role"> });
|
||||
}
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@ function traverse(
|
||||
visited.add(nodeId);
|
||||
|
||||
const node = nodeMap.get(nodeId);
|
||||
if (!node || node.type !== "role") return;
|
||||
if (node?.type !== "role") return;
|
||||
|
||||
const roleNode = node as WorkNode<"role">;
|
||||
const outEdges = outgoingEdges.get(nodeId) ?? [];
|
||||
|
||||
@@ -14,6 +14,11 @@
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"prepublishOnly": "echo 'Use bun run release from repo root' && exit 1",
|
||||
"test": "vitest run",
|
||||
"test:ci": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@uncaged/json-cas": "^0.5.3",
|
||||
"@uncaged/json-cas-fs": "^0.5.3"
|
||||
@@ -26,12 +31,12 @@
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/shazhou-ww/uncaged-workflow.git",
|
||||
"url": "https://git.shazhou.work/uncaged/workflow.git",
|
||||
"directory": "packages/workflow-protocol"
|
||||
},
|
||||
"homepage": "https://github.com/shazhou-ww/uncaged-workflow#readme",
|
||||
"homepage": "https://git.shazhou.work/uncaged/workflow#readme",
|
||||
"bugs": {
|
||||
"url": "https://github.com/shazhou-ww/uncaged-workflow/issues"
|
||||
"url": "https://git.shazhou.work/uncaged/workflow/issues"
|
||||
},
|
||||
"license": "MIT"
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import type { StartNodePayload, StepRecord, Target } from "../types.js";
|
||||
|
||||
describe("Protocol types for thread/edge location", () => {
|
||||
@@ -25,6 +25,7 @@ describe("Protocol types for thread/edge location", () => {
|
||||
edgePrompt: "Plan the implementation",
|
||||
startedAtMs: Date.now(),
|
||||
completedAtMs: Date.now() + 1000,
|
||||
assembledPrompt: null,
|
||||
cwd: "/home/user/project",
|
||||
};
|
||||
|
||||
|
||||
@@ -88,6 +88,9 @@ export const STEP_NODE_SCHEMA: JSONSchema = {
|
||||
startedAtMs: { type: "integer" },
|
||||
completedAtMs: { type: "integer" },
|
||||
cwd: { type: "string" },
|
||||
assembledPrompt: {
|
||||
anyOf: [{ type: "string", format: "cas_ref" }, { type: "null" }],
|
||||
},
|
||||
},
|
||||
additionalProperties: false,
|
||||
};
|
||||
|
||||
@@ -20,6 +20,8 @@ export type StepRecord = {
|
||||
completedAtMs: number;
|
||||
/** Working directory where the agent executed. Missing in legacy nodes → "". */
|
||||
cwd: string;
|
||||
/** CAS ref to the fully assembled prompt sent to the agent. null for legacy steps. */
|
||||
assembledPrompt: CasRef | null;
|
||||
};
|
||||
|
||||
// ── 4.2 Workflow 定义 ───────────────────────────────────────────────
|
||||
@@ -97,6 +99,8 @@ export type StepOutput = {
|
||||
thread: ThreadId;
|
||||
head: CasRef;
|
||||
status: ThreadStatus;
|
||||
/** The current or next role. Null when completed, cancelled, or next is $END. */
|
||||
currentRole: string | null;
|
||||
done: boolean;
|
||||
background: boolean | null;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { defineConfig } from "vitest/config";
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ["src/__tests__/**/*.test.ts"],
|
||||
passWithNoTests: true,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import { createMemoryStore, putSchema } from "@uncaged/json-cas";
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { tryFrontmatterFastPath } from "../src/frontmatter.js";
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────────
|
||||
|
||||
const PLANNER_SCHEMA = {
|
||||
type: "object",
|
||||
properties: {
|
||||
$status: { type: "string", enum: ["ready", "failed"] },
|
||||
plan: { type: "string" },
|
||||
},
|
||||
required: ["$status"],
|
||||
additionalProperties: false,
|
||||
};
|
||||
|
||||
describe("adapter-stdout: A4 retry loop survives JSON output", () => {
|
||||
test("A4. first extraction fails, second succeeds — final result has correct data", async () => {
|
||||
const store = createMemoryStore();
|
||||
const schemaHash = await putSchema(store, PLANNER_SCHEMA);
|
||||
|
||||
// Simulate the retry loop from createAgent (run.ts lines 163-173):
|
||||
// First attempt: agent outputs garbage (no frontmatter)
|
||||
const badOutput = "Here is my response without frontmatter.\nJust plain text.";
|
||||
const firstAttempt = await tryFrontmatterFastPath(badOutput, schemaHash, store);
|
||||
expect(firstAttempt).toBeNull();
|
||||
|
||||
// Second attempt (after correction message): agent outputs valid frontmatter
|
||||
const goodOutput = `---\n$status: ready\nplan: corrected-hash\n---\nCorrected body with valid frontmatter.`;
|
||||
const secondAttempt = await tryFrontmatterFastPath(goodOutput, schemaHash, store);
|
||||
|
||||
expect(secondAttempt).not.toBeNull();
|
||||
expect(secondAttempt!.outputHash).toMatch(/^[0-9A-Z]{13}$/);
|
||||
expect(secondAttempt!.frontmatter).toEqual({ $status: "ready", plan: "corrected-hash" });
|
||||
expect(secondAttempt!.body).toBe("Corrected body with valid frontmatter.");
|
||||
|
||||
// Verify the final AdapterOutput shape would be correct
|
||||
const adapterOutput = {
|
||||
stepHash: "MOCK_STEP_HASH",
|
||||
detailHash: "MOCK_DETAIL_HA",
|
||||
role: "planner",
|
||||
frontmatter: secondAttempt!.frontmatter,
|
||||
body: secondAttempt!.body,
|
||||
startedAtMs: 1000,
|
||||
completedAtMs: 2000,
|
||||
assembledPrompt: null,
|
||||
};
|
||||
|
||||
const json = JSON.stringify(adapterOutput);
|
||||
const parsed = JSON.parse(json);
|
||||
expect(parsed.frontmatter).toEqual({ $status: "ready", plan: "corrected-hash" });
|
||||
expect(parsed.body).toBe("Corrected body with valid frontmatter.");
|
||||
expect(parsed.completedAtMs).toBeGreaterThanOrEqual(parsed.startedAtMs);
|
||||
});
|
||||
|
||||
test("A4. all retries fail — extraction returns null on every attempt", async () => {
|
||||
const store = createMemoryStore();
|
||||
const schemaHash = await putSchema(store, PLANNER_SCHEMA);
|
||||
|
||||
const MAX_RETRIES = 2;
|
||||
const badOutput = "No frontmatter here";
|
||||
|
||||
// Simulate MAX_FRONTMATTER_RETRIES iterations all failing
|
||||
let extracted = await tryFrontmatterFastPath(badOutput, schemaHash, store);
|
||||
for (let retry = 0; retry < MAX_RETRIES && extracted === null; retry++) {
|
||||
// Each retry also gets bad output
|
||||
extracted = await tryFrontmatterFastPath(badOutput, schemaHash, store);
|
||||
}
|
||||
|
||||
expect(extracted).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
import { createMemoryStore, putSchema } from "@uncaged/json-cas";
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { tryFrontmatterFastPath } from "../src/frontmatter.js";
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────────
|
||||
|
||||
const PLANNER_SCHEMA = {
|
||||
type: "object",
|
||||
properties: {
|
||||
$status: { type: "string", enum: ["ready", "failed"] },
|
||||
plan: { type: "string" },
|
||||
},
|
||||
required: ["$status"],
|
||||
additionalProperties: false,
|
||||
};
|
||||
|
||||
const FRONTMATTER_SCHEMA = {
|
||||
type: "object",
|
||||
properties: {
|
||||
status: { anyOf: [{ type: "string" }, { type: "null" }] },
|
||||
next: { anyOf: [{ type: "string" }, { type: "null" }] },
|
||||
confidence: { anyOf: [{ type: "number" }, { type: "null" }] },
|
||||
artifacts: { type: "array", items: { type: "string" } },
|
||||
scope: { type: "string" },
|
||||
},
|
||||
required: ["status", "next", "confidence", "artifacts", "scope"],
|
||||
additionalProperties: false,
|
||||
};
|
||||
|
||||
describe("adapter-stdout: FrontmatterFastPathResult includes frontmatter", () => {
|
||||
test("A2. frontmatter field contains the parsed YAML frontmatter object", async () => {
|
||||
const store = createMemoryStore();
|
||||
const schemaHash = await putSchema(store, PLANNER_SCHEMA);
|
||||
|
||||
const raw = `---\n$status: ready\nplan: abc123\n---\nSome body text`;
|
||||
const result = await tryFrontmatterFastPath(raw, schemaHash, store);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.frontmatter).toEqual({ $status: "ready", plan: "abc123" });
|
||||
});
|
||||
|
||||
test("A3. body field contains the markdown body after frontmatter", async () => {
|
||||
const store = createMemoryStore();
|
||||
const schemaHash = await putSchema(store, PLANNER_SCHEMA);
|
||||
|
||||
const raw = `---\n$status: ready\nplan: hash123\n---\nHere is the body.\n\nWith multiple paragraphs.`;
|
||||
const result = await tryFrontmatterFastPath(raw, schemaHash, store);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.body).toBe("Here is the body.\n\nWith multiple paragraphs.");
|
||||
});
|
||||
|
||||
test("A1. result contains outputHash as valid CasRef", async () => {
|
||||
const store = createMemoryStore();
|
||||
const schemaHash = await putSchema(store, FRONTMATTER_SCHEMA);
|
||||
|
||||
const raw = `---\nstatus: done\nnext: null\nconfidence: 0.9\nartifacts: []\nscope: test\n---\nBody`;
|
||||
const result = await tryFrontmatterFastPath(raw, schemaHash, store);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.outputHash).toMatch(/^[0-9A-Z]{13}$/);
|
||||
expect(result!.frontmatter).toBeDefined();
|
||||
expect(result!.body).toBe("Body");
|
||||
});
|
||||
});
|
||||
|
||||
describe("adapter-stdout: AdapterOutput JSON shape", () => {
|
||||
test("A5. JSON.stringify produces valid parseable JSON with all fields", () => {
|
||||
const output = {
|
||||
stepHash: "0123456789ABC",
|
||||
detailHash: "DEFGH12345678",
|
||||
role: "planner",
|
||||
frontmatter: { $status: "ready", plan: "somehash" },
|
||||
body: "Plan body text",
|
||||
startedAtMs: 1000,
|
||||
completedAtMs: 2000,
|
||||
};
|
||||
|
||||
const json = JSON.stringify(output);
|
||||
const parsed = JSON.parse(json);
|
||||
|
||||
expect(parsed.stepHash).toBe("0123456789ABC");
|
||||
expect(parsed.detailHash).toBe("DEFGH12345678");
|
||||
expect(parsed.role).toBe("planner");
|
||||
expect(parsed.frontmatter).toEqual({ $status: "ready", plan: "somehash" });
|
||||
expect(parsed.body).toBe("Plan body text");
|
||||
expect(parsed.startedAtMs).toBe(1000);
|
||||
expect(parsed.completedAtMs).toBe(2000);
|
||||
});
|
||||
|
||||
test("completedAtMs >= startedAtMs", () => {
|
||||
const output = {
|
||||
stepHash: "0123456789ABC",
|
||||
detailHash: "DEFGH12345678",
|
||||
role: "planner",
|
||||
frontmatter: {},
|
||||
body: "",
|
||||
startedAtMs: 1000,
|
||||
completedAtMs: 2000,
|
||||
};
|
||||
|
||||
expect(output.completedAtMs).toBeGreaterThanOrEqual(output.startedAtMs);
|
||||
});
|
||||
});
|
||||
@@ -15,8 +15,9 @@
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"test": "bun test",
|
||||
"test:ci": "bun test"
|
||||
"prepublishOnly": "echo 'Use bun run release from repo root' && exit 1",
|
||||
"test": "vitest run",
|
||||
"test:ci": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@uncaged/json-cas": "^0.5.3",
|
||||
@@ -34,12 +35,12 @@
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/shazhou-ww/uncaged-workflow.git",
|
||||
"url": "https://git.shazhou.work/uncaged/workflow.git",
|
||||
"directory": "packages/workflow-util-agent"
|
||||
},
|
||||
"homepage": "https://github.com/shazhou-ww/uncaged-workflow#readme",
|
||||
"homepage": "https://git.shazhou.work/uncaged/workflow#readme",
|
||||
"bugs": {
|
||||
"url": "https://github.com/shazhou-ww/uncaged-workflow/issues"
|
||||
"url": "https://git.shazhou.work/uncaged/workflow/issues"
|
||||
},
|
||||
"license": "MIT"
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { afterEach, beforeEach, describe, expect, test } from "vitest";
|
||||
|
||||
describe("parseArgv empty prompt error message", () => {
|
||||
let stderrOutput: string;
|
||||
|
||||
@@ -214,7 +214,7 @@ function getConstValue(propSchema: JSONSchema): string {
|
||||
function buildVariantBlock(variant: JSONSchema, discriminant: string): string {
|
||||
const props = extractSchemaProperties(variant);
|
||||
const value = getConstValue(
|
||||
((variant.properties as Record<string, JSONSchema>) ?? {})[discriminant] ?? {},
|
||||
(variant.properties as Record<string, JSONSchema>)?.[discriminant] ?? {},
|
||||
);
|
||||
const yamlExample = buildYamlExampleBlock(props);
|
||||
const fieldList = buildFieldList(props);
|
||||
|
||||
@@ -131,6 +131,7 @@ async function buildHistory(
|
||||
startedAtMs: step.startedAtMs,
|
||||
completedAtMs: step.completedAtMs,
|
||||
cwd: step.cwd ?? "",
|
||||
assembledPrompt: step.assembledPrompt ?? null,
|
||||
content,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ type StandardKey = (typeof STANDARD_KEYS)[number];
|
||||
export type FrontmatterFastPathResult = {
|
||||
body: string;
|
||||
outputHash: CasRef;
|
||||
frontmatter: Record<string, unknown>;
|
||||
};
|
||||
|
||||
function extractYamlBlock(raw: string): string | null {
|
||||
@@ -176,5 +177,5 @@ export async function tryFrontmatterFastPath(
|
||||
return null;
|
||||
}
|
||||
|
||||
return { body, outputHash };
|
||||
return { body, outputHash, frontmatter: candidate };
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ export { createAgent, parseArgv } from "./run.js";
|
||||
export { getCachedSessionId, getCachePath, setCachedSessionId } from "./session-cache.js";
|
||||
export { getConfigPath, getEnvPath, loadWorkflowConfig, resolveStorageRoot } from "./storage.js";
|
||||
export type {
|
||||
AdapterOutput,
|
||||
AgentContext,
|
||||
AgentContinueFn,
|
||||
AgentOptions,
|
||||
|
||||
@@ -6,7 +6,7 @@ import { buildContextWithMeta } from "./context.js";
|
||||
import { tryFrontmatterFastPath } from "./frontmatter.js";
|
||||
import type { AgentStore } from "./storage.js";
|
||||
import { getEnvPath, resolveStorageRoot } from "./storage.js";
|
||||
import type { AgentOptions } from "./types.js";
|
||||
import type { AdapterOutput, AgentOptions } from "./types.js";
|
||||
|
||||
const MAX_FRONTMATTER_RETRIES = 2;
|
||||
|
||||
@@ -64,6 +64,7 @@ async function writeStepNode(options: {
|
||||
edgePrompt: string;
|
||||
startedAtMs: number;
|
||||
completedAtMs: number;
|
||||
assembledPromptHash: CasRef | null;
|
||||
}): Promise<CasRef> {
|
||||
const payload: StepNodePayload = {
|
||||
start: options.startHash,
|
||||
@@ -76,6 +77,7 @@ async function writeStepNode(options: {
|
||||
startedAtMs: options.startedAtMs,
|
||||
completedAtMs: options.completedAtMs,
|
||||
cwd: process.cwd(),
|
||||
assembledPrompt: options.assembledPromptHash,
|
||||
};
|
||||
const hash = await options.store.put(options.schemas.stepNode, payload);
|
||||
const node = options.store.get(hash);
|
||||
@@ -85,14 +87,24 @@ async function writeStepNode(options: {
|
||||
return hash;
|
||||
}
|
||||
|
||||
type ExtractedOutput = {
|
||||
outputHash: CasRef;
|
||||
frontmatter: Record<string, unknown>;
|
||||
body: string;
|
||||
};
|
||||
|
||||
async function tryExtractOutput(
|
||||
rawOutput: string,
|
||||
outputSchema: CasRef,
|
||||
ctx: Awaited<ReturnType<typeof buildContextWithMeta>>,
|
||||
): Promise<CasRef | null> {
|
||||
): Promise<ExtractedOutput | null> {
|
||||
const fastPath = await tryFrontmatterFastPath(rawOutput, outputSchema, ctx.meta.store);
|
||||
if (fastPath !== null) {
|
||||
return fastPath.outputHash;
|
||||
return {
|
||||
outputHash: fastPath.outputHash,
|
||||
frontmatter: fastPath.frontmatter,
|
||||
body: fastPath.body,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -104,6 +116,7 @@ async function persistStep(options: {
|
||||
agentName: string;
|
||||
startedAtMs: number;
|
||||
completedAtMs: number;
|
||||
assembledPromptHash: CasRef | null;
|
||||
}): Promise<CasRef> {
|
||||
const { store, schemas, chain, headHash } = options.ctx.meta;
|
||||
return writeStepNode({
|
||||
@@ -118,6 +131,7 @@ async function persistStep(options: {
|
||||
edgePrompt: options.ctx.edgePrompt,
|
||||
startedAtMs: options.startedAtMs,
|
||||
completedAtMs: options.completedAtMs,
|
||||
assembledPromptHash: options.assembledPromptHash,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -141,6 +155,7 @@ export function createAgent(options: AgentOptions): () => Promise<void> {
|
||||
|
||||
const startedAtMs = Date.now();
|
||||
let agentResult = await runWithMessage("agent run failed", () => options.run(ctx));
|
||||
agentResult.output = agentResult.output.trimStart();
|
||||
|
||||
// Preserve the primary detail from the first run — it contains the full
|
||||
// tool-call turn history. Continuation retries only fix frontmatter
|
||||
@@ -148,9 +163,9 @@ export function createAgent(options: AgentOptions): () => Promise<void> {
|
||||
const primaryDetailHash = agentResult.detailHash;
|
||||
|
||||
// Try to extract frontmatter; retry via continue if it fails
|
||||
let outputHash = await tryExtractOutput(agentResult.output, roleDef.frontmatter, ctx);
|
||||
let extracted = await tryExtractOutput(agentResult.output, roleDef.frontmatter, ctx);
|
||||
|
||||
for (let retry = 0; retry < MAX_FRONTMATTER_RETRIES && outputHash === null; retry++) {
|
||||
for (let retry = 0; retry < MAX_FRONTMATTER_RETRIES && extracted === null; retry++) {
|
||||
const correctionMessage =
|
||||
"Your previous response did not contain valid YAML frontmatter matching the role schema.\n" +
|
||||
"You MUST begin your response with a YAML frontmatter block (--- delimited).\n" +
|
||||
@@ -159,10 +174,11 @@ export function createAgent(options: AgentOptions): () => Promise<void> {
|
||||
agentResult = await runWithMessage("agent continue failed", () =>
|
||||
options.continue(agentResult.sessionId, correctionMessage, ctx.meta.store),
|
||||
);
|
||||
outputHash = await tryExtractOutput(agentResult.output, roleDef.frontmatter, ctx);
|
||||
agentResult.output = agentResult.output.trimStart();
|
||||
extracted = await tryExtractOutput(agentResult.output, roleDef.frontmatter, ctx);
|
||||
}
|
||||
|
||||
if (outputHash === null) {
|
||||
if (extracted === null) {
|
||||
fail(
|
||||
"Agent output does not contain valid YAML frontmatter matching the role schema " +
|
||||
`after ${MAX_FRONTMATTER_RETRIES} retries.\n` +
|
||||
@@ -170,15 +186,33 @@ export function createAgent(options: AgentOptions): () => Promise<void> {
|
||||
);
|
||||
}
|
||||
const completedAtMs = Date.now();
|
||||
|
||||
// Store the assembled prompt in CAS for later inspection via `step read --prompt`
|
||||
const promptText = agentResult.assembledPrompt;
|
||||
const assembledPromptHash =
|
||||
promptText !== ""
|
||||
? await ctx.meta.store.put(ctx.meta.schemas.text, promptText).catch(() => null)
|
||||
: null;
|
||||
|
||||
const stepHash = await persistStep({
|
||||
ctx,
|
||||
outputHash,
|
||||
outputHash: extracted.outputHash,
|
||||
detailHash: primaryDetailHash,
|
||||
agentName: agentLabel(options.name),
|
||||
startedAtMs,
|
||||
completedAtMs,
|
||||
assembledPromptHash,
|
||||
});
|
||||
|
||||
process.stdout.write(`${stepHash}\n`);
|
||||
const adapterOutput: AdapterOutput = {
|
||||
stepHash,
|
||||
detailHash: primaryDetailHash,
|
||||
role,
|
||||
frontmatter: extracted.frontmatter,
|
||||
body: extracted.body,
|
||||
startedAtMs,
|
||||
completedAtMs,
|
||||
};
|
||||
process.stdout.write(`${JSON.stringify(adapterOutput)}\n`);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -6,17 +6,21 @@ export type UwfAgentSchemaHashes = {
|
||||
workflow: Hash;
|
||||
startNode: Hash;
|
||||
stepNode: Hash;
|
||||
text: Hash;
|
||||
};
|
||||
|
||||
const TEXT_SCHEMA = { type: "string" as const };
|
||||
|
||||
/**
|
||||
* Register Workflow, StartNode, and StepNode JSON Schemas in the CAS store.
|
||||
* Idempotent: safe to call on every agent invocation.
|
||||
*/
|
||||
export async function registerAgentSchemas(store: Store): Promise<UwfAgentSchemaHashes> {
|
||||
const [workflow, startNode, stepNode] = await Promise.all([
|
||||
const [workflow, startNode, stepNode, text] = await Promise.all([
|
||||
putSchema(store, WORKFLOW_SCHEMA),
|
||||
putSchema(store, START_NODE_SCHEMA),
|
||||
putSchema(store, STEP_NODE_SCHEMA),
|
||||
putSchema(store, TEXT_SCHEMA),
|
||||
]);
|
||||
return { workflow, startNode, stepNode };
|
||||
return { workflow, startNode, stepNode, text };
|
||||
}
|
||||
|
||||
@@ -27,6 +27,8 @@ export type AgentRunResult = {
|
||||
output: string;
|
||||
detailHash: string;
|
||||
sessionId: string;
|
||||
/** The fully assembled prompt that was sent to the agent. */
|
||||
assembledPrompt: string;
|
||||
};
|
||||
|
||||
export type AgentContinueFn = (
|
||||
@@ -37,6 +39,16 @@ export type AgentContinueFn = (
|
||||
|
||||
export type AgentRunFn = (ctx: AgentContext) => Promise<AgentRunResult>;
|
||||
|
||||
export type AdapterOutput = {
|
||||
stepHash: string;
|
||||
detailHash: string;
|
||||
role: string;
|
||||
frontmatter: Record<string, unknown>;
|
||||
body: string;
|
||||
startedAtMs: number;
|
||||
completedAtMs: number;
|
||||
};
|
||||
|
||||
export type AgentOptions = {
|
||||
name: string;
|
||||
run: AgentRunFn;
|
||||
|
||||
@@ -5,5 +5,5 @@
|
||||
"outDir": "dist"
|
||||
},
|
||||
"include": ["src"],
|
||||
"references": [{ "path": "../workflow-protocol" }]
|
||||
"references": [{ "path": "../workflow-protocol" }, { "path": "../workflow-util" }]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { defineConfig } from "vitest/config";
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ["src/__tests__/**/*.test.ts"],
|
||||
passWithNoTests: true,
|
||||
},
|
||||
});
|
||||
@@ -14,6 +14,11 @@
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"prepublishOnly": "echo 'Use bun run release from repo root' && exit 1",
|
||||
"test": "vitest run",
|
||||
"test:ci": "vitest run"
|
||||
},
|
||||
"dependencies": {},
|
||||
"devDependencies": {
|
||||
"typescript": "^5.8.3"
|
||||
@@ -23,12 +28,12 @@
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/shazhou-ww/uncaged-workflow.git",
|
||||
"url": "https://git.shazhou.work/uncaged/workflow.git",
|
||||
"directory": "packages/workflow-util"
|
||||
},
|
||||
"homepage": "https://github.com/shazhou-ww/uncaged-workflow#readme",
|
||||
"homepage": "https://git.shazhou.work/uncaged/workflow#readme",
|
||||
"bugs": {
|
||||
"url": "https://github.com/shazhou-ww/uncaged-workflow/issues"
|
||||
"url": "https://git.shazhou.work/uncaged/workflow/issues"
|
||||
},
|
||||
"license": "MIT"
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { extractUlidTimestamp, generateUlid } from "../ulid.js";
|
||||
|
||||
describe("extractUlidTimestamp", () => {
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
export function generateBootstrapReference(): string {
|
||||
return `---
|
||||
name: uwf
|
||||
description: "Uncaged Workflow (uwf) — YAML 状态机工作流引擎。任务涉及 workflow 时加载此 skill。"
|
||||
tags: [workflow, uwf, uncaged]
|
||||
triggers:
|
||||
- uwf
|
||||
- workflow
|
||||
- 工作流
|
||||
---
|
||||
|
||||
# uwf (Uncaged Workflow)
|
||||
|
||||
YAML 状态机工作流引擎。当用户提到「workflow」「工作流」时,指的是 **uwf workflow**(YAML 定义的状态机),不是 Hermes skill。用 \`uwf\` CLI 操作,不要混淆。
|
||||
|
||||
## 首次使用
|
||||
|
||||
运行以下命令获取完整用法:
|
||||
|
||||
\`\`\`bash
|
||||
uwf skill user # 用户使用手册(CLI 命令、thread 生命周期)
|
||||
uwf skill author # workflow 编写指南(role 定义、graph 路由、schema)
|
||||
\`\`\`
|
||||
|
||||
## 快速参考
|
||||
|
||||
\`\`\`bash
|
||||
uwf workflow list # 查看已注册 workflow
|
||||
uwf workflow add <file.yaml> # 注册 workflow
|
||||
uwf thread start <workflow> -p "prompt" # 创建 thread
|
||||
uwf thread exec <thread-id> -c 10 # 执行最多 10 步
|
||||
uwf thread list # 查看所有 thread
|
||||
\`\`\`
|
||||
|
||||
## 示例 workflow
|
||||
|
||||
参考项目 \`examples/\` 目录下的 YAML 文件(analyze-topic、debate、solve-issue)。
|
||||
`;
|
||||
}
|
||||
@@ -3,6 +3,7 @@ export { generateAdapterReference } from "./adapter-reference.js";
|
||||
export { generateArchitectureReference } from "./architecture-reference.js";
|
||||
export { generateAuthorReference } from "./author-reference.js";
|
||||
export { encodeUint64AsCrockford } from "./base32.js";
|
||||
export { generateBootstrapReference } from "./bootstrap-reference.js";
|
||||
export { generateCliReference } from "./cli-reference.js";
|
||||
export { generateDeveloperReference } from "./developer-reference.js";
|
||||
export { env } from "./env.js";
|
||||
|
||||
@@ -121,5 +121,15 @@ uwf log clean --before <date> # delete old logs
|
||||
uwf --format <json|yaml> # output format (default: json)
|
||||
uwf -V, --version # print version
|
||||
\`\`\`
|
||||
|
||||
## Other Skill References
|
||||
|
||||
For specific scenarios, run the corresponding \`uwf skill\` command:
|
||||
|
||||
| Scenario | Command | When to use |
|
||||
|----------|---------|-------------|
|
||||
| Writing workflow YAML | \`uwf skill author\` | Designing roles, conditions, graphs, and edge prompts |
|
||||
| Contributing to the engine | \`uwf skill developer\` | Modifying the workflow engine codebase itself |
|
||||
| Building a new agent adapter | \`uwf skill adapter\` | Creating a new \`uwf-<name>\` CLI adapter |
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { defineConfig } from "vitest/config";
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ["src/__tests__/**/*.test.ts"],
|
||||
passWithNoTests: true,
|
||||
},
|
||||
});
|
||||
@@ -21,6 +21,7 @@ const publishOrder = [
|
||||
"workflow-util-agent",
|
||||
"workflow-agent-hermes",
|
||||
"workflow-agent-builtin",
|
||||
"workflow-agent-claude-code",
|
||||
"cli-workflow",
|
||||
];
|
||||
|
||||
@@ -59,7 +60,7 @@ let failed = false;
|
||||
for (const name of publishOrder) {
|
||||
const pkgDir = join(root, "packages", name);
|
||||
const tagFlag = tag ? `--tag ${tag}` : "";
|
||||
const cmd = `npm publish --access public ${tagFlag}`;
|
||||
const cmd = `npm publish --access public --ignore-scripts ${tagFlag}`;
|
||||
|
||||
console.log(`📦 ${name}...`);
|
||||
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
---
|
||||
name: uwf
|
||||
description: "Uncaged Workflow (uwf) — YAML 状态机工作流引擎。任务涉及 workflow 时加载此 skill。"
|
||||
tags: [workflow, uwf, uncaged]
|
||||
triggers:
|
||||
- uwf
|
||||
- workflow
|
||||
- 工作流
|
||||
---
|
||||
|
||||
# uwf (Uncaged Workflow)
|
||||
|
||||
YAML 状态机工作流引擎。当用户提到「workflow」「工作流」时,指的是 **uwf workflow**(YAML 定义的状态机),不是 Hermes skill。用 `uwf` CLI 操作,不要混淆。
|
||||
|
||||
## 首次使用
|
||||
|
||||
运行以下命令获取完整用法:
|
||||
|
||||
```bash
|
||||
uwf skill user # 用户使用手册(CLI 命令、thread 生命周期)
|
||||
uwf skill author # workflow 编写指南(role 定义、graph 路由、schema)
|
||||
```
|
||||
|
||||
## 快速参考
|
||||
|
||||
```bash
|
||||
uwf workflow list # 查看已注册 workflow
|
||||
uwf workflow add <file.yaml> # 注册 workflow
|
||||
uwf thread start <workflow> -p "prompt" # 创建 thread
|
||||
uwf thread exec <thread-id> -c 10 # 执行最多 10 步
|
||||
uwf thread list # 查看所有 thread
|
||||
```
|
||||
|
||||
## 示例 workflow
|
||||
|
||||
参考项目 `examples/` 目录下的 YAML 文件(analyze-topic、debate、solve-issue)。
|
||||
@@ -23,6 +23,7 @@
|
||||
{ "path": "packages/workflow-util-agent" },
|
||||
{ "path": "packages/workflow-agent-hermes" },
|
||||
{ "path": "packages/workflow-agent-builtin" },
|
||||
{ "path": "packages/workflow-agent-claude-code" },
|
||||
{ "path": "packages/cli-workflow" }
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,852 @@
|
||||
name: normalize-bun-monorepo
|
||||
graph:
|
||||
ci:
|
||||
done:
|
||||
role: solve-issue-workflow
|
||||
prompt: CI configured. Register solve-issue workflow for repo at {{{repoPath}}}.
|
||||
skipped:
|
||||
role: solve-issue-workflow
|
||||
prompt: "ci already configured, skipped."
|
||||
failed:
|
||||
role: solve-issue-workflow
|
||||
prompt: CI setup failed ({{{reason}}}), but continue. Register solve-issue workflow for repo at {{{repoPath}}}.
|
||||
biome:
|
||||
done:
|
||||
role: package-metadata
|
||||
prompt: Biome configured. Standardize package metadata for repo at {{{repoPath}}}.
|
||||
skipped:
|
||||
role: package-metadata
|
||||
prompt: "biome already configured, skipped."
|
||||
failed:
|
||||
role: package-metadata
|
||||
prompt: Biome setup failed ({{{reason}}}), but continue. Standardize package metadata for repo at {{{repoPath}}}.
|
||||
$START:
|
||||
_:
|
||||
role: workspace
|
||||
prompt: Set up bun workspace structure for repo at {{{repoPath}}}.
|
||||
release:
|
||||
done:
|
||||
role: testing
|
||||
prompt: Release pipeline configured. Set up vitest for repo at {{{repoPath}}}.
|
||||
skipped:
|
||||
role: testing
|
||||
prompt: "release already configured, skipped."
|
||||
failed:
|
||||
role: testing
|
||||
prompt: Release pipeline failed ({{{reason}}}), but continue. Set up vitest for repo at {{{repoPath}}}.
|
||||
testing:
|
||||
done:
|
||||
role: ci
|
||||
prompt: Testing configured. Set up Gitea CI for repo at {{{repoPath}}}.
|
||||
skipped:
|
||||
role: ci
|
||||
prompt: "testing already configured, skipped."
|
||||
failed:
|
||||
role: ci
|
||||
prompt: Testing setup failed ({{{reason}}}), but continue. Set up Gitea CI for repo at {{{repoPath}}}.
|
||||
committer:
|
||||
failed:
|
||||
role: $END
|
||||
prompt: "Commit failed: {{{reason}}}."
|
||||
committed:
|
||||
role: $END
|
||||
prompt: "Normalization committed: {{{commitHash}}}."
|
||||
no_changes:
|
||||
role: $END
|
||||
prompt: Repo already normalized, no changes needed.
|
||||
workspace:
|
||||
done:
|
||||
role: typescript
|
||||
prompt: Workspace ready. Configure TypeScript for repo at {{{repoPath}}}.
|
||||
skipped:
|
||||
role: typescript
|
||||
prompt: "workspace already configured, skipped."
|
||||
failed:
|
||||
role: typescript
|
||||
prompt: Workspace setup failed ({{{reason}}}), but continue. Configure TypeScript for repo at {{{repoPath}}}.
|
||||
guardrails:
|
||||
done:
|
||||
role: committer
|
||||
prompt: All normalization complete. Commit changes in repo at {{{repoPath}}}.
|
||||
skipped:
|
||||
role: committer
|
||||
prompt: "guardrails already configured, skipped."
|
||||
failed:
|
||||
role: committer
|
||||
prompt: Guardrails failed ({{{reason}}}), but commit whatever was done in repo at {{{repoPath}}}.
|
||||
typescript:
|
||||
done:
|
||||
role: biome
|
||||
prompt: TypeScript configured. Set up Biome for repo at {{{repoPath}}}.
|
||||
skipped:
|
||||
role: biome
|
||||
prompt: "typescript already configured, skipped."
|
||||
failed:
|
||||
role: biome
|
||||
prompt: TypeScript setup failed ({{{reason}}}), but continue. Set up Biome for repo at {{{repoPath}}}.
|
||||
package-metadata:
|
||||
done:
|
||||
role: release
|
||||
prompt: Package metadata standardized. Configure release pipeline for repo at {{{repoPath}}}.
|
||||
skipped:
|
||||
role: release
|
||||
prompt: "package-metadata already configured, skipped."
|
||||
failed:
|
||||
role: release
|
||||
prompt: Package metadata failed ({{{reason}}}), but continue. Configure release pipeline for repo at {{{repoPath}}}.
|
||||
solve-issue-workflow:
|
||||
done:
|
||||
role: guardrails
|
||||
prompt: Solve-issue workflow placed in .workflows/. Install guardrails for repo at {{{repoPath}}}.
|
||||
skipped:
|
||||
role: guardrails
|
||||
prompt: "solve-issue-workflow already configured, skipped."
|
||||
failed:
|
||||
role: guardrails
|
||||
prompt: Solve-issue workflow failed ({{{reason}}}), but continue. Install guardrails for repo at {{{repoPath}}}.
|
||||
roles:
|
||||
ci:
|
||||
goal: You configure Gitea Actions CI for build, lint, and test on push/PR.
|
||||
output: Describe the CI pipeline configured. Set $status to done or failed.
|
||||
procedure: |
|
||||
## GROUND RULES (read before doing anything)
|
||||
- Only report actions you ACTUALLY performed and files you ACTUALLY created or modified.
|
||||
- If everything is already correctly configured, set $status=skipped.
|
||||
- NEVER fabricate command output. Run every verification command for real and paste the actual stdout/stderr.
|
||||
- After writing a file, run `test -f <path> && echo EXISTS || echo MISSING` to confirm it was actually written.
|
||||
|
||||
cd into the repo path from your task prompt.
|
||||
|
||||
If `.gitea/workflows/ci.yml` already exists, review it for completeness but don't overwrite unless it's missing key steps.
|
||||
If `.github/workflows/` exists (GitHub Actions), keep it — add `.gitea/workflows/` alongside it.
|
||||
|
||||
Create `.gitea/workflows/ci.yml` (if not present):
|
||||
```yaml
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ['*']
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
check:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: oven-sh/setup-bun@v2
|
||||
|
||||
- run: bun install
|
||||
|
||||
- name: Build
|
||||
run: bun run build
|
||||
|
||||
- name: Lint
|
||||
run: bun run check
|
||||
|
||||
- name: Test
|
||||
run: bun run test:ci
|
||||
```
|
||||
|
||||
## Verification
|
||||
You MUST actually run each command below and include real output. Do NOT guess or fabricate results.
|
||||
```bash
|
||||
# 1. CI file exists
|
||||
test -f .gitea/workflows/ci.yml
|
||||
# 2. YAML is valid
|
||||
node -e "
|
||||
const fs = require('fs');
|
||||
const content = fs.readFileSync('.gitea/workflows/ci.yml', 'utf8');
|
||||
if (!content.includes('bun')) { console.error('Missing bun setup'); process.exit(1); }
|
||||
if (!content.includes('test')) { console.error('Missing test step'); process.exit(1); }
|
||||
console.log('CI YAML looks valid');
|
||||
"
|
||||
# 3. Required root scripts exist for CI to work
|
||||
node -e "
|
||||
const pkg = require('./package.json');
|
||||
const required = ['build', 'check', 'test:ci'];
|
||||
const missing = required.filter(s => !pkg.scripts?.[s]);
|
||||
if (missing.length) { console.error('Missing scripts for CI:', missing.join(', ')); process.exit(1); }
|
||||
console.log('All CI-required scripts present');
|
||||
"
|
||||
```
|
||||
|
||||
Post-condition: CI file exists, YAML references bun and test, all required scripts exist in package.json.
|
||||
description: Set up Gitea CI workflow
|
||||
frontmatter:
|
||||
oneOf:
|
||||
- properties:
|
||||
$status:
|
||||
const: done
|
||||
repoPath:
|
||||
type: string
|
||||
- properties:
|
||||
$status:
|
||||
const: skipped
|
||||
repoPath:
|
||||
type: string
|
||||
- properties:
|
||||
$status:
|
||||
const: failed
|
||||
reason:
|
||||
type: string
|
||||
repoPath:
|
||||
type: string
|
||||
capabilities:
|
||||
- ci-config
|
||||
biome:
|
||||
goal: You configure Biome for consistent code quality across the monorepo.
|
||||
output: List what was configured and any remaining lint issues. Set $status to done or failed.
|
||||
procedure: |
|
||||
## GROUND RULES (read before doing anything)
|
||||
- Only report actions you ACTUALLY performed and files you ACTUALLY created or modified.
|
||||
- If everything is already correctly configured, set $status=skipped.
|
||||
- NEVER fabricate command output. Run every verification command for real and paste the actual stdout/stderr.
|
||||
- After writing a file, run `test -f <path> && echo EXISTS || echo MISSING` to confirm it was actually written.
|
||||
|
||||
cd into the repo path from your task prompt.
|
||||
|
||||
Be idempotent — if biome.json already exists, merge missing settings rather than overwriting.
|
||||
|
||||
Check and fix:
|
||||
1. Install biome: add `@biomejs/biome` to root devDependencies (skip if already present)
|
||||
2. Root `biome.json` must exist with at minimum:
|
||||
- `files.includes`: `["**", "!**/dist", "!**/node_modules"]`
|
||||
- `formatter`: indentStyle space, indentWidth 2, lineWidth 100
|
||||
- `javascript.formatter`: quoteStyle double, semicolons always
|
||||
- `linter.rules.nursery.noConsole: "error"` (production code)
|
||||
- Override for test files (`**/__tests__/**`): `noConsole: "off"`, `noExplicitAny: "off"`
|
||||
- `assist.actions.source.organizeImports: "on"`
|
||||
If biome.json already exists, only add missing fields — preserve existing customizations.
|
||||
3. Root scripts must include: `"check"` (should include `biome check .`), `"format": "biome format --write ."`
|
||||
4. Run `bunx biome check .` — fix auto-fixable issues with `bunx biome check . --fix`
|
||||
5. Remaining unfixable issues: list them but don't block
|
||||
|
||||
## Verification
|
||||
You MUST actually run each command below and include real output. Do NOT guess or fabricate results.
|
||||
```bash
|
||||
# 1. biome.json exists
|
||||
test -f biome.json
|
||||
# 2. biome is installed
|
||||
bunx biome --version
|
||||
# 3. check runs (exit 0 or list remaining issues)
|
||||
bunx biome check . 2>&1 || true
|
||||
```
|
||||
|
||||
Post-condition: `biome.json` exists, `bunx biome check .` runs (may have warnings but no infrastructure errors).
|
||||
description: Configure Biome linter and formatter
|
||||
frontmatter:
|
||||
oneOf:
|
||||
- properties:
|
||||
$status:
|
||||
const: done
|
||||
repoPath:
|
||||
type: string
|
||||
- properties:
|
||||
$status:
|
||||
const: skipped
|
||||
repoPath:
|
||||
type: string
|
||||
- properties:
|
||||
$status:
|
||||
const: failed
|
||||
reason:
|
||||
type: string
|
||||
repoPath:
|
||||
type: string
|
||||
capabilities:
|
||||
- linter-config
|
||||
release:
|
||||
goal: "You set up the complete release pipeline: changesets for version management, publish script for npm release."
|
||||
output: Describe what was configured. Set $status to done or failed.
|
||||
procedure: |
|
||||
## GROUND RULES (read before doing anything)
|
||||
- Only report actions you ACTUALLY performed and files you ACTUALLY created or modified.
|
||||
- If everything is already correctly configured, set $status=skipped.
|
||||
- NEVER fabricate command output. Run every verification command for real and paste the actual stdout/stderr.
|
||||
- After writing a file, run `test -f <path> && echo EXISTS || echo MISSING` to confirm it was actually written.
|
||||
|
||||
cd into the repo path from your task prompt.
|
||||
|
||||
Be idempotent — skip steps that are already done.
|
||||
|
||||
## Part 1: Changesets
|
||||
1. Install: add `@changesets/cli` to root devDependencies (skip if present), run `bun install`
|
||||
2. If `.changeset/config.json` does not exist, run `bunx changeset init`
|
||||
3. Verify `.changeset/config.json` has:
|
||||
- `"access": "public"` (for @scoped packages)
|
||||
- `"baseBranch": "main"`
|
||||
4. Add `.changeset/README.md` if missing
|
||||
|
||||
## Part 2: Publish Script
|
||||
5. Create `scripts/publish-all.mjs` (skip if already exists and looks correct):
|
||||
- Scan `packages/` for non-private packages (skip `"private": true`)
|
||||
- Determine publish order by resolving workspace dependency graph (dependees before dependents)
|
||||
- For each package in order:
|
||||
a. Replace `"workspace:^"` deps with actual versions from workspace
|
||||
b. Run `npm publish --access public --ignore-scripts` (MUST use --ignore-scripts to bypass prepublishOnly guardrail)
|
||||
c. Restore original package.json
|
||||
- Support flags: `--dry-run`, `--tag <name>`
|
||||
- Handle errors: if one package fails, restore and continue
|
||||
CRITICAL: The publish command MUST include `--ignore-scripts` because the guardrails role adds a `prepublishOnly` script that blocks direct publishing.
|
||||
|
||||
## Part 3: Root Scripts
|
||||
6. Root scripts must include:
|
||||
- `"changeset": "bunx changeset"`
|
||||
- `"version": "bunx changeset version"`
|
||||
- `"release": "bun run build && bun run test && node scripts/publish-all.mjs"`
|
||||
|
||||
## Verification
|
||||
You MUST actually run each command below and include real output. Do NOT guess or fabricate results.
|
||||
```bash
|
||||
# 1. changeset config exists and is valid
|
||||
test -f .changeset/config.json
|
||||
node -e "const c = require('./.changeset/config.json'); console.log('access:', c.access, 'baseBranch:', c.baseBranch)"
|
||||
# 2. changeset status works
|
||||
bunx changeset status 2>&1 || true
|
||||
# 3. publish script exists and uses --ignore-scripts
|
||||
test -f scripts/publish-all.mjs
|
||||
grep -q 'ignore-scripts' scripts/publish-all.mjs
|
||||
# 4. dry run works
|
||||
node scripts/publish-all.mjs --dry-run
|
||||
```
|
||||
|
||||
Post-condition: All verification commands pass.
|
||||
description: Configure changesets and publish pipeline
|
||||
frontmatter:
|
||||
oneOf:
|
||||
- properties:
|
||||
$status:
|
||||
const: done
|
||||
repoPath:
|
||||
type: string
|
||||
- properties:
|
||||
$status:
|
||||
const: skipped
|
||||
repoPath:
|
||||
type: string
|
||||
- properties:
|
||||
$status:
|
||||
const: failed
|
||||
reason:
|
||||
type: string
|
||||
repoPath:
|
||||
type: string
|
||||
capabilities:
|
||||
- changeset-config
|
||||
- release-config
|
||||
testing:
|
||||
goal: You set up vitest test infrastructure across the monorepo.
|
||||
output: List what was configured per package. Set $status to done or failed.
|
||||
procedure: |
|
||||
## GROUND RULES (read before doing anything)
|
||||
- Only report actions you ACTUALLY performed and files you ACTUALLY created or modified.
|
||||
- If everything is already correctly configured, set $status=skipped.
|
||||
- NEVER fabricate command output. Run every verification command for real and paste the actual stdout/stderr.
|
||||
- After writing a file, run `test -f <path> && echo EXISTS || echo MISSING` to confirm it was actually written.
|
||||
|
||||
cd into the repo path from your task prompt.
|
||||
|
||||
Be idempotent — do NOT overwrite existing vitest.config.ts or test files.
|
||||
|
||||
Check and fix:
|
||||
1. Add `vitest` to root devDependencies (skip if present), run `bun install`
|
||||
2. For each package under `packages/`:
|
||||
- If `vitest.config.ts` does NOT already exist, create it:
|
||||
```ts
|
||||
import { defineConfig } from "vitest/config";
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ["src/__tests__/**/*.test.ts"],
|
||||
},
|
||||
});
|
||||
```
|
||||
- If package.json has no `"test"` script, add: `"test": "vitest run --passWithNoTests"`, `"test:ci": "vitest run --passWithNoTests"`
|
||||
- Create `src/__tests__/` directory if it doesn't exist
|
||||
3. Root package.json scripts must include:
|
||||
- `"test": "bun run --filter './packages/*' test"`
|
||||
- `"test:ci": "bun run --filter './packages/*' test:ci"`
|
||||
|
||||
## Verification
|
||||
You MUST actually run each command below and include real output. Do NOT guess or fabricate results.
|
||||
```bash
|
||||
# 1. vitest is installed
|
||||
bunx vitest --version
|
||||
# 2. each package has vitest config
|
||||
for d in packages/*/; do
|
||||
if [ -f "$d/vitest.config.ts" ]; then echo "$d: ✅"; else echo "$d: ❌ missing vitest.config.ts"; fi
|
||||
done
|
||||
# 3. root test script works
|
||||
bun run test 2>&1 || true
|
||||
```
|
||||
|
||||
Post-condition: `bun run test` runs without infrastructure errors (no tests is OK, test failures are OK).
|
||||
description: Configure vitest for all packages
|
||||
frontmatter:
|
||||
oneOf:
|
||||
- properties:
|
||||
$status:
|
||||
const: done
|
||||
repoPath:
|
||||
type: string
|
||||
- properties:
|
||||
$status:
|
||||
const: skipped
|
||||
repoPath:
|
||||
type: string
|
||||
- properties:
|
||||
$status:
|
||||
const: failed
|
||||
reason:
|
||||
type: string
|
||||
repoPath:
|
||||
type: string
|
||||
capabilities:
|
||||
- test-config
|
||||
committer:
|
||||
goal: You commit all the changes made by previous roles in a single clean commit.
|
||||
output: List files changed and commit hash. Set $status to committed or no_changes.
|
||||
procedure: |
|
||||
## GROUND RULES (read before doing anything)
|
||||
- Only report actions you ACTUALLY performed and files you ACTUALLY created or modified.
|
||||
- If everything is already correctly configured, set $status=skipped.
|
||||
- NEVER fabricate command output. Run every verification command for real and paste the actual stdout/stderr.
|
||||
- After writing a file, run `test -f <path> && echo EXISTS || echo MISSING` to confirm it was actually written.
|
||||
|
||||
cd into the repo path from your task prompt.
|
||||
|
||||
1. Review all changes: `git diff --stat` and `git status`
|
||||
2. Verify key files exist from previous roles (spot-check):
|
||||
```bash
|
||||
echo "=== Spot-check ==="
|
||||
if [ -f tsconfig.json ]; then echo "✅ tsconfig.json"; else echo "ℹ️ tsconfig.json (skipped for JS/MJS)"; fi
|
||||
for f in .gitignore biome.json .changeset/config.json .gitea/workflows/ci.yml .githooks/pre-push; do
|
||||
test -f "$f" && echo "✅ $f" || echo "⚠️ MISSING: $f"
|
||||
done
|
||||
node -e "
|
||||
const p = require('./package.json');
|
||||
const required = ['build', 'check', 'test', 'test:ci', 'format', 'preinstall', 'prepublishOnly'];
|
||||
const missing = required.filter(s => !p.scripts?.[s]);
|
||||
if (missing.length) console.log('⚠️ Missing scripts:', missing.join(', '));
|
||||
else console.log('✅ All scripts present');
|
||||
if (!p.packageManager) console.log('⚠️ Missing packageManager');
|
||||
else console.log('✅ packageManager:', p.packageManager);
|
||||
"
|
||||
```
|
||||
List any missing items as warnings but still commit what exists.
|
||||
3. If no changes: set $status=no_changes
|
||||
4. Stage all: `git add -A`
|
||||
5. **Before committing, check for build artifacts that should NOT be committed:**
|
||||
```bash
|
||||
# Detect compiled output accidentally staged
|
||||
git diff --cached --name-only | grep -E '\.(d\.ts|\.js\.map)$' | grep -v node_modules | head -20
|
||||
# Also check for .js files next to .ts sources (build output in src/)
|
||||
for f in $(git diff --cached --name-only | grep -E '\.js$' | grep -v node_modules | grep -v scripts/); do
|
||||
ts_file="${f%.js}.ts"
|
||||
if [ -f "$ts_file" ]; then echo "BUILD ARTIFACT: $f (has matching $ts_file)"; fi
|
||||
done
|
||||
```
|
||||
If build artifacts are found:
|
||||
- Unstage them: `git reset HEAD <files>`
|
||||
- Add patterns to `.gitignore` if missing (e.g. `*.d.ts`, `*.js.map`, or specific output dirs)
|
||||
- Re-run `git add -A` after updating `.gitignore`
|
||||
6. Commit: `git commit -m "chore: normalize to bun monorepo conventions"`
|
||||
7. Push: `git push`
|
||||
|
||||
Post-condition: Clean commit pushed, `git status` shows clean working tree. No build artifacts in the commit.
|
||||
description: Commits all normalization changes
|
||||
frontmatter:
|
||||
oneOf:
|
||||
- properties:
|
||||
$status:
|
||||
const: committed
|
||||
commitHash:
|
||||
type: string
|
||||
repoPath:
|
||||
type: string
|
||||
- properties:
|
||||
$status:
|
||||
const: no_changes
|
||||
repoPath:
|
||||
type: string
|
||||
- properties:
|
||||
$status:
|
||||
const: failed
|
||||
reason:
|
||||
type: string
|
||||
repoPath:
|
||||
type: string
|
||||
capabilities: []
|
||||
workspace:
|
||||
goal: You set up the foundational bun workspace configuration for a monorepo.
|
||||
output: List what was changed. Set $status to done (workspace working) or failed (with reason).
|
||||
procedure: |
|
||||
## GROUND RULES (read before doing anything)
|
||||
- Only report actions you ACTUALLY performed and files you ACTUALLY created or modified.
|
||||
- If everything is already correctly configured, set $status=skipped.
|
||||
- NEVER fabricate command output. Run every verification command for real and paste the actual stdout/stderr.
|
||||
- After writing a file, run `test -f <path> && echo EXISTS || echo MISSING` to confirm it was actually written.
|
||||
|
||||
cd into the repo path provided in your task prompt.
|
||||
|
||||
Be idempotent — check before modifying. If something is already correct, skip it.
|
||||
|
||||
Check and fix:
|
||||
1. Root `package.json` must have `"workspaces": ["packages/*"]`
|
||||
2. Root `package.json` must have `"private": true`
|
||||
3. If packages exist in other locations (e.g. root src/, top-level dirs), migrate them under `packages/`
|
||||
4. Each package under `packages/` must have its own `package.json` with `"name"` and `"type": "module"`
|
||||
5. `.gitignore` must exist and include at minimum:
|
||||
```
|
||||
node_modules/
|
||||
dist/
|
||||
*.tsbuildinfo
|
||||
```
|
||||
If `.gitignore` is missing or doesn't cover these, append the missing entries (don't overwrite existing content).
|
||||
6. If node_modules/ is already tracked in git, remove it: `git rm -r --cached node_modules/ */node_modules/ 2>/dev/null`
|
||||
7. Run `bun install` to verify workspace resolution works
|
||||
|
||||
## Verification (must all pass)
|
||||
You MUST actually run each command below and include real output. Do NOT guess or fabricate results.
|
||||
```bash
|
||||
# 1. bun install works
|
||||
bun install
|
||||
# 2. gitignore covers essentials
|
||||
grep -q 'node_modules' .gitignore
|
||||
grep -q 'dist' .gitignore
|
||||
# 3. no node_modules tracked
|
||||
test -z "$(git ls-files | grep node_modules)"
|
||||
# 4. all packages have package.json
|
||||
for d in packages/*/; do test -f "$d/package.json" || echo "MISSING: $d/package.json"; done
|
||||
```
|
||||
|
||||
Post-condition: All verification commands pass.
|
||||
description: Ensure bun workspace structure
|
||||
frontmatter:
|
||||
oneOf:
|
||||
- properties:
|
||||
$status:
|
||||
const: done
|
||||
repoPath:
|
||||
type: string
|
||||
- properties:
|
||||
$status:
|
||||
const: skipped
|
||||
repoPath:
|
||||
type: string
|
||||
- properties:
|
||||
$status:
|
||||
const: failed
|
||||
reason:
|
||||
type: string
|
||||
repoPath:
|
||||
type: string
|
||||
capabilities:
|
||||
- workspace-setup
|
||||
guardrails:
|
||||
goal: You configure enforcement mechanisms that block npm/pnpm/yarn usage and direct npm publish.
|
||||
output: List what guardrails were installed. Set $status to done or failed.
|
||||
procedure: |
|
||||
## GROUND RULES (read before doing anything)
|
||||
- Only report actions you ACTUALLY performed and files you ACTUALLY created or modified.
|
||||
- If everything is already correctly configured, set $status=skipped.
|
||||
- NEVER fabricate command output. Run every verification command for real and paste the actual stdout/stderr.
|
||||
- After writing a file, run `test -f <path> && echo EXISTS || echo MISSING` to confirm it was actually written.
|
||||
|
||||
cd into the repo path from your task prompt.
|
||||
|
||||
Be idempotent — check before adding.
|
||||
|
||||
## 1. Block wrong package manager
|
||||
Add to root `package.json` (if not already present):
|
||||
- `"packageManager": "bun@<version>"` — use the version from `bun --version`
|
||||
- `"scripts.preinstall": "npx only-allow bun"` — blocks npm/pnpm/yarn install
|
||||
|
||||
## 2. Block direct npm publish
|
||||
Add to root `package.json` (if not already present):
|
||||
- `"scripts.prepublishOnly": "echo 'Use bun run release instead' && exit 1"`
|
||||
|
||||
For each non-private package under `packages/`:
|
||||
- Add `"scripts.prepublishOnly": "echo 'Use bun run release from repo root' && exit 1"` to their package.json (if not present)
|
||||
|
||||
If `scripts/publish-all.mjs` exists, verify it uses `--ignore-scripts` in the npm publish command.
|
||||
If it doesn't, add `--ignore-scripts` to the publish command.
|
||||
|
||||
## 3. Git hooks
|
||||
Create `.githooks/pre-push` (if not already present):
|
||||
```bash
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
echo "🔍 Running checks..."
|
||||
bun run check
|
||||
echo "🧪 Running tests..."
|
||||
bun run test
|
||||
echo "✅ All checks passed!"
|
||||
```
|
||||
Make it executable: `chmod +x .githooks/pre-push`
|
||||
Configure git to use hooks dir: `git config core.hooksPath .githooks`
|
||||
|
||||
## Verification
|
||||
You MUST actually run each command below and include real output. Do NOT guess or fabricate results.
|
||||
```bash
|
||||
# 1. packageManager field exists
|
||||
node -e "const p = require('./package.json'); if (!p.packageManager) { console.error('❌ missing packageManager'); process.exit(1); } console.log('✅ packageManager:', p.packageManager)"
|
||||
# 2. preinstall guard exists
|
||||
node -e "const p = require('./package.json'); if (!p.scripts?.preinstall?.includes('only-allow')) { console.error('❌ missing preinstall guard'); process.exit(1); } console.log('✅ preinstall guard')"
|
||||
# 3. npm install is blocked (with timeout to prevent hang)
|
||||
timeout 10 npm install 2>&1 | head -5 || true
|
||||
# 4. prepublishOnly exists
|
||||
node -e "const p = require('./package.json'); if (!p.scripts?.prepublishOnly) { console.error('❌ missing prepublishOnly'); process.exit(1); } console.log('✅ prepublishOnly guard')"
|
||||
# 5. publish script uses --ignore-scripts
|
||||
if [ -f scripts/publish-all.mjs ]; then grep -q 'ignore-scripts' scripts/publish-all.mjs && echo '✅ publish uses --ignore-scripts' || echo '❌ publish missing --ignore-scripts'; fi
|
||||
# 6. git hooks configured
|
||||
test -f .githooks/pre-push && echo '✅ pre-push hook' || echo '❌ missing pre-push hook'
|
||||
```
|
||||
|
||||
Post-condition: All verification checks pass.
|
||||
description: Install project guardrails to prevent wrong package manager and publish workflow
|
||||
frontmatter:
|
||||
oneOf:
|
||||
- properties:
|
||||
$status:
|
||||
const: done
|
||||
repoPath:
|
||||
type: string
|
||||
- properties:
|
||||
$status:
|
||||
const: skipped
|
||||
repoPath:
|
||||
type: string
|
||||
- properties:
|
||||
$status:
|
||||
const: failed
|
||||
reason:
|
||||
type: string
|
||||
repoPath:
|
||||
type: string
|
||||
capabilities:
|
||||
- guardrails
|
||||
typescript:
|
||||
goal: You configure TypeScript for a bun monorepo with composite project references.
|
||||
output: List what was configured. Set $status to done or failed.
|
||||
procedure: |-
|
||||
## GROUND RULES (read before doing anything)
|
||||
- Only report actions you ACTUALLY performed and files you ACTUALLY created or modified.
|
||||
- If everything is already correctly configured, set $status=skipped.
|
||||
- NEVER fabricate command output. Run every verification command for real and paste the actual stdout/stderr.
|
||||
- After writing a file, run `test -f <path> && echo EXISTS || echo MISSING` to confirm it was actually written.
|
||||
|
||||
cd into the repo path from your task prompt.
|
||||
|
||||
Be idempotent — if tsconfig.json already exists with correct settings, don't overwrite.
|
||||
|
||||
## Step 0: Detect if project needs TypeScript compilation
|
||||
|
||||
```bash
|
||||
TS_FILES=$(find packages/ -name '*.ts' -o -name '*.tsx' | grep -v node_modules | grep -v dist | grep -v '.d.ts' | head -5)
|
||||
```
|
||||
|
||||
**If there are NO .ts/.tsx source files** (pure JS/MJS project):
|
||||
- Do NOT create root tsconfig.json
|
||||
- Do NOT add `bunx tsc --build` as the build script
|
||||
- Do NOT add typescript/bun-types to devDependencies unless already present
|
||||
- Preserve the existing `build` script (e.g. vite build, esbuild, etc.)
|
||||
- If no build script exists, add one based on the project's bundler (check for vite.config, esbuild, etc.)
|
||||
- Set $status=done with note "JS/MJS project — skipped TypeScript setup"
|
||||
- STOP HERE.
|
||||
|
||||
**If .ts/.tsx files exist**, continue with full TypeScript setup:
|
||||
|
||||
Check and fix:
|
||||
1. Root `tsconfig.json` must exist with:
|
||||
- `"compilerOptions"`: target ES2022, module NodeNext, moduleResolution NodeNext, strict true, composite true, declaration true, declarationMap true, sourceMap true
|
||||
- `"references"`: array with `{ "path": "packages/<name>" }` for each package
|
||||
- `"files": []` (root does not compile files directly)
|
||||
2. Each package must have `tsconfig.json` with:
|
||||
- `"extends": "../../tsconfig.json"` (inherit root config)
|
||||
- `"compilerOptions": { "rootDir": "src", "outDir": "dist" }`
|
||||
- `"include": ["src"]`
|
||||
- `"references"` to sibling packages it depends on
|
||||
3. Root scripts must include: `"build": "bunx tsc --build"`, `"typecheck": "bunx tsc --build"`
|
||||
4. `devDependencies` at root: `typescript`, `bun-types`, `@types/node`
|
||||
|
||||
## Verification
|
||||
You MUST actually run each command below and include real output. Do NOT guess or fabricate results.
|
||||
```bash
|
||||
if [ ! -f tsconfig.json ]; then
|
||||
echo "JS/MJS project — no tsconfig needed"
|
||||
node -e "const p = require('./package.json'); if (!p.scripts?.build) { console.error('Missing build script'); process.exit(1); } console.log('build:', p.scripts.build)"
|
||||
bun run build
|
||||
exit 0
|
||||
fi
|
||||
test -f tsconfig.json
|
||||
for d in packages/*/; do test -f "$d/tsconfig.json" || echo "MISSING: $d/tsconfig.json"; done
|
||||
bunx tsc --build
|
||||
```
|
||||
|
||||
Post-condition: For TS projects — `bunx tsc --build` succeeds. For JS/MJS projects — `bun run build` succeeds.
|
||||
description: Configure TypeScript with project references
|
||||
frontmatter:
|
||||
oneOf:
|
||||
- properties:
|
||||
$status:
|
||||
const: done
|
||||
repoPath:
|
||||
type: string
|
||||
- properties:
|
||||
$status:
|
||||
const: skipped
|
||||
repoPath:
|
||||
type: string
|
||||
- properties:
|
||||
$status:
|
||||
const: failed
|
||||
reason:
|
||||
type: string
|
||||
repoPath:
|
||||
type: string
|
||||
capabilities:
|
||||
- typescript-config
|
||||
package-metadata:
|
||||
goal: You ensure every package has consistent metadata for publishing and discoverability.
|
||||
output: List what was standardized per package. Set $status to done or failed.
|
||||
procedure: |
|
||||
## GROUND RULES (read before doing anything)
|
||||
- Only report actions you ACTUALLY performed and files you ACTUALLY created or modified.
|
||||
- If everything is already correctly configured, set $status=skipped.
|
||||
- NEVER fabricate command output. Run every verification command for real and paste the actual stdout/stderr.
|
||||
- After writing a file, run `test -f <path> && echo EXISTS || echo MISSING` to confirm it was actually written.
|
||||
|
||||
cd into the repo path from your task prompt.
|
||||
|
||||
Be idempotent — skip fields that are already correctly set.
|
||||
|
||||
For each package under `packages/`:
|
||||
1. `"type": "module"` — must be set
|
||||
2. `"files": ["src", "dist", "package.json"]` — for published packages (non-private)
|
||||
3. `"publishConfig": { "access": "public" }` — for @scoped public packages (non-private)
|
||||
4. `"repository"` — must point to the correct git remote and directory
|
||||
- Read remote URL: `git remote get-url origin`
|
||||
- Set `"directory": "packages/<name>"`
|
||||
5. `"exports"` — conditional exports for TypeScript packages:
|
||||
```json
|
||||
".": {
|
||||
"bun": "./src/index.ts",
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
```
|
||||
Skip if package has no `src/index.ts`.
|
||||
6. Private packages (server, frontend, tools) must have `"private": true` and can skip publishConfig/files
|
||||
7. Each package should have a `"scripts"` section with at least `"test"` if tests exist
|
||||
8. Workspace dependencies should use `"workspace:^"` protocol, not version numbers
|
||||
- Check: `grep -r '"@uncaged/' packages/*/package.json | grep -v 'workspace:'`
|
||||
|
||||
## Verification
|
||||
You MUST actually run each command below and include real output. Do NOT guess or fabricate results.
|
||||
```bash
|
||||
# Check every non-private package has required fields
|
||||
for d in packages/*/; do
|
||||
pkg="$d/package.json"
|
||||
test -f "$pkg" || continue
|
||||
node -e "
|
||||
const p = require('./$pkg');
|
||||
if (p.private) { console.log('$d: private, skip'); process.exit(0); }
|
||||
const issues = [];
|
||||
if (p.type !== 'module') issues.push('missing type:module');
|
||||
if (!p.exports) issues.push('missing exports');
|
||||
if (!p.publishConfig) issues.push('missing publishConfig');
|
||||
if (!p.files) issues.push('missing files');
|
||||
if (issues.length) console.log('$d:', issues.join(', '));
|
||||
else console.log('$d: OK');
|
||||
"
|
||||
done
|
||||
# No hardcoded workspace deps
|
||||
! grep -r '"@uncaged/' packages/*/package.json | grep -v 'workspace:' | grep -v node_modules
|
||||
```
|
||||
|
||||
Post-condition: Verification script shows OK for all non-private packages, no hardcoded workspace versions.
|
||||
description: Standardize package.json metadata across all packages
|
||||
frontmatter:
|
||||
oneOf:
|
||||
- properties:
|
||||
$status:
|
||||
const: done
|
||||
repoPath:
|
||||
type: string
|
||||
- properties:
|
||||
$status:
|
||||
const: skipped
|
||||
repoPath:
|
||||
type: string
|
||||
- properties:
|
||||
$status:
|
||||
const: failed
|
||||
reason:
|
||||
type: string
|
||||
repoPath:
|
||||
type: string
|
||||
capabilities:
|
||||
- package-config
|
||||
solve-issue-workflow:
|
||||
goal: You place a solve-issue workflow YAML in .workflows/ so the project can use uwf thread start .workflows/solve-issue.yaml for issue resolution.
|
||||
output: Describe the workflow registered. Set $status to done or failed.
|
||||
procedure: |-
|
||||
## GROUND RULES (read before doing anything)
|
||||
- Only report actions you ACTUALLY performed and files you ACTUALLY created or modified.
|
||||
- If everything is already correctly configured, set $status=skipped.
|
||||
- NEVER fabricate command output. Run every verification command for real and paste the actual stdout/stderr.
|
||||
- After writing a file, run `test -f <path> && echo EXISTS || echo MISSING` to confirm it was actually written.
|
||||
|
||||
cd into the repo path from your task prompt.
|
||||
|
||||
1. Check if `uwf` CLI is available: `which uwf`
|
||||
- If not available: set $status=failed, reason="uwf CLI not installed"
|
||||
2. Check if `.workflows/solve-issue.yaml` already exists:
|
||||
- If it exists and looks correct (has planner/developer/reviewer/tester/committer roles), skip. Set $status=done.
|
||||
3. Create `.workflows/solve-issue.yaml` adapted for this project:
|
||||
- Copy the standard solve-issue workflow structure (planner -> developer -> reviewer -> tester -> committer)
|
||||
- Adjust the developer role procedure to use this project's test runner and build commands
|
||||
- The workflow should reference the correct repo path and build toolchain (bun)
|
||||
NOTE: Place the file in `.workflows/` (dot-prefix), NOT `workflows/`. Do NOT run `uwf workflow add`. The file is used directly via `uwf thread start .workflows/solve-issue.yaml`.
|
||||
|
||||
## Verification
|
||||
You MUST actually run each command below and include real output. Do NOT guess or fabricate results.
|
||||
```bash
|
||||
test -f .workflows/solve-issue.yaml
|
||||
node -e "
|
||||
const fs = require('fs');
|
||||
const content = fs.readFileSync('.workflows/solve-issue.yaml', 'utf8');
|
||||
const required = ['planner', 'developer', 'reviewer', 'tester', 'committer'];
|
||||
const missing = required.filter(r => !content.includes(r + ':'));
|
||||
if (missing.length) { console.error('Missing roles:', missing.join(', ')); process.exit(1); }
|
||||
console.log('All roles present');
|
||||
"
|
||||
```
|
||||
|
||||
Post-condition: `.workflows/solve-issue.yaml` exists with all 5 roles.
|
||||
description: Register solve-issue workflow for the project
|
||||
frontmatter:
|
||||
oneOf:
|
||||
- properties:
|
||||
$status:
|
||||
const: done
|
||||
repoPath:
|
||||
type: string
|
||||
- properties:
|
||||
$status:
|
||||
const: skipped
|
||||
repoPath:
|
||||
type: string
|
||||
- properties:
|
||||
$status:
|
||||
const: failed
|
||||
reason:
|
||||
type: string
|
||||
repoPath:
|
||||
type: string
|
||||
capabilities:
|
||||
- workflow-config
|
||||
description: Normalize an existing project to @uncaged bun monorepo conventions. Supports both TypeScript and JS/MJS projects. Each role handles one configuration layer. All roles allow fail.
|
||||
@@ -0,0 +1,323 @@
|
||||
name: solve-issue
|
||||
description: TDD-driven issue resolution adapted for the workflow monorepo with bun + vitest
|
||||
roles:
|
||||
planner:
|
||||
description: Analyzes issue and outputs a TDD test spec
|
||||
goal: You are a planning agent. You analyze Gitea issues and produce a TDD test specification that downstream roles will implement and verify.
|
||||
capabilities:
|
||||
- issue-analysis
|
||||
- planning
|
||||
procedure: 'On first run (no previous steps):
|
||||
|
||||
1. Read the issue and all comments from Gitea using `tea issues <number> -r <owner/repo>`
|
||||
|
||||
2. Look for project conventions files (CLAUDE.md, CONTRIBUTING.md) in the repo
|
||||
|
||||
3. Assess whether the issue has enough information to produce a test spec
|
||||
|
||||
4. If insufficient info: comment on the issue via `echo "..." | tea comment <number> -r <owner/repo>` (skip if you already commented), then output $status=insufficient_info
|
||||
|
||||
5. If sufficient: produce a detailed TDD test spec in markdown covering all scenarios
|
||||
|
||||
|
||||
On subsequent runs (bounced back by tester with fix_spec):
|
||||
|
||||
1. Read the tester''s output from the previous step to understand what''s wrong with the spec
|
||||
|
||||
2. Revise the test spec accordingly
|
||||
|
||||
|
||||
After producing the test spec:
|
||||
|
||||
1. Store it via `uwf cas put-text "<markdown content>"` and capture the returned hash
|
||||
|
||||
2. Put the hash in frontmatter.plan (required when $status=ready)
|
||||
|
||||
3. Set repoPath to the absolute path of the repository root
|
||||
|
||||
|
||||
|
||||
IMPORTANT: Extract the repo remote (owner/repo) from git:
|
||||
|
||||
```bash
|
||||
|
||||
git remote get-url origin | sed ''s|.*[:/]\([^/]*/[^.]*\).*|\1|''
|
||||
|
||||
```
|
||||
|
||||
Store the result as repoRemote in your frontmatter output so downstream roles can use it for tea/API calls.'
|
||||
output: Output a brief summary of the test spec. Set $status to ready (with plan hash and repoPath) or insufficient_info.
|
||||
frontmatter:
|
||||
oneOf:
|
||||
- properties:
|
||||
$status:
|
||||
const: ready
|
||||
plan:
|
||||
type: string
|
||||
repoPath:
|
||||
type: string
|
||||
repoRemote:
|
||||
type: string
|
||||
required:
|
||||
- $status
|
||||
- plan
|
||||
- repoPath
|
||||
- properties:
|
||||
$status:
|
||||
const: insufficient_info
|
||||
required:
|
||||
- $status
|
||||
developer:
|
||||
description: TDD implementation per test spec
|
||||
goal: You are a developer agent. You implement code changes following TDD — write tests first, then implementation.
|
||||
capabilities:
|
||||
- coding
|
||||
procedure: "IMPORTANT: Always work in a git worktree, NEVER modify the main working directory directly.\nThe repo path and other details are provided in your task prompt.\n\nBefore starting any work,\
|
||||
\ set up an isolated worktree:\n1. cd into the repo path provided in your task prompt\n2. `git fetch origin` to get latest refs\n3. First time (no existing branch):\n - `git worktree add .worktrees/fix/<issue-number>-<short-slug>\
|
||||
\ -b fix/<issue-number>-<short-slug> origin/main`\n - `cd .worktrees/fix/<issue-number>-<short-slug> && bun install`\n4. If bounced back from reviewer or tester (branch already exists):\n - cd\
|
||||
\ into the existing worktree under `.worktrees/fix/<issue-number>-<short-slug>`\n - `git fetch origin && git rebase origin/main`\n5. ALL subsequent work must happen inside the worktree directory.\n\
|
||||
\nThen implement TDD:\n6. Read the test spec from CAS: `uwf cas get <plan hash>` (find the hash from the planner's output in your task prompt)\n7. If bounced back from reviewer or tester: read the\
|
||||
\ previous role's feedback in your task prompt\n8. Write tests first based on the spec (use vitest)\n9. Implement the code to make tests pass\n10. Ensure `bun run build` passes with no errors\n11.\
|
||||
\ Run `bun test` to verify all tests pass\n\nIf you cannot complete the implementation (e.g. the issue is too complex, blocked by external factors,\nor repeated attempts fail), set $status=failed\
|
||||
\ with a reason.\n"
|
||||
output: List all files changed and provide a summary. Set $status to done (with branch/worktree), or failed (with reason).
|
||||
frontmatter:
|
||||
oneOf:
|
||||
- properties:
|
||||
$status:
|
||||
const: done
|
||||
branch:
|
||||
type: string
|
||||
worktree:
|
||||
type: string
|
||||
repoRemote:
|
||||
type: string
|
||||
required:
|
||||
- $status
|
||||
- branch
|
||||
- worktree
|
||||
- properties:
|
||||
$status:
|
||||
const: failed
|
||||
reason:
|
||||
type: string
|
||||
repoRemote:
|
||||
type: string
|
||||
required:
|
||||
- $status
|
||||
- reason
|
||||
reviewer:
|
||||
description: Code standards compliance check
|
||||
goal: You are a code reviewer. You verify code standards compliance — NOT functionality (that's the tester's job).
|
||||
capabilities:
|
||||
- code-review
|
||||
- static-analysis
|
||||
procedure: 'The worktree path is provided in your task prompt. cd into it first.
|
||||
|
||||
|
||||
Before reviewing, verify the git branch:
|
||||
|
||||
1. Run `git branch --show-current` — confirm the branch name references the issue number being worked on
|
||||
|
||||
2. If the branch doesn''t correspond to the issue, flag it in your output and reject
|
||||
|
||||
|
||||
Then perform code review:
|
||||
|
||||
Hard checks (must all pass):
|
||||
|
||||
3. `bun run build` — no build errors
|
||||
|
||||
4. `bunx biome check` — no lint violations
|
||||
|
||||
5. TypeScript strict mode — no type errors
|
||||
|
||||
|
||||
Soft checks (review against project conventions from CLAUDE.md):
|
||||
|
||||
- Functional-first: functions + types, no classes (except for errors or third-party requirements)
|
||||
|
||||
- Named exports only, no default exports
|
||||
|
||||
- No optional properties (use `T | null` instead of `?:`)
|
||||
|
||||
- Folder module discipline: index.ts only re-exports, types in types.ts
|
||||
|
||||
- Crockford Base32 log tags (8-char, unique per call site)
|
||||
|
||||
- No `console.log` in production code (use createLogger from @uncaged/workflow-util)
|
||||
|
||||
- No dynamic imports in production code
|
||||
|
||||
|
||||
Only review standards compliance. Do NOT test functionality.
|
||||
|
||||
If rejecting, you MUST explain the specific reason in your output.
|
||||
|
||||
'
|
||||
output: Explain your decision with specific file/line references. Set $status to approved (with branch/worktree) or rejected (with comments).
|
||||
frontmatter:
|
||||
oneOf:
|
||||
- properties:
|
||||
$status:
|
||||
const: approved
|
||||
branch:
|
||||
type: string
|
||||
worktree:
|
||||
type: string
|
||||
repoRemote:
|
||||
type: string
|
||||
required:
|
||||
- $status
|
||||
- branch
|
||||
- worktree
|
||||
- properties:
|
||||
$status:
|
||||
const: rejected
|
||||
comments:
|
||||
type: string
|
||||
worktree:
|
||||
type: string
|
||||
repoRemote:
|
||||
type: string
|
||||
required:
|
||||
- $status
|
||||
- comments
|
||||
- worktree
|
||||
tester:
|
||||
description: Functional correctness verification
|
||||
goal: You are a tester agent. You verify that the implementation correctly satisfies every scenario in the test spec.
|
||||
capabilities:
|
||||
- testing
|
||||
procedure: "The worktree path is provided in your task prompt. cd into it first.\n\n1. Run `bun test` for automated test verification\n2. Read the test spec from CAS: `uwf cas get <plan hash>` (find\
|
||||
\ the hash from the planner step in the thread history)\n3. Verify each scenario in the spec is covered and passing\n4. Determine outcome:\n - passed: all scenarios verified, tests pass\n - fix_code:\
|
||||
\ tests fail or implementation doesn't match spec → send back to developer\n - fix_spec: the spec itself is wrong or incomplete → send back to planner\n"
|
||||
output: Report test results per scenario. Set $status to passed (with branch/worktree), fix_code (with report), or fix_spec (with report).
|
||||
frontmatter:
|
||||
oneOf:
|
||||
- properties:
|
||||
$status:
|
||||
const: passed
|
||||
branch:
|
||||
type: string
|
||||
worktree:
|
||||
type: string
|
||||
repoRemote:
|
||||
type: string
|
||||
required:
|
||||
- $status
|
||||
- branch
|
||||
- worktree
|
||||
- properties:
|
||||
$status:
|
||||
const: fix_code
|
||||
report:
|
||||
type: string
|
||||
repoRemote:
|
||||
type: string
|
||||
worktree:
|
||||
type: string
|
||||
branch:
|
||||
type: string
|
||||
required:
|
||||
- $status
|
||||
- report
|
||||
- properties:
|
||||
$status:
|
||||
const: fix_spec
|
||||
report:
|
||||
type: string
|
||||
repoRemote:
|
||||
type: string
|
||||
worktree:
|
||||
type: string
|
||||
branch:
|
||||
type: string
|
||||
required:
|
||||
- $status
|
||||
- report
|
||||
committer:
|
||||
description: Commits and creates PR
|
||||
goal: You are a committer agent. You create a clean commit and push a PR linking the original issue.
|
||||
capabilities: []
|
||||
procedure: "The worktree path, branch name, and repo remote (owner/repo) are provided in your task prompt.\ncd into the worktree first.\n\nNote: You inherit the developer's worktree and branch. Do NOT\
|
||||
\ create a new branch.\n1. Stage all changes: `git add -A`\n2. Commit with a descriptive message referencing the issue: `git commit -m \"type: description\\n\\nFixes #N\"`\n3. Push the branch: `git\
|
||||
\ push -u origin <branch-name>`\n4. **Verify push succeeded** — run `git ls-remote origin <branch-name>` and confirm it prints a commit hash.\n - If no output or push failed: capture the error, mark hook_failed\n\
|
||||
5. Create a PR using the Gitea API (do NOT use `tea pr create` — it fails in worktrees):\n ```bash\n GITEA_TOKEN=$(cfg get GITEA_TOKEN)\n curl -s -X POST -H \"Authorization: token $GITEA_TOKEN\" -H \"Content-Type: application/json\" \\\n\
|
||||
\ \"https://git.shazhou.work/api/v1/repos/<owner>/<repo>/pulls\" \\\n -d '{\"title\":\"...\",\"body\":\"...\",\"head\":\"<branch>\",\"base\":\"main\"}'\n ```\n - The repo remote (owner/repo format, e.g. \"uncaged/workflow\") is given in your task prompt — use it directly.\n\
|
||||
\ - PR body must include: What / Why / Changes / Ref sections, with `Fixes #N` in Ref\n6. **Verify PR was created** — parse the curl response JSON: it must contain a `\"number\"` field. Print the PR URL.\n\
|
||||
\ - If curl returns an error or no number field: capture the response, mark hook_failed\n7. After PR creation, clean up the worktree:\n - cd to the repo root (parent of .worktrees)\n - `git worktree remove <worktree-path>`"
|
||||
output: Include PR URL on success or error log on failure. Set $status to committed (with prUrl) or hook_failed (with error).
|
||||
frontmatter:
|
||||
oneOf:
|
||||
- properties:
|
||||
$status:
|
||||
const: committed
|
||||
prUrl:
|
||||
type: string
|
||||
repoRemote:
|
||||
type: string
|
||||
worktree:
|
||||
type: string
|
||||
branch:
|
||||
type: string
|
||||
required:
|
||||
- $status
|
||||
- prUrl
|
||||
- properties:
|
||||
$status:
|
||||
const: hook_failed
|
||||
error:
|
||||
type: string
|
||||
repoRemote:
|
||||
type: string
|
||||
worktree:
|
||||
type: string
|
||||
branch:
|
||||
type: string
|
||||
required:
|
||||
- $status
|
||||
- error
|
||||
graph:
|
||||
$START:
|
||||
_:
|
||||
role: planner
|
||||
prompt: Analyze the issue and produce an implementation plan.
|
||||
planner:
|
||||
insufficient_info:
|
||||
role: $END
|
||||
prompt: Insufficient information to proceed; end the workflow.
|
||||
ready:
|
||||
role: developer
|
||||
prompt: 'Implement the TDD test spec (CAS hash: {{{plan}}}) in repo {{{repoPath}}}. Repo remote: {{{repoRemote}}}.'
|
||||
developer:
|
||||
done:
|
||||
role: reviewer
|
||||
prompt: 'Review branch {{{branch}}} at {{{worktree}}} for code standards compliance. Repo remote: {{{repoRemote}}}.'
|
||||
failed:
|
||||
role: $END
|
||||
prompt: 'Developer failed: {{{reason}}}. Ending workflow.'
|
||||
reviewer:
|
||||
rejected:
|
||||
role: developer
|
||||
prompt: 'Reviewer rejected: {{{comments}}}. Fix the issues in repo {{{worktree}}}. Repo remote: {{{repoRemote}}}.'
|
||||
approved:
|
||||
role: tester
|
||||
prompt: 'Review passed. Run tests on branch {{{branch}}} at {{{worktree}}}. Repo remote: {{{repoRemote}}}.'
|
||||
tester:
|
||||
fix_code:
|
||||
role: developer
|
||||
prompt: 'Tests found code issues: {{{report}}}. Fix and re-submit. Worktree: {{{worktree}}}. Repo remote: {{{repoRemote}}}.'
|
||||
fix_spec:
|
||||
role: planner
|
||||
prompt: 'Tests found spec issues: {{{report}}}. Revise the test spec. Repo remote: {{{repoRemote}}}.'
|
||||
passed:
|
||||
role: committer
|
||||
prompt: 'All tests passed. Commit and push branch {{{branch}}} from {{{worktree}}}. Repo remote (owner/repo): {{{repoRemote}}}.'
|
||||
committer:
|
||||
hook_failed:
|
||||
role: developer
|
||||
prompt: 'Push hook failed: {{{error}}}. Fix and re-submit. Worktree: {{{worktree}}}. Repo remote: {{{repoRemote}}}.'
|
||||
committed:
|
||||
role: $END
|
||||
prompt: 'PR created: {{{prUrl}}}. Workflow complete.'
|
||||
Reference in New Issue
Block a user