@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,21 @@
|
|
|
1
|
+
// Public event read API. Writers use core.appendEvent; this surface is the
|
|
2
|
+
// cursor/history readers used by the WebSocket stream and tools.
|
|
3
|
+
|
|
4
|
+
export function createEventApi({ core }) {
|
|
5
|
+
const { db, appendEvent, eventById, eventsFor } = core;
|
|
6
|
+
|
|
7
|
+
return {
|
|
8
|
+
append: appendEvent,
|
|
9
|
+
get: eventById,
|
|
10
|
+
listFor: eventsFor,
|
|
11
|
+
lastEventId() {
|
|
12
|
+
return db.prepare("SELECT COALESCE(MAX(id),0) AS m FROM item_events").get().m;
|
|
13
|
+
},
|
|
14
|
+
since(id, limit = 200) {
|
|
15
|
+
return db.prepare("SELECT * FROM item_events WHERE id > ? ORDER BY id LIMIT ?").all(id, limit);
|
|
16
|
+
},
|
|
17
|
+
latest(limit = 200) {
|
|
18
|
+
return db.prepare("SELECT * FROM item_events ORDER BY id DESC LIMIT ?").all(limit).reverse();
|
|
19
|
+
},
|
|
20
|
+
};
|
|
21
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// Human gates: open a gate while a task is ready/in_progress, and resolve it
|
|
2
|
+
// back to ready. Open ends any live attempt as `gated`; resolve keeps the
|
|
3
|
+
// assignment, so the same worker is the one that can claim it again.
|
|
4
|
+
|
|
5
|
+
export function createGateMethods({ core, apis }) {
|
|
6
|
+
const {
|
|
7
|
+
db, cfg, now, splitSessionKey, ensureSession,
|
|
8
|
+
liveAttempt, endAttempt, createAttempt, appendEvent,
|
|
9
|
+
} = core;
|
|
10
|
+
|
|
11
|
+
return {
|
|
12
|
+
openGate({ id, gateType, reason, actor = "system", harness = null, session = null }) {
|
|
13
|
+
const existing = apis.task.get(id);
|
|
14
|
+
if (!existing || (existing.status !== "ready" && existing.status !== "in_progress")) return null;
|
|
15
|
+
const t = now();
|
|
16
|
+
const parsed = splitSessionKey(session);
|
|
17
|
+
db.exec("BEGIN IMMEDIATE");
|
|
18
|
+
try {
|
|
19
|
+
const live = liveAttempt(id);
|
|
20
|
+
const gateRecord = { type: gateType, reason: reason ?? null, actor, openedAt: t };
|
|
21
|
+
if (live) {
|
|
22
|
+
endAttempt(live.id, { status: "gated", endedAt: t, gateRecord });
|
|
23
|
+
} else {
|
|
24
|
+
const s = ensureSession({
|
|
25
|
+
harness: harness ?? parsed?.harness ?? "system",
|
|
26
|
+
agentId: actor,
|
|
27
|
+
externalSessionId: session ?? parsed?.session ?? `gate-${id}`,
|
|
28
|
+
itemId: id,
|
|
29
|
+
kind: "system",
|
|
30
|
+
});
|
|
31
|
+
createAttempt({ itemId: id, sessionId: s.id, status: "gated", claimedAt: t, endedAt: t, leaseSeconds: cfg.leaseSeconds, gateRecord });
|
|
32
|
+
}
|
|
33
|
+
db.prepare(`
|
|
34
|
+
UPDATE item_state SET revision=revision+1, status='blocked', updated_at=? WHERE item_id=?
|
|
35
|
+
`).run(t, id);
|
|
36
|
+
appendEvent({
|
|
37
|
+
itemId: id, fromStatus: existing.status, toStatus: "blocked", kind: "gate.opened",
|
|
38
|
+
actor, note: `gate open: ${gateType}${reason ? ` — ${reason}` : ""}`, at: t,
|
|
39
|
+
});
|
|
40
|
+
db.exec("COMMIT");
|
|
41
|
+
} catch (err) {
|
|
42
|
+
db.exec("ROLLBACK");
|
|
43
|
+
throw err;
|
|
44
|
+
}
|
|
45
|
+
return apis.task.get(id);
|
|
46
|
+
},
|
|
47
|
+
|
|
48
|
+
resumeGate({ id, actor = "operator", harness = null, session = null }) {
|
|
49
|
+
const existing = apis.task.get(id);
|
|
50
|
+
if (!existing || existing.status !== "blocked") return null;
|
|
51
|
+
const status = existing.assignee_harness && existing.assignee_agent ? "ready" : "backlog";
|
|
52
|
+
const state = { ...(existing.state_json ?? {}) };
|
|
53
|
+
delete state.wait;
|
|
54
|
+
const t = now();
|
|
55
|
+
const parsed = splitSessionKey(session);
|
|
56
|
+
let sessionId = null;
|
|
57
|
+
if (harness || parsed) {
|
|
58
|
+
const s = ensureSession({
|
|
59
|
+
harness: harness ?? parsed.harness,
|
|
60
|
+
agentId: actor,
|
|
61
|
+
externalSessionId: session ?? parsed.session,
|
|
62
|
+
itemId: id,
|
|
63
|
+
kind: "system",
|
|
64
|
+
});
|
|
65
|
+
sessionId = s.id;
|
|
66
|
+
}
|
|
67
|
+
db.exec("BEGIN IMMEDIATE");
|
|
68
|
+
try {
|
|
69
|
+
db.prepare(`
|
|
70
|
+
UPDATE item_state SET revision=revision+1, status=?, state_json=?, updated_at=?
|
|
71
|
+
WHERE item_id=?
|
|
72
|
+
`).run(status, JSON.stringify(state), t, id);
|
|
73
|
+
appendEvent({
|
|
74
|
+
itemId: id, sessionId, fromStatus: "blocked", toStatus: status,
|
|
75
|
+
kind: "gate.resolved", actor, note: "gate resume", at: t,
|
|
76
|
+
});
|
|
77
|
+
db.exec("COMMIT");
|
|
78
|
+
} catch (err) {
|
|
79
|
+
db.exec("ROLLBACK");
|
|
80
|
+
throw err;
|
|
81
|
+
}
|
|
82
|
+
return apis.task.get(id);
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
// store/index.js — data layer over better-sqlite3.
|
|
2
|
+
//
|
|
3
|
+
// One recursive `items` table holds epics, stories and tasks; `item_state`
|
|
4
|
+
// carries the mutable half, `attempts` one row per claim, `work_sessions` the
|
|
5
|
+
// actor, `item_events` the append-only ledger. The `epic`/`story`/`task`
|
|
6
|
+
// facades preserve the tool-facing method names on top of that model.
|
|
7
|
+
//
|
|
8
|
+
// Concurrency: WAL mode enabled. CLI and gateway processes can read/write the
|
|
9
|
+
// same DB concurrently; sqlite serializes the writes. Every multi-row
|
|
10
|
+
// transition (claim + attempt + event, gate + event, drop) runs inside one
|
|
11
|
+
// BEGIN IMMEDIATE transaction.
|
|
12
|
+
|
|
13
|
+
import { resolveConfig } from "../config.js";
|
|
14
|
+
import { resolveDbPath } from "../paths.js";
|
|
15
|
+
import { openDatabase } from "../db.js";
|
|
16
|
+
import {
|
|
17
|
+
EPIC_STATUSES,
|
|
18
|
+
STORY_STATUSES,
|
|
19
|
+
TASK_STATUSES,
|
|
20
|
+
EXECUTION_KINDS,
|
|
21
|
+
ITEM_KINDS,
|
|
22
|
+
} from "../schema.js";
|
|
23
|
+
import { createCore, jsonIn, MAX_ATTEMPTS } from "./core.js";
|
|
24
|
+
import { createItemApi } from "./items.js";
|
|
25
|
+
import { createAttemptApi } from "./attempts.js";
|
|
26
|
+
import { createArtifactApi } from "./artifacts.js";
|
|
27
|
+
import { createEpicApi } from "./epics.js";
|
|
28
|
+
import { createStoryApi } from "./stories.js";
|
|
29
|
+
import { createTaskApi } from "./tasks.js";
|
|
30
|
+
import { createClaimMethods } from "./claims.js";
|
|
31
|
+
import { createGateMethods } from "./gates.js";
|
|
32
|
+
import { createSweepMethods } from "./sweep.js";
|
|
33
|
+
import { createDepApi } from "./deps.js";
|
|
34
|
+
import { createWebhookApi } from "./webhook.js";
|
|
35
|
+
import { createEventApi } from "./events.js";
|
|
36
|
+
import { createAdmissionApi } from "./admission.js";
|
|
37
|
+
import { createDeliveryApi } from "./delivery.js";
|
|
38
|
+
import { createDispatchEventApi } from "./dispatch-events.js";
|
|
39
|
+
import { observe } from "../dispatch.js";
|
|
40
|
+
import { toEventMessage } from "../events-ws.js";
|
|
41
|
+
|
|
42
|
+
export { MAX_ATTEMPTS };
|
|
43
|
+
export { EPIC_STATUSES, STORY_STATUSES, TASK_STATUSES, EXECUTION_KINDS, ITEM_KINDS };
|
|
44
|
+
|
|
45
|
+
export function createStore({ dbPath, logger, config: explicitConfig, notifyDispatch = false, notifyUrl = null } = {}) {
|
|
46
|
+
const finalPath = dbPath || resolveDbPath();
|
|
47
|
+
const { sqlite: db, orm } = openDatabase({ dbPath: finalPath, logger });
|
|
48
|
+
const cfg = resolveConfig({ explicit: explicitConfig ?? {} });
|
|
49
|
+
const core = createCore({ db, cfg });
|
|
50
|
+
|
|
51
|
+
const apis = {};
|
|
52
|
+
apis.item = createItemApi({ core });
|
|
53
|
+
apis.attempt = createAttemptApi({ core });
|
|
54
|
+
apis.artifact = createArtifactApi({ core });
|
|
55
|
+
apis.epic = createEpicApi({ core, apis });
|
|
56
|
+
apis.story = createStoryApi({ core, apis });
|
|
57
|
+
|
|
58
|
+
const task = createTaskApi({ core, apis });
|
|
59
|
+
apis.task = task;
|
|
60
|
+
Object.assign(
|
|
61
|
+
task,
|
|
62
|
+
createClaimMethods({ core, apis }),
|
|
63
|
+
createGateMethods({ core, apis }),
|
|
64
|
+
createSweepMethods({ core, apis }),
|
|
65
|
+
);
|
|
66
|
+
|
|
67
|
+
apis.dep = createDepApi({ core });
|
|
68
|
+
apis.webhook = createWebhookApi({ core });
|
|
69
|
+
apis.event = createEventApi({ core });
|
|
70
|
+
apis.admission = createAdmissionApi({ core });
|
|
71
|
+
apis.delivery = createDeliveryApi({ core });
|
|
72
|
+
apis.dispatchEvent = createDispatchEventApi({ core });
|
|
73
|
+
|
|
74
|
+
const notifyBase = process.env.WINCH_DISPATCH_URL ?? `http://127.0.0.1:${cfg.dispatchPort}`;
|
|
75
|
+
const targetUrl = notifyUrl ?? `${notifyBase.replace(/\/+$/, "")}/dispatch/notify`;
|
|
76
|
+
let notifyScheduled = false;
|
|
77
|
+
|
|
78
|
+
function scheduleNotify() {
|
|
79
|
+
if (!notifyDispatch || notifyScheduled) return;
|
|
80
|
+
notifyScheduled = true;
|
|
81
|
+
queueMicrotask(() => {
|
|
82
|
+
notifyScheduled = false;
|
|
83
|
+
const headers = { "content-type": "application/json" };
|
|
84
|
+
const token = String(process.env.WINCH_DISPATCH_TOKEN ?? "").trim();
|
|
85
|
+
if (token) headers.authorization = `Bearer ${token}`;
|
|
86
|
+
fetch(targetUrl, {
|
|
87
|
+
method: "POST",
|
|
88
|
+
headers,
|
|
89
|
+
body: JSON.stringify({ type: "notify" }),
|
|
90
|
+
signal: AbortSignal.timeout(500),
|
|
91
|
+
}).catch(() => {});
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const store = {
|
|
96
|
+
db,
|
|
97
|
+
orm,
|
|
98
|
+
path: finalPath,
|
|
99
|
+
config: cfg,
|
|
100
|
+
item: apis.item,
|
|
101
|
+
state: {
|
|
102
|
+
get(itemId) {
|
|
103
|
+
const r = db.prepare("SELECT * FROM item_state WHERE item_id=?").get(itemId);
|
|
104
|
+
return r ? { ...r, state_json: jsonIn(r.state_json) ?? {} } : null;
|
|
105
|
+
},
|
|
106
|
+
},
|
|
107
|
+
attempt: apis.attempt,
|
|
108
|
+
session: {
|
|
109
|
+
ensure: core.ensureSession,
|
|
110
|
+
get(id) { return db.prepare("SELECT * FROM work_sessions WHERE id=?").get(id) ?? null; },
|
|
111
|
+
forItem(itemId) { return db.prepare("SELECT * FROM work_sessions WHERE item_id=? ORDER BY created_at DESC").all(itemId); },
|
|
112
|
+
},
|
|
113
|
+
artifact: apis.artifact,
|
|
114
|
+
event: apis.event,
|
|
115
|
+
admission: apis.admission,
|
|
116
|
+
delivery: apis.delivery,
|
|
117
|
+
dispatchEvent: apis.dispatchEvent,
|
|
118
|
+
epic: apis.epic,
|
|
119
|
+
story: apis.story,
|
|
120
|
+
task: apis.task,
|
|
121
|
+
dep: apis.dep,
|
|
122
|
+
webhook: apis.webhook,
|
|
123
|
+
itemKindOf(id) { return apis.item.kindOf(id); },
|
|
124
|
+
close() { db.close(); },
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
core.setEventHook((eventId) => {
|
|
128
|
+
const row = core.eventById(eventId);
|
|
129
|
+
if (!row) return;
|
|
130
|
+
observe(store, toEventMessage(store, row, { includeArtifacts: false }), row.created_at ?? Date.now());
|
|
131
|
+
scheduleNotify();
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
return store;
|
|
135
|
+
}
|
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
// The recursive item tree: create/get/list/tree/update, soft drop/restore,
|
|
2
|
+
// tags, and kind lookups. Facades (epic/story/task) add domain rules on top.
|
|
3
|
+
|
|
4
|
+
import { newItemId } from "../ids.js";
|
|
5
|
+
import { resolveAssignmentPair } from "../reserved.js";
|
|
6
|
+
import { EXECUTION_KINDS, ITEM_KINDS } from "../schema.js";
|
|
7
|
+
|
|
8
|
+
export function createItemApi({ core }) {
|
|
9
|
+
const {
|
|
10
|
+
db, now, jsonIn, ITEM_SELECT, decorate, getRow, listRows, appendEvent,
|
|
11
|
+
kindForTransition, STATUSES_BY_KIND, DEFAULT_STATUS, ITEM_TERMINAL,
|
|
12
|
+
} = core;
|
|
13
|
+
|
|
14
|
+
const itemApi = {
|
|
15
|
+
create(input = {}) {
|
|
16
|
+
const kind = input.kind;
|
|
17
|
+
if (!ITEM_KINDS.includes(kind)) throw new Error(`invalid item kind: ${kind}`);
|
|
18
|
+
const id = input.id || newItemId();
|
|
19
|
+
const pair = resolveAssignmentPair(
|
|
20
|
+
input.assigneeAgent ?? (input.assigned ?? null),
|
|
21
|
+
input.assigneeHarness ?? null,
|
|
22
|
+
);
|
|
23
|
+
const assigneeHarness = pair.harness;
|
|
24
|
+
const assigneeAgent = pair.agent;
|
|
25
|
+
if ((assigneeHarness == null) !== (assigneeAgent == null)) {
|
|
26
|
+
throw new Error(`assignment is a pair: ${id}`);
|
|
27
|
+
}
|
|
28
|
+
const assigned = assigneeHarness != null && assigneeAgent != null;
|
|
29
|
+
const status = input.status ?? DEFAULT_STATUS[kind];
|
|
30
|
+
if (!STATUSES_BY_KIND[kind].includes(status)) throw new Error(`invalid ${kind} status: ${status}`);
|
|
31
|
+
if (status === "ready" && !assigned) throw new Error(`ready item requires an assignment: ${id}`);
|
|
32
|
+
const executionKind = input.executionKind ?? "manual";
|
|
33
|
+
if (!EXECUTION_KINDS.includes(executionKind)) throw new Error(`invalid execution_kind: ${executionKind}`);
|
|
34
|
+
const childKey = input.childKey == null || input.childKey === "" ? null : String(input.childKey);
|
|
35
|
+
const visitSeq = input.visitSeq == null ? 0 : Number(input.visitSeq);
|
|
36
|
+
if (!Number.isInteger(visitSeq) || visitSeq < 0) throw new Error(`invalid visit_seq: ${id}`);
|
|
37
|
+
const parentId = kind === "epic" ? null : (input.parentId ?? null);
|
|
38
|
+
if (kind !== "epic" && !parentId) throw new Error(`${kind} requires a parentId`);
|
|
39
|
+
if (parentId) {
|
|
40
|
+
const parent = db.prepare("SELECT kind FROM items WHERE id=?").get(parentId);
|
|
41
|
+
if (!parent) throw new Error(`parent not found: ${parentId}`);
|
|
42
|
+
if (kind === "story" && parent.kind !== "epic") throw new Error(`story parent must be an epic: ${parentId}`);
|
|
43
|
+
if (kind === "task" && parent.kind !== "story" && parent.kind !== "task") throw new Error(`task parent must be a story or task: ${parentId}`);
|
|
44
|
+
}
|
|
45
|
+
const t = input.createdAt ?? now();
|
|
46
|
+
db.exec("BEGIN IMMEDIATE");
|
|
47
|
+
try {
|
|
48
|
+
db.prepare(`
|
|
49
|
+
INSERT INTO items(id, kind, parent_id, child_key, visit_seq, title, description, acceptance,
|
|
50
|
+
priority, size, owner_team, created_by, execution_kind, execution_args, created_at)
|
|
51
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
52
|
+
`).run(
|
|
53
|
+
id, kind, parentId, childKey, visitSeq, input.title,
|
|
54
|
+
input.description ?? null, input.acceptance ?? null,
|
|
55
|
+
input.priority ?? 50, input.size ?? null, input.ownerTeam ?? null,
|
|
56
|
+
input.createdBy ?? null, executionKind, JSON.stringify(input.executionArgs ?? {}), t,
|
|
57
|
+
);
|
|
58
|
+
db.prepare(`
|
|
59
|
+
INSERT INTO item_state(item_id, revision, status, state_json, assignee_harness, assignee_agent, updated_at, closed_at, deleted_at)
|
|
60
|
+
VALUES (?, 0, ?, ?, ?, ?, ?, ?, ?)
|
|
61
|
+
`).run(
|
|
62
|
+
id, status, JSON.stringify(input.state ?? {}),
|
|
63
|
+
assigneeHarness, assigneeAgent,
|
|
64
|
+
t, ITEM_TERMINAL.has(status) ? t : null, null,
|
|
65
|
+
);
|
|
66
|
+
for (const tag of input.capabilities ?? []) {
|
|
67
|
+
db.prepare("INSERT OR IGNORE INTO item_tags(item_id, tag, source, created_at) VALUES (?, ?, ?, ?)")
|
|
68
|
+
.run(id, String(tag), input.tagSource ?? "assign", t);
|
|
69
|
+
}
|
|
70
|
+
if (input.emit !== false) {
|
|
71
|
+
appendEvent({
|
|
72
|
+
itemId: id,
|
|
73
|
+
fromStatus: null,
|
|
74
|
+
toStatus: status,
|
|
75
|
+
kind: `${kind}.created`,
|
|
76
|
+
actor: input.actor ?? null,
|
|
77
|
+
note: input.note ?? `${kind} created`,
|
|
78
|
+
at: t,
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
// Birth is always the default (backlog); an assignee on the create
|
|
82
|
+
// call is an assignment, so it moves the item to ready immediately.
|
|
83
|
+
if (assigned && status === "backlog") {
|
|
84
|
+
db.prepare("UPDATE item_state SET revision=revision+1, status='ready', updated_at=? WHERE item_id=?").run(t, id);
|
|
85
|
+
if (input.emit !== false) {
|
|
86
|
+
appendEvent({
|
|
87
|
+
itemId: id,
|
|
88
|
+
fromStatus: "backlog",
|
|
89
|
+
toStatus: "ready",
|
|
90
|
+
kind: `${kind}.assigned`,
|
|
91
|
+
actor: input.actor ?? null,
|
|
92
|
+
note: `assign ${assigneeAgent}`,
|
|
93
|
+
at: t,
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
db.exec("COMMIT");
|
|
98
|
+
} catch (err) {
|
|
99
|
+
db.exec("ROLLBACK");
|
|
100
|
+
throw err;
|
|
101
|
+
}
|
|
102
|
+
return itemApi.get(id, { includeDeleted: true });
|
|
103
|
+
},
|
|
104
|
+
|
|
105
|
+
get(id, opts = {}) { return getRow(id, opts); },
|
|
106
|
+
|
|
107
|
+
byChild(parentId, childKey, visitSeq = 0) {
|
|
108
|
+
const row = db.prepare(`${ITEM_SELECT} WHERE i.parent_id=? AND i.child_key=? AND i.visit_seq=? AND s.deleted_at IS NULL`)
|
|
109
|
+
.get(parentId, childKey, visitSeq);
|
|
110
|
+
return row ? decorate(row) : null;
|
|
111
|
+
},
|
|
112
|
+
|
|
113
|
+
list(opts = {}) { return listRows(opts); },
|
|
114
|
+
|
|
115
|
+
children(id) {
|
|
116
|
+
return db.prepare(`${ITEM_SELECT} WHERE i.parent_id=? AND s.deleted_at IS NULL ORDER BY i.created_at ASC`)
|
|
117
|
+
.all(id).map((r) => decorate(r));
|
|
118
|
+
},
|
|
119
|
+
|
|
120
|
+
tree(id, { includeDeleted = false } = {}) {
|
|
121
|
+
const rows = db.prepare(`
|
|
122
|
+
WITH RECURSIVE down(id, depth) AS (
|
|
123
|
+
SELECT id, 0 FROM items WHERE id=?
|
|
124
|
+
UNION ALL
|
|
125
|
+
SELECT i.id, down.depth + 1 FROM items i JOIN down ON i.parent_id = down.id WHERE down.depth < 64
|
|
126
|
+
)
|
|
127
|
+
SELECT i.id FROM down JOIN items i ON i.id=down.id ORDER BY down.depth ASC
|
|
128
|
+
`).all(id);
|
|
129
|
+
return rows.map((r) => itemApi.get(r.id, { includeDeleted })).filter(Boolean);
|
|
130
|
+
},
|
|
131
|
+
|
|
132
|
+
update(id, patch = {}) {
|
|
133
|
+
const existing = getRow(id, { includeDeleted: true });
|
|
134
|
+
if (!existing) throw new Error(`item not found: ${id}`);
|
|
135
|
+
let status = patch.status ?? existing.status;
|
|
136
|
+
if (!STATUSES_BY_KIND[existing.kind].includes(status)) throw new Error(`invalid ${existing.kind} status: ${status}`);
|
|
137
|
+
const executionKind = patch.executionKind ?? existing.execution_kind;
|
|
138
|
+
if (!EXECUTION_KINDS.includes(executionKind)) throw new Error(`invalid execution_kind: ${executionKind}`);
|
|
139
|
+
const t = patch.updatedAt ?? now();
|
|
140
|
+
const next = {
|
|
141
|
+
title: patch.title ?? existing.title,
|
|
142
|
+
description: patch.description !== undefined ? patch.description : existing.description,
|
|
143
|
+
acceptance: patch.acceptance !== undefined ? patch.acceptance : existing.acceptance,
|
|
144
|
+
priority: patch.priority ?? existing.priority,
|
|
145
|
+
size: patch.size !== undefined ? patch.size : existing.size,
|
|
146
|
+
owner_team: patch.ownerTeam !== undefined ? patch.ownerTeam : existing.owner_team,
|
|
147
|
+
created_by: patch.createdBy !== undefined ? patch.createdBy : existing.created_by,
|
|
148
|
+
execution_kind: executionKind,
|
|
149
|
+
execution_args: patch.executionArgs !== undefined ? patch.executionArgs : existing.execution_args,
|
|
150
|
+
assignee_harness: patch.assigneeHarness !== undefined ? patch.assigneeHarness : existing.assignee_harness,
|
|
151
|
+
assignee_agent: patch.assigneeAgent !== undefined ? patch.assigneeAgent : existing.assignee_agent,
|
|
152
|
+
state_json: patch.state !== undefined ? patch.state : existing.state_json,
|
|
153
|
+
closed_at: patch.closedAt !== undefined ? patch.closedAt : existing.closed_at,
|
|
154
|
+
deleted_at: patch.deletedAt !== undefined ? patch.deletedAt : existing.deleted_at,
|
|
155
|
+
};
|
|
156
|
+
if (patch.assigned !== undefined) next.assignee_agent = patch.assigned ?? null;
|
|
157
|
+
const pair = resolveAssignmentPair(next.assignee_agent, next.assignee_harness);
|
|
158
|
+
next.assignee_agent = pair.agent;
|
|
159
|
+
next.assignee_harness = pair.harness;
|
|
160
|
+
if (next.assignee_agent == null) next.assignee_harness = null;
|
|
161
|
+
else if (next.assignee_harness == null) throw new Error(`assignment requires a harness: ${id}`);
|
|
162
|
+
if (patch.status && ITEM_TERMINAL.has(status) && !existing.closed_at) next.closed_at = t;
|
|
163
|
+
if (patch.status && !ITEM_TERMINAL.has(status) && existing.closed_at && patch.closedAt === undefined) next.closed_at = null;
|
|
164
|
+
if ((next.assignee_harness == null) !== (next.assignee_agent == null)) {
|
|
165
|
+
throw new Error(`assignment is a pair: ${id}`);
|
|
166
|
+
}
|
|
167
|
+
const assignmentChanged = patch.assigneeHarness !== undefined || patch.assigneeAgent !== undefined || patch.assigned !== undefined;
|
|
168
|
+
if (patch.status === undefined && assignmentChanged) {
|
|
169
|
+
if (status === "ready" && (next.assignee_harness == null || next.assignee_agent == null)) status = "backlog";
|
|
170
|
+
else if (status === "backlog" && next.assignee_harness != null && next.assignee_agent != null) status = "ready";
|
|
171
|
+
}
|
|
172
|
+
if (status === "ready" && (next.assignee_harness == null || next.assignee_agent == null)) {
|
|
173
|
+
throw new Error(`ready item requires an assignment: ${id}`);
|
|
174
|
+
}
|
|
175
|
+
if (existing.status === "blocked" && status !== "blocked" && next.state_json?.wait?.kind === "deps") {
|
|
176
|
+
const state = { ...next.state_json };
|
|
177
|
+
delete state.wait;
|
|
178
|
+
next.state_json = state;
|
|
179
|
+
}
|
|
180
|
+
const statusChanged = status !== existing.status;
|
|
181
|
+
const note = patch.note ?? null;
|
|
182
|
+
const actor = patch.actor ?? (statusChanged ? "system" : null);
|
|
183
|
+
const kind = patch.kind ?? kindForTransition(existing.kind, existing.status, status, existing.gate_type);
|
|
184
|
+
db.exec("BEGIN IMMEDIATE");
|
|
185
|
+
try {
|
|
186
|
+
db.prepare(`
|
|
187
|
+
UPDATE items SET title=?, description=?, acceptance=?, priority=?, size=?, owner_team=?,
|
|
188
|
+
created_by=?, execution_kind=?, execution_args=?
|
|
189
|
+
WHERE id=?
|
|
190
|
+
`).run(next.title, next.description, next.acceptance, next.priority, next.size, next.owner_team,
|
|
191
|
+
next.created_by, next.execution_kind, JSON.stringify(next.execution_args ?? {}), id);
|
|
192
|
+
db.prepare(`
|
|
193
|
+
UPDATE item_state SET revision=revision+1, status=?, state_json=?, assignee_harness=?, assignee_agent=?,
|
|
194
|
+
updated_at=?, closed_at=?, deleted_at=?
|
|
195
|
+
WHERE item_id=?
|
|
196
|
+
`).run(status, JSON.stringify(next.state_json ?? {}), next.assignee_harness, next.assignee_agent,
|
|
197
|
+
t, next.closed_at, next.deleted_at, id);
|
|
198
|
+
if (patch.capabilities !== undefined) {
|
|
199
|
+
db.prepare("DELETE FROM item_tags WHERE item_id=?").run(id);
|
|
200
|
+
for (const tag of patch.capabilities ?? []) {
|
|
201
|
+
db.prepare("INSERT OR IGNORE INTO item_tags(item_id, tag, source, created_at) VALUES (?, ?, ?, ?)")
|
|
202
|
+
.run(id, String(tag), patch.tagSource ?? "assign", t);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
if (statusChanged || patch.event) {
|
|
206
|
+
appendEvent({
|
|
207
|
+
itemId: id,
|
|
208
|
+
attemptId: patch.attemptId ?? null,
|
|
209
|
+
sessionId: patch.sessionId ?? null,
|
|
210
|
+
fromStatus: existing.status,
|
|
211
|
+
toStatus: status,
|
|
212
|
+
kind,
|
|
213
|
+
actor,
|
|
214
|
+
note,
|
|
215
|
+
payload: patch.payload ?? null,
|
|
216
|
+
at: t,
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
db.exec("COMMIT");
|
|
220
|
+
} catch (err) {
|
|
221
|
+
db.exec("ROLLBACK");
|
|
222
|
+
throw err;
|
|
223
|
+
}
|
|
224
|
+
return itemApi.get(id, { includeDeleted: true });
|
|
225
|
+
},
|
|
226
|
+
|
|
227
|
+
drop(id, { reason = null, actor = null, at = null } = {}) {
|
|
228
|
+
const row = getRow(id, { includeDeleted: true });
|
|
229
|
+
if (!row) return null;
|
|
230
|
+
const descendants = itemApi.tree(id, { includeDeleted: true }).filter((r) => r.id !== id);
|
|
231
|
+
const claimed = descendants.filter((r) => r.kind === "task" && (r.attempt_count > 0 || (r.status !== "backlog" && r.status !== "ready")));
|
|
232
|
+
const t = at ?? now();
|
|
233
|
+
const note = reason ? `dropped: ${String(reason).slice(0, 160)}` : `dropped with ${row.kind}`;
|
|
234
|
+
db.exec("BEGIN IMMEDIATE");
|
|
235
|
+
try {
|
|
236
|
+
for (const r of [...descendants, row]) {
|
|
237
|
+
const fresh = getRow(r.id, { includeDeleted: true });
|
|
238
|
+
if (!fresh || fresh.deleted_at != null) continue;
|
|
239
|
+
db.prepare(`
|
|
240
|
+
UPDATE item_state SET revision=revision+1, status='cancelled',
|
|
241
|
+
state_json=json_set(state_json, '$.priorStatus', status),
|
|
242
|
+
deleted_at=?, closed_at=?, updated_at=?
|
|
243
|
+
WHERE item_id=?
|
|
244
|
+
`).run(t, t, t, r.id);
|
|
245
|
+
appendEvent({
|
|
246
|
+
itemId: r.id,
|
|
247
|
+
fromStatus: fresh.status,
|
|
248
|
+
toStatus: "cancelled",
|
|
249
|
+
kind: r.kind === "task" ? "task.dropped" : `${r.kind}.cancelled`,
|
|
250
|
+
actor, note, at: t,
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
db.exec("COMMIT");
|
|
254
|
+
} catch (err) {
|
|
255
|
+
db.exec("ROLLBACK");
|
|
256
|
+
throw err;
|
|
257
|
+
}
|
|
258
|
+
return { row, descendants, claimed, at: t };
|
|
259
|
+
},
|
|
260
|
+
|
|
261
|
+
restore(id, { actor = null, at = null } = {}) {
|
|
262
|
+
const row = getRow(id, { includeDeleted: true });
|
|
263
|
+
if (!row) return null;
|
|
264
|
+
const t = at ?? now();
|
|
265
|
+
const state = row.state_json && typeof row.state_json === "object" ? row.state_json : jsonIn(row.state_json);
|
|
266
|
+
const prior = state?.priorStatus;
|
|
267
|
+
const status = prior && STATUSES_BY_KIND[row.kind].includes(prior) ? prior : DEFAULT_STATUS[row.kind];
|
|
268
|
+
db.exec("BEGIN IMMEDIATE");
|
|
269
|
+
try {
|
|
270
|
+
db.prepare(`
|
|
271
|
+
UPDATE item_state SET revision=revision+1, status=?,
|
|
272
|
+
state_json=json_remove(state_json, '$.priorStatus'),
|
|
273
|
+
deleted_at=NULL, closed_at=NULL, updated_at=?
|
|
274
|
+
WHERE item_id=?
|
|
275
|
+
`).run(status, t, id);
|
|
276
|
+
appendEvent({
|
|
277
|
+
itemId: id, fromStatus: row.status, toStatus: status,
|
|
278
|
+
kind: row.kind === "task" ? "task.restored" : `${row.kind}.restored`,
|
|
279
|
+
actor, note: "restored", at: t,
|
|
280
|
+
});
|
|
281
|
+
db.exec("COMMIT");
|
|
282
|
+
} catch (err) {
|
|
283
|
+
db.exec("ROLLBACK");
|
|
284
|
+
throw err;
|
|
285
|
+
}
|
|
286
|
+
return itemApi.get(id);
|
|
287
|
+
},
|
|
288
|
+
|
|
289
|
+
kindOf(id) {
|
|
290
|
+
const r = db.prepare("SELECT kind FROM items WHERE id=?").get(id);
|
|
291
|
+
return r?.kind ?? null;
|
|
292
|
+
},
|
|
293
|
+
|
|
294
|
+
addTags(id, tags, source = "assign") {
|
|
295
|
+
for (const tag of tags ?? []) {
|
|
296
|
+
db.prepare("INSERT OR IGNORE INTO item_tags(item_id, tag, source, created_at) VALUES (?, ?, ?, ?)")
|
|
297
|
+
.run(id, String(tag), source, now());
|
|
298
|
+
}
|
|
299
|
+
},
|
|
300
|
+
};
|
|
301
|
+
|
|
302
|
+
return itemApi;
|
|
303
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// Story facade: a story belongs to an epic and fans out into tasks.
|
|
2
|
+
|
|
3
|
+
export function createStoryApi({ core, apis }) {
|
|
4
|
+
const { db } = core;
|
|
5
|
+
|
|
6
|
+
return {
|
|
7
|
+
create({ epicId, title, description, acceptance, status, size, priority, assigned, capabilities, assigneeHarness, id }) {
|
|
8
|
+
if (!apis.epic.get(epicId)) throw new Error(`epic not found: ${epicId}`);
|
|
9
|
+
return apis.item.create({
|
|
10
|
+
id, kind: "story", parentId: epicId, title, description, acceptance,
|
|
11
|
+
status, size, priority, capabilities,
|
|
12
|
+
assigneeAgent: assigned ?? null,
|
|
13
|
+
assigneeHarness: assigned ? assigneeHarness : null,
|
|
14
|
+
emit: false,
|
|
15
|
+
});
|
|
16
|
+
},
|
|
17
|
+
get(id) {
|
|
18
|
+
const row = apis.item.get(id);
|
|
19
|
+
return row?.kind === "story" ? row : null;
|
|
20
|
+
},
|
|
21
|
+
list({ epicId, status, assigned, assignedHarness } = {}) {
|
|
22
|
+
return apis.item.list({ kind: "story", parentId: epicId, status, assigned, assignedHarness });
|
|
23
|
+
},
|
|
24
|
+
update(id, patch) {
|
|
25
|
+
const existing = apis.story.get(id);
|
|
26
|
+
if (!existing) throw new Error(`story not found: ${id}`);
|
|
27
|
+
const next = { ...patch };
|
|
28
|
+
if (patch.assignee_harness !== undefined) next.assigneeHarness = patch.assignee_harness;
|
|
29
|
+
if (patch.assigned !== undefined) next.assigneeAgent = patch.assigned ?? null;
|
|
30
|
+
return apis.item.update(id, next);
|
|
31
|
+
},
|
|
32
|
+
delete(id) {
|
|
33
|
+
const r = db.prepare("DELETE FROM items WHERE id=? AND kind='story'").run(id);
|
|
34
|
+
return r.changes > 0;
|
|
35
|
+
},
|
|
36
|
+
};
|
|
37
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// Lease sweeper and gate-age reminders. Both are watcher-driven ticks over
|
|
2
|
+
// attempts/item_events; neither spawns work.
|
|
3
|
+
|
|
4
|
+
export function createSweepMethods({ core, apis }) {
|
|
5
|
+
const { db, cfg, jsonIn, appendEvent } = core;
|
|
6
|
+
|
|
7
|
+
return {
|
|
8
|
+
sweepExpired({ now: at = Date.now() } = {}) {
|
|
9
|
+
const expired = db.prepare(`
|
|
10
|
+
SELECT a.id, a.item_id, a.attempt_no FROM attempts a
|
|
11
|
+
JOIN item_state s ON s.item_id=a.item_id
|
|
12
|
+
WHERE a.ended_at IS NULL AND s.status='in_progress' AND a.expires_at < ?
|
|
13
|
+
`).all(at);
|
|
14
|
+
const swept = [];
|
|
15
|
+
for (const e of expired) {
|
|
16
|
+
const task = apis.task.release(e.item_id, "sweeper", at);
|
|
17
|
+
if (!task) continue;
|
|
18
|
+
if (e.attempt_no >= cfg.maxAttempts) {
|
|
19
|
+
db.exec("BEGIN IMMEDIATE");
|
|
20
|
+
try {
|
|
21
|
+
const fromStatus = apis.task.get(e.item_id)?.status ?? "ready";
|
|
22
|
+
const r = db.prepare("UPDATE item_state SET status='blocked', updated_at=? WHERE item_id=? AND status IN ('ready','backlog')")
|
|
23
|
+
.run(at, e.item_id);
|
|
24
|
+
if (r.changes > 0) {
|
|
25
|
+
appendEvent({
|
|
26
|
+
itemId: e.item_id, fromStatus, toStatus: "blocked", kind: "task.blocked",
|
|
27
|
+
actor: "sweeper", note: "blocked: max attempts", at,
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
db.exec("COMMIT");
|
|
31
|
+
} catch (err) {
|
|
32
|
+
db.exec("ROLLBACK");
|
|
33
|
+
throw err;
|
|
34
|
+
}
|
|
35
|
+
swept.push(apis.task.get(e.item_id));
|
|
36
|
+
} else {
|
|
37
|
+
swept.push(task);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return swept;
|
|
41
|
+
},
|
|
42
|
+
|
|
43
|
+
recordGateWaits({ now: at = Date.now(), levels = null } = {}) {
|
|
44
|
+
const lv = levels ?? cfg.gateWaitLevels;
|
|
45
|
+
const gates = db.prepare(`
|
|
46
|
+
SELECT s.item_id AS id, a.gate_record_json, a.ended_at
|
|
47
|
+
FROM item_state s
|
|
48
|
+
JOIN attempts a ON a.id = (
|
|
49
|
+
SELECT a2.id FROM attempts a2
|
|
50
|
+
WHERE a2.item_id=s.item_id AND a2.gate_record_json IS NOT NULL
|
|
51
|
+
ORDER BY a2.attempt_no DESC LIMIT 1
|
|
52
|
+
)
|
|
53
|
+
WHERE s.status='blocked' AND s.deleted_at IS NULL
|
|
54
|
+
`).all();
|
|
55
|
+
const written = [];
|
|
56
|
+
for (const g of gates) {
|
|
57
|
+
const gate = jsonIn(g.gate_record_json) ?? {};
|
|
58
|
+
const opened = gate.openedAt ?? g.ended_at;
|
|
59
|
+
if (opened == null) continue;
|
|
60
|
+
const age = at - opened;
|
|
61
|
+
for (const { ms, label } of lv) {
|
|
62
|
+
if (age < ms) continue;
|
|
63
|
+
const note = `gate waiting: ${label} unanswered`;
|
|
64
|
+
const dup = db.prepare("SELECT 1 FROM item_events WHERE item_id=? AND note=? AND created_at>? LIMIT 1")
|
|
65
|
+
.get(g.id, note, opened);
|
|
66
|
+
if (dup) continue;
|
|
67
|
+
const eventId = appendEvent({
|
|
68
|
+
itemId: g.id, fromStatus: "blocked", toStatus: "blocked", kind: "gate.waiting",
|
|
69
|
+
actor: "watcher", note, at,
|
|
70
|
+
});
|
|
71
|
+
written.push({ taskId: g.id, label, eventId });
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return written;
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
}
|