@igorjpimenta/brayer 0.0.0-stage → 2026.10.28-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.migrations/0000_initial.sql +133 -0
- package/.migrations/0001_awesome_ben_parker.sql +8 -0
- package/.migrations/meta/0000_snapshot.json +931 -0
- package/.migrations/meta/0001_snapshot.json +983 -0
- package/.migrations/meta/_journal.json +20 -0
- package/LICENSE +21 -0
- package/README.md +245 -2
- package/bin/brayer.js +7 -0
- package/package.json +42 -4
- package/plugins/openclaw/brayer/index.js +119 -0
- package/plugins/openclaw/brayer/meta.js +23 -0
- package/plugins/openclaw/brayer/openclaw.plugin.json +14 -0
- package/plugins/openclaw/brayer/package.json +37 -0
- package/plugins/openclaw/brayer/session.js +30 -0
- package/plugins/openclaw/brayer/webhook.js +125 -0
- package/plugins/opencode/brayer/identity.js +11 -0
- package/plugins/opencode/brayer/index.js +92 -0
- package/plugins/opencode/brayer/package.json +27 -0
- package/plugins/opencode/brayer/session.js +25 -0
- package/plugins/shared/contract.js +193 -0
- package/plugins/wake/brayer/bin/brayer-wake.js +7 -0
- package/plugins/wake/brayer/index.js +125 -0
- package/plugins/wake/brayer/package.json +29 -0
- package/src/claim-webhook.js +66 -0
- package/src/cli.js +164 -0
- package/src/config.js +63 -0
- package/src/db.js +24 -0
- package/src/events-ws.js +121 -0
- package/src/evidence.js +42 -0
- package/src/identity.js +32 -0
- package/src/ids.js +17 -0
- package/src/mcp.js +114 -0
- package/src/schema.js +168 -0
- package/src/store/attempts.js +103 -0
- package/src/store/checkpoints.js +76 -0
- package/src/store/claims.js +139 -0
- package/src/store/events.js +24 -0
- package/src/store/evidence.js +67 -0
- package/src/store/orders.js +70 -0
- package/src/store/resume.js +38 -0
- package/src/store/rows.js +118 -0
- package/src/store/util.js +3 -0
- package/src/store/verdicts.js +61 -0
- package/src/store/webhooks.js +56 -0
- package/src/store.js +53 -0
- package/src/tools/attempts.js +75 -0
- package/src/tools/handoff.js +120 -0
- package/src/tools/index.js +28 -0
- package/src/tools/orders.js +146 -0
- package/src/tools/shared.js +7 -0
- package/src/tools/verdicts.js +46 -0
- package/src/version.js +5 -0
package/src/schema.js
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import { sql } from "drizzle-orm";
|
|
2
|
+
import {
|
|
3
|
+
sqliteTable,
|
|
4
|
+
text,
|
|
5
|
+
integer,
|
|
6
|
+
real,
|
|
7
|
+
index,
|
|
8
|
+
check,
|
|
9
|
+
} from "drizzle-orm/sqlite-core";
|
|
10
|
+
|
|
11
|
+
export const ORDER_STATUSES = [
|
|
12
|
+
"draft",
|
|
13
|
+
"ready",
|
|
14
|
+
"claimed",
|
|
15
|
+
"running",
|
|
16
|
+
"review",
|
|
17
|
+
"approved",
|
|
18
|
+
"rejected",
|
|
19
|
+
"blocked",
|
|
20
|
+
"done",
|
|
21
|
+
"cancelled",
|
|
22
|
+
];
|
|
23
|
+
export const APPROVAL_MODES = ["auto", "evidence", "human"];
|
|
24
|
+
export const ATTEMPT_STATUSES = ["running", "finished", "failed", "abandoned"];
|
|
25
|
+
export const EVIDENCE_KINDS = ["diff", "test", "lint", "screenshot", "artifact", "log"];
|
|
26
|
+
export const VERDICT_DECISIONS = ["approve", "reject", "escalate", "rollback"];
|
|
27
|
+
|
|
28
|
+
const inList = (values) => sql.raw(values.map((v) => `'${v}'`).join(", "));
|
|
29
|
+
|
|
30
|
+
export const workOrders = sqliteTable("work_orders", {
|
|
31
|
+
id: text("id").primaryKey(),
|
|
32
|
+
title: text("title").notNull(),
|
|
33
|
+
goal: text("goal").notNull(),
|
|
34
|
+
constraints: text("constraints"),
|
|
35
|
+
acceptance: text("acceptance").notNull(),
|
|
36
|
+
status: text("status").notNull(),
|
|
37
|
+
priority: integer("priority").notNull().default(50),
|
|
38
|
+
workspace: text("workspace"),
|
|
39
|
+
repo: text("repo"),
|
|
40
|
+
branch: text("branch"),
|
|
41
|
+
budgetTokens: integer("budget_tokens"),
|
|
42
|
+
budgetUsd: real("budget_usd"),
|
|
43
|
+
modelPolicy: text("model_policy"),
|
|
44
|
+
approvalMode: text("approval_mode").notNull().default("human"),
|
|
45
|
+
parentId: text("parent_id"),
|
|
46
|
+
assignee: text("assignee"),
|
|
47
|
+
claimExpiresAt: integer("claim_expires_at"),
|
|
48
|
+
leaseSeconds: integer("lease_seconds"),
|
|
49
|
+
lastHeartbeat: integer("last_heartbeat"),
|
|
50
|
+
attemptCount: integer("attempt_count").notNull().default(0),
|
|
51
|
+
createdAt: integer("created_at").notNull(),
|
|
52
|
+
updatedAt: integer("updated_at").notNull(),
|
|
53
|
+
closedAt: integer("closed_at"),
|
|
54
|
+
}, (table) => [
|
|
55
|
+
check("work_orders_status", sql`${table.status} IN (${inList(ORDER_STATUSES)})`),
|
|
56
|
+
check("work_orders_approval_mode", sql`${table.approvalMode} IN (${inList(APPROVAL_MODES)})`),
|
|
57
|
+
index("idx_work_orders_status_priority").on(table.status, table.priority),
|
|
58
|
+
index("idx_work_orders_assignee").on(table.assignee),
|
|
59
|
+
]);
|
|
60
|
+
|
|
61
|
+
export const attempts = sqliteTable("attempts", {
|
|
62
|
+
id: text("id").primaryKey(),
|
|
63
|
+
workOrderId: text("work_order_id").notNull().references(() => workOrders.id, { onDelete: "cascade" }),
|
|
64
|
+
harness: text("harness").notNull(),
|
|
65
|
+
agent: text("agent").notNull(),
|
|
66
|
+
sessionRef: text("session_ref"),
|
|
67
|
+
model: text("model"),
|
|
68
|
+
status: text("status").notNull(),
|
|
69
|
+
startedAt: integer("started_at").notNull(),
|
|
70
|
+
endedAt: integer("ended_at"),
|
|
71
|
+
tokensIn: integer("tokens_in").notNull().default(0),
|
|
72
|
+
tokensOut: integer("tokens_out").notNull().default(0),
|
|
73
|
+
cacheRead: integer("cache_read").notNull().default(0),
|
|
74
|
+
costUsd: real("cost_usd").notNull().default(0),
|
|
75
|
+
toolCalls: integer("tool_calls").notNull().default(0),
|
|
76
|
+
error: text("error"),
|
|
77
|
+
checkpointId: text("checkpoint_id"),
|
|
78
|
+
}, (table) => [
|
|
79
|
+
check("attempts_status", sql`${table.status} IN (${inList(ATTEMPT_STATUSES)})`),
|
|
80
|
+
index("idx_attempts_order").on(table.workOrderId),
|
|
81
|
+
]);
|
|
82
|
+
|
|
83
|
+
export const checkpoints = sqliteTable("checkpoints", {
|
|
84
|
+
id: text("id").primaryKey(),
|
|
85
|
+
workOrderId: text("work_order_id").notNull().references(() => workOrders.id, { onDelete: "cascade" }),
|
|
86
|
+
attemptId: text("attempt_id").notNull().references(() => attempts.id, { onDelete: "cascade" }),
|
|
87
|
+
kind: text("kind").notNull(),
|
|
88
|
+
goal: text("goal"),
|
|
89
|
+
stateJson: text("state_json").notNull(),
|
|
90
|
+
summary: text("summary"),
|
|
91
|
+
confidence: real("confidence"),
|
|
92
|
+
resumeRecipe: text("resume_recipe"),
|
|
93
|
+
treeHash: text("tree_hash"),
|
|
94
|
+
createdAt: integer("created_at").notNull(),
|
|
95
|
+
}, (table) => [
|
|
96
|
+
index("idx_checkpoints_order").on(table.workOrderId),
|
|
97
|
+
index("idx_checkpoints_attempt").on(table.attemptId),
|
|
98
|
+
]);
|
|
99
|
+
|
|
100
|
+
export const evidence = sqliteTable("evidence", {
|
|
101
|
+
id: text("id").primaryKey(),
|
|
102
|
+
workOrderId: text("work_order_id").notNull().references(() => workOrders.id, { onDelete: "cascade" }),
|
|
103
|
+
attemptId: text("attempt_id").notNull().references(() => attempts.id, { onDelete: "cascade" }),
|
|
104
|
+
kind: text("kind").notNull(),
|
|
105
|
+
uri: text("uri").notNull(),
|
|
106
|
+
sha256: text("sha256").notNull(),
|
|
107
|
+
summary: text("summary"),
|
|
108
|
+
command: text("command"),
|
|
109
|
+
exitCode: integer("exit_code"),
|
|
110
|
+
status: text("status"),
|
|
111
|
+
verifier: text("verifier"),
|
|
112
|
+
createdAt: integer("created_at").notNull(),
|
|
113
|
+
}, (table) => [
|
|
114
|
+
check("evidence_kind", sql`${table.kind} IN (${inList(EVIDENCE_KINDS)})`),
|
|
115
|
+
index("idx_evidence_order").on(table.workOrderId),
|
|
116
|
+
index("idx_evidence_attempt").on(table.attemptId),
|
|
117
|
+
]);
|
|
118
|
+
|
|
119
|
+
export const verdicts = sqliteTable("verdicts", {
|
|
120
|
+
id: text("id").primaryKey(),
|
|
121
|
+
workOrderId: text("work_order_id").notNull().references(() => workOrders.id, { onDelete: "cascade" }),
|
|
122
|
+
attemptId: text("attempt_id").references(() => attempts.id, { onDelete: "set null" }),
|
|
123
|
+
decision: text("decision").notNull(),
|
|
124
|
+
reason: text("reason"),
|
|
125
|
+
actor: text("actor").notNull(),
|
|
126
|
+
policy: text("policy"),
|
|
127
|
+
evidenceIds: text("evidence_ids"),
|
|
128
|
+
createdAt: integer("created_at").notNull(),
|
|
129
|
+
}, (table) => [
|
|
130
|
+
check("verdicts_decision", sql`${table.decision} IN (${inList(VERDICT_DECISIONS)})`),
|
|
131
|
+
index("idx_verdicts_order").on(table.workOrderId),
|
|
132
|
+
]);
|
|
133
|
+
|
|
134
|
+
export const playbooks = sqliteTable("playbooks", {
|
|
135
|
+
id: text("id").primaryKey(),
|
|
136
|
+
name: text("name").notNull(),
|
|
137
|
+
version: integer("version").notNull().default(1),
|
|
138
|
+
trigger: text("trigger"),
|
|
139
|
+
procedure: text("procedure").notNull(),
|
|
140
|
+
provenance: text("provenance"),
|
|
141
|
+
evalScore: real("eval_score"),
|
|
142
|
+
status: text("status").notNull().default("draft"),
|
|
143
|
+
createdAt: integer("created_at").notNull(),
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
export const webhookTargets = sqliteTable("webhook_targets", {
|
|
147
|
+
harness: text("harness").primaryKey(),
|
|
148
|
+
url: text("url").notNull(),
|
|
149
|
+
bearer: text("bearer"),
|
|
150
|
+
timeoutMs: integer("timeout_ms"),
|
|
151
|
+
createdAt: integer("created_at").notNull(),
|
|
152
|
+
updatedAt: integer("updated_at").notNull(),
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
export const events = sqliteTable("events", {
|
|
156
|
+
id: integer("id").primaryKey({ autoIncrement: true }),
|
|
157
|
+
workOrderId: text("work_order_id").notNull().references(() => workOrders.id, { onDelete: "cascade" }),
|
|
158
|
+
attemptId: text("attempt_id"),
|
|
159
|
+
fromStatus: text("from_status"),
|
|
160
|
+
toStatus: text("to_status"),
|
|
161
|
+
kind: text("kind"),
|
|
162
|
+
actor: text("actor"),
|
|
163
|
+
note: text("note"),
|
|
164
|
+
sessionRef: text("session_ref"),
|
|
165
|
+
at: integer("at").notNull(),
|
|
166
|
+
}, (table) => [
|
|
167
|
+
index("idx_events_order").on(table.workOrderId),
|
|
168
|
+
]);
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { newAttemptId } from "../ids.js";
|
|
2
|
+
import { now } from "./util.js";
|
|
3
|
+
import { rowAttempt } from "./rows.js";
|
|
4
|
+
|
|
5
|
+
export function createAttemptApi({ db, insertEvent, orderApi }) {
|
|
6
|
+
const attemptApi = {
|
|
7
|
+
get(id) {
|
|
8
|
+
return rowAttempt(db.prepare("SELECT * FROM attempts WHERE id=?").get(id));
|
|
9
|
+
},
|
|
10
|
+
|
|
11
|
+
list({ workOrderId, status } = {}) {
|
|
12
|
+
const where = [];
|
|
13
|
+
const args = [];
|
|
14
|
+
if (workOrderId) { where.push("work_order_id=?"); args.push(workOrderId); }
|
|
15
|
+
if (status) { where.push("status=?"); args.push(status); }
|
|
16
|
+
const sql = `SELECT * FROM attempts${where.length ? ` WHERE ${where.join(" AND ")}` : ""} ORDER BY started_at ASC`;
|
|
17
|
+
return db.prepare(sql).all(...args).map(rowAttempt);
|
|
18
|
+
},
|
|
19
|
+
|
|
20
|
+
start({ workOrderId, harness, agent, sessionRef = null, model = null } = {}) {
|
|
21
|
+
if (!workOrderId) throw new Error("workOrderId is required");
|
|
22
|
+
if (!harness) throw new Error("harness is required");
|
|
23
|
+
if (!agent) throw new Error("agent is required");
|
|
24
|
+
const t = now();
|
|
25
|
+
db.exec("BEGIN IMMEDIATE");
|
|
26
|
+
try {
|
|
27
|
+
const order = orderApi.get(workOrderId);
|
|
28
|
+
if (!order) { db.exec("ROLLBACK"); return { attempt: null, order: null, reason: "not_found" }; }
|
|
29
|
+
const live = db.prepare("SELECT id FROM attempts WHERE work_order_id=? AND status='running'").get(workOrderId);
|
|
30
|
+
if (live) { db.exec("ROLLBACK"); return { attempt: rowAttempt(db.prepare("SELECT * FROM attempts WHERE id=?").get(live.id)), order, reason: "already_running" }; }
|
|
31
|
+
if (order.status !== "claimed") { db.exec("ROLLBACK"); return { attempt: null, order, reason: "not_claimed" }; }
|
|
32
|
+
if (order.assignee !== agent) { db.exec("ROLLBACK"); return { attempt: null, order, reason: "assigned_elsewhere" }; }
|
|
33
|
+
|
|
34
|
+
const id = newAttemptId();
|
|
35
|
+
db.prepare(`
|
|
36
|
+
INSERT INTO attempts(id, work_order_id, harness, agent, session_ref, model, status, started_at)
|
|
37
|
+
VALUES (?, ?, ?, ?, ?, ?, 'running', ?)
|
|
38
|
+
`).run(id, workOrderId, harness, agent, sessionRef, model, t);
|
|
39
|
+
db.prepare("UPDATE work_orders SET status='running', updated_at=? WHERE id=? AND status='claimed'").run(t, workOrderId);
|
|
40
|
+
insertEvent({
|
|
41
|
+
workOrderId, attemptId: id, fromStatus: "claimed", toStatus: "running", kind: "attempt.started",
|
|
42
|
+
actor: agent, note: "attempt started", sessionRef, at: t,
|
|
43
|
+
});
|
|
44
|
+
db.exec("COMMIT");
|
|
45
|
+
return { attempt: attemptApi.get(id), order: orderApi.get(workOrderId), reason: null };
|
|
46
|
+
} catch (err) {
|
|
47
|
+
db.exec("ROLLBACK");
|
|
48
|
+
throw err;
|
|
49
|
+
}
|
|
50
|
+
},
|
|
51
|
+
|
|
52
|
+
finish({
|
|
53
|
+
attemptId,
|
|
54
|
+
status,
|
|
55
|
+
summary = null,
|
|
56
|
+
tokensIn = 0,
|
|
57
|
+
tokensOut = 0,
|
|
58
|
+
cacheRead = 0,
|
|
59
|
+
costUsd = 0,
|
|
60
|
+
toolCalls = 0,
|
|
61
|
+
error = null,
|
|
62
|
+
checkpointId = null,
|
|
63
|
+
} = {}) {
|
|
64
|
+
if (!attemptId) throw new Error("attemptId is required");
|
|
65
|
+
if (status !== "finished" && status !== "failed") throw new Error("status must be finished or failed");
|
|
66
|
+
const t = now();
|
|
67
|
+
db.exec("BEGIN IMMEDIATE");
|
|
68
|
+
try {
|
|
69
|
+
const attempt = attemptApi.get(attemptId);
|
|
70
|
+
if (!attempt) { db.exec("ROLLBACK"); return { attempt: null, order: null, reason: "not_found" }; }
|
|
71
|
+
if (attempt.status !== "running") { db.exec("ROLLBACK"); return { attempt, order: orderApi.get(attempt.workOrderId), reason: "not_running" }; }
|
|
72
|
+
|
|
73
|
+
db.prepare(`
|
|
74
|
+
UPDATE attempts
|
|
75
|
+
SET status=?, ended_at=?, tokens_in=?, tokens_out=?, cache_read=?, cost_usd=?,
|
|
76
|
+
tool_calls=?, error=?, checkpoint_id=?
|
|
77
|
+
WHERE id=? AND status='running'
|
|
78
|
+
`).run(status, t, tokensIn, tokensOut, cacheRead, costUsd, toolCalls, error, checkpointId, attemptId);
|
|
79
|
+
|
|
80
|
+
const order = orderApi.get(attempt.workOrderId);
|
|
81
|
+
const nextStatus = status === "finished" ? "review" : "ready";
|
|
82
|
+
db.prepare(`
|
|
83
|
+
UPDATE work_orders
|
|
84
|
+
SET status=?, assignee=?, claim_expires_at=NULL, lease_seconds=NULL, last_heartbeat=NULL, updated_at=?
|
|
85
|
+
WHERE id=? AND status='running'
|
|
86
|
+
`).run(nextStatus, status === "finished" ? order.assignee : null, t, attempt.workOrderId);
|
|
87
|
+
|
|
88
|
+
insertEvent({
|
|
89
|
+
workOrderId: attempt.workOrderId, attemptId, fromStatus: "running", toStatus: nextStatus,
|
|
90
|
+
kind: status === "finished" ? "attempt.finished" : "attempt.failed",
|
|
91
|
+
actor: attempt.agent, note: summary ?? error ?? status, sessionRef: attempt.sessionRef, at: t,
|
|
92
|
+
});
|
|
93
|
+
db.exec("COMMIT");
|
|
94
|
+
return { attempt: attemptApi.get(attemptId), order: orderApi.get(attempt.workOrderId), reason: null };
|
|
95
|
+
} catch (err) {
|
|
96
|
+
db.exec("ROLLBACK");
|
|
97
|
+
throw err;
|
|
98
|
+
}
|
|
99
|
+
},
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
return attemptApi;
|
|
103
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { newCheckpointId } from "../ids.js";
|
|
2
|
+
import { now } from "./util.js";
|
|
3
|
+
import { rowCheckpoint } from "./rows.js";
|
|
4
|
+
|
|
5
|
+
export function createCheckpointApi({ db, insertEvent, attemptApi }) {
|
|
6
|
+
const checkpointApi = {
|
|
7
|
+
get(id) {
|
|
8
|
+
return rowCheckpoint(db.prepare("SELECT * FROM checkpoints WHERE id=?").get(id));
|
|
9
|
+
},
|
|
10
|
+
|
|
11
|
+
latest({ workOrderId, attemptId } = {}) {
|
|
12
|
+
if (!workOrderId && !attemptId) throw new Error("workOrderId or attemptId is required");
|
|
13
|
+
const sql = attemptId
|
|
14
|
+
? "SELECT * FROM checkpoints WHERE attempt_id=? ORDER BY created_at DESC, rowid DESC LIMIT 1"
|
|
15
|
+
: "SELECT * FROM checkpoints WHERE work_order_id=? ORDER BY created_at DESC, rowid DESC LIMIT 1";
|
|
16
|
+
return rowCheckpoint(db.prepare(sql).get(attemptId ?? workOrderId));
|
|
17
|
+
},
|
|
18
|
+
|
|
19
|
+
list({ workOrderId, attemptId } = {}) {
|
|
20
|
+
const where = [];
|
|
21
|
+
const args = [];
|
|
22
|
+
if (workOrderId) { where.push("work_order_id=?"); args.push(workOrderId); }
|
|
23
|
+
if (attemptId) { where.push("attempt_id=?"); args.push(attemptId); }
|
|
24
|
+
const sql = `SELECT * FROM checkpoints${where.length ? ` WHERE ${where.join(" AND ")}` : ""} ORDER BY created_at ASC, rowid ASC`;
|
|
25
|
+
return db.prepare(sql).all(...args).map(rowCheckpoint);
|
|
26
|
+
},
|
|
27
|
+
|
|
28
|
+
write({
|
|
29
|
+
workOrderId,
|
|
30
|
+
attemptId,
|
|
31
|
+
kind = "manual",
|
|
32
|
+
goal = null,
|
|
33
|
+
state,
|
|
34
|
+
summary = null,
|
|
35
|
+
confidence = null,
|
|
36
|
+
resumeRecipe = null,
|
|
37
|
+
treeHash,
|
|
38
|
+
actor = "system",
|
|
39
|
+
} = {}) {
|
|
40
|
+
if (!workOrderId) throw new Error("workOrderId is required");
|
|
41
|
+
if (!attemptId) throw new Error("attemptId is required");
|
|
42
|
+
if (!state || typeof state !== "object" || Array.isArray(state)) throw new Error("state must be an object");
|
|
43
|
+
if (typeof treeHash !== "string" || !treeHash.trim()) throw new Error("treeHash is required");
|
|
44
|
+
if (confidence != null && (typeof confidence !== "number" || confidence < 0 || confidence > 1)) {
|
|
45
|
+
throw new Error("confidence must be between 0 and 1");
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const attempt = attemptApi.get(attemptId);
|
|
49
|
+
if (!attempt) throw new Error(`attempt not found: ${attemptId}`);
|
|
50
|
+
if (attempt.workOrderId !== workOrderId) throw new Error("attempt does not belong to the order");
|
|
51
|
+
if (attempt.status !== "running") throw new Error("checkpoint requires a running attempt");
|
|
52
|
+
|
|
53
|
+
const t = now();
|
|
54
|
+
const id = newCheckpointId();
|
|
55
|
+
db.exec("BEGIN IMMEDIATE");
|
|
56
|
+
try {
|
|
57
|
+
db.prepare(`
|
|
58
|
+
INSERT INTO checkpoints(id, work_order_id, attempt_id, kind, goal, state_json, summary, confidence, resume_recipe, tree_hash, created_at)
|
|
59
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
60
|
+
`).run(id, workOrderId, attemptId, kind, goal, JSON.stringify(state), summary, confidence, resumeRecipe, treeHash, t);
|
|
61
|
+
db.prepare("UPDATE attempts SET checkpoint_id=? WHERE id=?").run(id, attemptId);
|
|
62
|
+
insertEvent({
|
|
63
|
+
workOrderId, attemptId, fromStatus: "running", toStatus: "running", kind: "checkpoint.written",
|
|
64
|
+
actor, note: summary ?? kind, sessionRef: attempt.sessionRef, at: t,
|
|
65
|
+
});
|
|
66
|
+
db.exec("COMMIT");
|
|
67
|
+
} catch (err) {
|
|
68
|
+
db.exec("ROLLBACK");
|
|
69
|
+
throw err;
|
|
70
|
+
}
|
|
71
|
+
return checkpointApi.get(id);
|
|
72
|
+
},
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
return checkpointApi;
|
|
76
|
+
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { now } from "./util.js";
|
|
2
|
+
|
|
3
|
+
export function createClaimApi({ db, cfg, insertEvent, orderApi, notifyClaim }) {
|
|
4
|
+
const claimApi = {
|
|
5
|
+
claimById({ id, agentId, sessionRef = null, leaseSeconds = cfg.leaseSeconds } = {}) {
|
|
6
|
+
if (!id) throw new Error("order id is required");
|
|
7
|
+
if (!agentId) throw new Error("agentId is required");
|
|
8
|
+
const t = now();
|
|
9
|
+
const expires = t + leaseSeconds * 1000;
|
|
10
|
+
db.exec("BEGIN IMMEDIATE");
|
|
11
|
+
try {
|
|
12
|
+
const cur = db.prepare("SELECT status, assignee FROM work_orders WHERE id=?").get(id);
|
|
13
|
+
if (!cur) { db.exec("ROLLBACK"); return { claimed: null, reason: "not_found" }; }
|
|
14
|
+
if (cur.status !== "ready") { db.exec("ROLLBACK"); return { claimed: null, reason: "not_ready" }; }
|
|
15
|
+
if (cur.assignee && cur.assignee !== agentId) { db.exec("ROLLBACK"); return { claimed: null, reason: "assigned_elsewhere" }; }
|
|
16
|
+
|
|
17
|
+
const r = db.prepare(`
|
|
18
|
+
UPDATE work_orders
|
|
19
|
+
SET status='claimed', assignee=?, claim_expires_at=?, lease_seconds=?, last_heartbeat=?,
|
|
20
|
+
attempt_count=attempt_count+1, updated_at=?
|
|
21
|
+
WHERE id=? AND status='ready' AND (assignee IS NULL OR assignee=?)
|
|
22
|
+
`).run(agentId, expires, leaseSeconds, t, t, id, agentId);
|
|
23
|
+
if (r.changes === 0) { db.exec("ROLLBACK"); return { claimed: null, reason: "raced" }; }
|
|
24
|
+
|
|
25
|
+
insertEvent({
|
|
26
|
+
workOrderId: id, fromStatus: "ready", toStatus: "claimed", kind: "order.claimed",
|
|
27
|
+
actor: agentId, note: "claim", sessionRef, at: t,
|
|
28
|
+
});
|
|
29
|
+
db.exec("COMMIT");
|
|
30
|
+
const claimed = orderApi.get(id);
|
|
31
|
+
notifyClaim?.({ order: claimed, agentId, sessionRef, at: t });
|
|
32
|
+
return { claimed, reason: null };
|
|
33
|
+
} catch (err) {
|
|
34
|
+
db.exec("ROLLBACK");
|
|
35
|
+
throw err;
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
|
|
39
|
+
claimNext({ agentId, sessionRef = null, leaseSeconds = cfg.leaseSeconds } = {}) {
|
|
40
|
+
if (!agentId) throw new Error("agentId is required");
|
|
41
|
+
const candidates = db.prepare(`
|
|
42
|
+
SELECT id FROM work_orders
|
|
43
|
+
WHERE status='ready' AND (assignee IS NULL OR assignee=?)
|
|
44
|
+
ORDER BY priority DESC, created_at ASC
|
|
45
|
+
LIMIT 10
|
|
46
|
+
`).all(agentId);
|
|
47
|
+
for (const row of candidates) {
|
|
48
|
+
const res = claimApi.claimById({ id: row.id, agentId, sessionRef, leaseSeconds });
|
|
49
|
+
if (res.claimed) return res;
|
|
50
|
+
}
|
|
51
|
+
return { claimed: null, reason: "empty" };
|
|
52
|
+
},
|
|
53
|
+
|
|
54
|
+
heartbeat({ id, agentId, sessionRef = null, leaseSeconds = cfg.leaseSeconds } = {}) {
|
|
55
|
+
if (!id) throw new Error("order id is required");
|
|
56
|
+
if (!agentId) throw new Error("agentId is required");
|
|
57
|
+
const t = now();
|
|
58
|
+
const expires = t + leaseSeconds * 1000;
|
|
59
|
+
const r = db.prepare(`
|
|
60
|
+
UPDATE work_orders
|
|
61
|
+
SET claim_expires_at=?, lease_seconds=?, last_heartbeat=?, updated_at=?
|
|
62
|
+
WHERE id=? AND status='claimed' AND assignee=?
|
|
63
|
+
`).run(expires, leaseSeconds, t, t, id, agentId);
|
|
64
|
+
return r.changes ? orderApi.get(id) : null;
|
|
65
|
+
},
|
|
66
|
+
|
|
67
|
+
release({ id, agentId, actor = "system", reason = "released" } = {}) {
|
|
68
|
+
if (!id) throw new Error("order id is required");
|
|
69
|
+
const t = now();
|
|
70
|
+
db.exec("BEGIN IMMEDIATE");
|
|
71
|
+
try {
|
|
72
|
+
const r = db.prepare(`
|
|
73
|
+
UPDATE work_orders
|
|
74
|
+
SET status='ready', assignee=NULL, claim_expires_at=NULL, lease_seconds=NULL,
|
|
75
|
+
last_heartbeat=NULL, updated_at=?
|
|
76
|
+
WHERE id=? AND status='claimed' AND (? IS NULL OR assignee=?)
|
|
77
|
+
`).run(t, id, agentId ?? null, agentId ?? null);
|
|
78
|
+
if (r.changes === 0) { db.exec("ROLLBACK"); return null; }
|
|
79
|
+
insertEvent({
|
|
80
|
+
workOrderId: id, fromStatus: "claimed", toStatus: "ready", kind: "order.released",
|
|
81
|
+
actor, note: reason, at: t,
|
|
82
|
+
});
|
|
83
|
+
db.exec("COMMIT");
|
|
84
|
+
return orderApi.get(id);
|
|
85
|
+
} catch (err) {
|
|
86
|
+
db.exec("ROLLBACK");
|
|
87
|
+
throw err;
|
|
88
|
+
}
|
|
89
|
+
},
|
|
90
|
+
|
|
91
|
+
sweepExpired({ at = now(), maxAttempts = cfg.maxAttempts } = {}) {
|
|
92
|
+
const expired = db.prepare(`
|
|
93
|
+
SELECT id FROM work_orders
|
|
94
|
+
WHERE status='claimed' AND claim_expires_at IS NOT NULL AND claim_expires_at < ?
|
|
95
|
+
`).all(at);
|
|
96
|
+
let released = 0;
|
|
97
|
+
let blocked = 0;
|
|
98
|
+
for (const row of expired) {
|
|
99
|
+
db.exec("BEGIN IMMEDIATE");
|
|
100
|
+
try {
|
|
101
|
+
const cur = db.prepare("SELECT status, attempt_count FROM work_orders WHERE id=?").get(row.id);
|
|
102
|
+
if (!cur || cur.status !== "claimed") { db.exec("ROLLBACK"); continue; }
|
|
103
|
+
if (cur.attempt_count >= maxAttempts) {
|
|
104
|
+
db.prepare(`
|
|
105
|
+
UPDATE work_orders
|
|
106
|
+
SET status='blocked', assignee=NULL, claim_expires_at=NULL, lease_seconds=NULL,
|
|
107
|
+
last_heartbeat=NULL, updated_at=?
|
|
108
|
+
WHERE id=? AND status='claimed'
|
|
109
|
+
`).run(at, row.id);
|
|
110
|
+
insertEvent({
|
|
111
|
+
workOrderId: row.id, fromStatus: "claimed", toStatus: "blocked", kind: "order.blocked",
|
|
112
|
+
actor: "system", note: `lease expired after ${cur.attempt_count} attempts`, at,
|
|
113
|
+
});
|
|
114
|
+
blocked += 1;
|
|
115
|
+
} else {
|
|
116
|
+
db.prepare(`
|
|
117
|
+
UPDATE work_orders
|
|
118
|
+
SET status='ready', assignee=NULL, claim_expires_at=NULL, lease_seconds=NULL,
|
|
119
|
+
last_heartbeat=NULL, updated_at=?
|
|
120
|
+
WHERE id=? AND status='claimed'
|
|
121
|
+
`).run(at, row.id);
|
|
122
|
+
insertEvent({
|
|
123
|
+
workOrderId: row.id, fromStatus: "claimed", toStatus: "ready", kind: "order.released",
|
|
124
|
+
actor: "system", note: "lease expired", at,
|
|
125
|
+
});
|
|
126
|
+
released += 1;
|
|
127
|
+
}
|
|
128
|
+
db.exec("COMMIT");
|
|
129
|
+
} catch (err) {
|
|
130
|
+
db.exec("ROLLBACK");
|
|
131
|
+
throw err;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return { released, blocked };
|
|
135
|
+
},
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
return claimApi;
|
|
139
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { now } from "./util.js";
|
|
2
|
+
import { rowEvent } from "./rows.js";
|
|
3
|
+
|
|
4
|
+
export function createEventApi({ db }) {
|
|
5
|
+
function insertEvent({ workOrderId, attemptId = null, fromStatus = null, toStatus, kind, actor = "system", note = null, sessionRef = null, at = now() }) {
|
|
6
|
+
const r = db.prepare(`
|
|
7
|
+
INSERT INTO events(work_order_id, attempt_id, from_status, to_status, kind, actor, note, session_ref, at)
|
|
8
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
9
|
+
`).run(workOrderId, attemptId, fromStatus, toStatus, kind, actor, note, sessionRef, at);
|
|
10
|
+
return Number(r.lastInsertRowid);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const eventApi = {
|
|
14
|
+
list({ workOrderId, afterId = 0, limit = 200 } = {}) {
|
|
15
|
+
const sql = workOrderId
|
|
16
|
+
? "SELECT * FROM events WHERE work_order_id=? AND id>? ORDER BY id ASC LIMIT ?"
|
|
17
|
+
: "SELECT * FROM events WHERE id>? ORDER BY id ASC LIMIT ?";
|
|
18
|
+
const args = workOrderId ? [workOrderId, afterId, limit] : [afterId, limit];
|
|
19
|
+
return db.prepare(sql).all(...args).map(rowEvent);
|
|
20
|
+
},
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
return { insertEvent, eventApi };
|
|
24
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { EVIDENCE_KINDS } from "../schema.js";
|
|
2
|
+
import { newEvidenceId } from "../ids.js";
|
|
3
|
+
import { now } from "./util.js";
|
|
4
|
+
import { rowEvidence } from "./rows.js";
|
|
5
|
+
|
|
6
|
+
export function createEvidenceApi({ db, insertEvent, attemptApi }) {
|
|
7
|
+
const evidenceApi = {
|
|
8
|
+
get(id) {
|
|
9
|
+
return rowEvidence(db.prepare("SELECT * FROM evidence WHERE id=?").get(id));
|
|
10
|
+
},
|
|
11
|
+
|
|
12
|
+
list({ workOrderId, attemptId } = {}) {
|
|
13
|
+
const where = [];
|
|
14
|
+
const args = [];
|
|
15
|
+
if (workOrderId) { where.push("work_order_id=?"); args.push(workOrderId); }
|
|
16
|
+
if (attemptId) { where.push("attempt_id=?"); args.push(attemptId); }
|
|
17
|
+
const sql = `SELECT * FROM evidence${where.length ? ` WHERE ${where.join(" AND ")}` : ""} ORDER BY created_at ASC, rowid ASC`;
|
|
18
|
+
return db.prepare(sql).all(...args).map(rowEvidence);
|
|
19
|
+
},
|
|
20
|
+
|
|
21
|
+
attach({
|
|
22
|
+
workOrderId,
|
|
23
|
+
attemptId,
|
|
24
|
+
kind,
|
|
25
|
+
uri,
|
|
26
|
+
sha256,
|
|
27
|
+
summary = null,
|
|
28
|
+
command = null,
|
|
29
|
+
exitCode = null,
|
|
30
|
+
status = null,
|
|
31
|
+
verifier = null,
|
|
32
|
+
actor = "system",
|
|
33
|
+
} = {}) {
|
|
34
|
+
if (!workOrderId) throw new Error("workOrderId is required");
|
|
35
|
+
if (!attemptId) throw new Error("attemptId is required");
|
|
36
|
+
if (!EVIDENCE_KINDS.includes(kind)) throw new Error(`invalid evidence kind: ${kind}`);
|
|
37
|
+
if (!uri) throw new Error("uri is required");
|
|
38
|
+
if (typeof sha256 !== "string" || !/^[a-f0-9]{64}$/.test(sha256)) throw new Error("sha256 must be 64 lowercase hex characters");
|
|
39
|
+
|
|
40
|
+
const attempt = attemptApi.get(attemptId);
|
|
41
|
+
if (!attempt) throw new Error(`attempt not found: ${attemptId}`);
|
|
42
|
+
if (attempt.workOrderId !== workOrderId) throw new Error("attempt does not belong to the order");
|
|
43
|
+
if (attempt.status !== "running") throw new Error("evidence requires a running attempt");
|
|
44
|
+
|
|
45
|
+
const t = now();
|
|
46
|
+
const id = newEvidenceId();
|
|
47
|
+
db.exec("BEGIN IMMEDIATE");
|
|
48
|
+
try {
|
|
49
|
+
db.prepare(`
|
|
50
|
+
INSERT INTO evidence(id, work_order_id, attempt_id, kind, uri, sha256, summary, command, exit_code, status, verifier, created_at)
|
|
51
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
52
|
+
`).run(id, workOrderId, attemptId, kind, uri, sha256, summary, command, exitCode, status, verifier, t);
|
|
53
|
+
insertEvent({
|
|
54
|
+
workOrderId, attemptId, fromStatus: "running", toStatus: "running", kind: "evidence.attached",
|
|
55
|
+
actor, note: summary ?? kind, sessionRef: attempt.sessionRef, at: t,
|
|
56
|
+
});
|
|
57
|
+
db.exec("COMMIT");
|
|
58
|
+
} catch (err) {
|
|
59
|
+
db.exec("ROLLBACK");
|
|
60
|
+
throw err;
|
|
61
|
+
}
|
|
62
|
+
return evidenceApi.get(id);
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
return evidenceApi;
|
|
67
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { newOrderId } from "../ids.js";
|
|
2
|
+
import { APPROVAL_MODES, ORDER_STATUSES } from "../schema.js";
|
|
3
|
+
import { jsonOut, now } from "./util.js";
|
|
4
|
+
import { rowOrder } from "./rows.js";
|
|
5
|
+
|
|
6
|
+
export function createOrderApi({ db, insertEvent }) {
|
|
7
|
+
const orderApi = {
|
|
8
|
+
create({
|
|
9
|
+
id,
|
|
10
|
+
title,
|
|
11
|
+
goal,
|
|
12
|
+
constraints = null,
|
|
13
|
+
acceptance,
|
|
14
|
+
status = "draft",
|
|
15
|
+
priority = 50,
|
|
16
|
+
workspace = null,
|
|
17
|
+
repo = null,
|
|
18
|
+
branch = null,
|
|
19
|
+
budgetTokens = null,
|
|
20
|
+
budgetUsd = null,
|
|
21
|
+
modelPolicy = null,
|
|
22
|
+
approvalMode = "human",
|
|
23
|
+
parentId = null,
|
|
24
|
+
actor = "system",
|
|
25
|
+
} = {}) {
|
|
26
|
+
if (!title || !title.trim()) throw new Error("title is required");
|
|
27
|
+
if (!goal || !goal.trim()) throw new Error("goal is required");
|
|
28
|
+
if (!acceptance || !acceptance.trim()) throw new Error("acceptance is required");
|
|
29
|
+
if (!ORDER_STATUSES.includes(status)) throw new Error(`invalid order status: ${status}`);
|
|
30
|
+
if (!APPROVAL_MODES.includes(approvalMode)) throw new Error(`invalid approval mode: ${approvalMode}`);
|
|
31
|
+
|
|
32
|
+
const orderId = id || newOrderId();
|
|
33
|
+
const t = now();
|
|
34
|
+
db.exec("BEGIN IMMEDIATE");
|
|
35
|
+
try {
|
|
36
|
+
db.prepare(`
|
|
37
|
+
INSERT INTO work_orders(
|
|
38
|
+
id, title, goal, constraints, acceptance, status, priority, workspace, repo, branch,
|
|
39
|
+
budget_tokens, budget_usd, model_policy, approval_mode, parent_id,
|
|
40
|
+
created_at, updated_at
|
|
41
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
42
|
+
`).run(
|
|
43
|
+
orderId, title.trim(), goal.trim(), constraints, acceptance.trim(), status, priority,
|
|
44
|
+
workspace, repo, branch, budgetTokens, budgetUsd, jsonOut(modelPolicy), approvalMode,
|
|
45
|
+
parentId, t, t
|
|
46
|
+
);
|
|
47
|
+
insertEvent({ workOrderId: orderId, toStatus: status, kind: "order.created", actor, note: "order created", at: t });
|
|
48
|
+
db.exec("COMMIT");
|
|
49
|
+
} catch (err) {
|
|
50
|
+
db.exec("ROLLBACK");
|
|
51
|
+
throw err;
|
|
52
|
+
}
|
|
53
|
+
return orderApi.get(orderId);
|
|
54
|
+
},
|
|
55
|
+
|
|
56
|
+
get(id) {
|
|
57
|
+
return rowOrder(db.prepare("SELECT * FROM work_orders WHERE id=?").get(id));
|
|
58
|
+
},
|
|
59
|
+
|
|
60
|
+
list({ status, limit = 100 } = {}) {
|
|
61
|
+
const sql = status
|
|
62
|
+
? "SELECT * FROM work_orders WHERE status=? ORDER BY priority DESC, created_at ASC LIMIT ?"
|
|
63
|
+
: "SELECT * FROM work_orders ORDER BY priority DESC, created_at ASC LIMIT ?";
|
|
64
|
+
const args = status ? [status, limit] : [limit];
|
|
65
|
+
return db.prepare(sql).all(...args).map(rowOrder);
|
|
66
|
+
},
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
return orderApi;
|
|
70
|
+
}
|