@koreanhole/kandev 0.0.0-stage → 0.1.0
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/README.md +367 -2
- package/bin/codex-acp.js +16 -0
- package/bin/kandev-auto-sync.mjs +101 -0
- package/bin/kandev-config.js +53 -0
- package/bin/kandev.js +35 -0
- package/config/config.yaml +6 -0
- package/config/docker/projects/opencodex-cli.json +79 -0
- package/config/docker/projects/samsung-bus-tracker.json +91 -0
- package/config/gateways.json +14 -0
- package/config/pipeline.json +150 -0
- package/config/workflows/sdlc.yaml +1019 -0
- package/docker/Dockerfile +68 -0
- package/docker/Dockerfile.opencodex-cli +44 -0
- package/docker/Dockerfile.samsung-bus-tracker +75 -0
- package/package.json +61 -4
- package/scripts/agent-tools-docker.mjs +223 -0
- package/scripts/baseline.mjs +20 -0
- package/scripts/codex-medium +2 -0
- package/scripts/codex-stage +22 -0
- package/scripts/gate.mjs +909 -0
- package/scripts/gateways/docker.mjs +64 -0
- package/scripts/gateways/speckit.mjs +78 -0
- package/scripts/install-prerequisites.mjs +48 -0
- package/scripts/lib/artifacts.mjs +990 -0
- package/scripts/lib/bugfix.mjs +325 -0
- package/scripts/lib/checksum.mjs +166 -0
- package/scripts/lib/docker-workspace.mjs +1209 -0
- package/scripts/lib/gateways.mjs +79 -0
- package/scripts/lib/kandev.mjs +273 -0
- package/scripts/lib/mcp.mjs +111 -0
- package/scripts/lib/pipeline.mjs +548 -0
- package/scripts/lib/planning-replan.mjs +103 -0
- package/scripts/lib/resume.mjs +207 -0
- package/scripts/lib/review-history.mjs +260 -0
- package/scripts/lib/stage-boundary.mjs +146 -0
- package/scripts/lib/stage-model.mjs +23 -0
- package/scripts/lib/task-worktree.mjs +40 -0
- package/scripts/measure-tokens.mjs +121 -0
- package/scripts/planning-tools.mjs +166 -0
- package/scripts/replan-planning.mjs +82 -0
- package/scripts/review-digest.mjs +240 -0
- package/scripts/run-android-e2e.mjs +116 -0
- package/scripts/run-code-review.mjs +281 -0
- package/scripts/run-detached.mjs +163 -0
- package/scripts/run-doc-review.mjs +155 -0
- package/scripts/run-gateways.mjs +138 -0
- package/scripts/sync.mjs +588 -0
- package/scripts/verify-change.mjs +252 -0
- package/scripts/verify-node.mjs +288 -0
- package/scripts/verify.mjs +442 -0
- package/scripts/wait-status.mjs +88 -0
package/scripts/sync.mjs
ADDED
|
@@ -0,0 +1,588 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/** Idempotent reconciler: repository definitions -> live Kandev instance. */
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { connect } from "./lib/mcp.mjs";
|
|
6
|
+
import {
|
|
7
|
+
advertisedModels,
|
|
8
|
+
createProfile,
|
|
9
|
+
createStep,
|
|
10
|
+
createWorkflow,
|
|
11
|
+
deleteStep,
|
|
12
|
+
exportWorkflow,
|
|
13
|
+
findAgent,
|
|
14
|
+
findWorkspace,
|
|
15
|
+
getMcpConfig,
|
|
16
|
+
getWorkspaceDefaultProfiles,
|
|
17
|
+
listProfiles,
|
|
18
|
+
listSteps,
|
|
19
|
+
listTasks,
|
|
20
|
+
listWorkflows,
|
|
21
|
+
reorderSteps,
|
|
22
|
+
updateMcpConfig,
|
|
23
|
+
updateProfile,
|
|
24
|
+
updateProfileConfigOptions,
|
|
25
|
+
updateStep,
|
|
26
|
+
updateWorkflow,
|
|
27
|
+
updateWorkspaceDefaultProfiles,
|
|
28
|
+
} from "./lib/kandev.mjs";
|
|
29
|
+
import { loadEnv, loadPipeline, normalizePrompt, ValidationError } from "./lib/pipeline.mjs";
|
|
30
|
+
|
|
31
|
+
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
|
32
|
+
const LEGACY_STEPS = ["1. Requirements", "2. Implementation", "3. Code Review", "4. E2E", "5. Done"];
|
|
33
|
+
const APPROVAL_STEPS = [
|
|
34
|
+
"1. Agent Gateway",
|
|
35
|
+
"2. Planning",
|
|
36
|
+
"3. Implementation",
|
|
37
|
+
"4. Code Review",
|
|
38
|
+
"5. E2E",
|
|
39
|
+
"6. Done",
|
|
40
|
+
];
|
|
41
|
+
const LEGACY_TARGETS = {
|
|
42
|
+
"1. Requirements": "2. Planning",
|
|
43
|
+
"2. Implementation": "3. Implementation",
|
|
44
|
+
"3. Code Review": "4. Code Review",
|
|
45
|
+
"4. E2E": "5. E2E",
|
|
46
|
+
"5. Done": "7. Done",
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
function pick(obj, snake, camel) {
|
|
50
|
+
return obj?.[snake] !== undefined ? obj[snake] : obj?.[camel];
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function idToPosition(steps) {
|
|
54
|
+
const map = new Map();
|
|
55
|
+
for (const step of steps) map.set(step.id, Number(pick(step, "position", "position")));
|
|
56
|
+
return map;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function eventsProjection(events, positions) {
|
|
60
|
+
const out = {};
|
|
61
|
+
for (const [trigger, actions] of Object.entries(events || {})) {
|
|
62
|
+
if (!actions || actions.length === 0) continue;
|
|
63
|
+
out[trigger] = actions.map((action) => {
|
|
64
|
+
const cfg = action.config || {};
|
|
65
|
+
const target = cfg.step_id ? positions?.get(cfg.step_id) : cfg.step_position;
|
|
66
|
+
const config = { ...cfg };
|
|
67
|
+
delete config.step_id;
|
|
68
|
+
if (target !== undefined) config.step_position = target;
|
|
69
|
+
return { type: action.type, config };
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
return out;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function desiredEvents(isTerminal, human = false) {
|
|
76
|
+
if (isTerminal || human) return {};
|
|
77
|
+
return { on_enter: [{ type: "auto_start_agent" }] };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function stepComparable(step, positions) {
|
|
81
|
+
return {
|
|
82
|
+
name: step.name,
|
|
83
|
+
color: step.color,
|
|
84
|
+
prompt: normalizePrompt(step.prompt),
|
|
85
|
+
events: JSON.stringify(eventsProjection(step.events, positions)),
|
|
86
|
+
is_start_step: Boolean(pick(step, "is_start_step", "isStartStep")),
|
|
87
|
+
show_in_command_panel: Boolean(pick(step, "show_in_command_panel", "showInCommandPanel")),
|
|
88
|
+
allow_manual_move: Boolean(pick(step, "allow_manual_move", "allowManualMove")),
|
|
89
|
+
auto_advance_requires_signal: Boolean(
|
|
90
|
+
pick(step, "auto_advance_requires_signal", "autoAdvanceRequiresSignal"),
|
|
91
|
+
),
|
|
92
|
+
cancel_triggers_turn_complete: Boolean(
|
|
93
|
+
pick(step, "cancel_triggers_turn_complete", "cancelTriggersTurnComplete"),
|
|
94
|
+
),
|
|
95
|
+
complete_task_on_enter: Boolean(pick(step, "complete_task_on_enter", "completeTaskOnEnter")),
|
|
96
|
+
agent_profile_id: pick(step, "agent_profile_id", "agentProfileId") || "",
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function desiredComparable(step, agentProfileId, isTerminal, positions, human = false) {
|
|
101
|
+
return {
|
|
102
|
+
name: step.name,
|
|
103
|
+
color: step.color,
|
|
104
|
+
prompt: normalizePrompt(step.prompt),
|
|
105
|
+
events: JSON.stringify(eventsProjection(desiredEventsForCompare(isTerminal, human), positions)),
|
|
106
|
+
is_start_step: Boolean(step.is_start_step),
|
|
107
|
+
show_in_command_panel: Boolean(step.show_in_command_panel),
|
|
108
|
+
allow_manual_move: Boolean(step.allow_manual_move),
|
|
109
|
+
auto_advance_requires_signal: Boolean(step.auto_advance_requires_signal),
|
|
110
|
+
cancel_triggers_turn_complete: Boolean(step.cancel_triggers_turn_complete),
|
|
111
|
+
complete_task_on_enter: Boolean(step.complete_task_on_enter),
|
|
112
|
+
agent_profile_id: agentProfileId,
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function desiredEventsForCompare(isTerminal, human = false) {
|
|
117
|
+
if (isTerminal || human) return {};
|
|
118
|
+
return { on_enter: [{ type: "auto_start_agent" }] };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function changedFields(live, desired) {
|
|
122
|
+
return Object.keys(desired).filter((key) => live[key] !== desired[key]);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function legacyMigrationPlan(liveSteps, desiredNames) {
|
|
126
|
+
const orderedLive = liveSteps.slice().sort((a, b) => Number(a.position) - Number(b.position));
|
|
127
|
+
const isLegacy = orderedLive.length === LEGACY_STEPS.length
|
|
128
|
+
&& orderedLive.every((step, index) => step.name === LEGACY_STEPS[index]);
|
|
129
|
+
const isApproval = orderedLive.length === APPROVAL_STEPS.length
|
|
130
|
+
&& orderedLive.every((step, index) => step.name === APPROVAL_STEPS[index]);
|
|
131
|
+
const isDesired = orderedLive.length === desiredNames.length
|
|
132
|
+
&& orderedLive.every((step, index) => step.name === desiredNames[index]);
|
|
133
|
+
return { orderedLive, isLegacy, isApproval, isDesired };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Canonical MCP projection: sorted server names + wrapper enabled flag. */
|
|
137
|
+
export function normalizeMcpConfig(config, { desired = false } = {}) {
|
|
138
|
+
const servers = config?.servers || config?.mcp_servers || config?.mcpServers || config || {};
|
|
139
|
+
const out = {};
|
|
140
|
+
for (const [name, value] of Object.entries(servers).sort(([a], [b]) => a.localeCompare(b))) {
|
|
141
|
+
if (value === null || value === undefined) continue;
|
|
142
|
+
out[name] = serverProjection(value);
|
|
143
|
+
}
|
|
144
|
+
const hasServers = Object.keys(out).length > 0;
|
|
145
|
+
return { enabled: desired ? hasServers : config?.enabled !== false, servers: out };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export function normalizeServers(config) {
|
|
149
|
+
return normalizeMcpConfig(config).servers;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function serverProjection(value) {
|
|
153
|
+
const env = value.env && typeof value.env === "object"
|
|
154
|
+
? Object.fromEntries(Object.entries(value.env).sort(([a], [b]) => a.localeCompare(b)))
|
|
155
|
+
: {};
|
|
156
|
+
return {
|
|
157
|
+
command: value.command,
|
|
158
|
+
args: value.args ?? [],
|
|
159
|
+
env,
|
|
160
|
+
enabled: value.enabled !== false,
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export async function runSync({ dryRun = false, prune = false, migrateLegacy = false, migrateApproval = false, root = ROOT } = {}) {
|
|
165
|
+
loadEnv(root);
|
|
166
|
+
const { pipeline, document, workflow, stages } = loadPipeline(root);
|
|
167
|
+
const allSteps = [...stages.map((stage) => stage.stepDefinition), workflow.steps.at(-1)];
|
|
168
|
+
const terminalStep = workflow.steps.at(-1);
|
|
169
|
+
const results = [];
|
|
170
|
+
const record = (action, kind, name, detail = "") => results.push({ action, kind, name, detail });
|
|
171
|
+
|
|
172
|
+
const mcp = await connect();
|
|
173
|
+
const workspaceName = process.env.KANDEV_WORKSPACE || pipeline.workspace || "Default Workspace";
|
|
174
|
+
const workspace = await findWorkspace(mcp, workspaceName);
|
|
175
|
+
record("unchanged", "workspace", workspace.name, "found");
|
|
176
|
+
|
|
177
|
+
const agentKey = process.env.KANDEV_AGENT || pipeline.agent || "codex-acp";
|
|
178
|
+
const agent = await findAgent(mcp, agentKey);
|
|
179
|
+
if (agent.capability_status !== "ok") {
|
|
180
|
+
throw new Error(`Agent "${agent.name}" is not ready: ${agent.capability_status}`);
|
|
181
|
+
}
|
|
182
|
+
record("unchanged", "agent", agent.name, agent.capability_status);
|
|
183
|
+
|
|
184
|
+
const models = await advertisedModels(agent.name);
|
|
185
|
+
for (const stage of stages.filter((item) => item.human_approval !== true)) {
|
|
186
|
+
if (!models.includes(stage.model)) {
|
|
187
|
+
throw new Error(
|
|
188
|
+
`Model "${stage.model}" for ${stage.profile_name} is not advertised by ${agent.name}. Available: ${models.join(", ")}`,
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
if (pipeline.default_profile && !models.includes(pipeline.default_profile.model)) {
|
|
193
|
+
throw new Error(
|
|
194
|
+
`Model "${pipeline.default_profile.model}" for ${pipeline.default_profile.name} is not advertised by ${agent.name}. Available: ${models.join(", ")}`,
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// Profiles ---------------------------------------------------------------
|
|
199
|
+
let profiles = await listProfiles(mcp, agent.id);
|
|
200
|
+
async function reconcileProfile({
|
|
201
|
+
name,
|
|
202
|
+
model,
|
|
203
|
+
reasoningEffort,
|
|
204
|
+
autoApprove,
|
|
205
|
+
preserveAutoApprove = false,
|
|
206
|
+
}) {
|
|
207
|
+
let existing = profiles.find((p) => p.name === name);
|
|
208
|
+
const effortDetail = reasoningEffort ? `, reasoning_effort=${reasoningEffort}` : "";
|
|
209
|
+
if (!existing) {
|
|
210
|
+
record(dryRun ? "planned-create" : "created", "profile", name, `${model}${effortDetail}`);
|
|
211
|
+
if (dryRun) return null;
|
|
212
|
+
await createProfile(mcp, { agentId: agent.id, name, model, reasoningEffort, autoApprove });
|
|
213
|
+
profiles = await listProfiles(mcp, agent.id);
|
|
214
|
+
existing = profiles.find((p) => p.name === name);
|
|
215
|
+
if (!existing) throw new Error(`Profile ${name} was not created`);
|
|
216
|
+
if (reasoningEffort && (existing.config_options?.reasoning_effort || "") !== reasoningEffort) {
|
|
217
|
+
await updateProfileConfigOptions(mcp, {
|
|
218
|
+
profileId: existing.id,
|
|
219
|
+
configOptions: { ...(existing.config_options || {}), reasoning_effort: reasoningEffort },
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
return existing;
|
|
223
|
+
}
|
|
224
|
+
const targetAutoApprove = preserveAutoApprove ? existing.auto_approve : autoApprove;
|
|
225
|
+
const profileDrift = existing.model !== model || existing.auto_approve !== targetAutoApprove;
|
|
226
|
+
const effortDrift = Boolean(reasoningEffort) && (existing.config_options?.reasoning_effort || "") !== reasoningEffort;
|
|
227
|
+
if (profileDrift || effortDrift) {
|
|
228
|
+
const details = [];
|
|
229
|
+
if (profileDrift) details.push(`model -> ${model}, auto_approve -> ${targetAutoApprove}`);
|
|
230
|
+
if (effortDrift) details.push(`reasoning_effort -> ${reasoningEffort}`);
|
|
231
|
+
record(dryRun ? "planned-update" : "updated", "profile", name, details.join(", "));
|
|
232
|
+
if (!dryRun) {
|
|
233
|
+
if (profileDrift) {
|
|
234
|
+
await updateProfile(mcp, {
|
|
235
|
+
profileId: existing.id,
|
|
236
|
+
model,
|
|
237
|
+
autoApprove: targetAutoApprove,
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
if (effortDrift) {
|
|
241
|
+
await updateProfileConfigOptions(mcp, {
|
|
242
|
+
profileId: existing.id,
|
|
243
|
+
configOptions: { ...(existing.config_options || {}), reasoning_effort: reasoningEffort },
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
} else {
|
|
248
|
+
record("unchanged", "profile", name, `${model}${effortDetail}, auto_approve=${targetAutoApprove}`);
|
|
249
|
+
}
|
|
250
|
+
return existing;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
if (pipeline.default_profile) {
|
|
254
|
+
const dp = pipeline.default_profile;
|
|
255
|
+
const defaultProfile = await reconcileProfile({
|
|
256
|
+
name: dp.name,
|
|
257
|
+
model: dp.model,
|
|
258
|
+
reasoningEffort: dp.reasoning_effort,
|
|
259
|
+
autoApprove: false,
|
|
260
|
+
preserveAutoApprove: true,
|
|
261
|
+
});
|
|
262
|
+
const wsDefaults = await getWorkspaceDefaultProfiles(mcp, workspace.id);
|
|
263
|
+
const defaultId = defaultProfile?.id || "";
|
|
264
|
+
const defaultsDrift =
|
|
265
|
+
!defaultId ||
|
|
266
|
+
wsDefaults.default_agent_profile_id !== defaultId ||
|
|
267
|
+
wsDefaults.default_config_agent_profile_id !== defaultId;
|
|
268
|
+
if (defaultsDrift) {
|
|
269
|
+
record(
|
|
270
|
+
dryRun ? "planned-update" : "updated",
|
|
271
|
+
"workspace-defaults",
|
|
272
|
+
workspace.name,
|
|
273
|
+
`default_agent_profile_id -> ${dp.name}, default_config_agent_profile_id -> ${dp.name}`,
|
|
274
|
+
);
|
|
275
|
+
if (!dryRun) {
|
|
276
|
+
await updateWorkspaceDefaultProfiles(mcp, {
|
|
277
|
+
workspaceId: workspace.id,
|
|
278
|
+
defaultAgentProfileId: defaultId,
|
|
279
|
+
defaultConfigAgentProfileId: defaultId,
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
} else {
|
|
283
|
+
record("unchanged", "workspace-defaults", workspace.name, dp.name);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const profileIds = {};
|
|
288
|
+
for (const [index, stage] of stages.entries()) {
|
|
289
|
+
if (stage.human_approval === true) continue;
|
|
290
|
+
const existing = await reconcileProfile({
|
|
291
|
+
name: stage.profile_name,
|
|
292
|
+
model: stage.model,
|
|
293
|
+
reasoningEffort: stage.reasoning_effort,
|
|
294
|
+
autoApprove: stage.auto_approve,
|
|
295
|
+
});
|
|
296
|
+
if (!existing) continue;
|
|
297
|
+
profileIds[index] = existing.id;
|
|
298
|
+
|
|
299
|
+
const desiredServers = stage.mcp_servers || {};
|
|
300
|
+
const liveConfig = await getMcpConfig(mcp, existing.id);
|
|
301
|
+
const liveMcp = normalizeMcpConfig(liveConfig);
|
|
302
|
+
const desiredMcp = normalizeMcpConfig({ servers: desiredServers }, { desired: true });
|
|
303
|
+
const same = JSON.stringify(liveMcp) === JSON.stringify(desiredMcp);
|
|
304
|
+
if (!same) {
|
|
305
|
+
record(dryRun ? "planned-update" : "updated", "profile-mcp", stage.profile_name, Object.keys(desiredServers).join(",") || "none");
|
|
306
|
+
if (!dryRun) await updateMcpConfig(mcp, existing.id, desiredServers, desiredMcp.enabled);
|
|
307
|
+
} else {
|
|
308
|
+
record("unchanged", "profile-mcp", stage.profile_name, Object.keys(desiredServers).join(",") || "none");
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
const profileIdFor = (index) => (stages[index]?.human_approval ? "" : profileIds[index]) || "";
|
|
312
|
+
|
|
313
|
+
// Workflow ---------------------------------------------------------------
|
|
314
|
+
const workflows = await listWorkflows(mcp, workspace.id);
|
|
315
|
+
const matches = workflows.filter((w) => w.name === workflow.name || w.name === pipeline.pipeline);
|
|
316
|
+
if (matches.length > 1) throw new Error(`Multiple workflows named "${workflow.name}"`);
|
|
317
|
+
let liveWorkflow = matches[0];
|
|
318
|
+
let liveSteps = [];
|
|
319
|
+
|
|
320
|
+
if (!liveWorkflow) {
|
|
321
|
+
record(dryRun ? "planned-create" : "created", "workflow", pipeline.pipeline, document.workflows[0].description || "");
|
|
322
|
+
if (!dryRun) {
|
|
323
|
+
const created = await createWorkflow(mcp, {
|
|
324
|
+
workspaceId: workspace.id,
|
|
325
|
+
name: pipeline.pipeline,
|
|
326
|
+
description: document.workflows[0].description || "",
|
|
327
|
+
});
|
|
328
|
+
liveWorkflow = created?.workflow || created;
|
|
329
|
+
if (!liveWorkflow?.id) {
|
|
330
|
+
const list = await listWorkflows(mcp, workspace.id);
|
|
331
|
+
liveWorkflow = list.find((w) => w.name === pipeline.pipeline);
|
|
332
|
+
}
|
|
333
|
+
if (!liveWorkflow?.id) throw new Error("Workflow creation did not return an id");
|
|
334
|
+
}
|
|
335
|
+
} else {
|
|
336
|
+
record("unchanged", "workflow", liveWorkflow.name, "found");
|
|
337
|
+
liveSteps = await listSteps(mcp, liveWorkflow.id);
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
const desiredDescription = document.workflows[0].description || "";
|
|
341
|
+
if (liveWorkflow && (liveWorkflow.description || "") !== desiredDescription) {
|
|
342
|
+
record(dryRun ? "planned-update" : "updated", "workflow", liveWorkflow.name, "description");
|
|
343
|
+
if (!dryRun) {
|
|
344
|
+
await updateWorkflow(mcp, {
|
|
345
|
+
workflowId: liveWorkflow.id,
|
|
346
|
+
name: liveWorkflow.name,
|
|
347
|
+
description: desiredDescription,
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
if (dryRun && !liveWorkflow) {
|
|
353
|
+
for (const [index, step] of allSteps.entries()) {
|
|
354
|
+
record("planned-create", "step", step.name, `position ${index}`);
|
|
355
|
+
}
|
|
356
|
+
record("planned-create", "workflow-bindings", pipeline.pipeline, "profile bindings on create");
|
|
357
|
+
return finish();
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
if (!liveSteps.length && liveWorkflow) liveSteps = await listSteps(mcp, liveWorkflow.id);
|
|
361
|
+
const desiredNames = allSteps.map((s) => s.name);
|
|
362
|
+
const { orderedLive, isLegacy, isApproval, isDesired } = legacyMigrationPlan(liveSteps, desiredNames);
|
|
363
|
+
if (isLegacy && !isDesired) {
|
|
364
|
+
if (!migrateLegacy) {
|
|
365
|
+
throw new Error(
|
|
366
|
+
"Legacy 4-stage workflow detected. Run `npm run migrate:legacy` once to rename steps in place, then run sync again.",
|
|
367
|
+
);
|
|
368
|
+
}
|
|
369
|
+
if (dryRun) {
|
|
370
|
+
record("planned-create", "step", allSteps[0].name, "legacy migration");
|
|
371
|
+
for (const [oldName, newName] of Object.entries(LEGACY_TARGETS)) {
|
|
372
|
+
record("planned-update", "step", oldName, `rename -> ${newName}`);
|
|
373
|
+
}
|
|
374
|
+
record("planned-reorder", "workflow", pipeline.pipeline, "legacy migration");
|
|
375
|
+
return finish();
|
|
376
|
+
}
|
|
377
|
+
const tasks = await listTasks(mcp, liveWorkflow.id);
|
|
378
|
+
const active = tasks.filter((task) => task.state !== "COMPLETED");
|
|
379
|
+
if (active.length > 0) {
|
|
380
|
+
throw new Error(
|
|
381
|
+
`Refusing legacy migration while ${active.length} active task(s) remain; complete or remove them first.`,
|
|
382
|
+
);
|
|
383
|
+
}
|
|
384
|
+
record("created", "step", allSteps[0].name, "legacy migration");
|
|
385
|
+
await createStep(mcp, {
|
|
386
|
+
workflowId: liveWorkflow.id,
|
|
387
|
+
step: { ...allSteps[0], position: orderedLive.length, events: {} },
|
|
388
|
+
agentProfileId: profileIdFor(0),
|
|
389
|
+
});
|
|
390
|
+
for (const [oldName, newName] of Object.entries(LEGACY_TARGETS)) {
|
|
391
|
+
const live = orderedLive.find((step) => step.name === oldName);
|
|
392
|
+
const index = allSteps.findIndex((step) => step.name === newName);
|
|
393
|
+
if (!live || index < 0) throw new Error(`legacy step mapping failed: ${oldName} -> ${newName}`);
|
|
394
|
+
record("updated", "step", oldName, `rename -> ${newName}`);
|
|
395
|
+
await updateStep(mcp, {
|
|
396
|
+
stepId: live.id,
|
|
397
|
+
step: { ...allSteps[index], events: {} },
|
|
398
|
+
agentProfileId: profileIdFor(index),
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
const refreshed = await listSteps(mcp, liveWorkflow.id);
|
|
402
|
+
const idByName = new Map(refreshed.map((step) => [step.name, step.id]));
|
|
403
|
+
const missing = desiredNames.filter((name) => !idByName.has(name));
|
|
404
|
+
if (missing.length) throw new Error(`legacy migration did not create: ${missing.join(", ")}`);
|
|
405
|
+
await reorderSteps(mcp, liveWorkflow.id, desiredNames.map((name) => idByName.get(name)));
|
|
406
|
+
liveSteps = await listSteps(mcp, liveWorkflow.id);
|
|
407
|
+
record("updated", "workflow-order", pipeline.pipeline, "legacy migration");
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
if (isApproval && !isDesired) {
|
|
411
|
+
if (!migrateApproval) {
|
|
412
|
+
throw new Error(
|
|
413
|
+
"Existing five-stage workflow detected. Run `npm run migrate:approval` once to insert Human Approval and rename Done, then run sync again.",
|
|
414
|
+
);
|
|
415
|
+
}
|
|
416
|
+
if (dryRun) {
|
|
417
|
+
record("planned-update", "step", "6. Done", "rename -> 7. Done");
|
|
418
|
+
record("planned-create", "step", "6. Human Approval", "approval migration");
|
|
419
|
+
record("planned-reorder", "workflow", pipeline.pipeline, "approval migration");
|
|
420
|
+
return finish();
|
|
421
|
+
}
|
|
422
|
+
const done = orderedLive.find((step) => step.name === "6. Done");
|
|
423
|
+
const doneIndex = allSteps.findIndex((step) => step.name === "7. Done");
|
|
424
|
+
const humanIndex = allSteps.findIndex((step) => step.name === "6. Human Approval");
|
|
425
|
+
if (!done || doneIndex < 0 || humanIndex < 0) {
|
|
426
|
+
throw new Error("approval migration step mapping failed");
|
|
427
|
+
}
|
|
428
|
+
record("updated", "step", "6. Done", "rename -> 7. Done");
|
|
429
|
+
await updateStep(mcp, {
|
|
430
|
+
stepId: done.id,
|
|
431
|
+
step: { ...allSteps[doneIndex], events: {} },
|
|
432
|
+
agentProfileId: "",
|
|
433
|
+
});
|
|
434
|
+
record("created", "step", "6. Human Approval", "approval migration");
|
|
435
|
+
await createStep(mcp, {
|
|
436
|
+
workflowId: liveWorkflow.id,
|
|
437
|
+
step: { ...allSteps[humanIndex], events: {} },
|
|
438
|
+
agentProfileId: "",
|
|
439
|
+
});
|
|
440
|
+
const refreshed = await listSteps(mcp, liveWorkflow.id);
|
|
441
|
+
const idByName = new Map(refreshed.map((step) => [step.name, step.id]));
|
|
442
|
+
const missing = desiredNames.filter((name) => !idByName.has(name));
|
|
443
|
+
if (missing.length) throw new Error(`approval migration did not create: ${missing.join(", ")}`);
|
|
444
|
+
await reorderSteps(mcp, liveWorkflow.id, desiredNames.map((name) => idByName.get(name)));
|
|
445
|
+
liveSteps = await listSteps(mcp, liveWorkflow.id);
|
|
446
|
+
record("updated", "workflow-order", pipeline.pipeline, "approval migration");
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
const liveByName = new Map(liveSteps.map((s) => [s.name, s]));
|
|
450
|
+
const liveNames = liveSteps.map((s) => s.name).sort();
|
|
451
|
+
|
|
452
|
+
const extraNames = liveNames.filter((name) => !desiredNames.includes(name));
|
|
453
|
+
if (extraNames.length) {
|
|
454
|
+
if (!prune) {
|
|
455
|
+
for (const name of extraNames) {
|
|
456
|
+
record("conflict", "step", name, "present in Kandev but absent from repository definition");
|
|
457
|
+
}
|
|
458
|
+
throw new Error(
|
|
459
|
+
`Workflow has ${extraNames.length} step(s) not in the repository definition: ${extraNames.join(", ")}. ` +
|
|
460
|
+
"sync never deletes them. Move tasks out and rerun with --prune to remove empty extras.",
|
|
461
|
+
);
|
|
462
|
+
}
|
|
463
|
+
const tasks = await listTasks(mcp, liveWorkflow.id);
|
|
464
|
+
if (tasks.length > 0) {
|
|
465
|
+
throw new Error(
|
|
466
|
+
`Refusing to prune while the workflow still has ${tasks.length} task(s); ` +
|
|
467
|
+
"the task API does not expose queue references, so safety cannot be proven",
|
|
468
|
+
);
|
|
469
|
+
}
|
|
470
|
+
for (const name of extraNames) {
|
|
471
|
+
record(dryRun ? "planned-delete" : "deleted", "step", name, "explicit --prune");
|
|
472
|
+
if (!dryRun) await deleteStep(mcp, liveByName.get(name).id);
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
for (const [index, step] of allSteps.entries()) {
|
|
476
|
+
if (liveByName.has(step.name)) continue;
|
|
477
|
+
record(dryRun ? "planned-create" : "created", "step", step.name, `position ${index}`);
|
|
478
|
+
if (!dryRun) {
|
|
479
|
+
await createStep(mcp, {
|
|
480
|
+
workflowId: liveWorkflow.id,
|
|
481
|
+
step: { ...step, events: {} },
|
|
482
|
+
agentProfileId: profileIdFor(index),
|
|
483
|
+
});
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
if (!dryRun && (extraNames.length || allSteps.some((step) => !liveByName.has(step.name)))) {
|
|
487
|
+
liveSteps = await listSteps(mcp, liveWorkflow.id);
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
const positions = idToPosition(liveSteps);
|
|
491
|
+
const liveAfter = new Map(liveSteps.map((step) => [step.name, step]));
|
|
492
|
+
for (const [index, step] of allSteps.entries()) {
|
|
493
|
+
const current = liveAfter.get(step.name);
|
|
494
|
+
if (!current) continue;
|
|
495
|
+
const live = stepComparable(current, positions);
|
|
496
|
+
const isTerminal = index === allSteps.length - 1;
|
|
497
|
+
const desired = desiredComparable(
|
|
498
|
+
step,
|
|
499
|
+
profileIdFor(index),
|
|
500
|
+
isTerminal,
|
|
501
|
+
allSteps.map((_, position) => position),
|
|
502
|
+
stages[index]?.human_approval === true,
|
|
503
|
+
);
|
|
504
|
+
const fields = changedFields(live, desired);
|
|
505
|
+
// Runtime actions must reference step IDs, not portable positions.
|
|
506
|
+
if (/"step_position"/.test(JSON.stringify(current.events || {})) && !fields.includes("events")) {
|
|
507
|
+
fields.push("events");
|
|
508
|
+
}
|
|
509
|
+
if (fields.length === 0) {
|
|
510
|
+
record("unchanged", "step", step.name, "");
|
|
511
|
+
continue;
|
|
512
|
+
}
|
|
513
|
+
record(dryRun ? "planned-update" : "updated", "step", step.name, fields.join(", "));
|
|
514
|
+
if (!dryRun) {
|
|
515
|
+
await updateStep(mcp, {
|
|
516
|
+
stepId: current.id,
|
|
517
|
+
step: { ...step, events: desiredEvents(isTerminal, stages[index]?.human_approval === true) },
|
|
518
|
+
agentProfileId: profileIdFor(index),
|
|
519
|
+
});
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
const ordered = (dryRun ? liveSteps : await listSteps(mcp, liveWorkflow.id))
|
|
524
|
+
.slice()
|
|
525
|
+
.sort((a, b) => Number(pick(a, "position", "position")) - Number(pick(b, "position", "position")));
|
|
526
|
+
const orderedNames = ordered.map((s) => s.name);
|
|
527
|
+
if (JSON.stringify(orderedNames) !== JSON.stringify(desiredNames)) {
|
|
528
|
+
record(dryRun ? "planned-reorder" : "updated", "workflow-order", pipeline.pipeline, "reordered steps");
|
|
529
|
+
if (!dryRun) {
|
|
530
|
+
await reorderSteps(mcp, liveWorkflow.id, desiredNames.map((name) => ordered.find((s) => s.name === name).id));
|
|
531
|
+
}
|
|
532
|
+
} else if (JSON.stringify(orderedNames) === JSON.stringify(desiredNames)) {
|
|
533
|
+
record("unchanged", "workflow-order", pipeline.pipeline, "ordered");
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
function finish() {
|
|
537
|
+
return {
|
|
538
|
+
results,
|
|
539
|
+
converged: true,
|
|
540
|
+
dryRun,
|
|
541
|
+
summary: results.reduce((acc, r) => {
|
|
542
|
+
acc[r.action] = (acc[r.action] || 0) + 1;
|
|
543
|
+
return acc;
|
|
544
|
+
}, {}),
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
record("unchanged", "workflow-verify", pipeline.pipeline, "definition applied");
|
|
549
|
+
return finish();
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
async function main() {
|
|
553
|
+
const argv = process.argv.slice(2);
|
|
554
|
+
if (argv.includes("--help")) {
|
|
555
|
+
console.log("Usage: node scripts/sync.mjs [--dry-run] [--prune] [--migrate-legacy] [--migrate-approval] [--json]\n\nEnv: KANDEV_URL, KANDEV_WORKSPACE, KANDEV_AGENT");
|
|
556
|
+
return;
|
|
557
|
+
}
|
|
558
|
+
const dryRun = argv.includes("--dry-run");
|
|
559
|
+
const prune = argv.includes("--prune");
|
|
560
|
+
const migrateLegacy = argv.includes("--migrate-legacy");
|
|
561
|
+
const migrateApproval = argv.includes("--migrate-approval");
|
|
562
|
+
const json = argv.includes("--json");
|
|
563
|
+
const started = Date.now();
|
|
564
|
+
try {
|
|
565
|
+
const out = await runSync({ dryRun, prune, migrateLegacy, migrateApproval });
|
|
566
|
+
const elapsed = ((Date.now() - started) / 1000).toFixed(1);
|
|
567
|
+
if (json) {
|
|
568
|
+
console.log(JSON.stringify({ ...out, elapsed_seconds: Number(elapsed) }, null, 2));
|
|
569
|
+
} else {
|
|
570
|
+
const width = Math.max(...out.results.map((r) => r.name.length), 10);
|
|
571
|
+
for (const r of out.results) {
|
|
572
|
+
console.log(`${r.action.padEnd(14)} ${r.kind.padEnd(17)} ${r.name.padEnd(width)} ${r.detail}`);
|
|
573
|
+
}
|
|
574
|
+
const summary = Object.entries(out.summary).map(([k, v]) => `${v} ${k}`).join(", ");
|
|
575
|
+
console.log(`\nresult converged in ${elapsed}s${dryRun ? " (dry-run)" : ""} — ${summary}`);
|
|
576
|
+
}
|
|
577
|
+
process.exit(0);
|
|
578
|
+
} catch (err) {
|
|
579
|
+
const code = err instanceof ValidationError ? 2 : 1;
|
|
580
|
+
if (json) console.error(JSON.stringify({ error: err.message, exit_code: code }));
|
|
581
|
+
else console.error(`FAIL sync: ${err.message}`);
|
|
582
|
+
process.exit(code);
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
587
|
+
main();
|
|
588
|
+
}
|