@igorjpimenta/winch 0.0.0-stage → 2026.11.22-beta.2
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_next_katie_power.sql +99 -0
- package/.migrations/0001_add-events-kind.sql +8 -0
- package/.migrations/0002_drop-session-budgets.sql +1 -0
- package/.migrations/0003_pink_siren.sql +8 -0
- package/.migrations/0004_salty_trauma.sql +1 -0
- package/.migrations/0005_classy_havok.sql +1 -0
- package/.migrations/0006_recursive_items.sql +265 -0
- package/.migrations/0007_unify_statuses.sql +35 -0
- package/.migrations/0008_core_dispatch.sql +61 -0
- package/.migrations/0009_webhooks.sql +17 -0
- package/.migrations/0010_dispatch_consumer_id.sql +1 -0
- package/.migrations/0011_dispatch_delivery_leases.sql +53 -0
- package/.migrations/0012_dispatch_fencing_audit.sql +32 -0
- package/.migrations/meta/0000_snapshot.json +658 -0
- package/.migrations/meta/0001_snapshot.json +665 -0
- package/.migrations/meta/0002_snapshot.json +604 -0
- package/.migrations/meta/0003_snapshot.json +656 -0
- package/.migrations/meta/0004_snapshot.json +664 -0
- package/.migrations/meta/0005_snapshot.json +671 -0
- package/.migrations/meta/0006_snapshot.json +1089 -0
- package/.migrations/meta/0007_unify_statuses_snapshot.json +1097 -0
- package/.migrations/meta/0008_snapshot.json +1382 -0
- package/.migrations/meta/0009_snapshot.json +1428 -0
- package/.migrations/meta/0010_snapshot.json +1435 -0
- package/.migrations/meta/0011_snapshot.json +1670 -0
- package/.migrations/meta/0012_snapshot.json +1900 -0
- package/.migrations/meta/_journal.json +97 -0
- package/README.md +480 -2
- package/bin/winch.js +4 -0
- package/package.json +36 -4
- package/plugins/README.md +304 -0
- package/plugins/openclaw/winch/README.md +71 -0
- package/plugins/openclaw/winch/dispatch.js +236 -0
- package/plugins/openclaw/winch/index.js +139 -0
- package/plugins/openclaw/winch/meta.js +35 -0
- package/plugins/openclaw/winch/openclaw.plugin.json +43 -0
- package/plugins/openclaw/winch/package.json +37 -0
- package/plugins/opencode/winch/dispatch.js +228 -0
- package/plugins/opencode/winch/hooks.js +22 -0
- package/plugins/opencode/winch/identity.js +34 -0
- package/plugins/opencode/winch/index.js +104 -0
- package/plugins/opencode/winch/package.json +26 -0
- package/src/cli.js +434 -0
- package/src/config.js +181 -0
- package/src/db.js +39 -0
- package/src/deps.js +70 -0
- package/src/dispatch-server.js +204 -0
- package/src/dispatch-webhook.js +221 -0
- package/src/dispatch.js +258 -0
- package/src/events-ws.js +269 -0
- package/src/identity.js +140 -0
- package/src/ids.js +18 -0
- package/src/mcp-http.js +208 -0
- package/src/mcp.js +107 -0
- package/src/merges.js +150 -0
- package/src/paths.js +15 -0
- package/src/ready-queue.js +77 -0
- package/src/release.js +96 -0
- package/src/reserved.js +23 -0
- package/src/schema.js +302 -0
- package/src/store/admission.js +314 -0
- package/src/store/artifacts.js +24 -0
- package/src/store/attempts.js +22 -0
- package/src/store/claims.js +182 -0
- package/src/store/core.js +225 -0
- package/src/store/delivery.js +137 -0
- package/src/store/deps.js +62 -0
- package/src/store/dispatch-events.js +38 -0
- package/src/store/epics.js +31 -0
- package/src/store/events.js +21 -0
- package/src/store/gates.js +85 -0
- package/src/store/index.js +135 -0
- package/src/store/items.js +303 -0
- package/src/store/stories.js +37 -0
- package/src/store/sweep.js +77 -0
- package/src/store/tasks.js +190 -0
- package/src/store/webhook.js +197 -0
- package/src/tools/accept-wake.js +30 -0
- package/src/tools/assign.js +75 -0
- package/src/tools/claim.js +88 -0
- package/src/tools/definitions.js +371 -0
- package/src/tools/delegate.js +147 -0
- package/src/tools/index.js +44 -0
- package/src/tools/plan.js +262 -0
- package/src/tools/read.js +103 -0
- package/src/tools/report.js +190 -0
- package/src/tools/shared.js +62 -0
- package/src/watcher.js +105 -0
package/src/cli.js
ADDED
|
@@ -0,0 +1,434 @@
|
|
|
1
|
+
// cli.js — winch subcommands over the shared store. Every subcommand that
|
|
2
|
+
// needs the DB resolves it through paths.js: WINCH_DB, else
|
|
3
|
+
// ~/.winch/store.sqlite.
|
|
4
|
+
|
|
5
|
+
import { readFileSync } from "node:fs";
|
|
6
|
+
import crypto from "node:crypto";
|
|
7
|
+
import { parseArgs } from "node:util";
|
|
8
|
+
import { execFileSync } from "node:child_process";
|
|
9
|
+
import { createStore } from "./store/index.js";
|
|
10
|
+
import { readyTasks } from "./ready-queue.js";
|
|
11
|
+
import { tick } from "./watcher.js";
|
|
12
|
+
import { shipRelease } from "./release.js";
|
|
13
|
+
import { collectPRs, applyMergeOutcomes } from "./merges.js";
|
|
14
|
+
import { startMcpServer } from "./mcp.js";
|
|
15
|
+
import { startEventServer } from "./events-ws.js";
|
|
16
|
+
import { startDispatchServer } from "./dispatch-server.js";
|
|
17
|
+
import { declaredFromEnv } from "./identity.js";
|
|
18
|
+
import { resolveDbPath } from "./paths.js";
|
|
19
|
+
|
|
20
|
+
export { resolveDbPath };
|
|
21
|
+
|
|
22
|
+
// stdout is the data channel for every subcommand; diagnostics go to stderr.
|
|
23
|
+
function openStore(explicitConfig) {
|
|
24
|
+
return createStore({ dbPath: resolveDbPath(), config: explicitConfig, notifyDispatch: true });
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// --config takes a JSON object or a path to a JSON file, the way --harness
|
|
28
|
+
// takes a name: explicit object > WINCH_* env > code defaults. Malformed
|
|
29
|
+
// config fails the command, naming the key.
|
|
30
|
+
function loadConfig(values) {
|
|
31
|
+
if (!values.config) return undefined;
|
|
32
|
+
const raw = String(values.config);
|
|
33
|
+
try {
|
|
34
|
+
return JSON.parse(raw);
|
|
35
|
+
} catch {
|
|
36
|
+
try {
|
|
37
|
+
return JSON.parse(readFileSync(raw, "utf8"));
|
|
38
|
+
} catch (err) {
|
|
39
|
+
fail(`winch: --config is neither JSON nor a readable file: ${err?.message ?? err}`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const USAGE = `usage: winch <command>
|
|
45
|
+
|
|
46
|
+
serve --mcp stdio|http [--port N] [--host H]
|
|
47
|
+
serve the backlog tools over MCP stdio or Streamable HTTP
|
|
48
|
+
(stdio harness from WINCH_HARNESS env only; agent+session stamped per call)
|
|
49
|
+
serve --ws --port N [--host H] stream store events over WebSocket
|
|
50
|
+
watch one watcher tick (JSON manifest on stdout)
|
|
51
|
+
resume <taskId> [--actor <name>] resolve a human gate: blocked → ready
|
|
52
|
+
next list the current ready queue
|
|
53
|
+
release-epic --epic <id> [--task ID] [--version V] [--base B]
|
|
54
|
+
merge-detect [--dry-run] apply merged/closed PR outcomes
|
|
55
|
+
webhook serve [--port N] [--host H] serve dispatch registration, recovery and the wake pump
|
|
56
|
+
webhook bearer generate a dispatch bearer
|
|
57
|
+
webhook register --topic T [--harness H] [--executor E] --url U [--id I] [--bearer B] [--timeout-ms N]
|
|
58
|
+
register or replace a webhook subscription
|
|
59
|
+
webhook list [--topic T] [--harness H] list webhook subscriptions (bearer redacted)
|
|
60
|
+
webhook deliveries [--status S] [--admission ID] [--consumer ID] [--limit N]
|
|
61
|
+
list per-consumer delivery ledger rows
|
|
62
|
+
webhook revoke [--topic T] --id I remove a webhook subscription
|
|
63
|
+
webhook test [--topic T] [--harness H] [--id I]
|
|
64
|
+
POST a ping to webhook subscriptions`;
|
|
65
|
+
|
|
66
|
+
function fail(msg, code = 2) {
|
|
67
|
+
console.error(msg);
|
|
68
|
+
process.exit(code);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function manualExecutorId(url) {
|
|
72
|
+
return `manual-${crypto.createHash("sha256").update(String(url)).digest("hex").slice(0, 12)}`;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export async function runCli(argv) {
|
|
76
|
+
const [cmd, ...rest] = argv;
|
|
77
|
+
switch (cmd) {
|
|
78
|
+
case undefined:
|
|
79
|
+
case "--help":
|
|
80
|
+
case "-h":
|
|
81
|
+
case "help":
|
|
82
|
+
console.log(USAGE);
|
|
83
|
+
return;
|
|
84
|
+
|
|
85
|
+
case "watch": {
|
|
86
|
+
const { values } = parseArgs({
|
|
87
|
+
args: rest,
|
|
88
|
+
options: { config: { type: "string" } },
|
|
89
|
+
allowPositionals: true,
|
|
90
|
+
});
|
|
91
|
+
const store = openStore(loadConfig(values));
|
|
92
|
+
try {
|
|
93
|
+
console.log(JSON.stringify(tick(store)));
|
|
94
|
+
} finally {
|
|
95
|
+
store.close();
|
|
96
|
+
}
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
case "resume": {
|
|
101
|
+
const { values, positionals } = parseArgs({
|
|
102
|
+
args: rest,
|
|
103
|
+
options: { actor: { type: "string" } },
|
|
104
|
+
allowPositionals: true,
|
|
105
|
+
});
|
|
106
|
+
const taskId = positionals[0];
|
|
107
|
+
if (!taskId) fail("usage: winch resume <taskId> [--actor <name>]");
|
|
108
|
+
const store = openStore();
|
|
109
|
+
try {
|
|
110
|
+
const r = store.task.resumeGate({ id: taskId, actor: values.actor ?? "operator" });
|
|
111
|
+
if (!r) fail(`not resumable: ${taskId}`, 1);
|
|
112
|
+
console.log(JSON.stringify(r, null, 2));
|
|
113
|
+
} finally {
|
|
114
|
+
store.close();
|
|
115
|
+
}
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
case "next": {
|
|
120
|
+
const store = openStore();
|
|
121
|
+
try {
|
|
122
|
+
const rows = readyTasks(store, { limit: 20 });
|
|
123
|
+
console.log(JSON.stringify(
|
|
124
|
+
rows.map((r) => ({ taskId: r.task.id, title: r.task.title, assigned: r.task.assignee_agent, story: r.story.id, epic: r.epic.id })),
|
|
125
|
+
null, 2
|
|
126
|
+
));
|
|
127
|
+
} finally {
|
|
128
|
+
store.close();
|
|
129
|
+
}
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
case "release-epic": {
|
|
134
|
+
const { values } = parseArgs({
|
|
135
|
+
args: rest,
|
|
136
|
+
options: {
|
|
137
|
+
epic: { type: "string" },
|
|
138
|
+
task: { type: "string" },
|
|
139
|
+
version: { type: "string" },
|
|
140
|
+
base: { type: "string" },
|
|
141
|
+
},
|
|
142
|
+
});
|
|
143
|
+
if (!values.epic) fail("usage: winch release-epic --epic <id> [--task ID] [--version V] [--base B]");
|
|
144
|
+
const store = openStore();
|
|
145
|
+
try {
|
|
146
|
+
const r = shipRelease(store, {
|
|
147
|
+
epicId: values.epic,
|
|
148
|
+
taskId: values.task ?? null,
|
|
149
|
+
version: values.version ?? null,
|
|
150
|
+
base: values.base ?? "main",
|
|
151
|
+
});
|
|
152
|
+
console.log(r.prUrl);
|
|
153
|
+
} catch (e) {
|
|
154
|
+
fail(`release-epic failed: ${e.message ?? e}`, 1);
|
|
155
|
+
} finally {
|
|
156
|
+
store.close();
|
|
157
|
+
}
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
case "merge-detect": {
|
|
162
|
+
const { values } = parseArgs({ args: rest, options: { "dry-run": { type: "boolean" } } });
|
|
163
|
+
const store = openStore();
|
|
164
|
+
try {
|
|
165
|
+
const prs = collectPRs({ exec: execFileSync });
|
|
166
|
+
const summary = applyMergeOutcomes(store, prs, { exec: execFileSync, dryRun: !!values["dry-run"] });
|
|
167
|
+
console.log(JSON.stringify(summary, null, 2));
|
|
168
|
+
} catch (e) {
|
|
169
|
+
fail(`merge-detect failed: ${e.message ?? e}`, 1);
|
|
170
|
+
} finally {
|
|
171
|
+
store.close();
|
|
172
|
+
}
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
case "serve": {
|
|
177
|
+
let values;
|
|
178
|
+
try {
|
|
179
|
+
({ values } = parseArgs({
|
|
180
|
+
args: rest,
|
|
181
|
+
options: {
|
|
182
|
+
ws: { type: "boolean" },
|
|
183
|
+
mcp: { type: "string" },
|
|
184
|
+
port: { type: "string" },
|
|
185
|
+
host: { type: "string" },
|
|
186
|
+
config: { type: "string" },
|
|
187
|
+
},
|
|
188
|
+
}));
|
|
189
|
+
} catch (err) {
|
|
190
|
+
// --harness (or any unknown flag) on serve means the caller is still
|
|
191
|
+
// on the legacy `mcp --harness` surface: stdio harness is env-only.
|
|
192
|
+
if (/Unknown option|ERR_PARSE_ARGS_UNKNOWN_OPTION/.test(String(err?.message ?? err))) {
|
|
193
|
+
fail("winch serve --mcp takes no --harness flag: set WINCH_HARNESS in the environment.");
|
|
194
|
+
}
|
|
195
|
+
throw err;
|
|
196
|
+
}
|
|
197
|
+
if (values.mcp !== undefined && values.mcp !== "stdio" && values.mcp !== "http") {
|
|
198
|
+
fail(`winch: --mcp must be stdio or http, got ${JSON.stringify(values.mcp)}`);
|
|
199
|
+
}
|
|
200
|
+
const modes = ["ws", "mcp"].filter((k) => values[k]);
|
|
201
|
+
if (modes.length !== 1) {
|
|
202
|
+
fail("usage: winch serve (--ws | --mcp stdio|http) [--port N] [--host H] [--config JSON|PATH]");
|
|
203
|
+
}
|
|
204
|
+
const store = openStore(loadConfig(values));
|
|
205
|
+
const logger = {
|
|
206
|
+
info: (...a) => console.error(...a),
|
|
207
|
+
warn: (...a) => console.error(...a),
|
|
208
|
+
error: (...a) => console.error(...a),
|
|
209
|
+
};
|
|
210
|
+
// localhost-only unless asked: streams and tool traffic carry raw
|
|
211
|
+
// store rows, so they stay behind loopback or a bearer-checked proxy.
|
|
212
|
+
const host = values.host ?? "127.0.0.1";
|
|
213
|
+
const port = values.port ? Number(values.port) : undefined;
|
|
214
|
+
if (port !== undefined && !(Number.isInteger(port) && port >= 1 && port <= 65535)) {
|
|
215
|
+
fail(`winch: --port must be 1-65535, got ${JSON.stringify(values.port)}`);
|
|
216
|
+
}
|
|
217
|
+
if (values.mcp === "stdio") {
|
|
218
|
+
// Harness is env-only here by design: the spawner owns identity.
|
|
219
|
+
let base;
|
|
220
|
+
try {
|
|
221
|
+
base = declaredFromEnv();
|
|
222
|
+
} catch (err) {
|
|
223
|
+
fail(String(err?.message ?? err));
|
|
224
|
+
}
|
|
225
|
+
try {
|
|
226
|
+
await startMcpServer({ store, base, logger });
|
|
227
|
+
} catch (err) {
|
|
228
|
+
fail(String(err?.message ?? err));
|
|
229
|
+
}
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
if (values.mcp === "http") {
|
|
233
|
+
try {
|
|
234
|
+
const { startMcpHttpServer } = await import("./mcp-http.js");
|
|
235
|
+
await startMcpHttpServer({ store, port, host, logger });
|
|
236
|
+
} catch (err) {
|
|
237
|
+
fail(String(err?.message ?? err));
|
|
238
|
+
}
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
await startEventServer({ store, port, host, logger });
|
|
242
|
+
logger.info(`winch: events on ws://${host}:${port ?? store.config.wsPort} (append-only; subscribers track their own state)`);
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
case "webhook": {
|
|
247
|
+
const [sub, ...subRest] = rest;
|
|
248
|
+
if (!["serve", "bearer", "register", "list", "deliveries", "revoke", "test"].includes(sub)) {
|
|
249
|
+
fail("usage: winch webhook (serve|bearer|register|list|deliveries|revoke|test) …");
|
|
250
|
+
}
|
|
251
|
+
const { values } = parseArgs({
|
|
252
|
+
args: subRest,
|
|
253
|
+
options: {
|
|
254
|
+
harness: { type: "string" },
|
|
255
|
+
url: { type: "string" },
|
|
256
|
+
bearer: { type: "string" },
|
|
257
|
+
topic: { type: "string" },
|
|
258
|
+
id: { type: "string" },
|
|
259
|
+
executor: { type: "string" },
|
|
260
|
+
"timeout-ms": { type: "string" },
|
|
261
|
+
status: { type: "string" },
|
|
262
|
+
admission: { type: "string" },
|
|
263
|
+
consumer: { type: "string" },
|
|
264
|
+
limit: { type: "string" },
|
|
265
|
+
port: { type: "string" },
|
|
266
|
+
host: { type: "string" },
|
|
267
|
+
config: { type: "string" },
|
|
268
|
+
},
|
|
269
|
+
});
|
|
270
|
+
if (sub === "bearer") {
|
|
271
|
+
console.log(crypto.randomBytes(32).toString("hex"));
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
if (sub === "serve") {
|
|
275
|
+
const port = values.port ? Number(values.port) : undefined;
|
|
276
|
+
if (port !== undefined && !(Number.isInteger(port) && port >= 1 && port <= 65535)) {
|
|
277
|
+
fail(`winch: --port must be 1-65535, got ${JSON.stringify(values.port)}`);
|
|
278
|
+
}
|
|
279
|
+
const store = openStore(loadConfig(values));
|
|
280
|
+
const logger = {
|
|
281
|
+
info: (...a) => console.error(...a),
|
|
282
|
+
warn: (...a) => console.error(...a),
|
|
283
|
+
error: (...a) => console.error(...a),
|
|
284
|
+
};
|
|
285
|
+
const host = values.host ?? "127.0.0.1";
|
|
286
|
+
try {
|
|
287
|
+
const srv = await startDispatchServer({ store, port, host, logger });
|
|
288
|
+
logger.info(`winch: dispatch on http://${host}:${srv.port} (webhooks; queue pump; lease sweep)`);
|
|
289
|
+
} catch (err) {
|
|
290
|
+
store.close();
|
|
291
|
+
fail(String(err?.message ?? err));
|
|
292
|
+
}
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
const store = openStore(loadConfig(values));
|
|
296
|
+
try {
|
|
297
|
+
if (sub === "list") {
|
|
298
|
+
console.log(JSON.stringify(store.webhook.list({
|
|
299
|
+
topic: values.topic ?? null,
|
|
300
|
+
harness: values.harness ?? null,
|
|
301
|
+
}).map((r) => ({
|
|
302
|
+
topic: r.topic,
|
|
303
|
+
id: r.id,
|
|
304
|
+
harness: r.harness,
|
|
305
|
+
executorId: r.executorId,
|
|
306
|
+
url: r.url,
|
|
307
|
+
bearer: "<set>",
|
|
308
|
+
timeoutMs: r.timeoutMs,
|
|
309
|
+
lastSeenAt: r.lastSeenAt,
|
|
310
|
+
instanceId: r.instanceId,
|
|
311
|
+
generation: r.generation,
|
|
312
|
+
state: r.state,
|
|
313
|
+
failureCount: r.failureCount,
|
|
314
|
+
disabledAt: r.disabledAt,
|
|
315
|
+
leaseUntil: r.leaseUntil,
|
|
316
|
+
managed: r.managed,
|
|
317
|
+
})), null, 2));
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
if (sub === "deliveries") {
|
|
321
|
+
const limit = values.limit !== undefined ? Number(values.limit) : null;
|
|
322
|
+
if (limit !== null && (!Number.isInteger(limit) || limit <= 0)) {
|
|
323
|
+
fail(`winch: --limit must be a positive integer, got ${JSON.stringify(values.limit)}`);
|
|
324
|
+
}
|
|
325
|
+
const rows = store.delivery.list({
|
|
326
|
+
admissionId: values.admission ?? null,
|
|
327
|
+
consumerId: values.consumer ?? null,
|
|
328
|
+
status: values.status ?? null,
|
|
329
|
+
limit,
|
|
330
|
+
});
|
|
331
|
+
console.log(JSON.stringify({
|
|
332
|
+
count: rows.length,
|
|
333
|
+
rows: rows.map((r) => ({
|
|
334
|
+
id: r.id,
|
|
335
|
+
admissionId: r.admission_id,
|
|
336
|
+
attemptNo: r.attempt_no,
|
|
337
|
+
eventId: r.event_id,
|
|
338
|
+
consumerId: r.consumer_id,
|
|
339
|
+
status: r.status,
|
|
340
|
+
attempts: r.attempts,
|
|
341
|
+
nextAt: r.next_at,
|
|
342
|
+
lastStatus: r.last_status,
|
|
343
|
+
lastError: r.last_error,
|
|
344
|
+
deliveredAt: r.delivered_at,
|
|
345
|
+
deadAt: r.dead_at,
|
|
346
|
+
})),
|
|
347
|
+
}, null, 2));
|
|
348
|
+
return;
|
|
349
|
+
}
|
|
350
|
+
if (sub === "register") {
|
|
351
|
+
if (!values.url) fail("winch webhook register requires --url U");
|
|
352
|
+
const topic = (values.topic ?? "dispatch").trim();
|
|
353
|
+
if (!topic) fail("winch webhook register requires a non-empty --topic");
|
|
354
|
+
if (topic === "dispatch" && !values.harness) {
|
|
355
|
+
fail("winch webhook register --topic dispatch requires --harness H");
|
|
356
|
+
}
|
|
357
|
+
const timeoutMs = values["timeout-ms"] !== undefined ? Number(values["timeout-ms"]) : null;
|
|
358
|
+
if (timeoutMs !== null && (!Number.isInteger(timeoutMs) || timeoutMs <= 0)) {
|
|
359
|
+
fail(`winch: --timeout-ms must be a positive integer, got ${JSON.stringify(values["timeout-ms"])}`);
|
|
360
|
+
}
|
|
361
|
+
const envBearer = (process.env.WINCH_WEBHOOK_BEARER ?? "").trim();
|
|
362
|
+
const generated = !values.bearer && !envBearer;
|
|
363
|
+
const bearer = values.bearer || envBearer || crypto.randomBytes(32).toString("hex");
|
|
364
|
+
const id = values.id ?? values.executor ?? manualExecutorId(values.url);
|
|
365
|
+
const executorId = values.executor ?? (topic === "dispatch" ? id : null);
|
|
366
|
+
const row = store.webhook.upsert({
|
|
367
|
+
topic,
|
|
368
|
+
id,
|
|
369
|
+
harness: values.harness ?? null,
|
|
370
|
+
executorId,
|
|
371
|
+
url: values.url,
|
|
372
|
+
bearer,
|
|
373
|
+
timeoutMs,
|
|
374
|
+
managed: false,
|
|
375
|
+
fresh: true,
|
|
376
|
+
});
|
|
377
|
+
console.log(JSON.stringify({
|
|
378
|
+
topic: row.topic,
|
|
379
|
+
id: row.id,
|
|
380
|
+
harness: row.harness,
|
|
381
|
+
executorId: row.executorId,
|
|
382
|
+
url: row.url,
|
|
383
|
+
bearer: generated ? bearer : "<set>",
|
|
384
|
+
timeoutMs: row.timeoutMs,
|
|
385
|
+
lastSeenAt: row.lastSeenAt,
|
|
386
|
+
instanceId: row.instanceId,
|
|
387
|
+
generation: row.generation,
|
|
388
|
+
state: row.state,
|
|
389
|
+
failureCount: row.failureCount,
|
|
390
|
+
managed: row.managed,
|
|
391
|
+
}, null, 2));
|
|
392
|
+
return;
|
|
393
|
+
}
|
|
394
|
+
if (sub === "revoke") {
|
|
395
|
+
const topic = (values.topic ?? "dispatch").trim();
|
|
396
|
+
const id = values.id ?? values.executor;
|
|
397
|
+
if (!topic || !id) fail("winch webhook revoke requires --id E");
|
|
398
|
+
const removed = store.webhook.remove({ topic, id });
|
|
399
|
+
if (!removed) fail(`no webhook endpoint for ${topic}/${id}`, 1);
|
|
400
|
+
console.log(JSON.stringify({ revoked: `${topic}/${id}` }));
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
const topic = (values.topic ?? "dispatch").trim();
|
|
404
|
+
const id = values.id ?? values.executor;
|
|
405
|
+
const rows = store.webhook.list({ topic, harness: values.harness ?? null })
|
|
406
|
+
.filter((r) => !id || r.id === id);
|
|
407
|
+
if (!rows.length) fail(`no webhook endpoint for ${topic}${id ? `/${id}` : ""}`, 1);
|
|
408
|
+
const results = await Promise.all(rows.map(async (row) => {
|
|
409
|
+
const timeoutMs = row.timeoutMs ?? store.config.webhookTimeoutMs ?? 3000;
|
|
410
|
+
try {
|
|
411
|
+
const res = await fetch(row.url, {
|
|
412
|
+
method: "POST",
|
|
413
|
+
headers: { "content-type": "application/json", authorization: `Bearer ${row.bearer}` },
|
|
414
|
+
body: JSON.stringify({ type: "ping", topic: row.topic, id: row.id, harness: row.harness, executorId: row.executorId, at: Date.now() }),
|
|
415
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
416
|
+
});
|
|
417
|
+
const text = await res.text().catch(() => "");
|
|
418
|
+
return { topic: row.topic, id: row.id, harness: row.harness, executorId: row.executorId, url: row.url, ok: res.ok, status: res.status, body: text.slice(0, 500) };
|
|
419
|
+
} catch (err) {
|
|
420
|
+
return { topic: row.topic, id: row.id, harness: row.harness, executorId: row.executorId, url: row.url, ok: false, status: 0, error: String(err?.message ?? err) };
|
|
421
|
+
}
|
|
422
|
+
}));
|
|
423
|
+
console.log(JSON.stringify(results, null, 2));
|
|
424
|
+
if (results.some((r) => !r.ok)) process.exitCode = 1;
|
|
425
|
+
} finally {
|
|
426
|
+
store.close();
|
|
427
|
+
}
|
|
428
|
+
return;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
default:
|
|
432
|
+
fail(`unknown command: ${cmd}\n\n${USAGE}`);
|
|
433
|
+
}
|
|
434
|
+
}
|
package/src/config.js
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
// config.js — layered tuning config, declared the way the harness is.
|
|
2
|
+
//
|
|
3
|
+
// Precedence: per-call `_meta.winch.config` > constructor `{ config }` >
|
|
4
|
+
// `WINCH_*` env > code defaults. Nothing here is required: every knob has a
|
|
5
|
+
// safe default, so a server started with no config behaves exactly like the
|
|
6
|
+
// old hardcoded one. (Identity is the opposite — the triple refuses when
|
|
7
|
+
// absent. Config never refuses for being absent; it refuses only for being
|
|
8
|
+
// malformed, naming the key, the way a bad harness declaration does.)
|
|
9
|
+
|
|
10
|
+
const DURATION_RE = /^(\d+)(ms|s|m|h|d)$/;
|
|
11
|
+
const UNIT_MS = { ms: 1, s: 1000, m: 60 * 1000, h: 3600 * 1000, d: 24 * 3600 * 1000 };
|
|
12
|
+
|
|
13
|
+
function parseLevelToken(tok) {
|
|
14
|
+
const m = String(tok ?? "").trim().match(DURATION_RE);
|
|
15
|
+
if (!m) return null;
|
|
16
|
+
return { ms: Number(m[1]) * UNIT_MS[m[2]], label: String(tok).trim() };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function parseGateWaitLevels(raw) {
|
|
20
|
+
const toks = Array.isArray(raw) ? raw : String(raw ?? "").split(",");
|
|
21
|
+
const levels = [];
|
|
22
|
+
for (const t of toks) {
|
|
23
|
+
if (t != null && typeof t === "object" && Number.isFinite(t.ms)) {
|
|
24
|
+
levels.push({ ms: Math.floor(t.ms), label: String(t.label ?? `${t.ms}ms`) });
|
|
25
|
+
continue;
|
|
26
|
+
}
|
|
27
|
+
const p = parseLevelToken(t);
|
|
28
|
+
if (!p || p.ms <= 0) return null;
|
|
29
|
+
levels.push(p);
|
|
30
|
+
}
|
|
31
|
+
if (!levels.length) return null;
|
|
32
|
+
return [...levels].sort((a, b) => a.ms - b.ms);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function parseInt(raw) {
|
|
36
|
+
if (typeof raw === "number") return Number.isInteger(raw) ? raw : null;
|
|
37
|
+
const s = String(raw ?? "").trim();
|
|
38
|
+
if (!/^\d+$/.test(s)) return null;
|
|
39
|
+
return Number(s);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// key -> { env, parse, check }. parse normalizes (string|number|array) to the
|
|
43
|
+
// stored shape; check rejects out-of-range values. Stored shapes are plain
|
|
44
|
+
// JSON: a resolved config survives a round-trip through JSON by construction.
|
|
45
|
+
const SPEC = {
|
|
46
|
+
leaseSeconds: { env: "WINCH_LEASE_SECONDS", parse: parseInt, check: (v) => v > 0 },
|
|
47
|
+
maxAttempts: { env: "WINCH_MAX_ATTEMPTS", parse: parseInt, check: (v) => v > 0 },
|
|
48
|
+
gateWaitLevels: { env: "WINCH_GATE_WAIT_LEVELS", parse: parseGateWaitLevels, check: (v) => v !== null },
|
|
49
|
+
wsPort: { env: "WINCH_WS_PORT", parse: parseInt, check: (v) => v >= 1 && v <= 65535 },
|
|
50
|
+
mcpHttpPort: { env: "WINCH_MCP_HTTP_PORT", parse: parseInt, check: (v) => v >= 1 && v <= 65535 },
|
|
51
|
+
wsHistoryLimit: { env: "WINCH_WS_HISTORY_LIMIT", parse: parseInt, check: (v) => v > 0 },
|
|
52
|
+
wsIntervalMs: { env: "WINCH_WS_INTERVAL_MS", parse: parseInt, check: (v) => v > 0 },
|
|
53
|
+
dispatchPort: { env: "WINCH_DISPATCH_PORT", parse: parseInt, check: (v) => v >= 1 && v <= 65535 },
|
|
54
|
+
dispatchIntervalMs: { env: "WINCH_DISPATCH_INTERVAL_MS", parse: parseInt, check: (v) => v > 0 },
|
|
55
|
+
dispatchSweepMs: { env: "WINCH_DISPATCH_SWEEP_MS", parse: parseInt, check: (v) => v > 0 },
|
|
56
|
+
maxActivePerAgent: { env: "WINCH_MAX_ACTIVE_PER_AGENT", parse: parseInt, check: (v) => v > 0 },
|
|
57
|
+
dispatchHarnessMax: { env: "WINCH_DISPATCH_HARNESS_MAX", parse: parseInt, check: (v) => v > 0 },
|
|
58
|
+
dispatchGlobalMax: { env: "WINCH_DISPATCH_GLOBAL_MAX", parse: parseInt, check: (v) => v > 0 },
|
|
59
|
+
dispatchOfferMs: { env: "WINCH_DISPATCH_OFFER_MS", parse: parseInt, check: (v) => v > 0 },
|
|
60
|
+
dispatchOfferBackoffMs: { env: "WINCH_DISPATCH_OFFER_BACKOFF_MS", parse: parseInt, check: (v) => v > 0 },
|
|
61
|
+
dispatchOfferMaxBackoffMs: { env: "WINCH_DISPATCH_OFFER_MAX_BACKOFF_MS", parse: parseInt, check: (v) => v > 0 },
|
|
62
|
+
dispatchOfferMaxAttempts: { env: "WINCH_DISPATCH_OFFER_MAX_ATTEMPTS", parse: parseInt, check: (v) => v > 0 },
|
|
63
|
+
dispatchDeliveryBackoffMs: { env: "WINCH_DISPATCH_DELIVERY_BACKOFF_MS", parse: parseInt, check: (v) => v > 0 },
|
|
64
|
+
dispatchDeliveryMaxBackoffMs: { env: "WINCH_DISPATCH_DELIVERY_MAX_BACKOFF_MS", parse: parseInt, check: (v) => v > 0 },
|
|
65
|
+
dispatchDeliveryMaxAttempts: { env: "WINCH_DISPATCH_DELIVERY_MAX_ATTEMPTS", parse: parseInt, check: (v) => v > 0 },
|
|
66
|
+
dispatchDeliveryFailureThreshold: { env: "WINCH_DISPATCH_DELIVERY_FAILURE_THRESHOLD", parse: parseInt, check: (v) => v > 0 },
|
|
67
|
+
dispatchDeliveryLeaseMs: { env: "WINCH_DISPATCH_DELIVERY_LEASE_MS", parse: parseInt, check: (v) => v > 0 },
|
|
68
|
+
dispatchConsumerTtlMs: { env: "WINCH_DISPATCH_CONSUMER_TTL_MS", parse: parseInt, check: (v) => v > 0 },
|
|
69
|
+
webhookTimeoutMs: { env: "WINCH_WEBHOOK_TIMEOUT_MS", parse: parseInt, check: (v) => v > 0 },
|
|
70
|
+
scanLimit: { env: "WINCH_SCAN_LIMIT", parse: parseInt, check: (v) => v > 0 },
|
|
71
|
+
candidates: { env: "WINCH_CANDIDATES", parse: parseInt, check: (v) => v > 0 },
|
|
72
|
+
blockedLimit: { env: "WINCH_BLOCKED_LIMIT", parse: parseInt, check: (v) => v > 0 },
|
|
73
|
+
dfsNodes: { env: "WINCH_DFS_NODES", parse: parseInt, check: (v) => v > 0 },
|
|
74
|
+
noteProgressLimit: { env: "WINCH_NOTE_PROGRESS_LIMIT", parse: parseInt, check: (v) => v > 0 },
|
|
75
|
+
noteResultLimit: { env: "WINCH_NOTE_RESULT_LIMIT", parse: parseInt, check: (v) => v > 0 },
|
|
76
|
+
noteReasonLimit: { env: "WINCH_NOTE_REASON_LIMIT", parse: parseInt, check: (v) => v > 0 },
|
|
77
|
+
noteArtifactLimit: { env: "WINCH_NOTE_ARTIFACT_LIMIT", parse: parseInt, check: (v) => v > 0 },
|
|
78
|
+
maxArtifacts: { env: "WINCH_MAX_ARTIFACTS", parse: parseInt, check: (v) => v > 0 },
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
export const CONFIG_DEFAULTS = {
|
|
82
|
+
leaseSeconds: 1800,
|
|
83
|
+
maxAttempts: 3,
|
|
84
|
+
gateWaitLevels: "24h,72h",
|
|
85
|
+
wsPort: 38291,
|
|
86
|
+
mcpHttpPort: 38292,
|
|
87
|
+
wsHistoryLimit: 200,
|
|
88
|
+
wsIntervalMs: 1000,
|
|
89
|
+
dispatchPort: 38293,
|
|
90
|
+
dispatchIntervalMs: 1000,
|
|
91
|
+
dispatchSweepMs: 30000,
|
|
92
|
+
maxActivePerAgent: 2,
|
|
93
|
+
dispatchHarnessMax: 8,
|
|
94
|
+
dispatchGlobalMax: 16,
|
|
95
|
+
dispatchOfferMs: 120000,
|
|
96
|
+
dispatchOfferBackoffMs: 30000,
|
|
97
|
+
dispatchOfferMaxBackoffMs: 300000,
|
|
98
|
+
dispatchOfferMaxAttempts: 5,
|
|
99
|
+
dispatchDeliveryBackoffMs: 30000,
|
|
100
|
+
dispatchDeliveryMaxBackoffMs: 300000,
|
|
101
|
+
dispatchDeliveryMaxAttempts: 5,
|
|
102
|
+
dispatchDeliveryFailureThreshold: 4,
|
|
103
|
+
dispatchDeliveryLeaseMs: 300000,
|
|
104
|
+
dispatchConsumerTtlMs: 90000,
|
|
105
|
+
webhookTimeoutMs: 3000,
|
|
106
|
+
scanLimit: 50,
|
|
107
|
+
candidates: 5,
|
|
108
|
+
blockedLimit: 20,
|
|
109
|
+
dfsNodes: 500,
|
|
110
|
+
noteProgressLimit: 2000,
|
|
111
|
+
noteResultLimit: 4000,
|
|
112
|
+
noteReasonLimit: 1000,
|
|
113
|
+
noteArtifactLimit: 500,
|
|
114
|
+
maxArtifacts: 50,
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
export const CONFIG_ENV = Object.fromEntries(
|
|
118
|
+
Object.entries(SPEC).map(([key, s]) => [key, s.env])
|
|
119
|
+
);
|
|
120
|
+
|
|
121
|
+
function refused(what, key, hint) {
|
|
122
|
+
throw new Error(`winch: refused ${what} (bad ${key}). ${hint}`);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function parseKey(key, raw, what) {
|
|
126
|
+
const spec = SPEC[key];
|
|
127
|
+
const parsed = spec.parse(raw);
|
|
128
|
+
if (parsed === null || !spec.check(parsed)) {
|
|
129
|
+
refused(what, key, `Expected ${key === "gateWaitLevels" ? "a duration list like \"24h,72h\"" : key === "wsPort" ? "a port 1-65535" : "a positive integer"} — got ${JSON.stringify(raw) ?? "nothing"}.`);
|
|
130
|
+
}
|
|
131
|
+
return parsed;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Construction-time config: explicit object wins, then WINCH_* env, then
|
|
136
|
+
* code defaults. Unknown explicit keys refuse — a typo'd knob must fail at
|
|
137
|
+
* startup, not run for a month at the default while the operator believes
|
|
138
|
+
* otherwise. Env carries only known vars, so there is nothing to reject there.
|
|
139
|
+
*/
|
|
140
|
+
export function resolveConfig({ explicit = {}, env = process.env } = {}) {
|
|
141
|
+
if (explicit == null || typeof explicit !== "object" || Array.isArray(explicit)) {
|
|
142
|
+
refused("config", "config", "Pass an object keyed by knob name.");
|
|
143
|
+
}
|
|
144
|
+
for (const key of Object.keys(explicit)) {
|
|
145
|
+
if (!SPEC[key]) refused("config", key, `Unknown knob — known: ${Object.keys(SPEC).join(", ")}.`);
|
|
146
|
+
}
|
|
147
|
+
const out = {};
|
|
148
|
+
for (const [key, spec] of Object.entries(SPEC)) {
|
|
149
|
+
if (explicit[key] !== undefined) {
|
|
150
|
+
out[key] = parseKey(key, explicit[key], "config");
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
const envRaw = env?.[spec.env];
|
|
154
|
+
if (envRaw !== undefined && envRaw !== "") {
|
|
155
|
+
out[key] = parseKey(key, envRaw, `config (env ${spec.env})`);
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
out[key] = parseKey(key, CONFIG_DEFAULTS[key], "config");
|
|
159
|
+
}
|
|
160
|
+
return out;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Per-call overlay: `_meta.winch.config` merges over the construction
|
|
165
|
+
* config. Unknown keys are ignored (a newer harness stamping knobs an older
|
|
166
|
+
* server never heard of must not break the call); malformed known keys
|
|
167
|
+
* refuse the call, the way an unstamped identity does.
|
|
168
|
+
*/
|
|
169
|
+
export function resolveRequestConfig(base, meta) {
|
|
170
|
+
const patch = meta?.winch?.config ?? null;
|
|
171
|
+
if (patch == null) return base;
|
|
172
|
+
if (typeof patch !== "object" || Array.isArray(patch)) {
|
|
173
|
+
refused("caller config", "config", "Pass an object keyed by knob name.");
|
|
174
|
+
}
|
|
175
|
+
const out = { ...base };
|
|
176
|
+
for (const [key, raw] of Object.entries(patch)) {
|
|
177
|
+
if (!SPEC[key] || raw === undefined) continue;
|
|
178
|
+
out[key] = parseKey(key, raw, "caller config");
|
|
179
|
+
}
|
|
180
|
+
return out;
|
|
181
|
+
}
|
package/src/db.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// db.js — the better-sqlite3 connection and Drizzle client. Schema changes
|
|
2
|
+
// are generated into .migrations/ from src/schema.js and applied here on open.
|
|
3
|
+
|
|
4
|
+
import { existsSync, mkdirSync } from "node:fs";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import Database from "better-sqlite3";
|
|
7
|
+
import { drizzle } from "drizzle-orm/better-sqlite3";
|
|
8
|
+
import { migrate } from "drizzle-orm/better-sqlite3/migrator";
|
|
9
|
+
import * as schema from "./schema.js";
|
|
10
|
+
|
|
11
|
+
const MIGRATIONS_FOLDER = path.join(import.meta.dirname, "..", ".migrations");
|
|
12
|
+
|
|
13
|
+
export function openDatabase({ dbPath, logger } = {}) {
|
|
14
|
+
const dir = path.dirname(dbPath);
|
|
15
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
16
|
+
|
|
17
|
+
const sqlite = new Database(dbPath);
|
|
18
|
+
sqlite.exec("PRAGMA journal_mode = WAL;");
|
|
19
|
+
sqlite.exec("PRAGMA foreign_keys = ON;");
|
|
20
|
+
sqlite.exec("PRAGMA busy_timeout = 5000;");
|
|
21
|
+
|
|
22
|
+
const orm = drizzle(sqlite, { schema });
|
|
23
|
+
// Migrations that rebuild a referenced table cannot run with enforcement on:
|
|
24
|
+
// SQLite ignores `PRAGMA foreign_keys=OFF` inside the migration transaction.
|
|
25
|
+
// Turn it off for the whole run, then prove the result is clean.
|
|
26
|
+
sqlite.exec("PRAGMA foreign_keys = OFF;");
|
|
27
|
+
try {
|
|
28
|
+
migrate(orm, { migrationsFolder: MIGRATIONS_FOLDER });
|
|
29
|
+
} finally {
|
|
30
|
+
sqlite.exec("PRAGMA foreign_keys = ON;");
|
|
31
|
+
}
|
|
32
|
+
const violations = sqlite.pragma("foreign_key_check");
|
|
33
|
+
if (violations.length > 0) {
|
|
34
|
+
throw new Error(`winch: migration left ${violations.length} foreign-key violation(s)`);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
logger?.info?.(`backlog: store ready at ${dbPath}`);
|
|
38
|
+
return { sqlite, orm };
|
|
39
|
+
}
|