Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/daemon/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "ework-daemon",
"version": "0.4.217",
"version": "0.4.220",
"description": "Issue-driven AI development daemon. Spawns opencode subprocesses to resolve Gitea issues.",
"module": "src/index.ts",
"type": "module",
Expand Down
13 changes: 13 additions & 0 deletions packages/daemon/src/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,7 @@ async function runMigrations(db: AsyncDatabase): Promise<void> {
title TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
dispatch_priority INTEGER NOT NULL DEFAULT 0,
UNIQUE(tracker_type, tracker_scope_key, tracker_issue_id)
)`,
mysqlCreate: `CREATE TABLE ${tIssues} (
Expand All @@ -420,6 +421,7 @@ async function runMigrations(db: AsyncDatabase): Promise<void> {
title VARCHAR(512) NOT NULL DEFAULT '',
created_at VARCHAR(40) NOT NULL,
updated_at VARCHAR(40) NOT NULL,
dispatch_priority INT NOT NULL DEFAULT 0,
UNIQUE (tracker_type, tracker_scope_key, tracker_issue_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
oldCols:
Expand Down Expand Up @@ -551,6 +553,17 @@ async function runMigrations(db: AsyncDatabase): Promise<void> {
sqlite ? "reset_at INTEGER NOT NULL DEFAULT 0" : "reset_at BIGINT NOT NULL DEFAULT 0"
);

// issues.dispatch_priority — 1 = top-of-queue for the global drain
// (owner policy 2026-11-12: root-cause aggregation issues run ahead of the
// FIFO backlog). The classifier board re-stamps the live set every round via
// POST /api/admin/boost; stale flags are harmless (closed issues hold no
// pending messages).
await ensureColumn(
tIssues,
"dispatch_priority",
sqlite ? "dispatch_priority INTEGER NOT NULL DEFAULT 0" : "dispatch_priority INT NOT NULL DEFAULT 0"
);

// op_sessions runtime-state columns (previously in-memory Maps; now persisted
// so a restarted daemon can recover the nudge/generation state).
await ensureColumn(tSessions, "last_output_at", "last_output_at VARCHAR(40)");
Expand Down
22 changes: 20 additions & 2 deletions packages/daemon/src/op.ts
Original file line number Diff line number Diff line change
Expand Up @@ -399,7 +399,11 @@ export class Store {
const rows = this.projectPriorities.length > 0
? await this.priorityOrderedPending(now, limit)
: await getDB().all<MessageRow>(
`SELECT * FROM {{messages}} WHERE status = 'pending' AND ${Store.RETRY_HOLD_SQL} ORDER BY created_at ASC LIMIT ?`,
`SELECT m.* FROM {{messages}} m
JOIN {{op_sessions}} s ON s.uid = m.session_id
JOIN {{issues}} i ON i.uid = s.issue_id
WHERE m.status = 'pending' AND (m.retry_after IS NULL OR m.retry_after <= ?)
ORDER BY COALESCE(i.dispatch_priority, 0) DESC, m.created_at ASC LIMIT ?`,
[now, limit]
);
return rows.map(rowToMessage);
Expand All @@ -426,13 +430,27 @@ export class Store {
JOIN {{op_sessions}} s ON s.uid = m.session_id
JOIN {{issues}} i ON i.uid = s.issue_id
WHERE m.status = 'pending' AND (m.retry_after IS NULL OR m.retry_after <= ?)
ORDER BY m.created_at ASC,
ORDER BY COALESCE(i.dispatch_priority, 0) DESC, m.created_at ASC,
CASE ${whens.join(" ")} ELSE 0 END DESC
LIMIT ?`,
[nowIso, ...caseParams, limit]
);
}

/** Set the drain-dispatch priority of mirror issues (admin boost endpoint;
* the classifier board re-stamps the root-cause aggregation set every
* round). Tracker ids only, like stop-work. Returns rows updated. */
async setIssueDispatchPriority(trackerIssueIds: string[], priority: number): Promise<number> {
const ids = [...new Set(trackerIssueIds)];
if (ids.length === 0) return 0;
const ph = ids.map(() => "?").join(",");
const res = await getDB().run(
`UPDATE {{issues}} SET dispatch_priority = ?, updated_at = ? WHERE tracker_issue_id IN (${ph})`,
[priority, new Date().toISOString(), ...ids]
);
return res.changes;
}

async bumpMessageAttempts(id: string): Promise<void> {
await getDB().run("UPDATE {{messages}} SET attempts = attempts + 1, updated_at = ? WHERE uid = ?", [
new Date().toISOString(),
Expand Down
18 changes: 18 additions & 0 deletions packages/daemon/src/opencode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4222,6 +4222,11 @@ Check states: read the mirror cache (see AGENTS.md), do not poll gh for check st
`If it's empty, clone the repo: \`${instructions.clone}\``,
``,
`Read the issue, work on it, and reply via the \`reply\` tool — every reply starts with \`[bot] 🏷\`. Post the reply as soon as possible, then continue working if needed.`,
// 8-question contract must be in the INITIAL prompt too (owner 2026-11-13):
// [根因]/[Root Cause] aggregation tickets are dispatched by issue_opened —
// the forward/nudge-only injection meant the worker's main run never saw
// the verdict format (2026-11-12: RC threads answered with a bare 结论).
this.rcEightQuestionRule(title),
].filter(Boolean).join("\n");
}

Expand Down Expand Up @@ -4343,6 +4348,19 @@ Check states: read the mirror cache (see AGENTS.md), do not poll gh for check st
return { issues, killed, superseded };
}

/** Mark mirror issues top-of-queue for the global drain (owner policy
* 2026-11-12: root-cause aggregation issues run ahead of the FIFO
* backlog). Idempotent stamp — the classifier board re-applies the
* current set every round; a stale flag is harmless (a closed issue
* holds no pending messages). */
async boostIssueWork(mirrorIssueIds: string[]): Promise<{ issues: number }> {
const set = await this.store.setIssueDispatchPriority(mirrorIssueIds, 1);
if (set > 0) {
log.info(`engine: boost — ${set} issue(s) marked top-of-queue`);
}
return { issues: set };
}

private buildForwardPrompt(
opName: string,
commentBody: string,
Expand Down
9 changes: 9 additions & 0 deletions packages/daemon/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,15 @@ export function createServer(
const report = await engine.stopIssueWork(ids.map(String));
return json({ ok: true, ...report });
}
if (pathname === "/api/admin/boost" && req.method === "POST") {
const body = await req.json().catch(() => ({} as unknown));
const ids = (body as { issue_ids?: unknown })?.issue_ids;
if (!Array.isArray(ids) || ids.length === 0 || ids.some((x) => typeof x !== "string" && typeof x !== "number")) {
return json({ error: "issue_ids must be a non-empty array of mirror issue ids" }, 400);
}
const report = await engine.boostIssueWork(ids.map(String));
return json({ ok: true, ...report });
}

return json({ error: "not found" }, 404);
}
Expand Down
23 changes: 23 additions & 0 deletions packages/daemon/tests/incorporated-stop.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,4 +142,27 @@ describe("incorporated-issue auto-stop (owner policy 2026-11-12)", () => {
expect(Engine.prototype.rcEightQuestionRule.call(self, "普通 issue 标题")).toBe("");
expect(Engine.prototype.rcEightQuestionRule.call(self, undefined)).toBe("");
});

test("initial prompt carries the 8问 contract for [Root Cause] tickets (issue_opened path)", () => {
// RC aggregations are dispatched by issue_opened — the worker's first run
// only ever saw the forward/nudge rules, which is why 2026-11-13 RC threads
// answered with a bare 结论 and no 8-question verdict (owner: 「我发现root的8问没有了」).
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const self = Object.create(Engine.prototype) as Record<string, any>;
self.cfg = { daemon: { wakeLogins: [], noWakeLogins: [], nonWakingAuthors: [] } };
const args = ["body", "ranxianglei", "/w", { clone: "git clone x .", issueRef: "o/r#6453" }] as const;
const rcPrompt = Engine.prototype.buildInitialPrompt.call(
self, "bot", "[Root Cause] compression cache eviction (6 items)", ...args,
) as string;
expect(rcPrompt).toContain("8-question checklist");
expect(rcPrompt).toContain("待验证");
const zhPrompt = Engine.prototype.buildInitialPrompt.call(
self, "bot", "[根因] 压缩链路三连断(6090/6091/6092)", ...args,
) as string;
expect(zhPrompt).toContain("8-question checklist");
const plainPrompt = Engine.prototype.buildInitialPrompt.call(
self, "bot", "普通 issue 标题", ...args,
) as string;
expect(plainPrompt).not.toContain("8-question checklist");
});
});
136 changes: 136 additions & 0 deletions packages/daemon/tests/rc-boost.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import { beforeAll, beforeEach, describe, expect, it } from "bun:test";
import { Store } from "../src/op";
import { getDB, initDB } from "../src/db";
import type { TrackerRef } from "../src/trackers/types";

// Owner policy 2026-11-12: root-cause aggregation issues run AHEAD of the
// normal FIFO backlog (their member work is suppressed, so waiting on the
// tail wastes hours while the whole batch idles). The classifier board
// re-stamps the live set via POST /api/admin/boost every round; the drain
// orders dispatch_priority DESC before created_at.
beforeAll(async () => {
await initDB();
});

beforeEach(async () => {
const db = getDB();
const mysql = db.dialect === "mysql";
await db.exec(mysql ? "SET FOREIGN_KEY_CHECKS = 0" : "PRAGMA foreign_keys = OFF");
for (const t of ["messages", "op_sessions", "issues"]) {
await db.exec(`DELETE FROM {{${t}}}`);
}
await db.exec(mysql ? "SET FOREIGN_KEY_CHECKS = 1" : "PRAGMA foreign_keys = ON");
});

function ref(issueId: string, scopeKey: string): TrackerRef {
const [owner, repo] = scopeKey.split("/");
return { trackerType: "gitea", scope: { owner: owner!, repo: repo! }, issueId };
}

async function seedPending(scopeKey: string, issueNum: string, createdAt: string): Promise<string> {
const store = new Store();
const issue = await store.findOrCreateIssue(ref(issueNum, scopeKey), scopeKey, "t");
const session = await store.createSession(issue.id, "ework");
const msg = await store.createMessage(session.id, `msg ${scopeKey}#${issueNum}`);
await getDB().run("UPDATE {{messages}} SET created_at = ? WHERE uid = ?", [createdAt, msg.id]);
await store.close();
return msg.id;
}

async function pendingOrder(store: Store): Promise<string[]> {
return (await store.getGlobalPendingMessages(10)).map((m) => m.content);
}

describe("setIssueDispatchPriority", () => {
it("stamps by mirror tracker id and reports rows updated", async () => {
const store = new Store();
await seedPending("a/b", "7", "2026-11-12T10:00:00.000Z");
expect(await store.setIssueDispatchPriority(["7"], 1)).toBe(1);
const row = await getDB().get<{ p: number }>(
`SELECT dispatch_priority AS p FROM {{issues}} WHERE tracker_issue_id = '7'`
);
expect(row?.p).toBe(1);
// idempotent re-stamp (the board calls this every round)
expect(await store.setIssueDispatchPriority(["7", "7"], 1)).toBe(1);
// unknown ids change nothing, never throw
expect(await store.setIssueDispatchPriority(["nope"], 1)).toBe(0);
// text ids only: '645' must not match issue '6453'
await seedPending("a/b", "6453", "2026-11-12T10:00:00.000Z");
expect(await store.setIssueDispatchPriority(["645"], 1)).toBe(0);
const row6453 = await getDB().get<{ p: number }>(
`SELECT dispatch_priority AS p FROM {{issues}} WHERE tracker_issue_id = '6453'`
);
expect(row6453?.p).toBe(0);
await store.close();
});

it("empty list is a no-op", async () => {
const store = new Store();
expect(await store.setIssueDispatchPriority([], 1)).toBe(0);
await store.close();
});
});

describe("global drain ordering (pure FIFO branch, no project priorities)", () => {
it("boosted issue jumps an OLDER unboosted message", async () => {
const store = new Store();
// old normal message first in FIFO ...
await seedPending("a/b", "100", "2026-11-10T00:00:00.000Z");
// ... then a newer RC message that gets stamped.
await seedPending("a/b", "6442", "2026-11-12T23:00:00.000Z");
expect(await pendingOrder(store)).toEqual([
"msg a/b#100",
"msg a/b#6442",
]);
await store.setIssueDispatchPriority(["6442"], 1);
expect(await pendingOrder(store)).toEqual([
"msg a/b#6442",
"msg a/b#100",
]);
await store.close();
});

it("within the same priority bucket the FIFO order holds", async () => {
const store = new Store();
await seedPending("a/b", "6442", "2026-11-12T01:00:00.000Z");
await seedPending("a/b", "6443", "2026-11-12T02:00:00.000Z");
await store.setIssueDispatchPriority(["6442", "6443"], 1);
expect(await pendingOrder(store)).toEqual([
"msg a/b#6442",
"msg a/b#6443",
]);
await store.close();
});

it("unboosted rows keep strict FIFO after a boost elsewhere", async () => {
const store = new Store();
await seedPending("a/b", "1", "2026-11-12T01:00:00.000Z");
await seedPending("a/b", "2", "2026-11-12T02:00:00.000Z");
await seedPending("a/b", "3", "2026-11-12T03:00:00.000Z");
await store.setIssueDispatchPriority(["2"], 1);
expect(await pendingOrder(store)).toEqual([
"msg a/b#2",
"msg a/b#1",
"msg a/b#3",
]);
await store.close();
});
});

describe("global drain ordering (WORK_PROJECT_PRIORITIES branch)", () => {
it("issue dispatch priority outranks both age AND project priority", async () => {
const store = new Store([
{ scope: "low/repo", priority: 100 },
]);
// oldest + highest project priority ...
await seedPending("low/repo", "9", "2026-11-01T00:00:00.000Z");
// ... still loses to a newer stamped RC message.
await seedPending("other/repo", "6442", "2026-11-12T23:00:00.000Z");
await store.setIssueDispatchPriority(["6442"], 1);
expect(await pendingOrder(store)).toEqual([
"msg other/repo#6442",
"msg low/repo#9",
]);
await store.close();
});
});
Loading
Loading