@igorjpimenta/winch 0.0.0-stage → 2026.11.22-beta.3
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 +198 -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
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import { createWinchHooks } from "./hooks.js";
|
|
2
|
+
import { stampWinchEvent } from "./identity.js";
|
|
3
|
+
import { startDispatch, DEFAULT_DISPATCH_URL } from "./dispatch.js";
|
|
4
|
+
import { spawn, execFileSync } from "node:child_process";
|
|
5
|
+
import { mkdirSync, readdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
|
6
|
+
import os, { hostname } from "node:os";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
|
|
9
|
+
// A wake child is orphaned only when the process that spawned it is gone. A
|
|
10
|
+
// child whose owner is still running is doing real work, so it must not be
|
|
11
|
+
// reaped. The sweep therefore kills nothing except leftovers from a dead owner.
|
|
12
|
+
const SWEEP_MS = 60 * 1000;
|
|
13
|
+
|
|
14
|
+
function wakeStateDir() {
|
|
15
|
+
return path.join(os.homedir(), ".opencode", "state", "winch-wakes");
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function pidAlive(pid) {
|
|
19
|
+
try { process.kill(pid, 0); return true; }
|
|
20
|
+
catch (err) { return err?.code === "EPERM"; }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function processCommand(pid) {
|
|
24
|
+
try {
|
|
25
|
+
return execFileSync("ps", ["-o", "command=", "-p", String(pid)], { encoding: "utf8" }).trim();
|
|
26
|
+
} catch {
|
|
27
|
+
return "";
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function createWakeRunner({ logger = console, stateDir = wakeStateDir() } = {}) {
|
|
32
|
+
// Detached children lead their own process group; kill the group so a
|
|
33
|
+
// reaped turn's tool and MCP subprocesses go with it.
|
|
34
|
+
const reap = (pid) => {
|
|
35
|
+
try { process.kill(-pid, "SIGKILL"); }
|
|
36
|
+
catch { try { process.kill(pid, "SIGKILL"); } catch {} }
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const recordPath = (ownerPid, childPid) => path.join(stateDir, `wake-${ownerPid}-${childPid}.json`);
|
|
40
|
+
|
|
41
|
+
const wake = ({ agent, message }) =>
|
|
42
|
+
new Promise((resolve, reject) => {
|
|
43
|
+
const bin = process.env.OPENCODE_BIN || "opencode";
|
|
44
|
+
const child = spawn(bin, ["run", "--agent", agent, message], {
|
|
45
|
+
detached: true,
|
|
46
|
+
stdio: ["ignore", "ignore", "pipe"],
|
|
47
|
+
// A wake child loads the same config and would start its own dispatch
|
|
48
|
+
// listener, registering as another executor; then every wake fans out
|
|
49
|
+
// into more waking agents. Keep dispatch to the root instance only.
|
|
50
|
+
env: { ...process.env, WINCH_DISPATCH_ENABLED: "0" },
|
|
51
|
+
});
|
|
52
|
+
const file = child.pid ? recordPath(process.pid, child.pid) : null;
|
|
53
|
+
if (file) {
|
|
54
|
+
try {
|
|
55
|
+
mkdirSync(stateDir, { recursive: true });
|
|
56
|
+
writeFileSync(file, JSON.stringify({ pid: child.pid, ownerPid: process.pid, agent, message }));
|
|
57
|
+
} catch (err) {
|
|
58
|
+
logger?.warn?.(`winch: wake record not written: ${err?.message ?? err}`);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
const forget = () => { try { if (file) unlinkSync(file); } catch {} };
|
|
62
|
+
let stderr = "";
|
|
63
|
+
child.stderr?.on("data", (d) => { stderr = (stderr + d.toString()).slice(-2000); });
|
|
64
|
+
child.on("error", (err) => { forget(); reject(err); });
|
|
65
|
+
child.on("exit", (code) => {
|
|
66
|
+
forget();
|
|
67
|
+
code === 0 ? resolve() : reject(new Error(`exit ${code}${stderr ? `: ${stderr.trim().split("\n").slice(-2).join(" | ")}` : ""}`));
|
|
68
|
+
});
|
|
69
|
+
// Unref: an agent run must not hold its caller's event loop open, or a
|
|
70
|
+
// daemon could not shut down while a wake is in flight. A caller that
|
|
71
|
+
// awaits wake() must therefore keep its own handle alive — the exit
|
|
72
|
+
// event will not dispatch on an otherwise empty loop.
|
|
73
|
+
child.unref();
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
// Kill wake children whose spawning owner is no longer alive. Called at
|
|
77
|
+
// dispatch startup and on a sweep timer; never on close, because a child
|
|
78
|
+
// still owned by a live instance is not an orphan.
|
|
79
|
+
function reapOrphans() {
|
|
80
|
+
let names = [];
|
|
81
|
+
try { names = readdirSync(stateDir); } catch { return 0; }
|
|
82
|
+
let killed = 0;
|
|
83
|
+
for (const name of names) {
|
|
84
|
+
if (!name.startsWith("wake-") || !name.endsWith(".json")) continue;
|
|
85
|
+
const file = path.join(stateDir, name);
|
|
86
|
+
let entry;
|
|
87
|
+
try { entry = JSON.parse(readFileSync(file, "utf8")); }
|
|
88
|
+
catch { try { unlinkSync(file); } catch {} continue; }
|
|
89
|
+
if (!entry?.pid || !entry?.ownerPid) { try { unlinkSync(file); } catch {} continue; }
|
|
90
|
+
if (pidAlive(entry.ownerPid)) continue; // owner alive: not an orphan
|
|
91
|
+
if (pidAlive(entry.pid)) {
|
|
92
|
+
// Guard PID reuse: only kill a process still running this wake's
|
|
93
|
+
// command, never whatever now occupies the recycled pid.
|
|
94
|
+
const cmd = processCommand(entry.pid);
|
|
95
|
+
if (cmd.includes("--agent") && entry.message && cmd.includes(entry.message)) {
|
|
96
|
+
reap(entry.pid);
|
|
97
|
+
killed += 1;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
try { unlinkSync(file); } catch {}
|
|
101
|
+
}
|
|
102
|
+
if (killed) logger?.warn?.(`winch: reaped ${killed} orphaned wake(s)`);
|
|
103
|
+
return killed;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
return { wake, reapOrphans };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function consumerIdFor(harness, cfg = {}) {
|
|
110
|
+
return cfg.winchConsumerId ?? process.env.WINCH_CONSUMER_ID ?? `${harness}:${hostname()}`;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function start({ cfg = {}, harness, logger }) {
|
|
114
|
+
const runner = createWakeRunner({ logger, stateDir: cfg.wakeStateDir });
|
|
115
|
+
runner.reapOrphans();
|
|
116
|
+
|
|
117
|
+
const executorId = cfg.winchExecutorId ?? process.env.WINCH_EXECUTOR_ID;
|
|
118
|
+
const consumerId = consumerIdFor(harness, cfg);
|
|
119
|
+
const bearer = process.env.WINCH_WEBHOOK_BEARER;
|
|
120
|
+
if (!executorId || !bearer) {
|
|
121
|
+
logger?.warn?.("winch: dispatch needs WINCH_EXECUTOR_ID and WINCH_WEBHOOK_BEARER; receiver disabled");
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
const dispatch = startDispatch({
|
|
125
|
+
baseUrl: process.env.WINCH_DISPATCH_URL ?? DEFAULT_DISPATCH_URL,
|
|
126
|
+
harness,
|
|
127
|
+
consumerId,
|
|
128
|
+
executorId,
|
|
129
|
+
bearer,
|
|
130
|
+
wake: runner.wake,
|
|
131
|
+
port: Number(cfg.dispatchPort ?? process.env.WINCH_DISPATCH_PORT ?? 0),
|
|
132
|
+
reconcileMs: Number(cfg.dispatchReconcileMs ?? process.env.WINCH_DISPATCH_RECONCILE_MS ?? 30000),
|
|
133
|
+
logger,
|
|
134
|
+
});
|
|
135
|
+
dispatch.ready.catch((err) => logger?.warn?.(`winch: dispatch listener failed: ${err?.message ?? err}`));
|
|
136
|
+
|
|
137
|
+
const sweep = setInterval(() => runner.reapOrphans(), Number(cfg.wakeSweepMs ?? SWEEP_MS));
|
|
138
|
+
sweep.unref?.();
|
|
139
|
+
const close = dispatch.close.bind(dispatch);
|
|
140
|
+
dispatch.close = async () => { clearInterval(sweep); await close(); };
|
|
141
|
+
dispatch.reapOrphans = runner.reapOrphans;
|
|
142
|
+
return dispatch;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// One package, two hosts: V1 calls server() and gets the object hooks; V2
|
|
146
|
+
// reads id/setup() and gets the domain hooks. Both stamp the same identity pair.
|
|
147
|
+
export default {
|
|
148
|
+
id: "winch-opencode",
|
|
149
|
+
async setup(ctx) {
|
|
150
|
+
// SessionContext (the "context" hook event) carries both sessionID and
|
|
151
|
+
// the session's agent; session.get() in this beta returns a projection
|
|
152
|
+
// without agent, so the request hook is the reliable source.
|
|
153
|
+
const cfg = ctx.options ?? {};
|
|
154
|
+
const harness = cfg.winchHarness ?? process.env.WINCH_HARNESS ?? "opencode";
|
|
155
|
+
const consumerId = consumerIdFor(harness, cfg);
|
|
156
|
+
const executorId = cfg.winchExecutorId ?? process.env.WINCH_EXECUTOR_ID ?? null;
|
|
157
|
+
const agents = new Map();
|
|
158
|
+
let dispatch = null;
|
|
159
|
+
const ensureDispatch = () => {
|
|
160
|
+
if (dispatch) return;
|
|
161
|
+
if (cfg.dispatchEnabled === false || process.env.WINCH_DISPATCH_ENABLED === "0") return;
|
|
162
|
+
dispatch = start({ cfg, harness, logger: console });
|
|
163
|
+
};
|
|
164
|
+
await ctx.session.hook("context", (event) => {
|
|
165
|
+
if (event?.sessionID && event.agent) agents.set(event.sessionID, event.agent);
|
|
166
|
+
ensureDispatch();
|
|
167
|
+
});
|
|
168
|
+
await ctx.tool.hook("execute.before", (event) => {
|
|
169
|
+
const agent = agents.get(event.sessionID) ?? process.env.WINCH_AGENT ?? null;
|
|
170
|
+
// Unconditional: unknown agent blanks the slot, the server refuses
|
|
171
|
+
// rather than trusting whatever the model wrote there.
|
|
172
|
+
stampWinchEvent(event, agent, consumerId, executorId);
|
|
173
|
+
});
|
|
174
|
+
},
|
|
175
|
+
async server() {
|
|
176
|
+
const harness = process.env.WINCH_HARNESS ?? "opencode";
|
|
177
|
+
const consumerId = consumerIdFor(harness);
|
|
178
|
+
const executorId = process.env.WINCH_EXECUTOR_ID ?? null;
|
|
179
|
+
const hooks = createWinchHooks({ consumerId, instanceId: executorId });
|
|
180
|
+
let dispatch = null;
|
|
181
|
+
const ensureDispatch = () => {
|
|
182
|
+
if (dispatch) return;
|
|
183
|
+
if (process.env.WINCH_DISPATCH_ENABLED === "0") return;
|
|
184
|
+
dispatch = start({ cfg: {}, harness, logger: console });
|
|
185
|
+
};
|
|
186
|
+
const origMessage = hooks["chat.message"];
|
|
187
|
+
hooks["chat.message"] = async (input) => {
|
|
188
|
+
if (typeof origMessage === "function") await origMessage(input);
|
|
189
|
+
ensureDispatch();
|
|
190
|
+
};
|
|
191
|
+
const origParams = hooks["chat.params"];
|
|
192
|
+
hooks["chat.params"] = async (input) => {
|
|
193
|
+
if (typeof origParams === "function") await origParams(input);
|
|
194
|
+
ensureDispatch();
|
|
195
|
+
};
|
|
196
|
+
return hooks;
|
|
197
|
+
},
|
|
198
|
+
};
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@igorjpimenta/winch-opencode",
|
|
3
|
+
"version": "2026.11.19-beta.1",
|
|
4
|
+
"description": "OpenCode companion for winch: stamps agent and session identity on winch tool calls, receives HTTP dispatch wakes, and reconciles assigned in-progress work. No SDK dependency — a plain id/setup/server export.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/igorjpimenta/winch.git",
|
|
10
|
+
"directory": "plugins/opencode/winch"
|
|
11
|
+
},
|
|
12
|
+
"publishConfig": {
|
|
13
|
+
"registry": "https://registry.npmjs.org",
|
|
14
|
+
"access": "public"
|
|
15
|
+
},
|
|
16
|
+
"exports": {
|
|
17
|
+
".": "./index.js"
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"index.js",
|
|
21
|
+
"hooks.js",
|
|
22
|
+
"identity.js",
|
|
23
|
+
"dispatch.js"
|
|
24
|
+
],
|
|
25
|
+
"main": "index.js"
|
|
26
|
+
}
|
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
|
+
}
|