@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.
Files changed (88) hide show
  1. package/.migrations/0000_next_katie_power.sql +99 -0
  2. package/.migrations/0001_add-events-kind.sql +8 -0
  3. package/.migrations/0002_drop-session-budgets.sql +1 -0
  4. package/.migrations/0003_pink_siren.sql +8 -0
  5. package/.migrations/0004_salty_trauma.sql +1 -0
  6. package/.migrations/0005_classy_havok.sql +1 -0
  7. package/.migrations/0006_recursive_items.sql +265 -0
  8. package/.migrations/0007_unify_statuses.sql +35 -0
  9. package/.migrations/0008_core_dispatch.sql +61 -0
  10. package/.migrations/0009_webhooks.sql +17 -0
  11. package/.migrations/0010_dispatch_consumer_id.sql +1 -0
  12. package/.migrations/0011_dispatch_delivery_leases.sql +53 -0
  13. package/.migrations/0012_dispatch_fencing_audit.sql +32 -0
  14. package/.migrations/meta/0000_snapshot.json +658 -0
  15. package/.migrations/meta/0001_snapshot.json +665 -0
  16. package/.migrations/meta/0002_snapshot.json +604 -0
  17. package/.migrations/meta/0003_snapshot.json +656 -0
  18. package/.migrations/meta/0004_snapshot.json +664 -0
  19. package/.migrations/meta/0005_snapshot.json +671 -0
  20. package/.migrations/meta/0006_snapshot.json +1089 -0
  21. package/.migrations/meta/0007_unify_statuses_snapshot.json +1097 -0
  22. package/.migrations/meta/0008_snapshot.json +1382 -0
  23. package/.migrations/meta/0009_snapshot.json +1428 -0
  24. package/.migrations/meta/0010_snapshot.json +1435 -0
  25. package/.migrations/meta/0011_snapshot.json +1670 -0
  26. package/.migrations/meta/0012_snapshot.json +1900 -0
  27. package/.migrations/meta/_journal.json +97 -0
  28. package/README.md +480 -2
  29. package/bin/winch.js +4 -0
  30. package/package.json +36 -4
  31. package/plugins/README.md +304 -0
  32. package/plugins/openclaw/winch/README.md +71 -0
  33. package/plugins/openclaw/winch/dispatch.js +236 -0
  34. package/plugins/openclaw/winch/index.js +139 -0
  35. package/plugins/openclaw/winch/meta.js +35 -0
  36. package/plugins/openclaw/winch/openclaw.plugin.json +43 -0
  37. package/plugins/openclaw/winch/package.json +37 -0
  38. package/plugins/opencode/winch/dispatch.js +228 -0
  39. package/plugins/opencode/winch/hooks.js +22 -0
  40. package/plugins/opencode/winch/identity.js +34 -0
  41. package/plugins/opencode/winch/index.js +104 -0
  42. package/plugins/opencode/winch/package.json +26 -0
  43. package/src/cli.js +434 -0
  44. package/src/config.js +181 -0
  45. package/src/db.js +39 -0
  46. package/src/deps.js +70 -0
  47. package/src/dispatch-server.js +204 -0
  48. package/src/dispatch-webhook.js +221 -0
  49. package/src/dispatch.js +258 -0
  50. package/src/events-ws.js +269 -0
  51. package/src/identity.js +140 -0
  52. package/src/ids.js +18 -0
  53. package/src/mcp-http.js +208 -0
  54. package/src/mcp.js +107 -0
  55. package/src/merges.js +150 -0
  56. package/src/paths.js +15 -0
  57. package/src/ready-queue.js +77 -0
  58. package/src/release.js +96 -0
  59. package/src/reserved.js +23 -0
  60. package/src/schema.js +302 -0
  61. package/src/store/admission.js +314 -0
  62. package/src/store/artifacts.js +24 -0
  63. package/src/store/attempts.js +22 -0
  64. package/src/store/claims.js +182 -0
  65. package/src/store/core.js +225 -0
  66. package/src/store/delivery.js +137 -0
  67. package/src/store/deps.js +62 -0
  68. package/src/store/dispatch-events.js +38 -0
  69. package/src/store/epics.js +31 -0
  70. package/src/store/events.js +21 -0
  71. package/src/store/gates.js +85 -0
  72. package/src/store/index.js +135 -0
  73. package/src/store/items.js +303 -0
  74. package/src/store/stories.js +37 -0
  75. package/src/store/sweep.js +77 -0
  76. package/src/store/tasks.js +190 -0
  77. package/src/store/webhook.js +197 -0
  78. package/src/tools/accept-wake.js +30 -0
  79. package/src/tools/assign.js +75 -0
  80. package/src/tools/claim.js +88 -0
  81. package/src/tools/definitions.js +371 -0
  82. package/src/tools/delegate.js +147 -0
  83. package/src/tools/index.js +44 -0
  84. package/src/tools/plan.js +262 -0
  85. package/src/tools/read.js +103 -0
  86. package/src/tools/report.js +190 -0
  87. package/src/tools/shared.js +62 -0
  88. package/src/watcher.js +105 -0
@@ -0,0 +1,208 @@
1
+ // mcp-http.js — shared Streamable HTTP MCP server.
2
+ // Same tools + same identity contract as stdio (src/mcp.js), different door:
3
+ // one TCP socket, many harnesses as HTTP clients instead of one pipe per spawn.
4
+ // Ships as a portable container image; runs anywhere (VPS, compose, k8s) —
5
+ // no cloud-specific APIs.
6
+ //
7
+ // Auth: `Authorization: Bearer <WINCH_BEARER>` checked before any tool runs
8
+ // (WINCH_BEARER required; missing/empty refuses to start). Terminate TLS in
9
+ // front (reverse proxy / ingress) — the server itself speaks plain HTTP.
10
+ // Identity: `X-Winch-Harness: <name>` declares the harness per session and
11
+ // must be a usable layer; agent+session still arrive per call via _meta.winch
12
+ // (openclaw) or stamped args (opencode) — identical to stdio resolution.
13
+ // GET /health is unauthenticated for load-balancer / HEALTHCHECK probes.
14
+
15
+ import http from "node:http";
16
+ import net from "node:net";
17
+ import { randomUUID } from "node:crypto";
18
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
19
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
20
+ import * as z from "zod/v4-mini";
21
+ import { createToolHandlers } from "./tools/index.js";
22
+ import { resolveIdentity, identitySessionKey, assertDeclaration } from "./identity.js";
23
+ import { toolErrorResult } from "./mcp.js";
24
+ import { toMcpResult } from "./tools/shared.js";
25
+
26
+ // DNS rebinding: reject non-local Host/Origin before auth so a page served
27
+ // from an attacker domain cannot drive a loopback server. IP literals and the
28
+ // bound host stay allowed so an explicit LAN bind still works.
29
+ function headerHostname(raw) {
30
+ if (typeof raw !== "string" || !/^[A-Za-z0-9.\-:[\]]+$/.test(raw)) return null;
31
+ try {
32
+ return new URL(`http://${raw}`).hostname.replace(/^\[|\]$/g, "").toLowerCase().replace(/\.$/, "");
33
+ } catch {
34
+ return null;
35
+ }
36
+ }
37
+
38
+ function localHostname(hostname, boundHost, { anyIp = true } = {}) {
39
+ if (!hostname) return false;
40
+ if (hostname === "localhost" || hostname.endsWith(".localhost")) return true;
41
+ if (hostname === "127.0.0.1" || hostname === "::1") return true;
42
+ if (anyIp && net.isIP(hostname)) return true;
43
+ const bound = String(boundHost ?? "").toLowerCase().replace(/^\[|\]$/g, "").replace(/\.$/, "");
44
+ return bound !== "" && bound !== "0.0.0.0" && bound !== "::" && hostname === bound;
45
+ }
46
+
47
+ function localRequest(req, boundHost) {
48
+ const host = headerHostname(req.headers.host);
49
+ if (!localHostname(host, boundHost)) return false;
50
+ const origin = req.headers.origin;
51
+ if (origin === undefined || origin === "") return true;
52
+ if (typeof origin !== "string" || origin === "null") return false;
53
+ try {
54
+ const url = new URL(origin);
55
+ if (url.protocol !== "http:" && url.protocol !== "https:") return false;
56
+ return localHostname(
57
+ url.hostname.replace(/^\[|\]$/g, "").toLowerCase().replace(/\.$/, ""),
58
+ boundHost,
59
+ { anyIp: false },
60
+ );
61
+ } catch {
62
+ return false;
63
+ }
64
+ }
65
+
66
+ function fieldFromJson(schema) {
67
+ if (!schema || typeof schema !== "object") return z.unknown();
68
+ if (schema.enum && Array.isArray(schema.enum)) return z.enum(schema.enum);
69
+ if (schema.type === "string") return z.string();
70
+ if (schema.type === "integer" || schema.type === "number") return z.number();
71
+ if (schema.type === "boolean") return z.boolean();
72
+ if (schema.type === "array") return z.array(fieldFromJson(schema.items));
73
+ if (schema.type === "object") return z.object(shapeFromJson(schema));
74
+ return z.unknown();
75
+ }
76
+
77
+ function shapeFromJson(schema) {
78
+ const shape = {};
79
+ const required = new Set(schema.required ?? []);
80
+ for (const [key, sub] of Object.entries(schema.properties ?? {})) {
81
+ const field = fieldFromJson(sub);
82
+ shape[key] = required.has(key) ? field : z.optional(field);
83
+ }
84
+ shape.winch_agent = z.optional(z.string());
85
+ shape.winch_session = z.optional(z.string());
86
+ shape.winch_consumer = z.optional(z.string());
87
+ shape.winch_instance = z.optional(z.string());
88
+ shape._meta = z.optional(z.unknown());
89
+ return shape;
90
+ }
91
+
92
+ function readBody(req) {
93
+ return new Promise((resolve, reject) => {
94
+ const chunks = [];
95
+ req.on("data", (c) => chunks.push(c));
96
+ req.on("end", () => {
97
+ if (chunks.length === 0) return resolve(undefined);
98
+ try {
99
+ resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")));
100
+ } catch (err) {
101
+ reject(err);
102
+ }
103
+ });
104
+ req.on("error", reject);
105
+ });
106
+ }
107
+
108
+ export async function startMcpHttpServer({ store, port = null, host = "127.0.0.1", logger } = {}) {
109
+ const bearer = process.env.WINCH_BEARER;
110
+ if (!bearer || bearer.trim() === "") {
111
+ throw new Error("winch: serve --mcp http refuses without WINCH_BEARER (local, but with auth). Set a bearer token in the environment.");
112
+ }
113
+ const cfg = store.config ?? {};
114
+ const listenPort = port ?? cfg.mcpHttpPort ?? 38292;
115
+ const sessions = new Map();
116
+
117
+ async function sessionFor(req, base) {
118
+ const sid = req.headers["mcp-session-id"];
119
+ if (typeof sid === "string" && sessions.has(sid)) return sessions.get(sid);
120
+ const { TOOL_DEFS, handle } = createToolHandlers(store, logger);
121
+ const server = new McpServer({ name: "winch", version: "0.1.0" });
122
+ for (const def of TOOL_DEFS) {
123
+ server.registerTool(
124
+ def.name,
125
+ { description: def.description, inputSchema: z.object(shapeFromJson(def.inputSchema)) },
126
+ async (args, extra) => {
127
+ try {
128
+ const identity = resolveIdentity({ meta: extra?._meta, args, base });
129
+ logger?.info?.(`winch: ${def.name} from ${identitySessionKey(identity)}`);
130
+ const res = await handle(def.name, args, identity, extra?._meta);
131
+ return toMcpResult(res);
132
+ } catch (err) {
133
+ return toolErrorResult(err);
134
+ }
135
+ }
136
+ );
137
+ }
138
+ const transport = new StreamableHTTPServerTransport({
139
+ sessionIdGenerator: () => randomUUID(),
140
+ onsessioninitialized: (id) => sessions.set(id, { server, transport }),
141
+ });
142
+ transport.onclose = () => {
143
+ for (const [id, entry] of sessions) {
144
+ if (entry.transport === transport) sessions.delete(id);
145
+ }
146
+ };
147
+ await server.connect(transport);
148
+ return { server, transport };
149
+ }
150
+
151
+ const httpServer = http.createServer(async (req, res) => {
152
+ try {
153
+ const url = new URL(req.url ?? "/", "http://x");
154
+ if (url.pathname === "/health") {
155
+ res.writeHead(200, { "content-type": "application/json" });
156
+ res.end(JSON.stringify({ ok: true }));
157
+ return;
158
+ }
159
+ if (url.pathname !== "/mcp") {
160
+ res.writeHead(404, { "content-type": "text/plain" });
161
+ res.end("winch mcp-http: POST /mcp only\n");
162
+ return;
163
+ }
164
+ if (!localRequest(req, host)) {
165
+ res.writeHead(403, { "content-type": "application/json" });
166
+ res.end(JSON.stringify({ error: "forbidden: non-local Host/Origin" }));
167
+ return;
168
+ }
169
+ const auth = req.headers.authorization ?? "";
170
+ if (auth !== `Bearer ${bearer}`) {
171
+ res.writeHead(401, { "content-type": "application/json" });
172
+ res.end(JSON.stringify({ error: "unauthorized: bad or missing bearer" }));
173
+ return;
174
+ }
175
+ const harness = req.headers["x-winch-harness"];
176
+ let base;
177
+ try {
178
+ base = assertDeclaration({ harness: Array.isArray(harness) ? harness[0] : harness });
179
+ } catch {
180
+ res.writeHead(400, { "content-type": "application/json" });
181
+ res.end(JSON.stringify({ error: "missing or reserved X-Winch-Harness" }));
182
+ return;
183
+ }
184
+ const { transport } = await sessionFor(req, base);
185
+ let body;
186
+ if (req.method === "POST") body = await readBody(req);
187
+ await transport.handleRequest(req, res, body);
188
+ } catch (err) {
189
+ logger?.warn?.(`winch: mcp-http request failed: ${err?.message ?? err}`);
190
+ if (!res.headersSent) {
191
+ res.writeHead(500, { "content-type": "application/json" });
192
+ res.end(JSON.stringify({ error: "internal error" }));
193
+ }
194
+ }
195
+ });
196
+
197
+ return new Promise((resolve, reject) => {
198
+ httpServer.once("error", reject);
199
+ httpServer.listen(listenPort, host, () => {
200
+ logger?.info?.(`winch: mcp-http on http://${host}:${httpServer.address().port}/mcp (Streamable HTTP; bearer + X-Winch-Harness)`);
201
+ resolve({
202
+ port: httpServer.address().port,
203
+ host,
204
+ close: () => new Promise((res) => httpServer.close(() => res())),
205
+ });
206
+ });
207
+ });
208
+ }
package/src/mcp.js ADDED
@@ -0,0 +1,107 @@
1
+ // mcp.js — stdio MCP server exposing the backlog tools. stdout is the
2
+ // JSON-RPC channel: every log line goes to stderr, and nothing else may be
3
+ // written to stdout.
4
+ //
5
+ // Request `_meta` surfaces on the handler's second argument (`extra._meta`,
6
+ // the original request's params._meta — see the SDK's RequestHandlerExtra).
7
+ // `extra._meta.winch` is the trusted companion-plugin channel; models cannot
8
+ // forge it because the plugin overwrites it unconditionally.
9
+
10
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
11
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
12
+ import * as z from "zod/v4-mini";
13
+ import { createToolHandlers } from "./tools/index.js";
14
+ import { toMcpResult } from "./tools/shared.js";
15
+ import { resolveIdentity, identitySessionKey, assertDeclaration } from "./identity.js";
16
+
17
+ // JSON Schema → zod raw shape for the subset the tool defs use (string,
18
+ // boolean, string arrays, nested objects, string enums). zod is the MCP
19
+ // SDK's required peer dependency, not a direct winch dependency.
20
+ function fieldFromJson(schema) {
21
+ if (!schema || typeof schema !== "object") return z.unknown();
22
+ if (schema.enum && Array.isArray(schema.enum)) return z.enum(schema.enum);
23
+ if (schema.type === "string") return z.string();
24
+ if (schema.type === "integer" || schema.type === "number") return z.number();
25
+ if (schema.type === "boolean") return z.boolean();
26
+ if (schema.type === "array") return z.array(fieldFromJson(schema.items));
27
+ if (schema.type === "object") return z.object(shapeFromJson(schema));
28
+ return z.unknown();
29
+ }
30
+
31
+ function shapeFromJson(schema) {
32
+ const shape = {};
33
+ const required = new Set(schema.required ?? []);
34
+ for (const [key, sub] of Object.entries(schema.properties ?? {})) {
35
+ const field = fieldFromJson(sub);
36
+ shape[key] = required.has(key) ? field : z.optional(field);
37
+ }
38
+ // Identity is a transport concern, not a tool-domain one — like _meta, it
39
+ // rides every call without belonging to any tool's vocabulary. Declared
40
+ // here (optional, so schemas stay backward compatible) rather than in each
41
+ // TOOL_DEF: companions that can only mutate args (e.g. opencode's hook)
42
+ // stamp these, and resolveIdentity reads them — plus args._meta.winch for
43
+ // twins whose hook output lands inside arguments — when _meta is
44
+ // unreachable.
45
+ // Sound only over stdio, where the spawner is the sole peer; a companion
46
+ // overwrites them unconditionally, so model-supplied values never survive.
47
+ // The _meta passthrough below is load-bearing, not laxity: without a
48
+ // declared slot the SDK strips the twin's stamp before the handler runs,
49
+ // and the args._meta channel silently never fires.
50
+ shape.winch_agent = z.optional(z.string());
51
+ shape.winch_session = z.optional(z.string());
52
+ shape.winch_consumer = z.optional(z.string());
53
+ shape.winch_instance = z.optional(z.string());
54
+ shape._meta = z.optional(z.unknown());
55
+ return shape;
56
+ }
57
+
58
+ /**
59
+ * Unexpected failures — anything handle() throws, including a poisoned
60
+ * caller identity — become tool-error results. Domain rejections keep their
61
+ * own content; the call fails, the server survives the request.
62
+ */
63
+ export function toolErrorResult(err) {
64
+ const message = `winch: tool failed: ${String(err?.message ?? err)}`;
65
+ // keep stdio clean: diagnostics would corrupt the JSON-RPC stream
66
+ if (process.env.WINCH_MCP_DEBUG) {
67
+ console.error(message);
68
+ }
69
+ return {
70
+ content: [{ type: "text", text: JSON.stringify({ error: message }) }],
71
+ isError: true,
72
+ };
73
+ }
74
+
75
+ export async function startMcpServer({ store, base, logger }) {
76
+ // Identity is refused, never defaulted, at both layers: an undeclared
77
+ // server will not start, and an unstamped, unusable, or mismatched call
78
+ // will not run. No path mints a key the trail cannot attribute — failure
79
+ // happens at the boundary, never as poison downstream.
80
+ const declared = assertDeclaration(base);
81
+ const { TOOL_DEFS, handle } = createToolHandlers(store, logger);
82
+ const server = new McpServer({ name: "winch", version: "0.1.0" });
83
+
84
+ for (const def of TOOL_DEFS) {
85
+ server.registerTool(
86
+ def.name,
87
+ { description: def.description, inputSchema: z.object(shapeFromJson(def.inputSchema)) },
88
+ async (args, extra) => {
89
+ try {
90
+ const identity = resolveIdentity({ meta: extra?._meta, args, base: declared });
91
+ logger?.info?.(`winch: ${def.name} from ${identitySessionKey(identity)}`);
92
+ // Per-call config overlay rides the same trusted meta channel as
93
+ // agent/session; malformed knobs refuse the call, never the server.
94
+ const res = await handle(def.name, args, identity, extra?._meta);
95
+ return toMcpResult(res);
96
+ } catch (err) {
97
+ return toolErrorResult(err);
98
+ }
99
+ }
100
+ );
101
+ }
102
+
103
+ const transport = new StdioServerTransport();
104
+ await server.connect(transport);
105
+ logger?.info?.("winch: MCP server connected on stdio");
106
+ return server;
107
+ }
package/src/merges.js ADDED
@@ -0,0 +1,150 @@
1
+ // merges.js — read PR states and apply what a merge (or an unmerged close)
2
+ // means to backlog rows, idempotently.
3
+ //
4
+ // Markers come from release PR bodies: `Backlog: <item-id>`, optional
5
+ // `Backlog-Task: <task-id>`, optional `Release: vX.Y.Z`. gh reports state as
6
+ // MERGED / CLOSED / OPEN — normalized here, callers pass raw values.
7
+
8
+ export function parseMarkers(body = "") {
9
+ const out = { epicId: null, taskId: null, version: null };
10
+ const text = typeof body === "string" ? body : "";
11
+ const m = text.match(/^\s*Backlog:\s*(\S+)/m);
12
+ if (m) out.epicId = m[1];
13
+ const t = text.match(/^\s*Backlog-Task:\s*(\S+)/m);
14
+ if (t) out.taskId = t[1];
15
+ const v = text.match(/^\s*Release:\s*(\S+)/m);
16
+ if (v) out.version = v[1];
17
+ return out;
18
+ }
19
+
20
+ /**
21
+ * @param {Array<{number:number, state:string, title:string, body:string}>} prs
22
+ * @param {{exec?: Function, cwd?: string, dryRun?: boolean}} opts — exec runs
23
+ * the git tag when a Release marker lands; tests inject a recorder.
24
+ * @returns summary of every transition applied (idempotent on re-run)
25
+ */
26
+ export function applyMergeOutcomes(store, prs, { exec = null, cwd = process.cwd(), dryRun = false } = {}) {
27
+ const out = { doneTasks: [], reopenedTasks: [], closedEpics: [], tagged: [], skipped: [] };
28
+ for (const pr of prs) {
29
+ const markers = parseMarkers(pr.body);
30
+ const state = String(pr.state ?? "").toUpperCase();
31
+ if (!markers.epicId && !markers.taskId) continue;
32
+
33
+ const task = markers.taskId ? store.task.get(markers.taskId) : null;
34
+ const epic = markers.epicId ? store.epic.get(markers.epicId) : null;
35
+ if (epic && task && task.epic_id !== epic.id) {
36
+ out.skipped.push(`pr#${pr.number}:task-epic-mismatch`);
37
+ continue;
38
+ }
39
+
40
+ if (state === "MERGED") {
41
+ if (task) {
42
+ if (task.status !== "done") {
43
+ // A merge lands regardless of who holds the claim. When it takes
44
+ // a task out from under a working agent, the note names the
45
+ // displacement — the agent's next tool call would otherwise fail
46
+ // with no account of why its task completed itself.
47
+ const displaced = task.status === "in_progress" && task.assignee_agent ? ` (displaced ${task.assignee_agent})` : "";
48
+ if (!dryRun) {
49
+ store.task.update(task.id, {
50
+ status: "done",
51
+ result_summary: `merged via PR #${pr.number}: ${pr.title}`,
52
+ actor: "merge-detector",
53
+ note: `merged: PR #${pr.number}${displaced}`,
54
+ });
55
+ }
56
+ out.doneTasks.push(task.id);
57
+ }
58
+ }
59
+ if (markers.epicId && markers.version) {
60
+ if (epic && epic.status !== "done") {
61
+ if (!dryRun) store.epic.update(epic.id, { status: "done", actor: "merge-detector", note: `release ${markers.version}` });
62
+ out.closedEpics.push(epic.id);
63
+ }
64
+ // The shipped marker hangs off the release task: events are
65
+ // item-scoped, so a version without a task anchor has nowhere honest
66
+ // to live.
67
+ const releaseTask = task;
68
+ const releaseNote = `release shipped: ${markers.version}`;
69
+ const already = releaseTask
70
+ ? store.event.listFor(releaseTask.id).some((e) => e.note === releaseNote)
71
+ : null;
72
+ if (!releaseTask) out.skipped.push(`release:${markers.version} (no release task)`);
73
+ // Tag before the event: the shipped row asserts a tag exists, so a
74
+ // failed tag records a skip and writes nothing — the wire never
75
+ // claims an untagged shipment.
76
+ if (exec) {
77
+ if (!out.tagged.includes(markers.version)) {
78
+ if (!dryRun) {
79
+ try { exec("git", ["tag", markers.version], { cwd, stdio: "ignore" }); } catch { out.skipped.push(`tag:${markers.version}`); continue; }
80
+ }
81
+ out.tagged.push(markers.version);
82
+ }
83
+ if (releaseTask && !already && !dryRun) {
84
+ const cur = store.task.get(releaseTask.id);
85
+ store.event.append({
86
+ itemId: releaseTask.id, fromStatus: cur.status, toStatus: cur.status,
87
+ kind: "release.shipped", actor: "merge-detector", note: releaseNote,
88
+ });
89
+ }
90
+ } else if (releaseTask && !already) {
91
+ out.skipped.push(`release:${markers.version} (no tag executor)`);
92
+ }
93
+ }
94
+ } else if (state === "CLOSED") {
95
+ // Unmerged close = the work did not land. Anything mid-flight on that PR
96
+ // returns to the queue for a fresh claim; 'done' stays done — a later
97
+ // revert is a new ticket, not a rewrite of history.
98
+ if (task) {
99
+ const reopenable = task.status === "in_progress" || task.status === "review"
100
+ || (task.status === "blocked" && task.gate_type);
101
+ if (reopenable) {
102
+ // A gate dissolved this way is not a resolution — nobody approved —
103
+ // but it must still stream as a gate ending, not a plain release.
104
+ const dissolved = task.status === "blocked" && task.gate_type;
105
+ if (!dryRun) {
106
+ store.task.update(task.id, {
107
+ status: task.assignee_agent ? "ready" : "backlog", gate_type: null, blocked_at: null,
108
+ actor: "merge-detector",
109
+ note: dissolved ? `gate dissolved: closed unmerged PR #${pr.number}` : `closed unmerged: PR #${pr.number}`,
110
+ });
111
+ }
112
+ out.reopenedTasks.push(task.id);
113
+ }
114
+ }
115
+ } else {
116
+ out.skipped.push(`pr#${pr.number}:${state || "unknown"}`);
117
+ }
118
+ }
119
+ return out;
120
+ }
121
+
122
+ /**
123
+ * Pull PR rows via gh in `cwd`. exec is injectable; returns parsed JSON.
124
+ */
125
+ export function collectPRs({ exec, cwd = process.cwd(), limit = 100 } = {}) {
126
+ const raw = exec(
127
+ "gh",
128
+ ["pr", "list", "--state", "merged", "--state", "closed", "--limit", String(limit), "--json", "number,title,body,state"],
129
+ { cwd, encoding: "utf8" }
130
+ );
131
+ return JSON.parse(raw);
132
+ }
133
+
134
+ const invokedDirectly = process.argv[1]?.endsWith("merges.js");
135
+ if (invokedDirectly) {
136
+ const { execFileSync } = await import("node:child_process");
137
+ const { createStore } = await import("./store/index.js");
138
+ const dryRun = process.argv.includes("--dry-run");
139
+ const store = createStore();
140
+ try {
141
+ const prs = collectPRs({ exec: execFileSync });
142
+ const summary = applyMergeOutcomes(store, prs, { exec: execFileSync, dryRun });
143
+ console.log(JSON.stringify(summary));
144
+ } catch (e) {
145
+ console.error(`merge-detect failed: ${e.message ?? e}`);
146
+ process.exitCode = 1;
147
+ } finally {
148
+ store.close();
149
+ }
150
+ }
package/src/paths.js ADDED
@@ -0,0 +1,15 @@
1
+ // paths.js — winch's own data directory. The store belongs to the backlog
2
+ // server, not to whichever harness happens to launch it.
3
+ //
4
+ // Precedence: WINCH_DB, then ~/.winch/store.sqlite.
5
+
6
+ import os from "node:os";
7
+ import path from "node:path";
8
+
9
+ export function defaultDbPath(home = os.homedir()) {
10
+ return path.join(home, ".winch", "store.sqlite");
11
+ }
12
+
13
+ export function resolveDbPath({ env = process.env, home = os.homedir() } = {}) {
14
+ return env.WINCH_DB || defaultDbPath(home);
15
+ }
@@ -0,0 +1,77 @@
1
+ // ready-queue.js — compute "what's ready to work on" for a given agent.
2
+ //
3
+ // A task is *ready* iff:
4
+ // - status = 'ready' (which the store only permits for an assigned pair)
5
+ // - all of its outgoing deps resolve to status in {done, cancelled}
6
+ // - nearest story status in {ready, in_progress}
7
+ // - (when agentId is supplied) assigned to the same harness:agent pair
8
+ // - (when capabilities supplied) intersection with task/story tags is non-empty
9
+ //
10
+ // The reserved `human` / `human_in_the_loop` pair is ready for a person, never
11
+ // for an agent: dispatchers must keep it out of agent wake lists.
12
+ //
13
+ // Ordering: priority DESC (cascading story/epic priority on tie),
14
+ // then created_at ASC.
15
+
16
+ import { depsResolved } from "./deps.js";
17
+
18
+ function effectiveCaps(task, story) {
19
+ if (Array.isArray(task.capabilities) && task.capabilities.length > 0) return task.capabilities;
20
+ if (Array.isArray(story?.capabilities) && story.capabilities.length > 0) return story.capabilities;
21
+ return [];
22
+ }
23
+
24
+ function capMatch(required, offered) {
25
+ if (!required || required.length === 0) return true; // no requirement = open
26
+ if (!offered || offered.length === 0) return false;
27
+ return required.some((r) => offered.includes(r));
28
+ }
29
+
30
+ /**
31
+ * Return ready tasks, ordered by composite priority.
32
+ *
33
+ * @param {{agentId?: string, harness?: string, capabilities?: string[], limit?: number}} opts
34
+ */
35
+ export function readyTasks(store, opts = {}) {
36
+ const { agentId, harness, capabilities, limit, ignoreCapabilities = false } = opts;
37
+ const candidates = store.item.list({ kind: "task", status: "ready" });
38
+ const ready = [];
39
+ for (const task of candidates) {
40
+ const story = task.story_id ? store.item.get(task.story_id) : null;
41
+ if (!story) continue;
42
+ if (story.status !== "ready" && story.status !== "in_progress") continue;
43
+ const epic = task.epic_id ? store.item.get(task.epic_id) : null;
44
+ if (!epic) continue;
45
+ if (agentId) {
46
+ if (task.assignee_agent !== agentId) continue;
47
+ // Legacy assignments carry the wildcard harness; new ones name it.
48
+ if (harness && task.assignee_harness !== harness) continue;
49
+ }
50
+ const required = effectiveCaps(task, story);
51
+ if (!ignoreCapabilities && !capMatch(required, capabilities)) continue;
52
+ if (!depsResolved(store, task.id)) continue;
53
+ if (!depsResolved(store, story.id)) continue;
54
+ if (!depsResolved(store, epic.id)) continue;
55
+ ready.push({
56
+ task,
57
+ story,
58
+ epic,
59
+ composite: [task.assignee_agent === agentId ? 1 : 0, story.priority, epic.priority, -task.created_at],
60
+ });
61
+ }
62
+ ready.sort((a, b) => {
63
+ for (let i = 0; i < a.composite.length; i++) {
64
+ if (a.composite[i] !== b.composite[i]) return b.composite[i] - a.composite[i];
65
+ }
66
+ return 0;
67
+ });
68
+ return (limit && limit > 0) ? ready.slice(0, limit) : ready;
69
+ }
70
+
71
+ /**
72
+ * Return the single next-best ready task for an agent, or null. Read-only.
73
+ */
74
+ export function nextReadyTask(store, opts = {}) {
75
+ const list = readyTasks(store, { ...opts, limit: 1 });
76
+ return list[0] ?? null;
77
+ }
package/src/release.js ADDED
@@ -0,0 +1,96 @@
1
+ // release.js — render release notes from the store, then open a branch + PR
2
+ // that carries the backlog markers the merge detector keys on (`Backlog:
3
+ // <item-id>`, optional `Backlog-Task: <task-id>`, optional `Release: vX.Y.Z`).
4
+
5
+ import { execFileSync } from "node:child_process";
6
+
7
+ export function renderReleaseNotes(store, epicId) {
8
+ const epic = store.epic.get(epicId);
9
+ if (!epic) throw new Error(`epic not found: ${epicId}`);
10
+ const stories = store.item.list({ kind: "story", parentId: epicId });
11
+ const lines = [
12
+ `# Release notes — ${epic.title}`,
13
+ "",
14
+ `Epic: ${epic.id} · status: ${epic.status} · priority: ${epic.priority}`,
15
+ epic.acceptance ? `\n## Acceptance\n${epic.acceptance}` : "",
16
+ "",
17
+ "## Stories",
18
+ ];
19
+ for (const s of stories) {
20
+ lines.push(`- [${s.status}] ${s.id} ${s.title}${s.acceptance ? ` — ${s.acceptance}` : ""}`);
21
+ for (const t of store.item.tree(s.id).filter((r) => r.kind === "task")) {
22
+ const mark = t.status === "done" ? "x" : " ";
23
+ lines.push(` - [${mark}] ${t.id} ${t.title}${t.result_summary ? ` — ${t.result_summary.split("\n")[0]}` : ""}`);
24
+ }
25
+ }
26
+ const gated = store.item
27
+ .list({ kind: "task", status: "blocked" })
28
+ .filter((t) => t.epic_id === epicId && t.gate_type);
29
+ if (gated.length) {
30
+ lines.push("", "## Open gates");
31
+ for (const g of gated) lines.push(`- ${g.gate_type}: ${g.id} ${g.title}`);
32
+ }
33
+ const ids = store.item.tree(epicId).map((r) => r.id);
34
+ const count = ids.length
35
+ ? store.db.prepare(`SELECT COUNT(*) AS n FROM item_events WHERE item_id IN (${ids.map(() => "?").join(",")})`).get(...ids).n
36
+ : 0;
37
+ lines.push("", `## Audit`, `- ${count} recorded events across this epic's tasks`, "");
38
+ return lines.filter((l) => l !== null && l !== undefined).join("\n");
39
+ }
40
+
41
+ /**
42
+ * Open a release PR in `cwd` (a git checkout with gh auth). Returns
43
+ * {prUrl, branch, notes}. `exec` is injectable for tests; the default runs
44
+ * git/gh synchronously and throws on non-zero exit.
45
+ */
46
+ export function shipRelease(store, { epicId, taskId = null, version = null, base = "main", cwd = process.cwd(), exec = execFileSync } = {}) {
47
+ const epic = store.epic.get(epicId);
48
+ if (!epic) throw new Error(`epic not found: ${epicId}`);
49
+ const slug = epicId.toLowerCase().replace(/[^a-z0-9]+/g, "-");
50
+ const branch = `release/${slug}`;
51
+ const notes = renderReleaseNotes(store, epicId);
52
+ const marker = [`Backlog: ${epicId}`];
53
+ if (taskId) marker.push(`Backlog-Task: ${taskId}`);
54
+ if (version) marker.push(`Release: ${version}`);
55
+ const notesPath = `RELEASE-NOTES-${epicId}.md`;
56
+
57
+ const sh = (cmd, args) => exec(cmd, args, { cwd, encoding: "utf8" });
58
+ try { sh("git", ["checkout", base]); } catch { /* fresh branch from current HEAD */ }
59
+ sh("git", ["checkout", "-B", branch]);
60
+ sh("bash", ["-c", `cat > ${notesPath} <<'RELEASE_NOTES_EOF'\n${notes}\nRELEASE_NOTES_EOF`]);
61
+ sh("git", ["add", notesPath]);
62
+ sh("git", ["commit", "-m", `docs(release): ${epic.title}`]);
63
+ sh("git", ["push", "-u", "origin", branch, "--force-with-lease"]);
64
+ const body = [
65
+ notes,
66
+ "",
67
+ "---",
68
+ marker.join(" · "),
69
+ "_Opened by winch release automation; merge closes the loop with the merge detector._",
70
+ ].join("\n");
71
+ const prUrl = sh("gh", [
72
+ "pr", "create", "--base", base, "--head", branch,
73
+ "--title", `docs(release): ${epic.title}`,
74
+ "--body", body,
75
+ ]).trim();
76
+ return { prUrl, branch, notes, notesPath };
77
+ }
78
+
79
+ const invokedDirectly = process.argv[1]?.endsWith("release.js");
80
+ if (invokedDirectly) {
81
+ const { createStore } = await import("./store/index.js");
82
+ const argv = process.argv.slice(2);
83
+ const get = (flag) => { const i = argv.indexOf(flag); return i >= 0 ? argv[i + 1] : null; };
84
+ const epicId = get("--epic");
85
+ if (!epicId) { console.error("usage: release.js --epic <id> [--task <id>] [--version vX.Y.Z] [--base main]"); process.exit(2); }
86
+ const store = createStore();
87
+ try {
88
+ const r = shipRelease(store, { epicId, taskId: get("--task"), version: get("--version"), base: get("--base") || "main" });
89
+ console.log(r.prUrl);
90
+ } catch (e) {
91
+ console.error(`release failed: ${e.message ?? e}`);
92
+ process.exitCode = 1;
93
+ } finally {
94
+ store.close();
95
+ }
96
+ }
@@ -0,0 +1,23 @@
1
+ // Reserved assignment identities. They name human work, never a caller:
2
+ // `human` is an assignee sentinel and `human_in_the_loop` is the harness
3
+ // stamped with it. Both are refused as caller layers by identity.js.
4
+
5
+ export const HUMAN_AGENT = "human";
6
+ export const HUMAN_HARNESS = "human_in_the_loop";
7
+
8
+ export function isReservedLayer(layer, value) {
9
+ if (typeof value !== "string") return false;
10
+ const v = value.trim();
11
+ return (
12
+ (layer === "harness" && v === HUMAN_HARNESS) ||
13
+ (layer === "agent" && v === HUMAN_AGENT)
14
+ );
15
+ }
16
+
17
+ export function resolveAssignmentPair(agent, harness) {
18
+ if (agent === HUMAN_AGENT) return { agent, harness: HUMAN_HARNESS };
19
+ if (harness === HUMAN_HARNESS) {
20
+ throw new Error(`reserved assignment harness: ${HUMAN_HARNESS}`);
21
+ }
22
+ return { agent, harness: harness ?? null };
23
+ }