Compare commits
14 Commits
feat/266-k
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| a4625a4559 | |||
| c71212a0ce | |||
| 8186a23ceb | |||
| 29d47bd9c4 | |||
| 436ccf12b3 | |||
| 2f78c72e4e | |||
| dc1e96d8f3 | |||
| 7432f80d61 | |||
| 1da41c7f08 | |||
| 07be0d3dfa | |||
| 0fdd2d26cc | |||
| cf7e288874 | |||
| f7cf1a1cb2 | |||
| e4fd5d6ba4 |
1
.gitignore
vendored
1
.gitignore
vendored
@ -5,3 +5,4 @@ nerve.pid
|
||||
nerve.sock
|
||||
false/
|
||||
*.db
|
||||
dist/
|
||||
|
||||
22
nerve.yaml
22
nerve.yaml
@ -5,31 +5,11 @@ extract:
|
||||
model: qwen-plus
|
||||
|
||||
senses:
|
||||
linux-system-health:
|
||||
group: system
|
||||
interval: 30s
|
||||
throttle: 10s
|
||||
timeout: 15s
|
||||
hermes-gateway-health:
|
||||
group: system
|
||||
interval: 2m
|
||||
throttle: 30s
|
||||
timeout: 30s
|
||||
hermes-session-message-stats:
|
||||
group: hermes
|
||||
interval: 15m
|
||||
throttle: 30s
|
||||
timeout: 60s
|
||||
worker-process-metrics:
|
||||
group: system
|
||||
interval: 1m
|
||||
throttle: 15s
|
||||
timeout: 5s
|
||||
git-workspace-status:
|
||||
group: workspace
|
||||
interval: 2m
|
||||
throttle: 30s
|
||||
timeout: 15s
|
||||
|
||||
workflows:
|
||||
develop-sense:
|
||||
@ -41,6 +21,6 @@ workflows:
|
||||
solve-issue:
|
||||
concurrency: 1
|
||||
overflow: queue
|
||||
knowledge-extraction:
|
||||
extract-knowledge:
|
||||
concurrency: 1
|
||||
overflow: queue
|
||||
|
||||
@ -4,7 +4,7 @@
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "pnpm -r build"
|
||||
"build": "node scripts/build.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@uncaged/nerve-adapter-cursor": "link:../repos/nerve/packages/adapter-cursor",
|
||||
@ -19,7 +19,10 @@
|
||||
"zod": "^4.3.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"drizzle-kit": "latest"
|
||||
"@types/node": "^22.0.0",
|
||||
"drizzle-kit": "latest",
|
||||
"esbuild": "^0.27.0",
|
||||
"typescript": "^5.7.0"
|
||||
},
|
||||
"pnpm": {
|
||||
"onlyBuiltDependencies": [
|
||||
|
||||
11
pnpm-lock.yaml
generated
11
pnpm-lock.yaml
generated
@ -48,9 +48,18 @@ importers:
|
||||
specifier: ^4.3.6
|
||||
version: 4.3.6
|
||||
devDependencies:
|
||||
'@types/node':
|
||||
specifier: ^22.0.0
|
||||
version: 22.19.17
|
||||
drizzle-kit:
|
||||
specifier: latest
|
||||
version: 0.31.10
|
||||
esbuild:
|
||||
specifier: ^0.27.0
|
||||
version: 0.27.7
|
||||
typescript:
|
||||
specifier: ^5.7.0
|
||||
version: 5.9.3
|
||||
|
||||
senses/git-workspace-status:
|
||||
devDependencies:
|
||||
@ -174,7 +183,7 @@ importers:
|
||||
specifier: ^5.7.0
|
||||
version: 5.9.3
|
||||
|
||||
workflows/knowledge-extraction:
|
||||
workflows/extract-knowledge:
|
||||
dependencies:
|
||||
'@uncaged/nerve-adapter-cursor':
|
||||
specifier: link:../../../repos/nerve/packages/adapter-cursor
|
||||
|
||||
@ -1,3 +0,0 @@
|
||||
packages:
|
||||
- "workflows/*"
|
||||
- "senses/*"
|
||||
46
scripts/build.mjs
Normal file
46
scripts/build.mjs
Normal file
@ -0,0 +1,46 @@
|
||||
import * as esbuild from "esbuild";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const root = path.join(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const dist = path.join(root, "dist");
|
||||
|
||||
const opts = {
|
||||
bundle: true,
|
||||
platform: "node",
|
||||
format: "esm",
|
||||
packages: "external",
|
||||
};
|
||||
|
||||
function listDirs(dir) {
|
||||
if (!fs.existsSync(dir)) return [];
|
||||
return fs
|
||||
.readdirSync(dir)
|
||||
.filter((name) => !name.startsWith(".") && !name.startsWith("_"))
|
||||
.map((name) => ({ name, full: path.join(dir, name) }))
|
||||
.filter(({ full }) => fs.statSync(full).isDirectory());
|
||||
}
|
||||
|
||||
async function main() {
|
||||
// Clean dist/
|
||||
fs.rmSync(dist, { recursive: true, force: true });
|
||||
|
||||
for (const { name, full } of listDirs(path.join(root, "senses"))) {
|
||||
const entry = path.join(full, "src", "index.ts");
|
||||
if (!fs.existsSync(entry)) continue;
|
||||
const outfile = path.join(dist, "senses", name, "index.js");
|
||||
fs.mkdirSync(path.dirname(outfile), { recursive: true });
|
||||
await esbuild.build({ ...opts, entryPoints: [entry], outfile });
|
||||
}
|
||||
|
||||
for (const { name, full } of listDirs(path.join(root, "workflows"))) {
|
||||
const entry = path.join(full, "index.ts");
|
||||
if (!fs.existsSync(entry)) continue;
|
||||
const outfile = path.join(dist, "workflows", name, "index.js");
|
||||
fs.mkdirSync(path.dirname(outfile), { recursive: true });
|
||||
await esbuild.build({ ...opts, entryPoints: [entry], outfile });
|
||||
}
|
||||
}
|
||||
|
||||
await main();
|
||||
@ -1,85 +0,0 @@
|
||||
// src/index.ts
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
// src/schema.ts
|
||||
import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
|
||||
var snapshots = sqliteTable("snapshots", {
|
||||
ts: integer("ts").primaryKey(),
|
||||
branch: text("branch").notNull(),
|
||||
headShort: text("head_short").notNull(),
|
||||
porcelainLines: integer("porcelain_lines").notNull(),
|
||||
hasUpstream: integer("has_upstream").notNull(),
|
||||
aheadCount: integer("ahead_count").notNull(),
|
||||
behindCount: integer("behind_count").notNull(),
|
||||
/** Empty string when the snapshot succeeded; otherwise a short error summary. */
|
||||
gitError: text("git_error").notNull()
|
||||
});
|
||||
|
||||
// src/index.ts
|
||||
var GIT_TIMEOUT_MS = 15e3;
|
||||
function workspaceRoot() {
|
||||
const raw = process.env.GIT_WORKSPACE_ROOT;
|
||||
return raw ? resolve(raw) : resolve(process.cwd());
|
||||
}
|
||||
function gitErrorMessage(err) {
|
||||
if (err instanceof Error) {
|
||||
const m = err.message.trim();
|
||||
return m.length > 200 ? `${m.slice(0, 197)}...` : m;
|
||||
}
|
||||
return String(err);
|
||||
}
|
||||
function runGit(cwd, args) {
|
||||
return execFileSync("git", args, {
|
||||
cwd,
|
||||
encoding: "utf8",
|
||||
timeout: GIT_TIMEOUT_MS,
|
||||
maxBuffer: 2 * 1024 * 1024
|
||||
}).trimEnd();
|
||||
}
|
||||
function countPorcelainLines(output) {
|
||||
if (!output) return 0;
|
||||
return output.split("\n").filter((line) => line.length > 0).length;
|
||||
}
|
||||
async function compute() {
|
||||
const root = workspaceRoot();
|
||||
const ts = Date.now();
|
||||
let branch = "";
|
||||
let headShort = "";
|
||||
let porcelainLines = 0;
|
||||
let hasUpstream = 0;
|
||||
let aheadCount = 0;
|
||||
let behindCount = 0;
|
||||
let gitError = "";
|
||||
try {
|
||||
const inside = runGit(root, ["rev-parse", "--is-inside-work-tree"]).trim();
|
||||
if (inside !== "true") {
|
||||
gitError = "not a git work tree";
|
||||
return { signal: { ts, branch, headShort, porcelainLines, hasUpstream, aheadCount, behindCount, gitError }, workflow: null };
|
||||
}
|
||||
branch = runGit(root, ["rev-parse", "--abbrev-ref", "HEAD"]);
|
||||
headShort = runGit(root, ["rev-parse", "--short", "HEAD"]);
|
||||
porcelainLines = countPorcelainLines(runGit(root, ["status", "--porcelain"]));
|
||||
try {
|
||||
runGit(root, ["rev-parse", "--abbrev-ref", "@{upstream}"]);
|
||||
hasUpstream = 1;
|
||||
const lb = runGit(root, ["rev-list", "--left-right", "--count", "HEAD...@{upstream}"]);
|
||||
const parts = lb.split(/[\t\s]+/).filter(Boolean);
|
||||
if (parts.length >= 2) {
|
||||
aheadCount = Number.parseInt(parts[0], 10) || 0;
|
||||
behindCount = Number.parseInt(parts[1], 10) || 0;
|
||||
}
|
||||
} catch {
|
||||
hasUpstream = 0;
|
||||
aheadCount = 0;
|
||||
behindCount = 0;
|
||||
}
|
||||
} catch (e) {
|
||||
gitError = gitErrorMessage(e);
|
||||
}
|
||||
return { signal: { ts, branch, headShort, porcelainLines, hasUpstream, aheadCount, behindCount, gitError }, workflow: null };
|
||||
}
|
||||
export {
|
||||
compute,
|
||||
snapshots as table
|
||||
};
|
||||
@ -1,13 +0,0 @@
|
||||
-- Migration: 0001_init
|
||||
-- Creates the snapshots table for git-workspace-status sense.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS snapshots (
|
||||
ts INTEGER PRIMARY KEY,
|
||||
branch TEXT NOT NULL,
|
||||
head_short TEXT NOT NULL,
|
||||
porcelain_lines INTEGER NOT NULL,
|
||||
has_upstream INTEGER NOT NULL,
|
||||
ahead_count INTEGER NOT NULL,
|
||||
behind_count INTEGER NOT NULL,
|
||||
git_error TEXT NOT NULL
|
||||
);
|
||||
@ -1,14 +0,0 @@
|
||||
{
|
||||
"name": "sense-git-workspace-status",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "esbuild src/index.ts --bundle --platform=node --format=esm --outfile=index.js --packages=external"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.0",
|
||||
"esbuild": "^0.27.0",
|
||||
"typescript": "^5.7.0"
|
||||
}
|
||||
}
|
||||
@ -1,76 +0,0 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { resolve } from "node:path";
|
||||
export { snapshots as table } from "./schema.ts";
|
||||
|
||||
const GIT_TIMEOUT_MS = 15_000;
|
||||
|
||||
function workspaceRoot(): string {
|
||||
const raw = process.env.GIT_WORKSPACE_ROOT;
|
||||
return raw ? resolve(raw) : resolve(process.cwd());
|
||||
}
|
||||
|
||||
function gitErrorMessage(err: unknown): string {
|
||||
if (err instanceof Error) {
|
||||
const m = err.message.trim();
|
||||
return m.length > 200 ? `${m.slice(0, 197)}...` : m;
|
||||
}
|
||||
return String(err);
|
||||
}
|
||||
|
||||
function runGit(cwd: string, args: string[]): string {
|
||||
return execFileSync("git", args, {
|
||||
cwd,
|
||||
encoding: "utf8",
|
||||
timeout: GIT_TIMEOUT_MS,
|
||||
maxBuffer: 2 * 1024 * 1024,
|
||||
}).trimEnd();
|
||||
}
|
||||
|
||||
function countPorcelainLines(output: string): number {
|
||||
if (!output) return 0;
|
||||
return output.split("\n").filter((line) => line.length > 0).length;
|
||||
}
|
||||
|
||||
export async function compute() {
|
||||
const root = workspaceRoot();
|
||||
const ts = Date.now();
|
||||
|
||||
let branch = "";
|
||||
let headShort = "";
|
||||
let porcelainLines = 0;
|
||||
let hasUpstream = 0;
|
||||
let aheadCount = 0;
|
||||
let behindCount = 0;
|
||||
let gitError = "";
|
||||
|
||||
try {
|
||||
const inside = runGit(root, ["rev-parse", "--is-inside-work-tree"]).trim();
|
||||
if (inside !== "true") {
|
||||
gitError = "not a git work tree";
|
||||
return { signal: { ts, branch, headShort, porcelainLines, hasUpstream, aheadCount, behindCount, gitError }, workflow: null };
|
||||
}
|
||||
|
||||
branch = runGit(root, ["rev-parse", "--abbrev-ref", "HEAD"]);
|
||||
headShort = runGit(root, ["rev-parse", "--short", "HEAD"]);
|
||||
porcelainLines = countPorcelainLines(runGit(root, ["status", "--porcelain"]));
|
||||
|
||||
try {
|
||||
runGit(root, ["rev-parse", "--abbrev-ref", "@{upstream}"]);
|
||||
hasUpstream = 1;
|
||||
const lb = runGit(root, ["rev-list", "--left-right", "--count", "HEAD...@{upstream}"]);
|
||||
const parts = lb.split(/[\t\s]+/).filter(Boolean);
|
||||
if (parts.length >= 2) {
|
||||
aheadCount = Number.parseInt(parts[0], 10) || 0;
|
||||
behindCount = Number.parseInt(parts[1], 10) || 0;
|
||||
}
|
||||
} catch {
|
||||
hasUpstream = 0;
|
||||
aheadCount = 0;
|
||||
behindCount = 0;
|
||||
}
|
||||
} catch (e) {
|
||||
gitError = gitErrorMessage(e);
|
||||
}
|
||||
|
||||
return { signal: { ts, branch, headShort, porcelainLines, hasUpstream, aheadCount, behindCount, gitError }, workflow: null };
|
||||
}
|
||||
@ -1,13 +0,0 @@
|
||||
import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
|
||||
|
||||
export const snapshots = sqliteTable("snapshots", {
|
||||
ts: integer("ts").primaryKey(),
|
||||
branch: text("branch").notNull(),
|
||||
headShort: text("head_short").notNull(),
|
||||
porcelainLines: integer("porcelain_lines").notNull(),
|
||||
hasUpstream: integer("has_upstream").notNull(),
|
||||
aheadCount: integer("ahead_count").notNull(),
|
||||
behindCount: integer("behind_count").notNull(),
|
||||
/** Empty string when the snapshot succeeded; otherwise a short error summary. */
|
||||
gitError: text("git_error").notNull(),
|
||||
});
|
||||
@ -1,361 +0,0 @@
|
||||
// src/index.ts
|
||||
import { execFile } from "node:child_process";
|
||||
|
||||
// src/schema.ts
|
||||
import { integer, real, sqliteTable, text } from "drizzle-orm/sqlite-core";
|
||||
var hermesGatewayHealth = sqliteTable("hermes_gateway_health", {
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
ts: integer("ts").notNull(),
|
||||
alive: integer("alive").notNull(),
|
||||
mainPid: integer("main_pid").notNull(),
|
||||
rssBytes: integer("rss_bytes").notNull(),
|
||||
cpuPercent: real("cpu_percent").notNull(),
|
||||
uptimeSec: integer("uptime_sec").notNull(),
|
||||
activeSessions: integer("active_sessions").notNull(),
|
||||
childProcessCount: integer("child_process_count").notNull(),
|
||||
httpOk: integer("http_ok").notNull(),
|
||||
httpStatusCode: integer("http_status_code").notNull(),
|
||||
httpLatencyMs: integer("http_latency_ms").notNull(),
|
||||
httpError: text("http_error").notNull()
|
||||
});
|
||||
|
||||
// src/index.ts
|
||||
var EXEC_TIMEOUT_MS = 25e3;
|
||||
var HTTP_TIMEOUT_MS = Math.min(23e3, EXEC_TIMEOUT_MS - 2e3);
|
||||
var HTTP_ERROR_MAX_LEN = 256;
|
||||
function gatewayProbeUrl() {
|
||||
const u = process.env.HERMES_GATEWAY_HEALTH_URL ?? process.env.NERVE_HERMES_GATEWAY_URL ?? "";
|
||||
return String(u).trim();
|
||||
}
|
||||
function truncateHttpError(err) {
|
||||
const raw = err && typeof err === "object" && "code" in err && err.code ? String(err.code) : String(err?.message ?? err ?? "error");
|
||||
const s = raw.trim() || "error";
|
||||
return s.length > HTTP_ERROR_MAX_LEN ? s.slice(0, HTTP_ERROR_MAX_LEN) : s;
|
||||
}
|
||||
async function probeGatewayHttp(url) {
|
||||
if (!url) {
|
||||
return {
|
||||
httpOk: 0,
|
||||
httpStatusCode: 0,
|
||||
httpLatencyMs: 0,
|
||||
httpError: "missing_url"
|
||||
};
|
||||
}
|
||||
const t0 = Date.now();
|
||||
try {
|
||||
const signal = AbortSignal.timeout(HTTP_TIMEOUT_MS);
|
||||
const res = await fetch(url, {
|
||||
method: "GET",
|
||||
signal,
|
||||
redirect: "follow"
|
||||
});
|
||||
const httpLatencyMs = Date.now() - t0;
|
||||
const code = res.status;
|
||||
const ok = code >= 200 && code < 400;
|
||||
return {
|
||||
httpOk: ok ? 1 : 0,
|
||||
httpStatusCode: code,
|
||||
httpLatencyMs,
|
||||
httpError: ok ? "" : truncateHttpError({ message: `HTTP ${code}` })
|
||||
};
|
||||
} catch (err) {
|
||||
const httpLatencyMs = Date.now() - t0;
|
||||
return {
|
||||
httpOk: 0,
|
||||
httpStatusCode: 0,
|
||||
httpLatencyMs,
|
||||
httpError: truncateHttpError(err)
|
||||
};
|
||||
}
|
||||
}
|
||||
function etimeToSeconds(etime) {
|
||||
let s = String(etime).trim();
|
||||
if (!s) return 0;
|
||||
let days = 0;
|
||||
if (s.includes("-")) {
|
||||
const idx = s.indexOf("-");
|
||||
const d = Number.parseInt(s.slice(0, idx), 10);
|
||||
days = Number.isFinite(d) ? d : 0;
|
||||
s = s.slice(idx + 1);
|
||||
}
|
||||
const parts = s.split(":").map((x) => Number.parseInt(String(x).trim(), 10));
|
||||
if (parts.some((n) => !Number.isFinite(n))) return 0;
|
||||
if (parts.length === 3) {
|
||||
return Math.trunc(days * 86400 + parts[0] * 3600 + parts[1] * 60 + parts[2]);
|
||||
}
|
||||
if (parts.length === 2) {
|
||||
return Math.trunc(days * 86400 + parts[0] * 60 + parts[1]);
|
||||
}
|
||||
if (parts.length === 1) {
|
||||
return Math.trunc(days * 86400 + parts[0]);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
function execFileUtf8(file, args, opts = {}) {
|
||||
return new Promise((resolve) => {
|
||||
execFile(
|
||||
file,
|
||||
args,
|
||||
{
|
||||
encoding: "utf8",
|
||||
maxBuffer: 8 * 1024 * 1024,
|
||||
timeout: EXEC_TIMEOUT_MS,
|
||||
...opts
|
||||
},
|
||||
(err, stdout, stderr) => {
|
||||
const exitCode = err && typeof err.status === "number" ? err.status : err ? -1 : 0;
|
||||
resolve({
|
||||
exitCode,
|
||||
errCode: err?.code,
|
||||
stdout: String(stdout ?? ""),
|
||||
stderr: String(stderr ?? "")
|
||||
});
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
function parseMainPidFromStatus(text2) {
|
||||
const m = text2.match(/Main PID:\s*(\d+)/i);
|
||||
return m ? Math.trunc(Number.parseInt(m[1], 10)) || 0 : 0;
|
||||
}
|
||||
function parseActiveLineFromStatus(text2) {
|
||||
for (const line of text2.split("\n")) {
|
||||
if (/^\s*Active:/i.test(line)) {
|
||||
const m = line.match(/Active:\s*(\S+)\s*\(([^)]*)\)/i);
|
||||
if (m) {
|
||||
return {
|
||||
active: m[1].toLowerCase() === "active",
|
||||
subRunning: m[2].toLowerCase().includes("running")
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
return { active: false, subRunning: false };
|
||||
}
|
||||
function parseSystemctlShow(text2) {
|
||||
let mainPid = 0;
|
||||
let active = false;
|
||||
let subRunning = false;
|
||||
for (const line of text2.split("\n")) {
|
||||
const t = line.trim();
|
||||
if (t.startsWith("MainPID=")) {
|
||||
mainPid = Math.trunc(Number.parseInt(t.slice("MainPID=".length), 10)) || 0;
|
||||
} else if (t.startsWith("ActiveState=")) {
|
||||
active = t.slice("ActiveState=".length).trim().toLowerCase() === "active";
|
||||
} else if (t.startsWith("SubState=")) {
|
||||
subRunning = t.slice("SubState=".length).trim().toLowerCase() === "running";
|
||||
}
|
||||
}
|
||||
return { mainPid, active, subRunning };
|
||||
}
|
||||
async function readSystemdState() {
|
||||
const status = await execFileUtf8("systemctl", [
|
||||
"--user",
|
||||
"--no-pager",
|
||||
"status",
|
||||
"hermes-gateway"
|
||||
]);
|
||||
const combined = `${status.stdout}
|
||||
${status.stderr}`.trim();
|
||||
let mainPid = parseMainPidFromStatus(combined);
|
||||
let { active, subRunning } = parseActiveLineFromStatus(combined);
|
||||
const needShow = mainPid <= 0 || !active || !subRunning;
|
||||
if (needShow) {
|
||||
const show = await execFileUtf8("systemctl", [
|
||||
"--user",
|
||||
"--no-pager",
|
||||
"show",
|
||||
"hermes-gateway",
|
||||
"-p",
|
||||
"MainPID",
|
||||
"-p",
|
||||
"ActiveState",
|
||||
"-p",
|
||||
"SubState"
|
||||
]);
|
||||
const showText = `${show.stdout}
|
||||
${show.stderr}`;
|
||||
const s = parseSystemctlShow(showText);
|
||||
if (mainPid <= 0 && s.mainPid > 0) mainPid = s.mainPid;
|
||||
if (!active) active = s.active;
|
||||
if (!subRunning) subRunning = s.subRunning;
|
||||
}
|
||||
return { mainPid, systemdActiveRunning: active && subRunning };
|
||||
}
|
||||
async function processExists(mainPid) {
|
||||
if (mainPid <= 0) return false;
|
||||
const r = await execFileUtf8("ps", ["-p", String(mainPid), "-o", "pid="]);
|
||||
if (r.errCode === "ENOENT") return false;
|
||||
return r.stdout.trim().length > 0;
|
||||
}
|
||||
async function readPsMetrics(mainPid) {
|
||||
if (mainPid <= 0) {
|
||||
return { rssBytes: 0, cpuPercent: 0, uptimeSec: 0 };
|
||||
}
|
||||
let r = await execFileUtf8("ps", [
|
||||
"-p",
|
||||
String(mainPid),
|
||||
"-o",
|
||||
"rss=,%cpu=,etimes="
|
||||
]);
|
||||
let line = r.stdout.trim().replace(/\s+/g, " ");
|
||||
if (r.errCode === "ENOENT" || !line) {
|
||||
return { rssBytes: 0, cpuPercent: 0, uptimeSec: 0 };
|
||||
}
|
||||
let parts = line.split(" ").filter(Boolean);
|
||||
if (parts.length < 3) {
|
||||
r = await execFileUtf8("ps", [
|
||||
"-p",
|
||||
String(mainPid),
|
||||
"-o",
|
||||
"rss=,%cpu=,etime="
|
||||
]);
|
||||
line = r.stdout.trim().replace(/\s+/g, " ");
|
||||
parts = line.split(" ").filter(Boolean);
|
||||
if (parts.length < 3) {
|
||||
return { rssBytes: 0, cpuPercent: 0, uptimeSec: 0 };
|
||||
}
|
||||
const rssKiB2 = Number(parts[0]);
|
||||
const cpu2 = Number(parts[1]);
|
||||
const uptimeSec2 = etimeToSeconds(parts.slice(2).join(" "));
|
||||
const rssBytes2 = Number.isFinite(rssKiB2) ? Math.trunc(rssKiB2 * 1024) : 0;
|
||||
const cpuPercent2 = Number.isFinite(cpu2) ? Math.round(cpu2 * 100) / 100 : 0;
|
||||
return { rssBytes: rssBytes2, cpuPercent: cpuPercent2, uptimeSec: uptimeSec2 };
|
||||
}
|
||||
const rssKiB = Number(parts[0]);
|
||||
const cpu = Number(parts[1]);
|
||||
const etimes = Number(parts[2]);
|
||||
const rssBytes = Number.isFinite(rssKiB) ? Math.trunc(rssKiB * 1024) : 0;
|
||||
const cpuPercent = Number.isFinite(cpu) ? Math.round(cpu * 100) / 100 : 0;
|
||||
const uptimeSec = Number.isFinite(etimes) ? Math.trunc(etimes) : 0;
|
||||
return { rssBytes, cpuPercent, uptimeSec };
|
||||
}
|
||||
function parseActiveSessionsFromHermesStats(text2) {
|
||||
const src = String(text2);
|
||||
const patterns = [
|
||||
/^\s*Active\s+sessions?:\s*(\d+)/gim,
|
||||
/^\s*active\s+sessions?:\s*(\d+)/gim,
|
||||
/^\s*Total\s+sessions?:\s*(\d+)/gim
|
||||
];
|
||||
for (const re of patterns) {
|
||||
re.lastIndex = 0;
|
||||
const m = re.exec(src);
|
||||
if (m) {
|
||||
const n = Math.trunc(Number.parseInt(m[1], 10));
|
||||
return Number.isFinite(n) ? n : 0;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
async function readActiveSessions() {
|
||||
try {
|
||||
const r = await execFileUtf8("hermes", ["sessions", "stats"]);
|
||||
if (r.errCode === "ENOENT") return 0;
|
||||
return parseActiveSessionsFromHermesStats(`${r.stdout}
|
||||
${r.stderr}`);
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
async function countDirectChildren(mainPid) {
|
||||
if (mainPid <= 0) return 0;
|
||||
try {
|
||||
const r = await execFileUtf8("ps", [
|
||||
"--no-headers",
|
||||
"-o",
|
||||
"pid",
|
||||
"--ppid",
|
||||
String(mainPid)
|
||||
]);
|
||||
if (r.errCode === "ENOENT") return 0;
|
||||
const lines = r.stdout.split("\n").map((l) => l.trim()).filter(Boolean);
|
||||
return lines.length;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
async function compute() {
|
||||
const ts = Date.now();
|
||||
let mainPid = 0;
|
||||
let systemdActiveRunning = false;
|
||||
try {
|
||||
const st = await readSystemdState();
|
||||
mainPid = st.mainPid;
|
||||
systemdActiveRunning = st.systemdActiveRunning;
|
||||
} catch {
|
||||
mainPid = 0;
|
||||
systemdActiveRunning = false;
|
||||
}
|
||||
let psOk = false;
|
||||
try {
|
||||
psOk = await processExists(mainPid);
|
||||
} catch {
|
||||
psOk = false;
|
||||
}
|
||||
let rssBytes = 0;
|
||||
let cpuPercent = 0;
|
||||
let uptimeSec = 0;
|
||||
if (psOk) {
|
||||
try {
|
||||
const m = await readPsMetrics(mainPid);
|
||||
rssBytes = m.rssBytes;
|
||||
cpuPercent = m.cpuPercent;
|
||||
uptimeSec = m.uptimeSec;
|
||||
} catch {
|
||||
rssBytes = 0;
|
||||
cpuPercent = 0;
|
||||
uptimeSec = 0;
|
||||
}
|
||||
}
|
||||
const alive = systemdActiveRunning && mainPid > 0 && psOk ? 1 : 0;
|
||||
let activeSessions = 0;
|
||||
try {
|
||||
activeSessions = await readActiveSessions();
|
||||
} catch {
|
||||
activeSessions = 0;
|
||||
}
|
||||
let childProcessCount = 0;
|
||||
if (alive && mainPid > 0) {
|
||||
try {
|
||||
childProcessCount = await countDirectChildren(mainPid);
|
||||
} catch {
|
||||
childProcessCount = 0;
|
||||
}
|
||||
}
|
||||
let httpOk = 0;
|
||||
let httpStatusCode = 0;
|
||||
let httpLatencyMs = 0;
|
||||
let httpError = "";
|
||||
try {
|
||||
const h = await probeGatewayHttp(gatewayProbeUrl());
|
||||
httpOk = h.httpOk;
|
||||
httpStatusCode = h.httpStatusCode;
|
||||
httpLatencyMs = h.httpLatencyMs;
|
||||
httpError = h.httpError;
|
||||
} catch {
|
||||
httpOk = 0;
|
||||
httpStatusCode = 0;
|
||||
httpLatencyMs = 0;
|
||||
httpError = "probe_failed";
|
||||
}
|
||||
const storedMainPid = mainPid > 0 ? mainPid : 0;
|
||||
const row = {
|
||||
ts,
|
||||
alive,
|
||||
mainPid: storedMainPid,
|
||||
rssBytes: alive ? rssBytes : 0,
|
||||
cpuPercent: alive ? cpuPercent : 0,
|
||||
uptimeSec: alive ? uptimeSec : 0,
|
||||
activeSessions,
|
||||
childProcessCount: alive ? childProcessCount : 0,
|
||||
httpOk,
|
||||
httpStatusCode,
|
||||
httpLatencyMs,
|
||||
httpError
|
||||
};
|
||||
return { signal: row, workflow: null };
|
||||
}
|
||||
export {
|
||||
compute,
|
||||
hermesGatewayHealth as table
|
||||
};
|
||||
@ -1,14 +0,0 @@
|
||||
-- Migration: 0001_init
|
||||
-- Creates the hermes_gateway_health table for hermes-gateway-health sense.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS hermes_gateway_health (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
ts INTEGER NOT NULL,
|
||||
alive INTEGER NOT NULL,
|
||||
main_pid INTEGER NOT NULL,
|
||||
rss_bytes INTEGER NOT NULL,
|
||||
cpu_percent REAL NOT NULL,
|
||||
uptime_sec INTEGER NOT NULL,
|
||||
active_sessions INTEGER NOT NULL,
|
||||
child_process_count INTEGER NOT NULL
|
||||
);
|
||||
@ -1,7 +0,0 @@
|
||||
-- Migration: 0002_add_http_probe
|
||||
-- HTTP reachability columns for hermes-gateway-health sense.
|
||||
|
||||
ALTER TABLE hermes_gateway_health ADD COLUMN http_ok INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE hermes_gateway_health ADD COLUMN http_status_code INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE hermes_gateway_health ADD COLUMN http_latency_ms INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE hermes_gateway_health ADD COLUMN http_error TEXT NOT NULL DEFAULT '';
|
||||
@ -1,14 +0,0 @@
|
||||
{
|
||||
"name": "sense-hermes-gateway-health",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "esbuild src/index.ts --bundle --platform=node --format=esm --outfile=index.js --packages=external"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.0",
|
||||
"esbuild": "^0.27.0",
|
||||
"typescript": "^5.7.0"
|
||||
}
|
||||
}
|
||||
@ -1,6 +1,4 @@
|
||||
import { execFile } from "node:child_process";
|
||||
export { hermesGatewayHealth as table } from "./schema.ts";
|
||||
|
||||
/** Keep subprocess deadlines slightly under typical sense timeout (30s). */
|
||||
const EXEC_TIMEOUT_MS = 25_000;
|
||||
|
||||
@ -9,6 +7,22 @@ const HTTP_TIMEOUT_MS = Math.min(23_000, EXEC_TIMEOUT_MS - 2000);
|
||||
|
||||
const HTTP_ERROR_MAX_LEN = 256;
|
||||
|
||||
/** How many consecutive failures before triggering a restart. */
|
||||
const FAILURE_THRESHOLD = 3;
|
||||
|
||||
type SenseState = {
|
||||
consecutiveFailures: number;
|
||||
lastRestartTs: number;
|
||||
/** Minimum ms between restart attempts to avoid restart loops. */
|
||||
restartCooldownMs: number;
|
||||
};
|
||||
|
||||
export const initialState: SenseState = {
|
||||
consecutiveFailures: 0,
|
||||
lastRestartTs: 0,
|
||||
restartCooldownMs: 300_000, // 5 minutes
|
||||
};
|
||||
|
||||
function gatewayProbeUrl(): string {
|
||||
const u =
|
||||
process.env.HERMES_GATEWAY_HEALTH_URL ??
|
||||
@ -26,17 +40,13 @@ function truncateHttpError(err: unknown): string {
|
||||
return s.length > HTTP_ERROR_MAX_LEN ? s.slice(0, HTTP_ERROR_MAX_LEN) : s;
|
||||
}
|
||||
|
||||
interface HttpProbeResult {
|
||||
type HttpProbeResult = {
|
||||
httpOk: number;
|
||||
httpStatusCode: number;
|
||||
httpLatencyMs: number;
|
||||
httpError: string;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* GET the gateway URL; success = HTTP 200–399.
|
||||
* URL must be set via HERMES_GATEWAY_HEALTH_URL or NERVE_HERMES_GATEWAY_URL.
|
||||
*/
|
||||
async function probeGatewayHttp(url: string): Promise<HttpProbeResult> {
|
||||
if (!url) {
|
||||
return {
|
||||
@ -74,10 +84,6 @@ async function probeGatewayHttp(url: string): Promise<HttpProbeResult> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* When `ps` lacks `etimes` (wall-clock seconds since start), parse `etime`
|
||||
* ([[dd-]hh:]mm:ss) into seconds. See ps(1) `etime` field description.
|
||||
*/
|
||||
function etimeToSeconds(etime: string): number {
|
||||
let s = String(etime).trim();
|
||||
if (!s) return 0;
|
||||
@ -102,12 +108,12 @@ function etimeToSeconds(etime: string): number {
|
||||
return 0;
|
||||
}
|
||||
|
||||
interface ExecResult {
|
||||
type ExecResult = {
|
||||
exitCode: number;
|
||||
errCode: string | undefined;
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
}
|
||||
};
|
||||
|
||||
function execFileUtf8(file: string, args: string[], opts: Record<string, unknown> = {}): Promise<ExecResult> {
|
||||
return new Promise((resolve) => {
|
||||
@ -216,11 +222,11 @@ async function processExists(mainPid: number): Promise<boolean> {
|
||||
return r.stdout.trim().length > 0;
|
||||
}
|
||||
|
||||
interface PsMetrics {
|
||||
type PsMetrics = {
|
||||
rssBytes: number;
|
||||
cpuPercent: number;
|
||||
uptimeSec: number;
|
||||
}
|
||||
};
|
||||
|
||||
async function readPsMetrics(mainPid: number): Promise<PsMetrics> {
|
||||
if (mainPid <= 0) {
|
||||
@ -265,61 +271,12 @@ async function readPsMetrics(mainPid: number): Promise<PsMetrics> {
|
||||
return { rssBytes, cpuPercent, uptimeSec };
|
||||
}
|
||||
|
||||
function parseActiveSessionsFromHermesStats(text: string): number {
|
||||
const src = String(text);
|
||||
const patterns = [
|
||||
/^\s*Active\s+sessions?:\s*(\d+)/gim,
|
||||
/^\s*active\s+sessions?:\s*(\d+)/gim,
|
||||
/^\s*Total\s+sessions?:\s*(\d+)/gim,
|
||||
];
|
||||
for (const re of patterns) {
|
||||
re.lastIndex = 0;
|
||||
const m = re.exec(src);
|
||||
if (m) {
|
||||
const n = Math.trunc(Number.parseInt(m[1], 10));
|
||||
return Number.isFinite(n) ? n : 0;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
async function readActiveSessions(): Promise<number> {
|
||||
try {
|
||||
const r = await execFileUtf8("hermes", ["sessions", "stats"]);
|
||||
if (r.errCode === "ENOENT") return 0;
|
||||
return parseActiveSessionsFromHermesStats(`${r.stdout}\n${r.stderr}`);
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
async function countDirectChildren(mainPid: number): Promise<number> {
|
||||
if (mainPid <= 0) return 0;
|
||||
try {
|
||||
const r = await execFileUtf8("ps", [
|
||||
"--no-headers",
|
||||
"-o",
|
||||
"pid",
|
||||
"--ppid",
|
||||
String(mainPid),
|
||||
]);
|
||||
if (r.errCode === "ENOENT") return 0;
|
||||
const lines = r.stdout
|
||||
.split("\n")
|
||||
.map((l) => l.trim())
|
||||
.filter(Boolean);
|
||||
return lines.length;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
export async function compute() {
|
||||
const ts = Date.now();
|
||||
export async function compute(prevState: SenseState) {
|
||||
const now = Date.now();
|
||||
|
||||
// --- probe gateway ---
|
||||
let mainPid = 0;
|
||||
let systemdActiveRunning = false;
|
||||
|
||||
try {
|
||||
const st = await readSystemdState();
|
||||
mainPid = st.mainPid;
|
||||
@ -354,22 +311,6 @@ export async function compute() {
|
||||
|
||||
const alive = systemdActiveRunning && mainPid > 0 && psOk ? 1 : 0;
|
||||
|
||||
let activeSessions = 0;
|
||||
try {
|
||||
activeSessions = await readActiveSessions();
|
||||
} catch {
|
||||
activeSessions = 0;
|
||||
}
|
||||
|
||||
let childProcessCount = 0;
|
||||
if (alive && mainPid > 0) {
|
||||
try {
|
||||
childProcessCount = await countDirectChildren(mainPid);
|
||||
} catch {
|
||||
childProcessCount = 0;
|
||||
}
|
||||
}
|
||||
|
||||
let httpOk = 0;
|
||||
let httpStatusCode = 0;
|
||||
let httpLatencyMs = 0;
|
||||
@ -387,22 +328,42 @@ export async function compute() {
|
||||
httpError = "probe_failed";
|
||||
}
|
||||
|
||||
const storedMainPid = mainPid > 0 ? mainPid : 0;
|
||||
// --- decide health ---
|
||||
const healthy = alive === 1 && httpOk === 1;
|
||||
|
||||
const row = {
|
||||
ts,
|
||||
// --- state machine: track consecutive failures ---
|
||||
const consecutiveFailures = healthy ? 0 : prevState.consecutiveFailures + 1;
|
||||
const lastRestartTs = prevState.lastRestartTs;
|
||||
const cooldown = prevState.restartCooldownMs;
|
||||
const cooldownElapsed = now - lastRestartTs >= cooldown;
|
||||
|
||||
// --- trigger restart? ---
|
||||
const shouldRestart =
|
||||
consecutiveFailures >= FAILURE_THRESHOLD && cooldownElapsed;
|
||||
|
||||
const nextState: SenseState = {
|
||||
consecutiveFailures,
|
||||
lastRestartTs: shouldRestart ? now : lastRestartTs,
|
||||
restartCooldownMs: cooldown,
|
||||
};
|
||||
|
||||
const signal = {
|
||||
ts: now,
|
||||
alive,
|
||||
mainPid: storedMainPid,
|
||||
mainPid: mainPid > 0 ? mainPid : 0,
|
||||
rssBytes: alive ? rssBytes : 0,
|
||||
cpuPercent: alive ? cpuPercent : 0,
|
||||
uptimeSec: alive ? uptimeSec : 0,
|
||||
activeSessions,
|
||||
childProcessCount: alive ? childProcessCount : 0,
|
||||
httpOk,
|
||||
httpStatusCode,
|
||||
httpLatencyMs,
|
||||
httpError,
|
||||
consecutiveFailures,
|
||||
};
|
||||
|
||||
return { signal: row, workflow: null };
|
||||
const trigger = shouldRestart
|
||||
? { command: "systemctl --user restart hermes-gateway" }
|
||||
: null;
|
||||
|
||||
return { state: nextState, signal, trigger };
|
||||
}
|
||||
|
||||
@ -1,17 +0,0 @@
|
||||
import { integer, real, sqliteTable, text } from "drizzle-orm/sqlite-core";
|
||||
|
||||
export const hermesGatewayHealth = sqliteTable("hermes_gateway_health", {
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
ts: integer("ts").notNull(),
|
||||
alive: integer("alive").notNull(),
|
||||
mainPid: integer("main_pid").notNull(),
|
||||
rssBytes: integer("rss_bytes").notNull(),
|
||||
cpuPercent: real("cpu_percent").notNull(),
|
||||
uptimeSec: integer("uptime_sec").notNull(),
|
||||
activeSessions: integer("active_sessions").notNull(),
|
||||
childProcessCount: integer("child_process_count").notNull(),
|
||||
httpOk: integer("http_ok").notNull(),
|
||||
httpStatusCode: integer("http_status_code").notNull(),
|
||||
httpLatencyMs: integer("http_latency_ms").notNull(),
|
||||
httpError: text("http_error").notNull(),
|
||||
});
|
||||
@ -1,110 +0,0 @@
|
||||
// src/index.ts
|
||||
import { createReadStream } from "node:fs";
|
||||
import { readdir } from "node:fs/promises";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { createInterface } from "node:readline";
|
||||
|
||||
// src/schema.ts
|
||||
import { integer, sqliteTable } from "drizzle-orm/sqlite-core";
|
||||
var hermesSessionMessageStats = sqliteTable("hermes_session_message_stats", {
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
ts: integer("ts").notNull(),
|
||||
totalUserMessages: integer("total_user_messages").notNull(),
|
||||
totalAssistantMessages: integer("total_assistant_messages").notNull(),
|
||||
totalToolMessages: integer("total_tool_messages").notNull(),
|
||||
totalMessages: integer("total_messages").notNull(),
|
||||
activeSessions: integer("active_sessions").notNull(),
|
||||
measurementWindowSeconds: integer("measurement_window_seconds").notNull()
|
||||
});
|
||||
|
||||
// src/index.ts
|
||||
var MEASUREMENT_WINDOW_MS = 9e5;
|
||||
var MEASUREMENT_WINDOW_SECONDS = 900;
|
||||
async function aggregateJsonlFile(filePath, cutoffMs, nowMs) {
|
||||
let user = 0;
|
||||
let assistant = 0;
|
||||
let tool = 0;
|
||||
let fileHadActivity = false;
|
||||
const input = createReadStream(filePath, { encoding: "utf8" });
|
||||
const rl = createInterface({ input, crlfDelay: Infinity });
|
||||
try {
|
||||
for await (const line of rl) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed) continue;
|
||||
let obj;
|
||||
try {
|
||||
obj = JSON.parse(trimmed);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
if (typeof obj !== "object" || obj === null || typeof obj.role !== "string" || typeof obj.timestamp !== "string") {
|
||||
continue;
|
||||
}
|
||||
const record = obj;
|
||||
const t = Date.parse(record.timestamp);
|
||||
if (!Number.isFinite(t) || t < cutoffMs || t > nowMs) continue;
|
||||
const roleNorm = record.role.trim().toLowerCase();
|
||||
if (roleNorm === "user") {
|
||||
user++;
|
||||
fileHadActivity = true;
|
||||
} else if (roleNorm === "assistant") {
|
||||
assistant++;
|
||||
fileHadActivity = true;
|
||||
} else if (roleNorm === "tool") {
|
||||
tool++;
|
||||
fileHadActivity = true;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
rl.close();
|
||||
}
|
||||
return { user, assistant, tool, fileHadActivity };
|
||||
}
|
||||
async function compute() {
|
||||
const nowMs = Date.now();
|
||||
const cutoffMs = nowMs - MEASUREMENT_WINDOW_MS;
|
||||
const ts = nowMs;
|
||||
let totalUserMessages = 0;
|
||||
let totalAssistantMessages = 0;
|
||||
let totalToolMessages = 0;
|
||||
let activeSessions = 0;
|
||||
const sessionsDir = join(homedir(), ".hermes", "sessions");
|
||||
let files = [];
|
||||
try {
|
||||
const entries = await readdir(sessionsDir, { withFileTypes: true });
|
||||
files = entries.filter((e) => e.isFile() && e.name.endsWith(".jsonl")).map((e) => join(sessionsDir, e.name));
|
||||
} catch (err) {
|
||||
if (err && typeof err === "object" && "code" in err && err.code === "ENOENT") {
|
||||
files = [];
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
for (const filePath of files) {
|
||||
const { user, assistant, tool, fileHadActivity } = await aggregateJsonlFile(
|
||||
filePath,
|
||||
cutoffMs,
|
||||
nowMs
|
||||
);
|
||||
totalUserMessages += user;
|
||||
totalAssistantMessages += assistant;
|
||||
totalToolMessages += tool;
|
||||
if (fileHadActivity) activeSessions++;
|
||||
}
|
||||
const totalMessages = totalUserMessages + totalAssistantMessages + totalToolMessages;
|
||||
const row = {
|
||||
ts,
|
||||
totalUserMessages,
|
||||
totalAssistantMessages,
|
||||
totalToolMessages,
|
||||
totalMessages,
|
||||
activeSessions,
|
||||
measurementWindowSeconds: MEASUREMENT_WINDOW_SECONDS
|
||||
};
|
||||
return { signal: row, workflow: null };
|
||||
}
|
||||
export {
|
||||
compute,
|
||||
hermesSessionMessageStats as table
|
||||
};
|
||||
@ -1,13 +0,0 @@
|
||||
-- Migration: 0001_init
|
||||
-- Creates the hermes_session_message_stats table for hermes-session-message-stats sense.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS hermes_session_message_stats (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
ts INTEGER NOT NULL,
|
||||
total_user_messages INTEGER NOT NULL,
|
||||
total_assistant_messages INTEGER NOT NULL,
|
||||
total_tool_messages INTEGER NOT NULL,
|
||||
total_messages INTEGER NOT NULL,
|
||||
active_sessions INTEGER NOT NULL,
|
||||
measurement_window_seconds INTEGER NOT NULL
|
||||
);
|
||||
@ -1,14 +0,0 @@
|
||||
{
|
||||
"name": "sense-hermes-session-message-stats",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "esbuild src/index.ts --bundle --platform=node --format=esm --outfile=index.js --packages=external"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.0",
|
||||
"esbuild": "^0.27.0",
|
||||
"typescript": "^5.7.0"
|
||||
}
|
||||
}
|
||||
@ -1,117 +0,0 @@
|
||||
import { createReadStream } from "node:fs";
|
||||
import { readdir } from "node:fs/promises";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { createInterface } from "node:readline";
|
||||
export { hermesSessionMessageStats as table } from "./schema.ts";
|
||||
|
||||
const MEASUREMENT_WINDOW_MS = 900_000;
|
||||
const MEASUREMENT_WINDOW_SECONDS = 900;
|
||||
|
||||
interface MessageCounts {
|
||||
user: number;
|
||||
assistant: number;
|
||||
tool: number;
|
||||
fileHadActivity: boolean;
|
||||
}
|
||||
|
||||
async function aggregateJsonlFile(filePath: string, cutoffMs: number, nowMs: number): Promise<MessageCounts> {
|
||||
let user = 0;
|
||||
let assistant = 0;
|
||||
let tool = 0;
|
||||
let fileHadActivity = false;
|
||||
|
||||
const input = createReadStream(filePath, { encoding: "utf8" });
|
||||
const rl = createInterface({ input, crlfDelay: Infinity });
|
||||
try {
|
||||
for await (const line of rl) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed) continue;
|
||||
let obj: unknown;
|
||||
try {
|
||||
obj = JSON.parse(trimmed);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
typeof obj !== "object" || obj === null ||
|
||||
typeof (obj as Record<string, unknown>).role !== "string" ||
|
||||
typeof (obj as Record<string, unknown>).timestamp !== "string"
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const record = obj as { role: string; timestamp: string };
|
||||
const t = Date.parse(record.timestamp);
|
||||
if (!Number.isFinite(t) || t < cutoffMs || t > nowMs) continue;
|
||||
|
||||
const roleNorm = record.role.trim().toLowerCase();
|
||||
if (roleNorm === "user") {
|
||||
user++;
|
||||
fileHadActivity = true;
|
||||
} else if (roleNorm === "assistant") {
|
||||
assistant++;
|
||||
fileHadActivity = true;
|
||||
} else if (roleNorm === "tool") {
|
||||
tool++;
|
||||
fileHadActivity = true;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
rl.close();
|
||||
}
|
||||
|
||||
return { user, assistant, tool, fileHadActivity };
|
||||
}
|
||||
|
||||
export async function compute() {
|
||||
const nowMs = Date.now();
|
||||
const cutoffMs = nowMs - MEASUREMENT_WINDOW_MS;
|
||||
const ts = nowMs;
|
||||
|
||||
let totalUserMessages = 0;
|
||||
let totalAssistantMessages = 0;
|
||||
let totalToolMessages = 0;
|
||||
let activeSessions = 0;
|
||||
|
||||
const sessionsDir = join(homedir(), ".hermes", "sessions");
|
||||
let files: string[] = [];
|
||||
try {
|
||||
const entries = await readdir(sessionsDir, { withFileTypes: true });
|
||||
files = entries
|
||||
.filter((e) => e.isFile() && e.name.endsWith(".jsonl"))
|
||||
.map((e) => join(sessionsDir, e.name));
|
||||
} catch (err) {
|
||||
if (err && typeof err === "object" && "code" in err && (err as NodeJS.ErrnoException).code === "ENOENT") {
|
||||
files = [];
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
for (const filePath of files) {
|
||||
const { user, assistant, tool, fileHadActivity } = await aggregateJsonlFile(
|
||||
filePath,
|
||||
cutoffMs,
|
||||
nowMs,
|
||||
);
|
||||
totalUserMessages += user;
|
||||
totalAssistantMessages += assistant;
|
||||
totalToolMessages += tool;
|
||||
if (fileHadActivity) activeSessions++;
|
||||
}
|
||||
|
||||
const totalMessages =
|
||||
totalUserMessages + totalAssistantMessages + totalToolMessages;
|
||||
|
||||
const row = {
|
||||
ts,
|
||||
totalUserMessages,
|
||||
totalAssistantMessages,
|
||||
totalToolMessages,
|
||||
totalMessages,
|
||||
activeSessions,
|
||||
measurementWindowSeconds: MEASUREMENT_WINDOW_SECONDS,
|
||||
};
|
||||
|
||||
return { signal: row, workflow: null };
|
||||
}
|
||||
@ -1,12 +0,0 @@
|
||||
import { integer, sqliteTable } from "drizzle-orm/sqlite-core";
|
||||
|
||||
export const hermesSessionMessageStats = sqliteTable("hermes_session_message_stats", {
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
ts: integer("ts").notNull(),
|
||||
totalUserMessages: integer("total_user_messages").notNull(),
|
||||
totalAssistantMessages: integer("total_assistant_messages").notNull(),
|
||||
totalToolMessages: integer("total_tool_messages").notNull(),
|
||||
totalMessages: integer("total_messages").notNull(),
|
||||
activeSessions: integer("active_sessions").notNull(),
|
||||
measurementWindowSeconds: integer("measurement_window_seconds").notNull(),
|
||||
});
|
||||
@ -1,107 +0,0 @@
|
||||
// src/index.ts
|
||||
import { loadavg, totalmem, freemem, uptime } from "node:os";
|
||||
import { execSync } from "node:child_process";
|
||||
import { readFile } from "node:fs/promises";
|
||||
|
||||
// src/schema.ts
|
||||
import { integer, real, sqliteTable } from "drizzle-orm/sqlite-core";
|
||||
var snapshots = sqliteTable("snapshots", {
|
||||
ts: integer("ts").primaryKey(),
|
||||
cpuLoad1m: real("cpu_load_1m").notNull(),
|
||||
cpuLoad5m: real("cpu_load_5m").notNull(),
|
||||
cpuLoad15m: real("cpu_load_15m").notNull(),
|
||||
memTotalMB: integer("mem_total_mb").notNull(),
|
||||
memUsedMB: integer("mem_used_mb").notNull(),
|
||||
memUsedPct: real("mem_used_pct").notNull(),
|
||||
diskTotalGB: real("disk_total_gb").notNull(),
|
||||
diskUsedGB: real("disk_used_gb").notNull(),
|
||||
diskUsedPct: real("disk_used_pct").notNull(),
|
||||
uptimeSec: integer("uptime_sec").notNull(),
|
||||
// TCP socket stats (merged from linux-tcp-socket-stats)
|
||||
socketsUsed: integer("sockets_used"),
|
||||
tcpInuse: integer("tcp_inuse"),
|
||||
tcpOrphan: integer("tcp_orphan"),
|
||||
tcpTw: integer("tcp_tw"),
|
||||
tcpAlloc: integer("tcp_alloc"),
|
||||
tcpMemPages: integer("tcp_mem_pages")
|
||||
});
|
||||
|
||||
// src/index.ts
|
||||
var SOCKSTAT_PATH = "/proc/net/sockstat";
|
||||
function parseSockstat(content) {
|
||||
let socketsUsed = 0, tcpInuse = 0, tcpOrphan = 0, tcpTw = 0, tcpAlloc = 0, tcpMemPages = 0;
|
||||
for (const line of content.split("\n")) {
|
||||
const trimmed = line.trim();
|
||||
if (trimmed.startsWith("sockets:")) {
|
||||
const parts = trimmed.split(/\s+/);
|
||||
const idx = parts.indexOf("used");
|
||||
if (idx !== -1 && idx + 1 < parts.length) {
|
||||
socketsUsed = Number.parseInt(parts[idx + 1], 10) || 0;
|
||||
}
|
||||
} else if (trimmed.startsWith("TCP:")) {
|
||||
const parts = trimmed.split(/\s+/);
|
||||
const map = {};
|
||||
for (let i = 1; i + 1 < parts.length; i += 2) {
|
||||
map[parts[i]] = Number.parseInt(parts[i + 1], 10) || 0;
|
||||
}
|
||||
tcpInuse = map.inuse ?? 0;
|
||||
tcpOrphan = map.orphan ?? 0;
|
||||
tcpTw = map.tw ?? 0;
|
||||
tcpAlloc = map.alloc ?? 0;
|
||||
tcpMemPages = map.mem ?? 0;
|
||||
}
|
||||
}
|
||||
return { socketsUsed, tcpInuse, tcpOrphan, tcpTw, tcpAlloc, tcpMemPages };
|
||||
}
|
||||
async function compute() {
|
||||
const [load1, load5, load15] = loadavg();
|
||||
const memTotal = totalmem();
|
||||
const memFree = freemem();
|
||||
const memUsed = memTotal - memFree;
|
||||
const memTotalMB = Math.round(memTotal / 1024 / 1024);
|
||||
const memUsedMB = Math.round(memUsed / 1024 / 1024);
|
||||
const memUsedPct = Math.round(memUsed / memTotal * 1e4) / 100;
|
||||
let diskTotalGB = 0, diskUsedGB = 0, diskUsedPct = 0;
|
||||
try {
|
||||
const df = execSync("df -B1 / | tail -1", { encoding: "utf-8" }).trim();
|
||||
const parts = df.split(/\s+/);
|
||||
const total = Number(parts[1]);
|
||||
const used = Number(parts[2]);
|
||||
diskTotalGB = Math.round(total / 1024 / 1024 / 1024 * 100) / 100;
|
||||
diskUsedGB = Math.round(used / 1024 / 1024 / 1024 * 100) / 100;
|
||||
diskUsedPct = total > 0 ? Math.round(used / total * 1e4) / 100 : 0;
|
||||
} catch {
|
||||
}
|
||||
let tcp = { socketsUsed: 0, tcpInuse: 0, tcpOrphan: 0, tcpTw: 0, tcpAlloc: 0, tcpMemPages: 0 };
|
||||
try {
|
||||
const content = await readFile(SOCKSTAT_PATH, "utf8");
|
||||
tcp = parseSockstat(content);
|
||||
} catch {
|
||||
}
|
||||
const ts = Date.now();
|
||||
const uptimeSec = Math.round(uptime());
|
||||
const data = {
|
||||
ts,
|
||||
cpuLoad1m: load1,
|
||||
cpuLoad5m: load5,
|
||||
cpuLoad15m: load15,
|
||||
memTotalMB,
|
||||
memUsedMB,
|
||||
memUsedPct,
|
||||
diskTotalGB,
|
||||
diskUsedGB,
|
||||
diskUsedPct,
|
||||
uptimeSec,
|
||||
socketsUsed: tcp.socketsUsed,
|
||||
tcpInuse: tcp.tcpInuse,
|
||||
tcpOrphan: tcp.tcpOrphan,
|
||||
tcpTw: tcp.tcpTw,
|
||||
tcpAlloc: tcp.tcpAlloc,
|
||||
tcpMemPages: tcp.tcpMemPages
|
||||
};
|
||||
return { signal: data, workflow: null };
|
||||
}
|
||||
export {
|
||||
compute,
|
||||
snapshots as table
|
||||
};
|
||||
@ -1,16 +0,0 @@
|
||||
-- Migration: 0001_init
|
||||
-- Creates the snapshots table for linux-system-health sense.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS snapshots (
|
||||
ts INTEGER PRIMARY KEY,
|
||||
cpu_load_1m REAL NOT NULL,
|
||||
cpu_load_5m REAL NOT NULL,
|
||||
cpu_load_15m REAL NOT NULL,
|
||||
mem_total_mb INTEGER NOT NULL,
|
||||
mem_used_mb INTEGER NOT NULL,
|
||||
mem_used_pct REAL NOT NULL,
|
||||
disk_total_gb REAL NOT NULL,
|
||||
disk_used_gb REAL NOT NULL,
|
||||
disk_used_pct REAL NOT NULL,
|
||||
uptime_sec INTEGER NOT NULL
|
||||
);
|
||||
@ -1,6 +0,0 @@
|
||||
ALTER TABLE snapshots ADD COLUMN sockets_used INTEGER;
|
||||
ALTER TABLE snapshots ADD COLUMN tcp_inuse INTEGER;
|
||||
ALTER TABLE snapshots ADD COLUMN tcp_orphan INTEGER;
|
||||
ALTER TABLE snapshots ADD COLUMN tcp_tw INTEGER;
|
||||
ALTER TABLE snapshots ADD COLUMN tcp_alloc INTEGER;
|
||||
ALTER TABLE snapshots ADD COLUMN tcp_mem_pages INTEGER;
|
||||
@ -1,14 +0,0 @@
|
||||
{
|
||||
"name": "sense-linux-system-health",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "esbuild src/index.ts --bundle --platform=node --format=esm --outfile=index.js --packages=external"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.0",
|
||||
"esbuild": "^0.27.0",
|
||||
"typescript": "^5.7.0"
|
||||
}
|
||||
}
|
||||
@ -1,88 +0,0 @@
|
||||
import { loadavg, totalmem, freemem, uptime } from "node:os";
|
||||
import { execSync } from "node:child_process";
|
||||
import { readFile } from "node:fs/promises";
|
||||
export { snapshots as table } from "./schema.ts";
|
||||
|
||||
const SOCKSTAT_PATH = "/proc/net/sockstat";
|
||||
|
||||
interface SockstatResult {
|
||||
socketsUsed: number;
|
||||
tcpInuse: number;
|
||||
tcpOrphan: number;
|
||||
tcpTw: number;
|
||||
tcpAlloc: number;
|
||||
tcpMemPages: number;
|
||||
}
|
||||
|
||||
function parseSockstat(content: string): SockstatResult {
|
||||
let socketsUsed = 0, tcpInuse = 0, tcpOrphan = 0, tcpTw = 0, tcpAlloc = 0, tcpMemPages = 0;
|
||||
|
||||
for (const line of content.split("\n")) {
|
||||
const trimmed = line.trim();
|
||||
if (trimmed.startsWith("sockets:")) {
|
||||
const parts = trimmed.split(/\s+/);
|
||||
const idx = parts.indexOf("used");
|
||||
if (idx !== -1 && idx + 1 < parts.length) {
|
||||
socketsUsed = Number.parseInt(parts[idx + 1], 10) || 0;
|
||||
}
|
||||
} else if (trimmed.startsWith("TCP:")) {
|
||||
const parts = trimmed.split(/\s+/);
|
||||
const map: Record<string, number> = {};
|
||||
for (let i = 1; i + 1 < parts.length; i += 2) {
|
||||
map[parts[i]] = Number.parseInt(parts[i + 1], 10) || 0;
|
||||
}
|
||||
tcpInuse = map.inuse ?? 0;
|
||||
tcpOrphan = map.orphan ?? 0;
|
||||
tcpTw = map.tw ?? 0;
|
||||
tcpAlloc = map.alloc ?? 0;
|
||||
tcpMemPages = map.mem ?? 0;
|
||||
}
|
||||
}
|
||||
|
||||
return { socketsUsed, tcpInuse, tcpOrphan, tcpTw, tcpAlloc, tcpMemPages };
|
||||
}
|
||||
|
||||
export async function compute() {
|
||||
const [load1, load5, load15] = loadavg();
|
||||
|
||||
const memTotal = totalmem();
|
||||
const memFree = freemem();
|
||||
const memUsed = memTotal - memFree;
|
||||
const memTotalMB = Math.round(memTotal / 1024 / 1024);
|
||||
const memUsedMB = Math.round(memUsed / 1024 / 1024);
|
||||
const memUsedPct = Math.round((memUsed / memTotal) * 10000) / 100;
|
||||
|
||||
let diskTotalGB = 0, diskUsedGB = 0, diskUsedPct = 0;
|
||||
try {
|
||||
const df = execSync("df -B1 / | tail -1", { encoding: "utf-8" }).trim();
|
||||
const parts = df.split(/\s+/);
|
||||
const total = Number(parts[1]);
|
||||
const used = Number(parts[2]);
|
||||
diskTotalGB = Math.round(total / 1024 / 1024 / 1024 * 100) / 100;
|
||||
diskUsedGB = Math.round(used / 1024 / 1024 / 1024 * 100) / 100;
|
||||
diskUsedPct = total > 0 ? Math.round((used / total) * 10000) / 100 : 0;
|
||||
} catch {}
|
||||
|
||||
let tcp: SockstatResult = { socketsUsed: 0, tcpInuse: 0, tcpOrphan: 0, tcpTw: 0, tcpAlloc: 0, tcpMemPages: 0 };
|
||||
try {
|
||||
const content = await readFile(SOCKSTAT_PATH, "utf8");
|
||||
tcp = parseSockstat(content);
|
||||
} catch {}
|
||||
|
||||
const ts = Date.now();
|
||||
const uptimeSec = Math.round(uptime());
|
||||
|
||||
const data = {
|
||||
ts, cpuLoad1m: load1, cpuLoad5m: load5, cpuLoad15m: load15,
|
||||
memTotalMB, memUsedMB, memUsedPct,
|
||||
diskTotalGB, diskUsedGB, diskUsedPct,
|
||||
uptimeSec,
|
||||
socketsUsed: tcp.socketsUsed,
|
||||
tcpInuse: tcp.tcpInuse,
|
||||
tcpOrphan: tcp.tcpOrphan,
|
||||
tcpTw: tcp.tcpTw,
|
||||
tcpAlloc: tcp.tcpAlloc,
|
||||
tcpMemPages: tcp.tcpMemPages,
|
||||
};
|
||||
return { signal: data, workflow: null };
|
||||
}
|
||||
@ -1,22 +0,0 @@
|
||||
import { integer, real, sqliteTable, text } from "drizzle-orm/sqlite-core";
|
||||
|
||||
export const snapshots = sqliteTable("snapshots", {
|
||||
ts: integer("ts").primaryKey(),
|
||||
cpuLoad1m: real("cpu_load_1m").notNull(),
|
||||
cpuLoad5m: real("cpu_load_5m").notNull(),
|
||||
cpuLoad15m: real("cpu_load_15m").notNull(),
|
||||
memTotalMB: integer("mem_total_mb").notNull(),
|
||||
memUsedMB: integer("mem_used_mb").notNull(),
|
||||
memUsedPct: real("mem_used_pct").notNull(),
|
||||
diskTotalGB: real("disk_total_gb").notNull(),
|
||||
diskUsedGB: real("disk_used_gb").notNull(),
|
||||
diskUsedPct: real("disk_used_pct").notNull(),
|
||||
uptimeSec: integer("uptime_sec").notNull(),
|
||||
// TCP socket stats (merged from linux-tcp-socket-stats)
|
||||
socketsUsed: integer("sockets_used"),
|
||||
tcpInuse: integer("tcp_inuse"),
|
||||
tcpOrphan: integer("tcp_orphan"),
|
||||
tcpTw: integer("tcp_tw"),
|
||||
tcpAlloc: integer("tcp_alloc"),
|
||||
tcpMemPages: integer("tcp_mem_pages"),
|
||||
});
|
||||
@ -1,37 +0,0 @@
|
||||
// src/schema.ts
|
||||
import { integer, real, sqliteTable } from "drizzle-orm/sqlite-core";
|
||||
var workerProcessMetrics = sqliteTable("worker_process_metrics", {
|
||||
ts: integer("ts").primaryKey(),
|
||||
pid: integer("pid").notNull(),
|
||||
uptimeSec: real("uptime_sec").notNull(),
|
||||
heapUsedMB: real("heap_used_mb").notNull(),
|
||||
rssMB: real("rss_mb").notNull(),
|
||||
externalMB: real("external_mb").notNull()
|
||||
});
|
||||
|
||||
// src/index.ts
|
||||
function round2(n) {
|
||||
return Math.round(n * 100) / 100;
|
||||
}
|
||||
async function compute() {
|
||||
const ts = Date.now();
|
||||
const pid = process.pid;
|
||||
const uptimeSec = process.uptime();
|
||||
const m = process.memoryUsage();
|
||||
const heapUsedMB = round2(m.heapUsed / 1024 / 1024);
|
||||
const rssMB = round2(m.rss / 1024 / 1024);
|
||||
const externalMB = round2(m.external / 1024 / 1024);
|
||||
const row = {
|
||||
ts,
|
||||
pid,
|
||||
uptimeSec,
|
||||
heapUsedMB,
|
||||
rssMB,
|
||||
externalMB
|
||||
};
|
||||
return { signal: row, workflow: null };
|
||||
}
|
||||
export {
|
||||
compute,
|
||||
workerProcessMetrics as table
|
||||
};
|
||||
@ -1,11 +0,0 @@
|
||||
-- Migration: 0001_init
|
||||
-- Creates the worker_process_metrics table for worker-process-metrics sense.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS worker_process_metrics (
|
||||
ts INTEGER PRIMARY KEY,
|
||||
pid INTEGER NOT NULL,
|
||||
uptime_sec REAL NOT NULL,
|
||||
heap_used_mb REAL NOT NULL,
|
||||
rss_mb REAL NOT NULL,
|
||||
external_mb REAL NOT NULL
|
||||
);
|
||||
@ -1,14 +0,0 @@
|
||||
{
|
||||
"name": "sense-worker-process-metrics",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "esbuild src/index.ts --bundle --platform=node --format=esm --outfile=index.js --packages=external"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.0",
|
||||
"esbuild": "^0.27.0",
|
||||
"typescript": "^5.7.0"
|
||||
}
|
||||
}
|
||||
@ -1,26 +0,0 @@
|
||||
export { workerProcessMetrics as table } from "./schema.ts";
|
||||
|
||||
function round2(n: number): number {
|
||||
return Math.round(n * 100) / 100;
|
||||
}
|
||||
|
||||
export async function compute() {
|
||||
const ts = Date.now();
|
||||
const pid = process.pid;
|
||||
const uptimeSec = process.uptime();
|
||||
const m = process.memoryUsage();
|
||||
const heapUsedMB = round2(m.heapUsed / 1024 / 1024);
|
||||
const rssMB = round2(m.rss / 1024 / 1024);
|
||||
const externalMB = round2(m.external / 1024 / 1024);
|
||||
|
||||
const row = {
|
||||
ts,
|
||||
pid,
|
||||
uptimeSec,
|
||||
heapUsedMB,
|
||||
rssMB,
|
||||
externalMB,
|
||||
};
|
||||
|
||||
return { signal: row, workflow: null };
|
||||
}
|
||||
@ -1,10 +0,0 @@
|
||||
import { integer, real, sqliteTable } from "drizzle-orm/sqlite-core";
|
||||
|
||||
export const workerProcessMetrics = sqliteTable("worker_process_metrics", {
|
||||
ts: integer("ts").primaryKey(),
|
||||
pid: integer("pid").notNull(),
|
||||
uptimeSec: real("uptime_sec").notNull(),
|
||||
heapUsedMB: real("heap_used_mb").notNull(),
|
||||
rssMB: real("rss_mb").notNull(),
|
||||
externalMB: real("external_mb").notNull(),
|
||||
});
|
||||
@ -7,7 +7,13 @@
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"noEmit": true,
|
||||
"allowImportingTsExtensions": true,
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["./**/*.ts", "../_shared/**/*.ts"]
|
||||
"include": [
|
||||
"senses/**/*.ts",
|
||||
"workflows/**/*.ts",
|
||||
"scripts/**/*.ts",
|
||||
"workflows/_shared/**/*.ts"
|
||||
]
|
||||
}
|
||||
1
workflows/develop-sense/.gitignore
vendored
1
workflows/develop-sense/.gitignore
vendored
@ -1 +0,0 @@
|
||||
dist/
|
||||
@ -1,22 +0,0 @@
|
||||
{
|
||||
"name": "generate-sense-workflow",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "esbuild index.ts --bundle --platform=node --format=esm --outdir=dist --packages=external"
|
||||
},
|
||||
"dependencies": {
|
||||
"@uncaged/nerve-adapter-cursor": "latest",
|
||||
"@uncaged/nerve-adapter-hermes": "latest",
|
||||
"@uncaged/nerve-core": "latest",
|
||||
"@uncaged/nerve-workflow-meta": "link:../../../repos/nerve/packages/workflow-meta",
|
||||
"@uncaged/nerve-workflow-utils": "latest",
|
||||
"zod": "^4.3.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.0",
|
||||
"esbuild": "^0.27.0",
|
||||
"typescript": "^5.7.0"
|
||||
}
|
||||
}
|
||||
@ -1,14 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"lib": ["ES2022"],
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"noEmit": false,
|
||||
"declaration": false,
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["./**/*.ts", "../_shared/**/*.ts"]
|
||||
}
|
||||
1
workflows/develop-workflow/.gitignore
vendored
1
workflows/develop-workflow/.gitignore
vendored
@ -1 +0,0 @@
|
||||
dist/
|
||||
@ -1,22 +0,0 @@
|
||||
{
|
||||
"name": "generate-workflow-workflow",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "esbuild index.ts --bundle --platform=node --format=esm --outdir=dist --packages=external"
|
||||
},
|
||||
"dependencies": {
|
||||
"@uncaged/nerve-adapter-cursor": "latest",
|
||||
"@uncaged/nerve-adapter-hermes": "latest",
|
||||
"@uncaged/nerve-core": "latest",
|
||||
"@uncaged/nerve-workflow-meta": "link:../../../repos/nerve/packages/workflow-meta",
|
||||
"@uncaged/nerve-workflow-utils": "latest",
|
||||
"zod": "^4.3.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.0",
|
||||
"esbuild": "^0.27.0",
|
||||
"typescript": "^5.7.0"
|
||||
}
|
||||
}
|
||||
@ -1,5 +1,6 @@
|
||||
import type { AgentFn, WorkflowDefinition } from "@uncaged/nerve-core";
|
||||
import type { LlmExtractorConfig } from "@uncaged/nerve-workflow-utils";
|
||||
import { createLlmAdapter } from "@uncaged/nerve-workflow-utils";
|
||||
|
||||
import { moderator } from "./moderator.js";
|
||||
import type { WorkflowMeta } from "./moderator.js";
|
||||
@ -19,11 +20,12 @@ export function createKnowledgeExtractionWorkflow({
|
||||
extract,
|
||||
}: CreateKnowledgeExtractionDeps): WorkflowDefinition<WorkflowMeta> {
|
||||
const a = (role: keyof WorkflowMeta) => adapters?.[role] ?? defaultAdapter;
|
||||
const llmAdapter = createLlmAdapter(extract.provider);
|
||||
return {
|
||||
name: "knowledge-extraction",
|
||||
name: "extract-knowledge",
|
||||
roles: {
|
||||
questioner: createQuestionerRole({ extract }),
|
||||
answerer: createAnswererRole({ extract }),
|
||||
questioner: createQuestionerRole(adapters?.questioner ?? llmAdapter, { extract }),
|
||||
answerer: createAnswererRole(adapters?.answerer ?? llmAdapter, { extract }),
|
||||
explorer: createExplorerRole(a("explorer"), { extract }),
|
||||
},
|
||||
moderator,
|
||||
@ -20,7 +20,7 @@ const workflow = createKnowledgeExtractionWorkflow({
|
||||
adapters: {
|
||||
explorer: createCursorAdapter({
|
||||
type: "cursor",
|
||||
model: "auto",
|
||||
model: "claude-sonnet-4",
|
||||
timeout: CURSOR_TIMEOUT_MS,
|
||||
}),
|
||||
},
|
||||
21
workflows/extract-knowledge/lib/workdir.ts
Normal file
21
workflows/extract-knowledge/lib/workdir.ts
Normal file
@ -0,0 +1,21 @@
|
||||
import type { StartStep } from "@uncaged/nerve-core";
|
||||
|
||||
type StartMetaWithWorkdir = StartStep["meta"] & { workdir?: string | null };
|
||||
|
||||
/**
|
||||
* Resolve the target repo working directory.
|
||||
* Priority: start.meta.workdir → prompt second line (if absolute path) → cwd.
|
||||
*/
|
||||
export function resolveWorkdir(start: StartStep): string {
|
||||
const m = start.meta as StartMetaWithWorkdir;
|
||||
if (m.workdir) return m.workdir;
|
||||
|
||||
// Allow prompt to carry workdir on the second line: "seed\n/abs/path"
|
||||
const lines = start.content.split(/\r?\n/);
|
||||
if (lines.length >= 2) {
|
||||
const candidate = lines[1]!.trim();
|
||||
if (candidate.startsWith("/")) return candidate;
|
||||
}
|
||||
|
||||
return process.cwd();
|
||||
}
|
||||
@ -1,5 +1,5 @@
|
||||
import { END } from "@uncaged/nerve-core";
|
||||
import type { Moderator, ModeratorContext } from "@uncaged/nerve-core";
|
||||
import type { Moderator, ThreadContext } from "@uncaged/nerve-core";
|
||||
|
||||
import type { AnswererMeta } from "./roles/answerer.js";
|
||||
import type { ExplorerMeta } from "./roles/explorer.js";
|
||||
@ -11,7 +11,7 @@ export type WorkflowMeta = {
|
||||
explorer: ExplorerMeta;
|
||||
};
|
||||
|
||||
type Steps = ModeratorContext<WorkflowMeta>["steps"];
|
||||
type Steps = ThreadContext<WorkflowMeta>["steps"];
|
||||
|
||||
function lastQuestionerRemaining(steps: Steps): QuestionerMeta | undefined {
|
||||
for (let i = steps.length - 1; i >= 0; i--) {
|
||||
102
workflows/extract-knowledge/roles/answerer.ts
Normal file
102
workflows/extract-knowledge/roles/answerer.ts
Normal file
@ -0,0 +1,102 @@
|
||||
import type { AgentFn, Role, ThreadContext, WorkflowMessage } from "@uncaged/nerve-core";
|
||||
import type { LlmExtractorConfig } from "@uncaged/nerve-workflow-utils";
|
||||
import { createRole, nerveCommandEnv, spawnSafe } from "@uncaged/nerve-workflow-utils";
|
||||
import { z } from "zod";
|
||||
|
||||
import { resolveWorkdir } from "../lib/workdir.js";
|
||||
|
||||
import type { QuestionerMeta } from "./questioner.js";
|
||||
|
||||
export const answererMetaSchema = z.object({
|
||||
results: z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
found: z.boolean(),
|
||||
source: z.string(),
|
||||
note: z.string(),
|
||||
}),
|
||||
),
|
||||
has_unanswered: z.boolean(),
|
||||
});
|
||||
|
||||
export type AnswererMeta = z.infer<typeof answererMetaSchema>;
|
||||
|
||||
export type CreateAnswererRoleDeps = {
|
||||
extract: LlmExtractorConfig;
|
||||
};
|
||||
|
||||
function lastQuestionerMeta(messages: WorkflowMessage[]): QuestionerMeta | undefined {
|
||||
for (let i = messages.length - 1; i >= 0; i--) {
|
||||
if (messages[i].role === "questioner") {
|
||||
return messages[i].meta as QuestionerMeta;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export async function answererPrompt(ctx: ThreadContext): Promise<string> {
|
||||
const messages = ctx.steps as unknown as WorkflowMessage[];
|
||||
const cwd = resolveWorkdir(ctx.start);
|
||||
const qm = lastQuestionerMeta(messages);
|
||||
if (!qm || qm.questions.length === 0) {
|
||||
throw new Error("answerer: prompt invoked without questioner questions — wrapped role should short-circuit");
|
||||
}
|
||||
|
||||
const blocks: string[] = [];
|
||||
for (const q of qm.questions) {
|
||||
if ((ctx.start.meta as Record<string, unknown>).dryRun) {
|
||||
blocks.push(`### ${q.id}\n[dryRun] skipped nerve knowledge query\n`);
|
||||
continue;
|
||||
}
|
||||
const res = await spawnSafe(
|
||||
"nerve",
|
||||
["knowledge", "query", q.question],
|
||||
{
|
||||
cwd,
|
||||
env: nerveCommandEnv(),
|
||||
timeoutMs: 120_000,
|
||||
dryRun: false,
|
||||
abortSignal: null,
|
||||
},
|
||||
);
|
||||
if (res.ok) {
|
||||
blocks.push(`### ${q.id} (${q.domain})\nQuestion: ${q.question}\n---\n${res.value.stdout}\n`);
|
||||
} else {
|
||||
const err = res.error;
|
||||
const detail =
|
||||
err.kind === "non_zero_exit"
|
||||
? `exit ${err.exitCode}\n${err.stderr}`
|
||||
: err.kind === "timeout"
|
||||
? `timeout\n${err.stderr}`
|
||||
: err.kind === "spawn_failed"
|
||||
? err.message
|
||||
: "aborted";
|
||||
blocks.push(`### ${q.id}\nnerve knowledge query failed: ${detail}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
"You are the **answerer**. You MUST NOT read repository source code — only the CLI retrieval excerpts below.",
|
||||
"For each question id, decide whether the knowledge base already answers it.",
|
||||
"Set found=true only when the excerpt supports a confident answer; otherwise found=false.",
|
||||
"Set has_unanswered=true if any question remains unanswered by the knowledge base.",
|
||||
"",
|
||||
...blocks,
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
export function createAnswererRole(adapter: AgentFn, { extract }: CreateAnswererRoleDeps): Role<AnswererMeta> {
|
||||
const inner = createRole(adapter, answererPrompt, answererMetaSchema, extract);
|
||||
|
||||
return async (ctx: ThreadContext) => {
|
||||
const messages = ctx.steps as unknown as WorkflowMessage[];
|
||||
const qm = lastQuestionerMeta(messages);
|
||||
if (!qm || qm.questions.length === 0) {
|
||||
return {
|
||||
content: "answerer: no questions from questioner; skipping CLI lookup.",
|
||||
meta: { results: [], has_unanswered: false },
|
||||
};
|
||||
}
|
||||
return inner(ctx);
|
||||
};
|
||||
}
|
||||
@ -1,4 +1,4 @@
|
||||
import type { AgentFn, Role, StartStep, WorkflowMessage } from "@uncaged/nerve-core";
|
||||
import type { AgentFn, Role, ThreadContext, WorkflowMessage } from "@uncaged/nerve-core";
|
||||
import type { LlmExtractorConfig } from "@uncaged/nerve-workflow-utils";
|
||||
import { createRole } from "@uncaged/nerve-workflow-utils";
|
||||
import { z } from "zod";
|
||||
@ -33,16 +33,17 @@ function lastMeta<M>(messages: WorkflowMessage[], role: string): M | undefined {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function explorerPrompt(start: StartStep, messages: WorkflowMessage[]): string {
|
||||
const threadId = start.meta.threadId;
|
||||
export function explorerPrompt(ctx: ThreadContext): string {
|
||||
const messages = ctx.steps as unknown as WorkflowMessage[];
|
||||
const threadId = ctx.start.meta.threadId;
|
||||
const qm = lastMeta<QuestionerMeta>(messages, "questioner");
|
||||
const am = lastMeta<AnswererMeta>(messages, "answerer");
|
||||
const cwd = resolveWorkdir(start);
|
||||
const cwd = resolveWorkdir(ctx.start);
|
||||
|
||||
const unanswered =
|
||||
am?.results.filter((r) => !r.found).map((r) => r.id) ?? [];
|
||||
|
||||
return `You are the **explorer** in a knowledge-extraction workflow.
|
||||
return `You are the **explorer** in an extract-knowledge workflow.
|
||||
|
||||
## Context
|
||||
|
||||
@ -85,7 +86,7 @@ export function createExplorerRole(
|
||||
): Role<ExplorerMeta> {
|
||||
return createRole(
|
||||
adapter,
|
||||
async (innerStart: StartStep, msgs: WorkflowMessage[]) => explorerPrompt(innerStart, msgs),
|
||||
async (ctx: ThreadContext) => explorerPrompt(ctx),
|
||||
explorerMetaSchema,
|
||||
extract,
|
||||
);
|
||||
108
workflows/extract-knowledge/roles/questioner.ts
Normal file
108
workflows/extract-knowledge/roles/questioner.ts
Normal file
@ -0,0 +1,108 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import type { AgentFn, Role, ThreadContext, WorkflowMessage } from "@uncaged/nerve-core";
|
||||
import type { LlmExtractorConfig } from "@uncaged/nerve-workflow-utils";
|
||||
import { createRole } from "@uncaged/nerve-workflow-utils";
|
||||
import { z } from "zod";
|
||||
|
||||
import { resolveQueueForQuestioner } from "../lib/knowledge-queue.js";
|
||||
import { resolveWorkdir } from "../lib/workdir.js";
|
||||
|
||||
const questionerExtractSchema = z.object({
|
||||
questions: z
|
||||
.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
question: z.string(),
|
||||
domain: z.string(),
|
||||
}),
|
||||
)
|
||||
.length(5),
|
||||
});
|
||||
|
||||
export type QuestionerMeta = {
|
||||
/** Empty when no .knowledge cards and no work to do. */
|
||||
card: string;
|
||||
questions: { id: string; question: string; domain: string }[];
|
||||
remaining_queue: string[];
|
||||
};
|
||||
|
||||
export type CreateQuestionerRoleDeps = {
|
||||
extract: LlmExtractorConfig;
|
||||
};
|
||||
|
||||
function questionerSystem(): string {
|
||||
return `You are the **questioner** in an extract-knowledge workflow.
|
||||
|
||||
Read the given markdown knowledge card. Propose exactly **five** technical questions that are **not** already answered or covered by that card.
|
||||
|
||||
Rules:
|
||||
- Questions must be concrete and technical.
|
||||
- Each question needs a stable string id (e.g. q1, q2, q3, q4, q5), a short domain label (e.g. routing, storage), and the question text.
|
||||
- Do not assume access to other files or tools — reason only from the card content shown.`;
|
||||
}
|
||||
|
||||
function questionerUser(card: string, cardBody: string, remainingHint: string[]): string {
|
||||
return `Current card path: ${card}
|
||||
|
||||
Remaining queue after this card (paths, may be empty): ${JSON.stringify(remainingHint)}
|
||||
|
||||
--- Card content ---
|
||||
|
||||
${cardBody}`;
|
||||
}
|
||||
|
||||
export async function questionerPrompt(ctx: ThreadContext): Promise<string> {
|
||||
const messages = ctx.steps as unknown as WorkflowMessage[];
|
||||
const cwd = resolveWorkdir(ctx.start);
|
||||
const queue = await resolveQueueForQuestioner(ctx.start, messages, cwd);
|
||||
if (queue.length === 0) {
|
||||
throw new Error(
|
||||
"questioner: prompt invoked with empty queue — wrapped role should short-circuit before LLM",
|
||||
);
|
||||
}
|
||||
const card = queue[0]!;
|
||||
const remaining_queue = queue.slice(1);
|
||||
let cardBody: string;
|
||||
try {
|
||||
cardBody = await readFile(join(cwd, card), "utf8");
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
throw new Error(`questioner: failed to read ${card}: ${msg}`);
|
||||
}
|
||||
return `${questionerSystem()}\n\n${questionerUser(card, cardBody, remaining_queue)}`;
|
||||
}
|
||||
|
||||
export function createQuestionerRole(adapter: AgentFn, { extract }: CreateQuestionerRoleDeps): Role<QuestionerMeta> {
|
||||
const inner = createRole(adapter, questionerPrompt, questionerExtractSchema, extract);
|
||||
|
||||
return async (ctx: ThreadContext) => {
|
||||
const messages = ctx.steps as unknown as WorkflowMessage[];
|
||||
const cwd = resolveWorkdir(ctx.start);
|
||||
const queue = await resolveQueueForQuestioner(ctx.start, messages, cwd);
|
||||
if (queue.length === 0) {
|
||||
return {
|
||||
content:
|
||||
"questioner: no `.knowledge` markdown files found and no seed path in the trigger prompt; queue is empty.",
|
||||
meta: {
|
||||
card: "",
|
||||
questions: [],
|
||||
remaining_queue: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const card = queue[0]!;
|
||||
const remaining_queue = queue.slice(1);
|
||||
const r = await inner(ctx);
|
||||
return {
|
||||
content: r.content,
|
||||
meta: {
|
||||
card,
|
||||
questions: r.meta.questions,
|
||||
remaining_queue,
|
||||
},
|
||||
};
|
||||
};
|
||||
}
|
||||
3
workflows/knowledge-extraction/.gitignore
vendored
3
workflows/knowledge-extraction/.gitignore
vendored
@ -1,3 +0,0 @@
|
||||
node_modules/
|
||||
dist/
|
||||
false/
|
||||
@ -1,8 +0,0 @@
|
||||
import type { StartStep } from "@uncaged/nerve-core";
|
||||
|
||||
type StartMetaWithWorkdir = StartStep["meta"] & { workdir?: string | null };
|
||||
|
||||
export function resolveWorkdir(start: StartStep): string {
|
||||
const m = start.meta as StartMetaWithWorkdir;
|
||||
return m.workdir ?? process.cwd();
|
||||
}
|
||||
@ -1,21 +0,0 @@
|
||||
{
|
||||
"name": "knowledge-extraction-workflow",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "esbuild index.ts --bundle --platform=node --format=esm --outdir=dist --packages=external"
|
||||
},
|
||||
"dependencies": {
|
||||
"@uncaged/nerve-adapter-cursor": "latest",
|
||||
"@uncaged/nerve-adapter-hermes": "latest",
|
||||
"@uncaged/nerve-core": "latest",
|
||||
"@uncaged/nerve-workflow-utils": "latest",
|
||||
"zod": "^4.3.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.0",
|
||||
"esbuild": "^0.27.0",
|
||||
"typescript": "^5.7.0"
|
||||
}
|
||||
}
|
||||
@ -1,104 +0,0 @@
|
||||
import type { Role, StartStep, WorkflowMessage } from "@uncaged/nerve-core";
|
||||
import type { LlmExtractorConfig } from "@uncaged/nerve-workflow-utils";
|
||||
import { llmExtract, nerveCommandEnv, spawnSafe } from "@uncaged/nerve-workflow-utils";
|
||||
import { z } from "zod";
|
||||
|
||||
import { resolveWorkdir } from "../lib/workdir.js";
|
||||
|
||||
import type { QuestionerMeta } from "./questioner.js";
|
||||
|
||||
export const answererMetaSchema = z.object({
|
||||
results: z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
found: z.boolean(),
|
||||
source: z.string(),
|
||||
note: z.string(),
|
||||
}),
|
||||
),
|
||||
has_unanswered: z.boolean(),
|
||||
});
|
||||
|
||||
export type AnswererMeta = z.infer<typeof answererMetaSchema>;
|
||||
|
||||
export type CreateAnswererRoleDeps = {
|
||||
extract: LlmExtractorConfig;
|
||||
};
|
||||
|
||||
function lastQuestionerMeta(messages: WorkflowMessage[]): QuestionerMeta | undefined {
|
||||
for (let i = messages.length - 1; i >= 0; i--) {
|
||||
if (messages[i].role === "questioner") {
|
||||
return messages[i].meta as QuestionerMeta;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function createAnswererRole(deps: CreateAnswererRoleDeps): Role<AnswererMeta> {
|
||||
const { extract } = deps;
|
||||
|
||||
return async (start: StartStep, messages: WorkflowMessage[]) => {
|
||||
const cwd = resolveWorkdir(start);
|
||||
const qm = lastQuestionerMeta(messages);
|
||||
if (!qm || qm.questions.length === 0) {
|
||||
return {
|
||||
content: "answerer: no questions from questioner; skipping CLI lookup.",
|
||||
meta: { results: [], has_unanswered: false },
|
||||
};
|
||||
}
|
||||
|
||||
const blocks: string[] = [];
|
||||
for (const q of qm.questions) {
|
||||
if (start.meta.dryRun) {
|
||||
blocks.push(`### ${q.id}\n[dryRun] skipped nerve knowledge query\n`);
|
||||
continue;
|
||||
}
|
||||
const res = await spawnSafe(
|
||||
"nerve",
|
||||
["knowledge", "query", q.question],
|
||||
{
|
||||
cwd,
|
||||
env: nerveCommandEnv(),
|
||||
timeoutMs: 120_000,
|
||||
dryRun: false,
|
||||
abortSignal: null,
|
||||
},
|
||||
);
|
||||
if (res.ok) {
|
||||
blocks.push(`### ${q.id} (${q.domain})\nQuestion: ${q.question}\n---\n${res.value.stdout}\n`);
|
||||
} else {
|
||||
const err = res.error;
|
||||
const detail =
|
||||
err.kind === "non_zero_exit"
|
||||
? `exit ${err.exitCode}\n${err.stderr}`
|
||||
: err.kind === "timeout"
|
||||
? `timeout\n${err.stderr}`
|
||||
: err.kind === "spawn_failed"
|
||||
? err.message
|
||||
: "aborted";
|
||||
blocks.push(`### ${q.id}\nnerve knowledge query failed: ${detail}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
const bundle = [
|
||||
"You are the **answerer**. You MUST NOT read repository source code — only the CLI retrieval excerpts below.",
|
||||
"For each question id, decide whether the knowledge base already answers it.",
|
||||
"Set found=true only when the excerpt supports a confident answer; otherwise found=false.",
|
||||
"Set has_unanswered=true if any question remains unanswered by the knowledge base.",
|
||||
"",
|
||||
...blocks,
|
||||
].join("\n");
|
||||
|
||||
const metaR = await llmExtract({
|
||||
text: bundle,
|
||||
schema: answererMetaSchema,
|
||||
provider: extract.provider,
|
||||
dryRun: start.meta.dryRun,
|
||||
});
|
||||
if (!metaR.ok) {
|
||||
throw new Error(`answerer llmExtract: ${JSON.stringify(metaR.error)}`);
|
||||
}
|
||||
|
||||
return { content: bundle, meta: metaR.value };
|
||||
};
|
||||
}
|
||||
@ -1,106 +0,0 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import type { Role, StartStep, WorkflowMessage } from "@uncaged/nerve-core";
|
||||
import type { LlmExtractorConfig } from "@uncaged/nerve-workflow-utils";
|
||||
import { createLlmRole } from "@uncaged/nerve-workflow-utils";
|
||||
import { z } from "zod";
|
||||
|
||||
import { resolveQueueForQuestioner } from "../lib/knowledge-queue.js";
|
||||
import { resolveWorkdir } from "../lib/workdir.js";
|
||||
|
||||
const questionerExtractSchema = z.object({
|
||||
questions: z
|
||||
.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
question: z.string(),
|
||||
domain: z.string(),
|
||||
}),
|
||||
)
|
||||
.length(3),
|
||||
});
|
||||
|
||||
export type QuestionerMeta = {
|
||||
/** Empty when no .knowledge cards and no work to do. */
|
||||
card: string;
|
||||
questions: { id: string; question: string; domain: string }[];
|
||||
remaining_queue: string[];
|
||||
};
|
||||
|
||||
export type CreateQuestionerRoleDeps = {
|
||||
extract: LlmExtractorConfig;
|
||||
};
|
||||
|
||||
function questionerSystem(): string {
|
||||
return `You are the **questioner** in a knowledge-extraction workflow.
|
||||
|
||||
Read the given markdown knowledge card. Propose exactly **three** technical questions that are **not** already answered or covered by that card.
|
||||
|
||||
Rules:
|
||||
- Questions must be concrete and technical.
|
||||
- Each question needs a stable string id (e.g. q1, q2, q3), a short domain label (e.g. routing, storage), and the question text.
|
||||
- Do not assume access to other files or tools — reason only from the card content shown.`;
|
||||
}
|
||||
|
||||
function questionerUser(card: string, cardBody: string, remainingHint: string[]): string {
|
||||
return `Current card path: ${card}
|
||||
|
||||
Remaining queue after this card (paths, may be empty): ${JSON.stringify(remainingHint)}
|
||||
|
||||
--- Card content ---
|
||||
|
||||
${cardBody}`;
|
||||
}
|
||||
|
||||
export function createQuestionerRole(adapterExtract: CreateQuestionerRoleDeps): Role<QuestionerMeta> {
|
||||
const { extract } = adapterExtract;
|
||||
|
||||
return async (start: StartStep, messages: WorkflowMessage[]) => {
|
||||
const cwd = resolveWorkdir(start);
|
||||
const queue = await resolveQueueForQuestioner(start, messages, cwd);
|
||||
if (queue.length === 0) {
|
||||
return {
|
||||
content:
|
||||
"questioner: no `.knowledge` markdown files found and no seed path in the trigger prompt; queue is empty.",
|
||||
meta: {
|
||||
card: "",
|
||||
questions: [],
|
||||
remaining_queue: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const card = queue[0]!;
|
||||
const remaining_queue = queue.slice(1);
|
||||
let cardBody: string;
|
||||
try {
|
||||
cardBody = await readFile(join(cwd, card), "utf8");
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
throw new Error(`questioner: failed to read ${card}: ${msg}`);
|
||||
}
|
||||
|
||||
const inner = createLlmRole({
|
||||
provider: extract.provider,
|
||||
prompt: async () => [
|
||||
{ role: "system", content: questionerSystem() },
|
||||
{ role: "user", content: questionerUser(card, cardBody, remaining_queue) },
|
||||
],
|
||||
extract: {
|
||||
schema: questionerExtractSchema,
|
||||
provider: extract.provider,
|
||||
},
|
||||
});
|
||||
|
||||
const r = await inner(start, messages);
|
||||
return {
|
||||
content: r.content,
|
||||
meta: {
|
||||
card,
|
||||
questions: r.meta.questions,
|
||||
remaining_queue,
|
||||
},
|
||||
};
|
||||
};
|
||||
}
|
||||
@ -1,13 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"lib": ["ES2022"],
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"noEmit": true,
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["./**/*.ts"]
|
||||
}
|
||||
1
workflows/solve-issue/.gitignore
vendored
1
workflows/solve-issue/.gitignore
vendored
@ -1 +0,0 @@
|
||||
dist/
|
||||
@ -3,14 +3,14 @@ import type { LlmExtractorConfig } from "@uncaged/nerve-workflow-utils";
|
||||
|
||||
import { moderator } from "./moderator.js";
|
||||
import type { WorkflowMeta } from "./moderator.js";
|
||||
import { createCommitterRole } from "./roles/committer/index.js";
|
||||
import { createImplementRole } from "./roles/implement/index.js";
|
||||
import { createPlanRole } from "./roles/plan/index.js";
|
||||
import { createPrepareRole } from "./roles/prepare/index.js";
|
||||
import { createPublishRole } from "./roles/publish/index.js";
|
||||
import { createReadIssueRole } from "./roles/read-issue/index.js";
|
||||
import { createReviewRole } from "./roles/review/index.js";
|
||||
import { createTestRole } from "./roles/test/index.js";
|
||||
import { createCommitterRole } from "./roles/committer.js";
|
||||
import { createImplementRole } from "./roles/implement.js";
|
||||
import { createPlanRole } from "./roles/plan.js";
|
||||
import { createPrepareRole } from "./roles/prepare.js";
|
||||
import { createPublishRole } from "./roles/publish.js";
|
||||
import { createReadIssueRole } from "./roles/read-issue.js";
|
||||
import { createReviewRole } from "./roles/review.js";
|
||||
import { createTestRole } from "./roles/test.js";
|
||||
|
||||
export type CreateSolveIssueDeps = {
|
||||
defaultAdapter: AgentFn;
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import { join } from "node:path";
|
||||
import type { WorkflowMessage } from "@uncaged/nerve-core";
|
||||
import type { RoleStep, WorkflowMessage } from "@uncaged/nerve-core";
|
||||
|
||||
type SolveIssueParse = {
|
||||
host: string;
|
||||
|
||||
@ -1,13 +1,13 @@
|
||||
import { END } from "@uncaged/nerve-core";
|
||||
import type { Moderator } from "@uncaged/nerve-core";
|
||||
import type { ReadIssueMeta } from "./roles/read-issue/index.js";
|
||||
import type { PrepareMeta } from "./roles/prepare/index.js";
|
||||
import type { PlanMeta } from "./roles/plan/index.js";
|
||||
import type { ImplementMeta } from "./roles/implement/index.js";
|
||||
import type { CommitterMeta } from "./roles/committer/index.js";
|
||||
import type { ReviewMeta } from "./roles/review/index.js";
|
||||
import type { TestMeta } from "./roles/test/index.js";
|
||||
import type { PublishMeta } from "./roles/publish/index.js";
|
||||
import type { ReadIssueMeta } from "./roles/read-issue.js";
|
||||
import type { PrepareMeta } from "./roles/prepare.js";
|
||||
import type { PlanMeta } from "./roles/plan.js";
|
||||
import type { ImplementMeta } from "./roles/implement.js";
|
||||
import type { CommitterMeta } from "./roles/committer.js";
|
||||
import type { ReviewMeta } from "./roles/review.js";
|
||||
import type { TestMeta } from "./roles/test.js";
|
||||
import type { PublishMeta } from "./roles/publish.js";
|
||||
|
||||
export type WorkflowMeta = {
|
||||
"read-issue": ReadIssueMeta;
|
||||
|
||||
@ -1,21 +0,0 @@
|
||||
{
|
||||
"name": "solve-issue-workflow",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "esbuild index.ts --bundle --platform=node --format=esm --outdir=dist --packages=external"
|
||||
},
|
||||
"dependencies": {
|
||||
"@uncaged/nerve-adapter-cursor": "latest",
|
||||
"@uncaged/nerve-adapter-hermes": "latest",
|
||||
"@uncaged/nerve-core": "latest",
|
||||
"@uncaged/nerve-workflow-utils": "latest",
|
||||
"zod": "^4.3.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.0",
|
||||
"esbuild": "^0.27.0",
|
||||
"typescript": "^5.7.0"
|
||||
}
|
||||
}
|
||||
@ -1,4 +1,9 @@
|
||||
export function committerPrompt({ threadId }: { threadId: string }): string {
|
||||
import type { AgentFn, Role, ThreadContext } from "@uncaged/nerve-core";
|
||||
import type { LlmExtractorConfig } from "@uncaged/nerve-workflow-utils";
|
||||
import { createRole, decorateRole, withDryRun, onFail } from "@uncaged/nerve-workflow-utils";
|
||||
import { z } from "zod";
|
||||
|
||||
function committerPrompt({ threadId }: { threadId: string }): string {
|
||||
return `You are the committer agent. The **implement** step finished with a passing build; your job is to branch, commit, and push.
|
||||
|
||||
1. Read the workflow thread: \`nerve thread show ${threadId}\` — understand what was planned, implemented, and reviewed.
|
||||
@ -26,3 +31,27 @@ or
|
||||
{ "committed": false }
|
||||
\`\`\``;
|
||||
}
|
||||
|
||||
export const committerMetaSchema = z.object({
|
||||
committed: z
|
||||
.boolean()
|
||||
.describe("true if branch created, changes committed, and pushed successfully"),
|
||||
});
|
||||
export type CommitterMeta = z.infer<typeof committerMetaSchema>;
|
||||
|
||||
export function createCommitterRole(
|
||||
adapter: AgentFn,
|
||||
extract: LlmExtractorConfig,
|
||||
): Role<CommitterMeta> {
|
||||
const inner = createRole(
|
||||
adapter,
|
||||
async (ctx: ThreadContext) => committerPrompt({ threadId: ctx.start.meta.threadId }),
|
||||
committerMetaSchema,
|
||||
extract,
|
||||
);
|
||||
|
||||
return decorateRole(inner, [
|
||||
withDryRun({ label: "committer", meta: { committed: true } as CommitterMeta }),
|
||||
onFail({ label: "committer", meta: { committed: false } as CommitterMeta }),
|
||||
]) as Role<CommitterMeta>;
|
||||
}
|
||||
@ -1,30 +0,0 @@
|
||||
import type { AgentFn, Role, StartStep } from "@uncaged/nerve-core";
|
||||
import type { LlmExtractorConfig } from "@uncaged/nerve-workflow-utils";
|
||||
import { createRole, decorateRole, withDryRun, onFail } from "@uncaged/nerve-workflow-utils";
|
||||
import { z } from "zod";
|
||||
|
||||
import { committerPrompt } from "./prompt.js";
|
||||
|
||||
export const committerMetaSchema = z.object({
|
||||
committed: z
|
||||
.boolean()
|
||||
.describe("true if branch created, changes committed, and pushed successfully"),
|
||||
});
|
||||
export type CommitterMeta = z.infer<typeof committerMetaSchema>;
|
||||
|
||||
export function createCommitterRole(
|
||||
adapter: AgentFn,
|
||||
extract: LlmExtractorConfig,
|
||||
): Role<CommitterMeta> {
|
||||
const inner = createRole(
|
||||
adapter,
|
||||
async (start: StartStep) => committerPrompt({ threadId: start.meta.threadId }),
|
||||
committerMetaSchema,
|
||||
extract,
|
||||
);
|
||||
|
||||
return decorateRole(inner, [
|
||||
withDryRun({ label: "committer", meta: { committed: true } as CommitterMeta }),
|
||||
onFail({ label: "committer", meta: { committed: false } as CommitterMeta }),
|
||||
]) as Role<CommitterMeta>;
|
||||
}
|
||||
86
workflows/solve-issue/roles/implement.ts
Normal file
86
workflows/solve-issue/roles/implement.ts
Normal file
@ -0,0 +1,86 @@
|
||||
import type { AgentFn, Role, RoleResult, ThreadContext, WorkflowMessage } from "@uncaged/nerve-core";
|
||||
import type { LlmExtractorConfig } from "@uncaged/nerve-workflow-utils";
|
||||
import { createRole } from "@uncaged/nerve-workflow-utils";
|
||||
import { z } from "zod";
|
||||
|
||||
import { resolveRepoCwd } from "../lib/repo-context.js";
|
||||
|
||||
function buildImplementPrompt({ threadId, nerveRoot }: { threadId: string; nerveRoot: string }): string {
|
||||
return `You are the **implement** agent. You apply code changes for the issue.
|
||||
|
||||
Read workflow context (plan, reviewer/test feedback): \`nerve thread show ${threadId}\`
|
||||
|
||||
Read Nerve workspace conventions: \`cat ${nerveRoot}/CONVENTIONS.md\`
|
||||
|
||||
Your cwd is the target repository.
|
||||
|
||||
## Requirements
|
||||
|
||||
1. Implement the planned changes; address reviewer/tester feedback from the thread if any.
|
||||
2. Run the project **build** (\`pnpm build\`, \`npm run build\`, etc.) and fix issues until build passes.
|
||||
3. Multi-step: if you cannot finish this round, explain why and set **done** to false.
|
||||
|
||||
Do **not** run \`git checkout -b\`, \`git add\`, \`git commit\`, or \`git push\`. **Never** create commits on any branch — branching and commits are handled by the **committer** step after you finish.
|
||||
|
||||
Then close with JSON:
|
||||
\`\`\`json
|
||||
{ "done": true }
|
||||
\`\`\`
|
||||
or \`{ "done": false }\` matching whether implementation is complete.
|
||||
|
||||
**done=true** only when changes are complete **and** build passes in this round.`;
|
||||
}
|
||||
|
||||
export const implementMetaSchema = z.object({
|
||||
done: z.boolean().describe("true when changes are complete and build passes this round"),
|
||||
});
|
||||
export type ImplementMeta = z.infer<typeof implementMetaSchema>;
|
||||
|
||||
export type CreateImplementRoleDeps = {
|
||||
extract: LlmExtractorConfig;
|
||||
nerveRoot: string;
|
||||
};
|
||||
|
||||
export function createImplementRole(
|
||||
adapter: AgentFn,
|
||||
{ extract, nerveRoot }: CreateImplementRoleDeps,
|
||||
): Role<ImplementMeta> {
|
||||
return async (ctx: ThreadContext): Promise<RoleResult<ImplementMeta>> => {
|
||||
const messages = ctx.steps as unknown as WorkflowMessage[];
|
||||
const cwd = resolveRepoCwd(messages);
|
||||
if (cwd === null) {
|
||||
return {
|
||||
content: "implement cannot run: missing repo path in thread markers",
|
||||
meta: { done: false },
|
||||
};
|
||||
}
|
||||
|
||||
const innerRole = createRole(
|
||||
adapter,
|
||||
async (innerCtx: ThreadContext) =>
|
||||
buildImplementPrompt({
|
||||
threadId: innerCtx.start.meta.threadId,
|
||||
nerveRoot,
|
||||
}),
|
||||
implementMetaSchema,
|
||||
extract,
|
||||
);
|
||||
|
||||
const innerCtx: ThreadContext = {
|
||||
...ctx,
|
||||
start: {
|
||||
...ctx.start,
|
||||
meta: { ...ctx.start.meta, workdir: cwd },
|
||||
},
|
||||
};
|
||||
try {
|
||||
return await innerRole(innerCtx);
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
return {
|
||||
content: `implement failed: ${msg}`,
|
||||
meta: { done: false },
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
@ -1,58 +0,0 @@
|
||||
import type { AgentFn, Role, RoleResult, StartStep, WorkflowMessage } from "@uncaged/nerve-core";
|
||||
import type { LlmExtractorConfig } from "@uncaged/nerve-workflow-utils";
|
||||
import { createRole } from "@uncaged/nerve-workflow-utils";
|
||||
import { z } from "zod";
|
||||
|
||||
import { resolveRepoCwd } from "../../lib/repo-context.js";
|
||||
import { buildImplementPrompt } from "./prompt.js";
|
||||
|
||||
export const implementMetaSchema = z.object({
|
||||
done: z.boolean().describe("true when changes are complete and build passes this round"),
|
||||
});
|
||||
export type ImplementMeta = z.infer<typeof implementMetaSchema>;
|
||||
|
||||
export type CreateImplementRoleDeps = {
|
||||
extract: LlmExtractorConfig;
|
||||
nerveRoot: string;
|
||||
};
|
||||
|
||||
export function createImplementRole(
|
||||
adapter: AgentFn,
|
||||
{ extract, nerveRoot }: CreateImplementRoleDeps,
|
||||
): Role<ImplementMeta> {
|
||||
return async (start: StartStep, messages: WorkflowMessage[]): Promise<RoleResult<ImplementMeta>> => {
|
||||
const cwd = resolveRepoCwd(messages);
|
||||
if (cwd === null) {
|
||||
return {
|
||||
content: "implement cannot run: missing repo path in thread markers",
|
||||
meta: { done: false },
|
||||
};
|
||||
}
|
||||
|
||||
const innerRole = createRole(
|
||||
adapter,
|
||||
async (innerStart: StartStep) =>
|
||||
buildImplementPrompt({
|
||||
threadId: innerStart.meta.threadId,
|
||||
nerveRoot,
|
||||
}),
|
||||
implementMetaSchema,
|
||||
extract,
|
||||
);
|
||||
|
||||
const innerStart = {
|
||||
...start,
|
||||
meta: { ...start.meta, workdir: cwd },
|
||||
} as StartStep;
|
||||
|
||||
try {
|
||||
return await innerRole(innerStart, messages);
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
return {
|
||||
content: `implement failed: ${msg}`,
|
||||
meta: { done: false },
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
@ -1,25 +0,0 @@
|
||||
export function buildImplementPrompt({ threadId, nerveRoot }: { threadId: string; nerveRoot: string }): string {
|
||||
return `You are the **implement** agent. You apply code changes for the issue.
|
||||
|
||||
Read workflow context (plan, reviewer/test feedback): \`nerve thread show ${threadId}\`
|
||||
|
||||
Read Nerve workspace conventions: \`cat ${nerveRoot}/CONVENTIONS.md\`
|
||||
|
||||
Your cwd is the target repository.
|
||||
|
||||
## Requirements
|
||||
|
||||
1. Implement the planned changes; address reviewer/tester feedback from the thread if any.
|
||||
2. Run the project **build** (\`pnpm build\`, \`npm run build\`, etc.) and fix issues until build passes.
|
||||
3. Multi-step: if you cannot finish this round, explain why and set **done** to false.
|
||||
|
||||
Do **not** run \`git checkout -b\`, \`git add\`, \`git commit\`, or \`git push\`. **Never** create commits on any branch — branching and commits are handled by the **committer** step after you finish.
|
||||
|
||||
Then close with JSON:
|
||||
\`\`\`json
|
||||
{ "done": true }
|
||||
\`\`\`
|
||||
or \`{ "done": false }\` matching whether implementation is complete.
|
||||
|
||||
**done=true** only when changes are complete **and** build passes in this round.`;
|
||||
}
|
||||
88
workflows/solve-issue/roles/plan.ts
Normal file
88
workflows/solve-issue/roles/plan.ts
Normal file
@ -0,0 +1,88 @@
|
||||
import type { AgentFn, Role, RoleResult, ThreadContext, WorkflowMessage } from "@uncaged/nerve-core";
|
||||
import type { LlmExtractorConfig } from "@uncaged/nerve-workflow-utils";
|
||||
import { createRole } from "@uncaged/nerve-workflow-utils";
|
||||
import { z } from "zod";
|
||||
|
||||
import { resolveRepoCwd } from "../lib/repo-context.js";
|
||||
|
||||
function buildPlanPrompt({ threadId, nerveRoot }: { threadId: string; nerveRoot: string }): string {
|
||||
return `You are the **plan** agent (analysis only — ask mode). You produce an implementation plan for fixing the issue.
|
||||
|
||||
Read workflow context: \`nerve thread show ${threadId}\`
|
||||
|
||||
Read Nerve workspace conventions (coding rules for agents): \`cat ${nerveRoot}/CONVENTIONS.md\`
|
||||
|
||||
In the **target repository** (your cwd), skim relevant files and read \`CONVENTIONS.md\` **if it exists** there.
|
||||
|
||||
## Output
|
||||
|
||||
Write an implementation plan in **markdown** with:
|
||||
|
||||
1. Problem understanding
|
||||
2. Change strategy
|
||||
3. Target files (paths)
|
||||
4. **Test commands** to run (explicit shell commands, e.g. \`pnpm test\`, \`pnpm vitest run\`)
|
||||
5. Risks
|
||||
|
||||
End your reply with a JSON code block (meta signal):
|
||||
\`\`\`json
|
||||
{ "ready": true }
|
||||
\`\`\`
|
||||
Use \`{ "ready": false }\` if the plan cannot be made actionable.
|
||||
|
||||
**ready=true** only when the plan is clear and actionable.`;
|
||||
}
|
||||
|
||||
export const planMetaSchema = z.object({
|
||||
ready: z.boolean().describe("true if plan is clear and actionable"),
|
||||
});
|
||||
export type PlanMeta = z.infer<typeof planMetaSchema>;
|
||||
|
||||
export type CreatePlanRoleDeps = {
|
||||
extract: LlmExtractorConfig;
|
||||
nerveRoot: string;
|
||||
};
|
||||
|
||||
export function createPlanRole(
|
||||
adapter: AgentFn,
|
||||
{ extract, nerveRoot }: CreatePlanRoleDeps,
|
||||
): Role<PlanMeta> {
|
||||
return async (ctx: ThreadContext): Promise<RoleResult<PlanMeta>> => {
|
||||
const messages = ctx.steps as unknown as WorkflowMessage[];
|
||||
const cwd = resolveRepoCwd(messages);
|
||||
if (cwd === null) {
|
||||
return {
|
||||
content: "plan cannot run: missing ---SOLVE_ISSUE_REPO--- or ---SOLVE_ISSUE_PARSE--- in thread",
|
||||
meta: { ready: false },
|
||||
};
|
||||
}
|
||||
|
||||
const innerRole = createRole(
|
||||
adapter,
|
||||
async (innerCtx: ThreadContext) =>
|
||||
buildPlanPrompt({
|
||||
threadId: innerCtx.start.meta.threadId,
|
||||
nerveRoot,
|
||||
}),
|
||||
planMetaSchema,
|
||||
extract,
|
||||
);
|
||||
|
||||
const innerCtx: ThreadContext = {
|
||||
...ctx,
|
||||
start: {
|
||||
...ctx.start,
|
||||
meta: { ...ctx.start.meta, workdir: cwd },
|
||||
},
|
||||
};
|
||||
try {
|
||||
return await innerRole(innerCtx);
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
return {
|
||||
content: `plan failed: ${msg}`,
|
||||
meta: { ready: false },
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
@ -1,58 +0,0 @@
|
||||
import type { AgentFn, Role, RoleResult, StartStep, WorkflowMessage } from "@uncaged/nerve-core";
|
||||
import type { LlmExtractorConfig } from "@uncaged/nerve-workflow-utils";
|
||||
import { createRole } from "@uncaged/nerve-workflow-utils";
|
||||
import { z } from "zod";
|
||||
|
||||
import { resolveRepoCwd } from "../../lib/repo-context.js";
|
||||
import { buildPlanPrompt } from "./prompt.js";
|
||||
|
||||
export const planMetaSchema = z.object({
|
||||
ready: z.boolean().describe("true if plan is clear and actionable"),
|
||||
});
|
||||
export type PlanMeta = z.infer<typeof planMetaSchema>;
|
||||
|
||||
export type CreatePlanRoleDeps = {
|
||||
extract: LlmExtractorConfig;
|
||||
nerveRoot: string;
|
||||
};
|
||||
|
||||
export function createPlanRole(
|
||||
adapter: AgentFn,
|
||||
{ extract, nerveRoot }: CreatePlanRoleDeps,
|
||||
): Role<PlanMeta> {
|
||||
return async (start: StartStep, messages: WorkflowMessage[]): Promise<RoleResult<PlanMeta>> => {
|
||||
const cwd = resolveRepoCwd(messages);
|
||||
if (cwd === null) {
|
||||
return {
|
||||
content: "plan cannot run: missing ---SOLVE_ISSUE_REPO--- or ---SOLVE_ISSUE_PARSE--- in thread",
|
||||
meta: { ready: false },
|
||||
};
|
||||
}
|
||||
|
||||
const innerRole = createRole(
|
||||
adapter,
|
||||
async (innerStart: StartStep) =>
|
||||
buildPlanPrompt({
|
||||
threadId: innerStart.meta.threadId,
|
||||
nerveRoot,
|
||||
}),
|
||||
planMetaSchema,
|
||||
extract,
|
||||
);
|
||||
|
||||
const innerStart = {
|
||||
...start,
|
||||
meta: { ...start.meta, workdir: cwd },
|
||||
} as StartStep;
|
||||
|
||||
try {
|
||||
return await innerRole(innerStart, messages);
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
return {
|
||||
content: `plan failed: ${msg}`,
|
||||
meta: { ready: false },
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
@ -1,27 +0,0 @@
|
||||
export function buildPlanPrompt({ threadId, nerveRoot }: { threadId: string; nerveRoot: string }): string {
|
||||
return `You are the **plan** agent (analysis only — ask mode). You produce an implementation plan for fixing the issue.
|
||||
|
||||
Read workflow context: \`nerve thread show ${threadId}\`
|
||||
|
||||
Read Nerve workspace conventions (coding rules for agents): \`cat ${nerveRoot}/CONVENTIONS.md\`
|
||||
|
||||
In the **target repository** (your cwd), skim relevant files and read \`CONVENTIONS.md\` **if it exists** there.
|
||||
|
||||
## Output
|
||||
|
||||
Write an implementation plan in **markdown** with:
|
||||
|
||||
1. Problem understanding
|
||||
2. Change strategy
|
||||
3. Target files (paths)
|
||||
4. **Test commands** to run (explicit shell commands, e.g. \`pnpm test\`, \`pnpm vitest run\`)
|
||||
5. Risks
|
||||
|
||||
End your reply with a JSON code block (meta signal):
|
||||
\`\`\`json
|
||||
{ "ready": true }
|
||||
\`\`\`
|
||||
Use \`{ "ready": false }\` if the plan cannot be made actionable.
|
||||
|
||||
**ready=true** only when the plan is clear and actionable.`;
|
||||
}
|
||||
@ -1,4 +1,9 @@
|
||||
export function preparePrompt({ threadId }: { threadId: string }): string {
|
||||
import type { AgentFn, Role, ThreadContext } from "@uncaged/nerve-core";
|
||||
import type { LlmExtractorConfig } from "@uncaged/nerve-workflow-utils";
|
||||
import { createRole } from "@uncaged/nerve-workflow-utils";
|
||||
import { z } from "zod";
|
||||
|
||||
function preparePrompt({ threadId }: { threadId: string }): string {
|
||||
return `You are the **prepare** agent. You ensure the target repository is ready for work.
|
||||
|
||||
Read prior messages / thread for issue markers: \`nerve thread show ${threadId}\`
|
||||
@ -52,3 +57,17 @@ or \`{ "ready": false }\` if the repo is invalid, or install/build baseline fail
|
||||
|
||||
**ready=true** only when the repo exists at \`path\`, is clean, dependencies installed, and baseline build succeeded (or no build script).`;
|
||||
}
|
||||
|
||||
export const prepareMetaSchema = z.object({
|
||||
ready: z.boolean().describe("true if repo is ready and baseline build ok"),
|
||||
});
|
||||
export type PrepareMeta = z.infer<typeof prepareMetaSchema>;
|
||||
|
||||
export function createPrepareRole(adapter: AgentFn, extract: LlmExtractorConfig): Role<PrepareMeta> {
|
||||
return createRole(
|
||||
adapter,
|
||||
async (ctx: ThreadContext) => preparePrompt({ threadId: ctx.start.meta.threadId }),
|
||||
prepareMetaSchema,
|
||||
extract,
|
||||
);
|
||||
}
|
||||
@ -1,20 +0,0 @@
|
||||
import type { AgentFn, Role, StartStep } from "@uncaged/nerve-core";
|
||||
import type { LlmExtractorConfig } from "@uncaged/nerve-workflow-utils";
|
||||
import { createRole } from "@uncaged/nerve-workflow-utils";
|
||||
import { z } from "zod";
|
||||
|
||||
import { preparePrompt } from "./prompt.js";
|
||||
|
||||
export const prepareMetaSchema = z.object({
|
||||
ready: z.boolean().describe("true if repo is ready and baseline build ok"),
|
||||
});
|
||||
export type PrepareMeta = z.infer<typeof prepareMetaSchema>;
|
||||
|
||||
export function createPrepareRole(adapter: AgentFn, extract: LlmExtractorConfig): Role<PrepareMeta> {
|
||||
return createRole(
|
||||
adapter,
|
||||
async (start: StartStep) => preparePrompt({ threadId: start.meta.threadId }),
|
||||
prepareMetaSchema,
|
||||
extract,
|
||||
);
|
||||
}
|
||||
@ -1,4 +1,11 @@
|
||||
export function buildPublishPrompt({ threadId, nerveRoot }: { threadId: string; nerveRoot: string }): string {
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import type { AgentFn, Role, RoleResult, ThreadContext } from "@uncaged/nerve-core";
|
||||
import type { LlmExtractorConfig } from "@uncaged/nerve-workflow-utils";
|
||||
import { createRole, isDryRun } from "@uncaged/nerve-workflow-utils";
|
||||
import { z } from "zod";
|
||||
|
||||
function buildPublishPrompt({ threadId, nerveRoot }: { threadId: string; nerveRoot: string }): string {
|
||||
return `You are the **publish** agent (Hermes). Test has passed. Open a pull request for the current branch using the **tea** CLI.
|
||||
|
||||
## Context
|
||||
@ -40,3 +47,64 @@ or
|
||||
{ "success": false }
|
||||
\`\`\``;
|
||||
}
|
||||
|
||||
export const publishMetaSchema = z.object({
|
||||
success: z.boolean().describe("true if git push and tea pr create both succeeded"),
|
||||
});
|
||||
export type PublishMeta = z.infer<typeof publishMetaSchema>;
|
||||
|
||||
export type CreatePublishRoleDeps = {
|
||||
extract: LlmExtractorConfig;
|
||||
nerveRoot: string;
|
||||
};
|
||||
|
||||
function logPath(nerveRoot: string): string {
|
||||
return join(nerveRoot, "logs", `solve-issue-publish-${Date.now()}.log`);
|
||||
}
|
||||
|
||||
export function createPublishRole(
|
||||
adapter: AgentFn,
|
||||
{ extract, nerveRoot }: CreatePublishRoleDeps,
|
||||
): Role<PublishMeta> {
|
||||
const innerRole = createRole(
|
||||
adapter,
|
||||
async (ctx: ThreadContext) =>
|
||||
buildPublishPrompt({ threadId: ctx.start.meta.threadId, nerveRoot }),
|
||||
publishMetaSchema,
|
||||
extract,
|
||||
);
|
||||
|
||||
return async (ctx: ThreadContext): Promise<RoleResult<PublishMeta>> => {
|
||||
const file = logPath(nerveRoot);
|
||||
mkdirSync(join(file, ".."), { recursive: true });
|
||||
|
||||
if (isDryRun(ctx.start)) {
|
||||
const msg = "[dry-run] publish skipped (no git push / PR)";
|
||||
writeFileSync(file, `${msg}\n`, "utf-8");
|
||||
return {
|
||||
content: `[dry-run] publish skipped — log: ${file}`,
|
||||
meta: { success: true },
|
||||
};
|
||||
}
|
||||
|
||||
const innerCtx: ThreadContext = {
|
||||
...ctx,
|
||||
start: {
|
||||
...ctx.start,
|
||||
meta: { ...ctx.start.meta, workdir: nerveRoot },
|
||||
},
|
||||
};
|
||||
|
||||
try {
|
||||
return await innerRole(innerCtx);
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
const body = `publish failed: ${msg}\n`;
|
||||
writeFileSync(file, body, "utf-8");
|
||||
return {
|
||||
content: `publish failed: ${msg}\nLog: ${file}`,
|
||||
meta: { success: false },
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
@ -1,66 +0,0 @@
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import type { AgentFn, Role, RoleResult, StartStep, WorkflowMessage } from "@uncaged/nerve-core";
|
||||
import type { LlmExtractorConfig } from "@uncaged/nerve-workflow-utils";
|
||||
import { createRole, isDryRun } from "@uncaged/nerve-workflow-utils";
|
||||
import { z } from "zod";
|
||||
|
||||
import { buildPublishPrompt } from "./prompt.js";
|
||||
|
||||
export const publishMetaSchema = z.object({
|
||||
success: z.boolean().describe("true if git push and tea pr create both succeeded"),
|
||||
});
|
||||
export type PublishMeta = z.infer<typeof publishMetaSchema>;
|
||||
|
||||
export type CreatePublishRoleDeps = {
|
||||
extract: LlmExtractorConfig;
|
||||
nerveRoot: string;
|
||||
};
|
||||
|
||||
function logPath(nerveRoot: string): string {
|
||||
return join(nerveRoot, "logs", `solve-issue-publish-${Date.now()}.log`);
|
||||
}
|
||||
|
||||
export function createPublishRole(
|
||||
adapter: AgentFn,
|
||||
{ extract, nerveRoot }: CreatePublishRoleDeps,
|
||||
): Role<PublishMeta> {
|
||||
const innerRole = createRole(
|
||||
adapter,
|
||||
async (start: StartStep) =>
|
||||
buildPublishPrompt({ threadId: start.meta.threadId, nerveRoot }),
|
||||
publishMetaSchema,
|
||||
extract,
|
||||
);
|
||||
|
||||
return async (start: StartStep, messages: WorkflowMessage[]): Promise<RoleResult<PublishMeta>> => {
|
||||
const file = logPath(nerveRoot);
|
||||
mkdirSync(join(file, ".."), { recursive: true });
|
||||
|
||||
if (isDryRun(start)) {
|
||||
const msg = "[dry-run] publish skipped (no git push / PR)";
|
||||
writeFileSync(file, `${msg}\n`, "utf-8");
|
||||
return {
|
||||
content: `[dry-run] publish skipped — log: ${file}`,
|
||||
meta: { success: true },
|
||||
};
|
||||
}
|
||||
|
||||
const innerStart = {
|
||||
...start,
|
||||
meta: { ...start.meta, workdir: nerveRoot },
|
||||
} as StartStep;
|
||||
|
||||
try {
|
||||
return await innerRole(innerStart, messages);
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
const body = `publish failed: ${msg}\n`;
|
||||
writeFileSync(file, body, "utf-8");
|
||||
return {
|
||||
content: `publish failed: ${msg}\nLog: ${file}`,
|
||||
meta: { success: false },
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
@ -1,4 +1,9 @@
|
||||
export function readIssuePrompt({ threadId }: { threadId: string }): string {
|
||||
import type { AgentFn, Role, ThreadContext } from "@uncaged/nerve-core";
|
||||
import type { LlmExtractorConfig } from "@uncaged/nerve-workflow-utils";
|
||||
import { createRole } from "@uncaged/nerve-workflow-utils";
|
||||
import { z } from "zod";
|
||||
|
||||
function readIssuePrompt({ threadId }: { threadId: string }): string {
|
||||
return `You are the **read-issue** agent. You fetch Gitea issue content via the \`tea\` CLI.
|
||||
|
||||
Read the workflow thread start prompt for the issue URL (same run): \`nerve thread show ${threadId}\`
|
||||
@ -32,3 +37,17 @@ Use \`{ "ready": false }\` if you could not fetch or parse the issue.
|
||||
|
||||
**ready=true** only if the issue was fetched successfully and the marker block is correct.`;
|
||||
}
|
||||
|
||||
export const readIssueMetaSchema = z.object({
|
||||
ready: z.boolean().describe("true if issue content was fetched and markers are present"),
|
||||
});
|
||||
export type ReadIssueMeta = z.infer<typeof readIssueMetaSchema>;
|
||||
|
||||
export function createReadIssueRole(adapter: AgentFn, extract: LlmExtractorConfig): Role<ReadIssueMeta> {
|
||||
return createRole(
|
||||
adapter,
|
||||
async (ctx: ThreadContext) => readIssuePrompt({ threadId: ctx.start.meta.threadId }),
|
||||
readIssueMetaSchema,
|
||||
extract,
|
||||
);
|
||||
}
|
||||
@ -1,20 +0,0 @@
|
||||
import type { AgentFn, Role, StartStep } from "@uncaged/nerve-core";
|
||||
import type { LlmExtractorConfig } from "@uncaged/nerve-workflow-utils";
|
||||
import { createRole } from "@uncaged/nerve-workflow-utils";
|
||||
import { z } from "zod";
|
||||
|
||||
import { readIssuePrompt } from "./prompt.js";
|
||||
|
||||
export const readIssueMetaSchema = z.object({
|
||||
ready: z.boolean().describe("true if issue content was fetched and markers are present"),
|
||||
});
|
||||
export type ReadIssueMeta = z.infer<typeof readIssueMetaSchema>;
|
||||
|
||||
export function createReadIssueRole(adapter: AgentFn, extract: LlmExtractorConfig): Role<ReadIssueMeta> {
|
||||
return createRole(
|
||||
adapter,
|
||||
async (start: StartStep) => readIssuePrompt({ threadId: start.meta.threadId }),
|
||||
readIssueMetaSchema,
|
||||
extract,
|
||||
);
|
||||
}
|
||||
@ -1,4 +1,9 @@
|
||||
export function reviewPrompt({ threadId, nerveRoot }: { threadId: string; nerveRoot: string }): string {
|
||||
import type { AgentFn, Role, ThreadContext } from "@uncaged/nerve-core";
|
||||
import type { LlmExtractorConfig } from "@uncaged/nerve-workflow-utils";
|
||||
import { createRole } from "@uncaged/nerve-workflow-utils";
|
||||
import { z } from "zod";
|
||||
|
||||
function reviewPrompt({ threadId, nerveRoot }: { threadId: string; nerveRoot: string }): string {
|
||||
return `You are a **code reviewer** (Hermes). You run after implement and before test.
|
||||
|
||||
Read Nerve workspace conventions: \`cat ${nerveRoot}/CONVENTIONS.md\`
|
||||
@ -33,3 +38,22 @@ or
|
||||
{ "approved": false }
|
||||
\`\`\``;
|
||||
}
|
||||
|
||||
export const reviewMetaSchema = z.object({
|
||||
approved: z.boolean().describe("true if diff is clean and ready for tests"),
|
||||
});
|
||||
export type ReviewMeta = z.infer<typeof reviewMetaSchema>;
|
||||
|
||||
export function createReviewRole(
|
||||
adapter: AgentFn,
|
||||
extract: LlmExtractorConfig,
|
||||
nerveRoot: string,
|
||||
): Role<ReviewMeta> {
|
||||
return createRole(
|
||||
adapter,
|
||||
async (ctx: ThreadContext) =>
|
||||
reviewPrompt({ threadId: ctx.start.meta.threadId, nerveRoot }),
|
||||
reviewMetaSchema,
|
||||
extract,
|
||||
);
|
||||
}
|
||||
@ -1,25 +0,0 @@
|
||||
import type { AgentFn, Role, StartStep } from "@uncaged/nerve-core";
|
||||
import type { LlmExtractorConfig } from "@uncaged/nerve-workflow-utils";
|
||||
import { createRole } from "@uncaged/nerve-workflow-utils";
|
||||
import { z } from "zod";
|
||||
|
||||
import { reviewPrompt } from "./prompt.js";
|
||||
|
||||
export const reviewMetaSchema = z.object({
|
||||
approved: z.boolean().describe("true if diff is clean and ready for tests"),
|
||||
});
|
||||
export type ReviewMeta = z.infer<typeof reviewMetaSchema>;
|
||||
|
||||
export function createReviewRole(
|
||||
adapter: AgentFn,
|
||||
extract: LlmExtractorConfig,
|
||||
nerveRoot: string,
|
||||
): Role<ReviewMeta> {
|
||||
return createRole(
|
||||
adapter,
|
||||
async (start: StartStep) =>
|
||||
reviewPrompt({ threadId: start.meta.threadId, nerveRoot }),
|
||||
reviewMetaSchema,
|
||||
extract,
|
||||
);
|
||||
}
|
||||
@ -1,4 +1,9 @@
|
||||
export function testPrompt({ threadId }: { threadId: string }): string {
|
||||
import type { AgentFn, Role, ThreadContext } from "@uncaged/nerve-core";
|
||||
import type { LlmExtractorConfig } from "@uncaged/nerve-workflow-utils";
|
||||
import { createRole } from "@uncaged/nerve-workflow-utils";
|
||||
import { z } from "zod";
|
||||
|
||||
function testPrompt({ threadId }: { threadId: string }): string {
|
||||
return `You are the **test** agent (Hermes). You execute automated tests for the change.
|
||||
|
||||
Read workflow context: \`nerve thread show ${threadId}\`
|
||||
@ -19,3 +24,17 @@ or \`{ "passed": false }\`
|
||||
|
||||
**passed=true** only if every executed command exited 0 (or skip was justified with no failing command).`;
|
||||
}
|
||||
|
||||
export const testMetaSchema = z.object({
|
||||
passed: z.boolean().describe("true if all test commands passed"),
|
||||
});
|
||||
export type TestMeta = z.infer<typeof testMetaSchema>;
|
||||
|
||||
export function createTestRole(adapter: AgentFn, extract: LlmExtractorConfig): Role<TestMeta> {
|
||||
return createRole(
|
||||
adapter,
|
||||
async (ctx: ThreadContext) => testPrompt({ threadId: ctx.start.meta.threadId }),
|
||||
testMetaSchema,
|
||||
extract,
|
||||
);
|
||||
}
|
||||
@ -1,20 +0,0 @@
|
||||
import type { AgentFn, Role, StartStep } from "@uncaged/nerve-core";
|
||||
import type { LlmExtractorConfig } from "@uncaged/nerve-workflow-utils";
|
||||
import { createRole } from "@uncaged/nerve-workflow-utils";
|
||||
import { z } from "zod";
|
||||
|
||||
import { testPrompt } from "./prompt.js";
|
||||
|
||||
export const testMetaSchema = z.object({
|
||||
passed: z.boolean().describe("true if all test commands passed"),
|
||||
});
|
||||
export type TestMeta = z.infer<typeof testMetaSchema>;
|
||||
|
||||
export function createTestRole(adapter: AgentFn, extract: LlmExtractorConfig): Role<TestMeta> {
|
||||
return createRole(
|
||||
adapter,
|
||||
async (start: StartStep) => testPrompt({ threadId: start.meta.threadId }),
|
||||
testMetaSchema,
|
||||
extract,
|
||||
);
|
||||
}
|
||||
@ -1,13 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"lib": ["ES2022"],
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"noEmit": true,
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["./**/*.ts"]
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user