trackops 1.0.1 → 1.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.
Files changed (57) hide show
  1. package/README.md +326 -270
  2. package/bin/trackops.js +102 -70
  3. package/lib/config.js +260 -35
  4. package/lib/control.js +517 -475
  5. package/lib/env.js +227 -0
  6. package/lib/i18n.js +61 -53
  7. package/lib/init.js +135 -46
  8. package/lib/locale.js +63 -0
  9. package/lib/opera-bootstrap.js +523 -0
  10. package/lib/opera.js +319 -170
  11. package/lib/registry.js +27 -13
  12. package/lib/release.js +56 -0
  13. package/lib/resources.js +42 -0
  14. package/lib/server.js +907 -554
  15. package/lib/skills.js +148 -124
  16. package/lib/workspace.js +260 -0
  17. package/locales/en.json +331 -139
  18. package/locales/es.json +331 -139
  19. package/package.json +7 -9
  20. package/scripts/skills-marketplace-smoke.js +124 -0
  21. package/scripts/smoke-tests.js +445 -0
  22. package/scripts/sync-skill-version.js +21 -0
  23. package/scripts/validate-skill.js +88 -0
  24. package/skills/trackops/SKILL.md +64 -0
  25. package/skills/trackops/agents/openai.yaml +3 -0
  26. package/skills/trackops/references/activation.md +39 -0
  27. package/skills/trackops/references/troubleshooting.md +34 -0
  28. package/skills/trackops/references/workflow.md +20 -0
  29. package/skills/trackops/scripts/bootstrap-trackops.js +201 -0
  30. package/skills/trackops/skill.json +29 -0
  31. package/templates/opera/en/agent.md +26 -0
  32. package/templates/opera/en/genesis.md +79 -0
  33. package/templates/opera/en/references/autonomy-and-recovery.md +23 -0
  34. package/templates/opera/en/references/opera-cycle.md +62 -0
  35. package/templates/opera/en/registry.md +28 -0
  36. package/templates/opera/en/router.md +39 -0
  37. package/templates/opera/genesis.md +79 -94
  38. package/templates/skills/changelog-updater/locales/en/SKILL.md +11 -0
  39. package/templates/skills/commiter/locales/en/SKILL.md +11 -0
  40. package/templates/skills/project-starter-skill/locales/en/SKILL.md +24 -0
  41. package/ui/css/panels.css +956 -953
  42. package/ui/index.html +1 -1
  43. package/ui/js/api.js +211 -194
  44. package/ui/js/app.js +200 -199
  45. package/ui/js/i18n.js +14 -0
  46. package/ui/js/onboarding.js +439 -437
  47. package/ui/js/state.js +130 -129
  48. package/ui/js/utils.js +175 -172
  49. package/ui/js/views/board.js +255 -254
  50. package/ui/js/views/execution.js +256 -256
  51. package/ui/js/views/insights.js +340 -339
  52. package/ui/js/views/overview.js +365 -364
  53. package/ui/js/views/settings.js +340 -202
  54. package/ui/js/views/sidebar.js +131 -132
  55. package/ui/js/views/skills.js +163 -162
  56. package/ui/js/views/tasks.js +406 -405
  57. package/ui/js/views/topbar.js +239 -183
package/lib/server.js CHANGED
@@ -1,592 +1,945 @@
1
- #!/usr/bin/env node
2
-
3
- const fs = require("fs");
4
- const http = require("http");
5
- const path = require("path");
6
- const { spawn } = require("child_process");
7
-
1
+ #!/usr/bin/env node
2
+
3
+ const fs = require("fs");
4
+ const http = require("http");
5
+ const net = require("net");
6
+ const os = require("os");
7
+ const path = require("path");
8
+ const { spawn, spawnSync } = require("child_process");
9
+
8
10
  const config = require("./config");
9
11
  const control = require("./control");
12
+ const env = require("./env");
10
13
  const registry = require("./registry");
11
- const { t, setLocale } = require("./i18n");
12
-
13
- const UI_DIR = path.join(__dirname, "..", "ui");
14
- const HOST = process.env.OPS_UI_HOST || "127.0.0.1";
15
- const PORT = Number(process.env.OPS_UI_PORT || 4173);
16
- const ORPHAN_TIMEOUT_MS = Number(process.env.OPS_COMMAND_ORPHAN_TIMEOUT_MS || 120000);
17
- const MAX_COMMAND_RUNTIME_MS = Number(process.env.OPS_COMMAND_MAX_RUNTIME_MS || 600000);
18
- const sessions = new Map();
19
-
20
- const MIME_TYPES = {
21
- ".css": "text/css; charset=utf-8",
22
- ".html": "text/html; charset=utf-8",
23
- ".js": "text/javascript; charset=utf-8",
24
- ".mjs": "text/javascript; charset=utf-8",
25
- ".json": "application/json; charset=utf-8",
26
- ".svg": "image/svg+xml",
27
- ".woff2": "font/woff2",
28
- ".woff": "font/woff",
29
- };
30
-
31
- /* ── helpers ── */
32
-
33
- function sendJson(res, statusCode, payload) {
34
- res.writeHead(statusCode, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
35
- res.end(JSON.stringify(payload));
36
- }
37
-
38
- function sendText(res, statusCode, message) {
39
- res.writeHead(statusCode, { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" });
40
- res.end(message);
41
- }
42
-
43
- function parseBody(req) {
44
- return new Promise((resolve, reject) => {
45
- const chunks = [];
46
- let size = 0;
47
- req.on("data", (chunk) => {
48
- size += chunk.length;
49
- if (size > 1024 * 1024) { reject(new Error(t("server.payloadTooLarge", { limit: "1 MB" }))); req.destroy(); return; }
50
- chunks.push(chunk);
51
- });
52
- req.on("end", () => {
53
- if (!chunks.length) { resolve({}); return; }
54
- try { resolve(JSON.parse(Buffer.concat(chunks).toString("utf8"))); }
55
- catch (_e) { reject(new Error(t("server.invalidJson"))); }
56
- });
57
- req.on("error", reject);
58
- });
59
- }
60
-
61
- function slugify(value) {
62
- return String(value || "").normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48);
63
- }
64
-
65
- function toList(value) {
66
- if (Array.isArray(value)) return value.map((i) => String(i).trim()).filter(Boolean);
67
- return String(value || "").split(/\r?\n|,/).map((i) => i.trim()).filter(Boolean);
68
- }
69
-
70
- /* ── project resolution ── */
71
-
72
- let startupRoot = null;
73
-
74
- function ensureCurrentProjectRegistered() {
75
- if (!startupRoot) return null;
76
- try { return registry.registerProject(startupRoot); }
77
- catch (_e) { return null; }
78
- }
79
-
80
- function resolveProjectEntry(projectRef) {
81
- const current = ensureCurrentProjectRegistered();
82
- const entry = registry.resolveProject(projectRef, startupRoot) || current;
83
- if (!entry) throw new Error(t("server.projectNotResolved"));
84
- return entry;
85
- }
86
-
87
- function loadControlApi(projectRoot) {
88
- return control.forProject(projectRoot);
89
- }
90
-
91
- function buildI18nPayload(controlState) {
92
- const phases = config.getPhases(controlState);
93
- const locale = config.getLocale(controlState);
94
- const statusLabels = {};
95
- for (const s of control.STATUS_ORDER) {
96
- statusLabels[s] = control.statusLabel(s);
97
- }
98
- return { locale, statusLabels, phases };
99
- }
100
-
14
+ const { t, setLocale, getMessages } = require("./i18n");
15
+ const { normalizeLocale } = require("./locale");
16
+
17
+ const UI_DIR = path.join(__dirname, "..", "ui");
18
+ const DEFAULT_HOST = "127.0.0.1";
19
+ const DEFAULT_PORT = 4173;
20
+ const PORT_SEARCH_LIMIT = 100;
21
+ const ORPHAN_TIMEOUT_MS = Number(process.env.OPS_COMMAND_ORPHAN_TIMEOUT_MS || 120000);
22
+ const MAX_COMMAND_RUNTIME_MS = Number(process.env.OPS_COMMAND_MAX_RUNTIME_MS || 600000);
23
+ const sessions = new Map();
24
+ const VIRTUAL_INTERFACE_MARKERS = ["tailscale", "vethernet", "docker", "vbox", "vmware", "hyper-v", "loopback", "virtual", "wsl"];
25
+
26
+ const MIME_TYPES = {
27
+ ".css": "text/css; charset=utf-8",
28
+ ".html": "text/html; charset=utf-8",
29
+ ".js": "text/javascript; charset=utf-8",
30
+ ".mjs": "text/javascript; charset=utf-8",
31
+ ".json": "application/json; charset=utf-8",
32
+ ".svg": "image/svg+xml",
33
+ ".woff2": "font/woff2",
34
+ ".woff": "font/woff",
35
+ };
36
+
37
+ /* ── helpers ── */
38
+
39
+ function sendJson(res, statusCode, payload) {
40
+ res.writeHead(statusCode, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
41
+ res.end(JSON.stringify(payload));
42
+ }
43
+
44
+ function sendText(res, statusCode, message) {
45
+ res.writeHead(statusCode, { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" });
46
+ res.end(message);
47
+ }
48
+
49
+ function parseBody(req) {
50
+ return new Promise((resolve, reject) => {
51
+ const chunks = [];
52
+ let size = 0;
53
+ req.on("data", (chunk) => {
54
+ size += chunk.length;
55
+ if (size > 1024 * 1024) { reject(new Error(t("server.payloadTooLarge", { limit: "1 MB" }))); req.destroy(); return; }
56
+ chunks.push(chunk);
57
+ });
58
+ req.on("end", () => {
59
+ if (!chunks.length) { resolve({}); return; }
60
+ try { resolve(JSON.parse(Buffer.concat(chunks).toString("utf8"))); }
61
+ catch (_e) { reject(new Error(t("server.invalidJson"))); }
62
+ });
63
+ req.on("error", reject);
64
+ });
65
+ }
66
+
67
+ function slugify(value) {
68
+ return String(value || "").normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48);
69
+ }
70
+
71
+ function toList(value) {
72
+ if (Array.isArray(value)) return value.map((i) => String(i).trim()).filter(Boolean);
73
+ return String(value || "").split(/\r?\n|,/).map((i) => i.trim()).filter(Boolean);
74
+ }
75
+
76
+ function parseDashboardArgs(args = []) {
77
+ const options = {
78
+ port: null,
79
+ host: null,
80
+ public: false,
81
+ strictPort: false,
82
+ };
83
+
84
+ for (let i = 0; i < args.length; i += 1) {
85
+ const arg = args[i];
86
+ if ((arg === "--port" || arg === "-p") && args[i + 1]) {
87
+ options.port = args[i + 1];
88
+ i += 1;
89
+ continue;
90
+ }
91
+ if (arg.startsWith("--port=")) {
92
+ options.port = arg.slice("--port=".length);
93
+ continue;
94
+ }
95
+ if ((arg === "--host" || arg === "-H") && args[i + 1]) {
96
+ options.host = args[i + 1];
97
+ i += 1;
98
+ continue;
99
+ }
100
+ if (arg.startsWith("--host=")) {
101
+ options.host = arg.slice("--host=".length);
102
+ continue;
103
+ }
104
+ if (arg === "--public") {
105
+ options.public = true;
106
+ continue;
107
+ }
108
+ if (arg === "--strict-port") {
109
+ options.strictPort = true;
110
+ }
111
+ }
112
+
113
+ return options;
114
+ }
115
+
116
+ function parsePortValue(value) {
117
+ const port = Number(value);
118
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
119
+ throw new Error(t("server.invalidPort", { value: String(value) }));
120
+ }
121
+ return port;
122
+ }
123
+
124
+ function isLoopbackHost(host) {
125
+ const normalized = String(host || "").trim().toLowerCase();
126
+ return normalized === "127.0.0.1" || normalized === "localhost" || normalized === "::1";
127
+ }
128
+
129
+ function isWildcardHost(host) {
130
+ const normalized = String(host || "").trim().toLowerCase();
131
+ return normalized === "0.0.0.0" || normalized === "::";
132
+ }
133
+
134
+ function isPrivateIpv4(address) {
135
+ const parts = String(address || "").split(".").map(Number);
136
+ if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) return false;
137
+ if (parts[0] === 10) return true;
138
+ if (parts[0] === 192 && parts[1] === 168) return true;
139
+ if (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) return true;
140
+ return false;
141
+ }
142
+
143
+ function getLocalUrlHost(host) {
144
+ if (isWildcardHost(host) || isLoopbackHost(host)) return "localhost";
145
+ return host;
146
+ }
147
+
148
+ function resolveDashboardConfig(args = [], env = process.env) {
149
+ const options = parseDashboardArgs(args);
150
+ const host = options.host || env.OPS_UI_HOST || (options.public ? "0.0.0.0" : DEFAULT_HOST);
151
+ const startPort = options.port != null
152
+ ? parsePortValue(options.port)
153
+ : env.OPS_UI_PORT
154
+ ? parsePortValue(env.OPS_UI_PORT)
155
+ : DEFAULT_PORT;
156
+
157
+ return {
158
+ host,
159
+ startPort,
160
+ strictPort: options.strictPort,
161
+ publicMode: options.public || isWildcardHost(host) || !isLoopbackHost(host),
162
+ };
163
+ }
164
+
165
+ function isPortAvailable(host, port) {
166
+ return new Promise((resolve) => {
167
+ const tester = net.createServer();
168
+
169
+ tester.once("error", () => {
170
+ resolve(false);
171
+ });
172
+
173
+ tester.once("listening", () => {
174
+ tester.close(() => resolve(true));
175
+ });
176
+
177
+ tester.listen(port, host);
178
+ });
179
+ }
180
+
181
+ async function findAvailablePort({ host, startPort, strict }) {
182
+ if (strict) {
183
+ const available = await isPortAvailable(host, startPort);
184
+ if (!available) {
185
+ throw new Error(t("server.portBusyStrict", { port: startPort }));
186
+ }
187
+ return { port: startPort, requestedPort: startPort, fallbackUsed: false };
188
+ }
189
+
190
+ for (let offset = 0; offset < PORT_SEARCH_LIMIT; offset += 1) {
191
+ const port = startPort + offset;
192
+ if (port > 65535) break;
193
+ // Probe a temporary bind before creating the real server to avoid immediate EADDRINUSE failures.
194
+ if (await isPortAvailable(host, port)) {
195
+ return { port, requestedPort: startPort, fallbackUsed: port !== startPort };
196
+ }
197
+ }
198
+
199
+ throw new Error(t("server.portSearchExhausted", { port: startPort, limit: PORT_SEARCH_LIMIT }));
200
+ }
201
+
202
+ function buildNetworkCandidates() {
203
+ const interfaces = os.networkInterfaces();
204
+ const candidates = [];
205
+
206
+ for (const [name, addresses] of Object.entries(interfaces)) {
207
+ for (const address of addresses || []) {
208
+ if (!address || address.internal || address.family !== "IPv4") continue;
209
+ const normalizedName = String(name || "").toLowerCase();
210
+ const isVirtual = VIRTUAL_INTERFACE_MARKERS.some((marker) => normalizedName.includes(marker));
211
+ const isPrivate = isPrivateIpv4(address.address);
212
+ let priority = 3;
213
+ if (isPrivate && !isVirtual) priority = 0;
214
+ else if (isPrivate) priority = 1;
215
+ else priority = 2;
216
+ candidates.push({
217
+ name,
218
+ address: address.address,
219
+ priority,
220
+ });
221
+ }
222
+ }
223
+
224
+ return candidates.sort((a, b) => {
225
+ if (a.priority !== b.priority) return a.priority - b.priority;
226
+ if (a.name !== b.name) return a.name.localeCompare(b.name);
227
+ return a.address.localeCompare(b.address);
228
+ });
229
+ }
230
+
231
+ function collectReachableUrls({ host, port, publicMode }) {
232
+ const localUrl = `http://${getLocalUrlHost(host)}:${port}`;
233
+ const networkUrls = [];
234
+ const seen = new Set();
235
+
236
+ function add(url) {
237
+ if (seen.has(url)) return;
238
+ seen.add(url);
239
+ networkUrls.push(url);
240
+ }
241
+
242
+ if (publicMode) {
243
+ if (!isWildcardHost(host) && !isLoopbackHost(host)) {
244
+ add(`http://${host}:${port}`);
245
+ }
246
+
247
+ buildNetworkCandidates().forEach((candidate) => {
248
+ add(`http://${candidate.address}:${port}`);
249
+ });
250
+ }
251
+
252
+ return { localUrl, networkUrls };
253
+ }
254
+
255
+ function copyTextToClipboard(text) {
256
+ const commands = process.platform === "win32"
257
+ ? [["clip"]]
258
+ : process.platform === "darwin"
259
+ ? [["pbcopy"]]
260
+ : [["wl-copy"], ["xclip", "-selection", "clipboard"], ["xsel", "--clipboard", "--input"]];
261
+
262
+ let sawNonAvailabilityError = false;
263
+
264
+ for (const [command, ...args] of commands) {
265
+ const result = spawnSync(command, args, {
266
+ input: text,
267
+ encoding: "utf8",
268
+ stdio: ["pipe", "ignore", "ignore"],
269
+ windowsHide: true,
270
+ });
271
+
272
+ if (!result.error && result.status === 0) {
273
+ return { copied: true, reason: null };
274
+ }
275
+
276
+ if (result.error && result.error.code !== "ENOENT") {
277
+ sawNonAvailabilityError = true;
278
+ }
279
+ }
280
+
281
+ return { copied: false, reason: sawNonAvailabilityError ? "failed" : "unavailable" };
282
+ }
283
+
284
+ function renderStartupBanner(info) {
285
+ const lines = [
286
+ t("server.bannerTitle"),
287
+ "",
288
+ t("server.localUrl", { url: info.urls.localUrl }),
289
+ ];
290
+
291
+ if (info.publicMode) {
292
+ if (info.urls.networkUrls.length > 0) {
293
+ lines.push(t("server.networkUrl", { url: info.urls.networkUrls[0] }));
294
+ info.urls.networkUrls.slice(1).forEach((url) => lines.push(t("server.networkAltUrl", { url })));
295
+ } else {
296
+ lines.push(t("server.noNetworkAddress"));
297
+ }
298
+ }
299
+
300
+ lines.push("");
301
+
302
+ if (info.fallbackUsed) {
303
+ lines.push(t("server.portFallback", { requestedPort: info.requestedPort, actualPort: info.port }));
304
+ }
305
+
306
+ if (info.clipboard.copied) {
307
+ lines.push(t("server.copiedToClipboard"));
308
+ } else if (info.clipboard.reason === "failed") {
309
+ lines.push(t("server.clipboardUnavailable"));
310
+ }
311
+
312
+ if (info.defaultProject) {
313
+ lines.push(t("server.defaultProject", { name: info.defaultProject.name, id: info.defaultProject.id }));
314
+ }
315
+
316
+ return lines.join("\n");
317
+ }
318
+
319
+ function listenServer(server, host, port) {
320
+ return new Promise((resolve, reject) => {
321
+ function onError(error) {
322
+ server.off("listening", onListening);
323
+ reject(error);
324
+ }
325
+
326
+ function onListening() {
327
+ server.off("error", onError);
328
+ resolve(server.address());
329
+ }
330
+
331
+ server.once("error", onError);
332
+ server.once("listening", onListening);
333
+ server.listen(port, host);
334
+ });
335
+ }
336
+
337
+ /* ── project resolution ── */
338
+
339
+ let startupRoot = null;
340
+
341
+ function ensureCurrentProjectRegistered() {
342
+ if (!startupRoot) return null;
343
+ try { return registry.registerProject(startupRoot); }
344
+ catch (_e) { return null; }
345
+ }
346
+
347
+ function resolveProjectEntry(projectRef) {
348
+ const current = ensureCurrentProjectRegistered();
349
+ const entry = registry.resolveProject(projectRef, startupRoot) || current;
350
+ if (!entry) throw new Error(t("server.projectNotResolved"));
351
+ return entry;
352
+ }
353
+
354
+ function loadControlApi(projectRoot) {
355
+ return control.forProject(projectRoot);
356
+ }
357
+
358
+ function buildI18nPayload(controlState) {
359
+ const phases = config.getPhases(controlState);
360
+ const locale = config.getLocale(controlState);
361
+ const statusLabels = {};
362
+ for (const s of control.STATUS_ORDER) {
363
+ statusLabels[s] = control.statusLabel(s);
364
+ }
365
+ return { locale, statusLabels, phases, messages: getMessages(locale) };
366
+ }
367
+
101
368
  function getStatePayload(projectRef) {
102
369
  const project = resolveProjectEntry(projectRef);
103
370
  const api = loadControlApi(project.root);
104
371
  const controlState = api.loadControl();
105
372
  const runtime = api.refreshRepoRuntime({ quiet: true });
373
+ const envState = env.auditEnvironment(project.root, controlState);
106
374
 
107
375
  return {
108
376
  project,
109
377
  control: controlState,
110
378
  derived: api.derive(controlState),
111
379
  runtime,
380
+ env: envState,
112
381
  docsDirty: api.getDocDrift(controlState),
113
382
  i18n: buildI18nPayload(controlState),
114
383
  generatedAt: new Date().toISOString(),
115
- };
116
- }
117
-
118
- function persist(projectRoot) {
119
- const api = loadControlApi(projectRoot);
120
- const controlState = api.loadControl();
121
- api.saveControl(controlState);
122
- api.syncDocs(controlState);
123
- api.refreshRepoRuntime({ quiet: true });
124
- }
125
-
126
- /* ── task operations ── */
127
-
128
- function makeTaskId(controlState, seed) {
129
- const base = slugify(seed) || `task-${Date.now()}`;
130
- const existing = new Set(controlState.tasks.map((t) => t.id));
131
- if (!existing.has(base)) return base;
132
- let idx = 2;
133
- while (existing.has(`${base}-${idx}`)) idx += 1;
134
- return `${base}-${idx}`;
135
- }
136
-
137
- function createTask(projectRoot, payload) {
138
- const api = loadControlApi(projectRoot);
139
- const controlState = api.loadControl();
140
- const title = String(payload.title || "").trim();
141
- if (!title) throw new Error(t("server.titleRequired"));
142
-
143
- const task = {
144
- id: makeTaskId(controlState, payload.id || title),
145
- title,
146
- phase: payload.phase || config.getPhases(controlState)[0]?.id || "E",
147
- stream: String(payload.stream || "Operations").trim(),
148
- priority: payload.priority || "P1",
149
- status: payload.status || "pending",
150
- required: payload.required !== false,
151
- dependsOn: toList(payload.dependsOn),
152
- summary: String(payload.summary || "").trim(),
153
- acceptance: toList(payload.acceptance),
154
- history: [{ at: new Date().toISOString(), action: "create", note: t("server.taskCreatedNote") }],
155
- };
156
-
157
- const blocker = String(payload.blocker || "").trim();
158
- if (blocker) task.blocker = blocker;
159
- controlState.tasks.push(task);
160
- api.saveControl(controlState);
161
- api.syncDocs(controlState);
162
- api.refreshRepoRuntime({ quiet: true });
163
- return task;
164
- }
165
-
166
- function patchTask(projectRoot, taskId, payload) {
167
- const api = loadControlApi(projectRoot);
168
- const controlState = api.loadControl();
169
- const task = controlState.tasks.find((t) => t.id === taskId);
170
- if (!task) throw new Error(t("cli.taskNotFound", { taskId }));
171
-
172
- if (typeof payload.title === "string") task.title = payload.title.trim() || task.title;
173
- if (typeof payload.phase === "string") task.phase = payload.phase;
174
- if (typeof payload.stream === "string") task.stream = payload.stream.trim() || task.stream;
175
- if (typeof payload.priority === "string") task.priority = payload.priority;
176
- if (typeof payload.status === "string") task.status = payload.status;
177
- if (typeof payload.required === "boolean") task.required = payload.required;
178
- if (payload.summary !== undefined) task.summary = String(payload.summary || "").trim();
179
- if (payload.dependsOn !== undefined) task.dependsOn = toList(payload.dependsOn);
180
- if (payload.acceptance !== undefined) task.acceptance = toList(payload.acceptance);
181
-
182
- const blocker = String(payload.blocker || "").trim();
183
- if (blocker) task.blocker = blocker;
184
- else delete task.blocker;
185
-
186
- task.history = task.history || [];
187
- task.history.push({ at: new Date().toISOString(), action: "edit", note: String(payload.note || t("server.taskEditedNote")).trim() });
188
-
189
- api.saveControl(controlState);
190
- api.syncDocs(controlState);
191
- api.refreshRepoRuntime({ quiet: true });
192
- return task;
193
- }
194
-
195
- /* ── sessions (command execution) ── */
196
-
197
- function emitSession(res, payload) { res.write(`data: ${JSON.stringify(payload)}\n\n`); }
198
-
199
- function cleanupSession(session) {
200
- if (session.killTimer) { clearTimeout(session.killTimer); session.killTimer = null; }
201
- if (session.maxRuntimeTimer) { clearTimeout(session.maxRuntimeTimer); session.maxRuntimeTimer = null; }
202
- }
203
-
204
- function terminateSession(session, reason) {
205
- if (!session || session.status !== "running" || !session.process) return;
206
- cleanupSession(session);
207
- session.status = "terminated";
208
- session.exitCode = 1;
209
- session.output += `\n[ops] ${reason}\n`;
210
- try { session.process.kill(); } catch (_e) { /* noop */ }
211
- session.listeners.forEach((res) => {
212
- emitSession(res, { type: "done", status: session.status, exitCode: session.exitCode, output: session.output, projectId: session.projectId });
213
- res.end();
214
- });
215
- session.listeners.clear();
216
- }
217
-
218
- function scheduleOrphanTermination(session) {
219
- if (!session || session.status !== "running" || session.listeners.size > 0) return;
220
- cleanupSession(session);
221
- session.killTimer = setTimeout(() => terminateSession(session, "orphan timeout"), ORPHAN_TIMEOUT_MS);
222
- }
223
-
224
- function createSession(commandText, project) {
225
- const id = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
226
- const session = {
227
- id, projectId: project.id, projectName: project.name, projectRoot: project.root,
228
- command: commandText, startedAt: new Date().toISOString(),
229
- status: "running", exitCode: null, output: "", listeners: new Set(),
230
- };
231
-
232
- const shell = process.platform === "win32" ? "powershell.exe" : process.env.SHELL || "/bin/sh";
233
- const shellArgs = process.platform === "win32"
234
- ? ["-NoLogo", "-NoProfile", "-Command", commandText]
235
- : ["-lc", commandText];
236
-
237
- const child = spawn(shell, shellArgs, { cwd: project.root, env: process.env });
238
- session.process = child;
239
- session.killTimer = null;
240
- session.maxRuntimeTimer = setTimeout(() => terminateSession(session, "max runtime exceeded"), MAX_COMMAND_RUNTIME_MS);
241
- sessions.set(id, session);
242
-
243
- function pushChunk(type, chunk) {
244
- const text = chunk.toString("utf8");
245
- session.output += text;
246
- session.listeners.forEach((res) => emitSession(res, { type, chunk: text, status: session.status, projectId: session.projectId }));
247
- }
248
-
249
- child.stdout.on("data", (c) => pushChunk("stdout", c));
250
- child.stderr.on("data", (c) => pushChunk("stderr", c));
251
- child.on("close", (code) => {
252
- cleanupSession(session);
253
- session.status = "completed";
254
- session.exitCode = code;
255
- session.listeners.forEach((res) => {
256
- emitSession(res, { type: "done", status: session.status, exitCode: code, output: session.output, projectId: session.projectId });
257
- res.end();
258
- });
259
- session.listeners.clear();
260
- });
261
- child.on("error", (err) => {
262
- cleanupSession(session);
263
- session.status = "failed";
264
- session.exitCode = 1;
265
- session.output += `${err.message}\n`;
266
- session.listeners.forEach((res) => {
267
- emitSession(res, { type: "done", status: session.status, exitCode: 1, output: session.output, projectId: session.projectId });
268
- res.end();
269
- });
270
- session.listeners.clear();
271
- });
272
-
273
- return session;
274
- }
275
-
276
- function serveSessionStream(res, session) {
277
- res.writeHead(200, { "Content-Type": "text/event-stream; charset=utf-8", "Cache-Control": "no-store", Connection: "keep-alive" });
278
- emitSession(res, { type: "snapshot", status: session.status, exitCode: session.exitCode, command: session.command, output: session.output, projectId: session.projectId });
279
- if (session.status !== "running") { res.end(); return; }
280
- cleanupSession(session);
281
- session.listeners.add(res);
282
- res.on("close", () => { session.listeners.delete(res); scheduleOrphanTermination(session); });
283
- }
284
-
285
- /* ── static files ── */
286
-
287
- function serveStatic(res, pathname) {
288
- const safePath = pathname === "/" ? "/index.html" : pathname;
289
- const normalized = path.normalize(safePath).replace(/^(\.\.[\\/])+/, "");
290
- const filePath = path.join(UI_DIR, normalized);
291
- if (!filePath.startsWith(UI_DIR)) { sendText(res, 403, "Forbidden."); return; }
292
- if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory()) { sendText(res, 404, "Not found."); return; }
293
- const ext = path.extname(filePath).toLowerCase();
294
- res.writeHead(200, { "Content-Type": MIME_TYPES[ext] || "application/octet-stream", "Cache-Control": "no-store" });
295
- fs.createReadStream(filePath).pipe(res);
296
- }
297
-
298
- /* ── API handler ── */
299
-
300
- async function handleApi(req, res, url) {
301
- try {
302
- if (req.method === "GET" && url.pathname === "/api/projects") {
303
- const current = ensureCurrentProjectRegistered();
304
- sendJson(res, 200, { ok: true, currentProjectId: current?.id || null, registryFile: registry.REGISTRY_FILE, projects: registry.listProjects() });
305
- return;
306
- }
307
-
308
- if (req.method === "POST" && url.pathname === "/api/projects/register") {
309
- const body = await parseBody(req);
310
- const project = registry.registerProject(body.root || startupRoot || process.cwd());
311
- sendJson(res, 201, { ok: true, project, projects: registry.listProjects() });
312
- return;
313
- }
314
-
315
- if (req.method === "POST" && url.pathname === "/api/projects/install") {
316
- const body = await parseBody(req);
317
- if (!body.root) { sendJson(res, 400, { ok: false, error: "Project path required." }); return; }
318
- try {
319
- const initMod = require("./init");
320
- const result = initMod.initProject(body.root, {});
321
- const project = registry.registerProject(result.root);
322
- sendJson(res, 201, { ok: true, project, projects: registry.listProjects() });
323
- } catch (err) {
324
- sendJson(res, 500, { ok: false, error: err.message });
325
- }
326
- return;
327
- }
328
-
329
- if (req.method === "GET" && url.pathname === "/api/state") {
330
- sendJson(res, 200, getStatePayload(url.searchParams.get("project")));
331
- return;
332
- }
333
-
334
- if (req.method === "POST" && url.pathname === "/api/tasks") {
335
- const body = await parseBody(req);
336
- const project = resolveProjectEntry(body.projectId || body.project || url.searchParams.get("project"));
337
- const task = createTask(project.root, body);
338
- sendJson(res, 201, { ok: true, task, state: getStatePayload(project.id) });
339
- return;
340
- }
341
-
342
- const taskMatch = url.pathname.match(/^\/api\/tasks\/([^/]+)$/);
343
- if (req.method === "PUT" && taskMatch) {
344
- const body = await parseBody(req);
345
- const project = resolveProjectEntry(body.projectId || body.project || url.searchParams.get("project"));
346
- const task = patchTask(project.root, decodeURIComponent(taskMatch[1]), body);
347
- sendJson(res, 200, { ok: true, task, state: getStatePayload(project.id) });
348
- return;
349
- }
350
-
351
- const actionMatch = url.pathname.match(/^\/api\/tasks\/([^/]+)\/action$/);
352
- if (req.method === "POST" && actionMatch) {
353
- const body = await parseBody(req);
354
- const project = resolveProjectEntry(body.projectId || body.project || url.searchParams.get("project"));
355
- const action = String(body.action || "").trim();
356
- if (!action) { sendJson(res, 400, { ok: false, error: "Action required." }); return; }
357
- const api = loadControlApi(project.root);
358
- const controlState = api.loadControl();
359
- api.updateTask(controlState, action, decodeURIComponent(actionMatch[1]), body.note || "");
360
- sendJson(res, 200, { ok: true, state: getStatePayload(project.id) });
361
- return;
362
- }
363
-
384
+ };
385
+ }
386
+
387
+ function persist(projectRoot) {
388
+ const api = loadControlApi(projectRoot);
389
+ const controlState = api.loadControl();
390
+ api.saveControl(controlState);
391
+ api.syncDocs(controlState);
392
+ api.refreshRepoRuntime({ quiet: true });
393
+ }
394
+
395
+ function updateProjectLocale(projectRoot, locale) {
396
+ const nextLocale = normalizeLocale(locale);
397
+ if (!nextLocale) {
398
+ throw new Error(t("server.invalidLocale", { value: String(locale || "") }));
399
+ }
400
+
401
+ const api = loadControlApi(projectRoot);
402
+ const controlState = api.loadControl();
403
+ controlState.meta = controlState.meta || {};
404
+ controlState.meta.locale = nextLocale;
405
+
406
+ api.saveControl(controlState);
407
+
408
+ if (config.isOperaInstalled(controlState)) {
409
+ const opera = require("./opera");
410
+ opera.installStructure(projectRoot, controlState, nextLocale, { rewriteLocalizedTemplates: true });
411
+ api.saveControl(controlState);
412
+ }
413
+
414
+ api.syncDocs(controlState);
415
+ api.refreshRepoRuntime({ quiet: true });
416
+ setLocale(nextLocale);
417
+ return controlState;
418
+ }
419
+
420
+ /* ── task operations ── */
421
+
422
+ function makeTaskId(controlState, seed) {
423
+ const base = slugify(seed) || `task-${Date.now()}`;
424
+ const existing = new Set(controlState.tasks.map((t) => t.id));
425
+ if (!existing.has(base)) return base;
426
+ let idx = 2;
427
+ while (existing.has(`${base}-${idx}`)) idx += 1;
428
+ return `${base}-${idx}`;
429
+ }
430
+
431
+ function createTask(projectRoot, payload) {
432
+ const api = loadControlApi(projectRoot);
433
+ const controlState = api.loadControl();
434
+ const title = String(payload.title || "").trim();
435
+ if (!title) throw new Error(t("server.titleRequired"));
436
+
437
+ const task = {
438
+ id: makeTaskId(controlState, payload.id || title),
439
+ title,
440
+ phase: payload.phase || config.getPhases(controlState)[0]?.id || "E",
441
+ stream: String(payload.stream || "Operations").trim(),
442
+ priority: payload.priority || "P1",
443
+ status: payload.status || "pending",
444
+ required: payload.required !== false,
445
+ dependsOn: toList(payload.dependsOn),
446
+ summary: String(payload.summary || "").trim(),
447
+ acceptance: toList(payload.acceptance),
448
+ history: [{ at: new Date().toISOString(), action: "create", note: t("server.taskCreatedNote") }],
449
+ };
450
+
451
+ const blocker = String(payload.blocker || "").trim();
452
+ if (blocker) task.blocker = blocker;
453
+ controlState.tasks.push(task);
454
+ api.saveControl(controlState);
455
+ api.syncDocs(controlState);
456
+ api.refreshRepoRuntime({ quiet: true });
457
+ return task;
458
+ }
459
+
460
+ function patchTask(projectRoot, taskId, payload) {
461
+ const api = loadControlApi(projectRoot);
462
+ const controlState = api.loadControl();
463
+ const task = controlState.tasks.find((t) => t.id === taskId);
464
+ if (!task) throw new Error(t("cli.taskNotFound", { taskId }));
465
+
466
+ if (typeof payload.title === "string") task.title = payload.title.trim() || task.title;
467
+ if (typeof payload.phase === "string") task.phase = payload.phase;
468
+ if (typeof payload.stream === "string") task.stream = payload.stream.trim() || task.stream;
469
+ if (typeof payload.priority === "string") task.priority = payload.priority;
470
+ if (typeof payload.status === "string") task.status = payload.status;
471
+ if (typeof payload.required === "boolean") task.required = payload.required;
472
+ if (payload.summary !== undefined) task.summary = String(payload.summary || "").trim();
473
+ if (payload.dependsOn !== undefined) task.dependsOn = toList(payload.dependsOn);
474
+ if (payload.acceptance !== undefined) task.acceptance = toList(payload.acceptance);
475
+
476
+ const blocker = String(payload.blocker || "").trim();
477
+ if (blocker) task.blocker = blocker;
478
+ else delete task.blocker;
479
+
480
+ task.history = task.history || [];
481
+ task.history.push({ at: new Date().toISOString(), action: "edit", note: String(payload.note || t("server.taskEditedNote")).trim() });
482
+
483
+ api.saveControl(controlState);
484
+ api.syncDocs(controlState);
485
+ api.refreshRepoRuntime({ quiet: true });
486
+ return task;
487
+ }
488
+
489
+ /* ── sessions (command execution) ── */
490
+
491
+ function emitSession(res, payload) { res.write(`data: ${JSON.stringify(payload)}\n\n`); }
492
+
493
+ function cleanupSession(session) {
494
+ if (session.killTimer) { clearTimeout(session.killTimer); session.killTimer = null; }
495
+ if (session.maxRuntimeTimer) { clearTimeout(session.maxRuntimeTimer); session.maxRuntimeTimer = null; }
496
+ }
497
+
498
+ function terminateSession(session, reason) {
499
+ if (!session || session.status !== "running" || !session.process) return;
500
+ cleanupSession(session);
501
+ session.status = "terminated";
502
+ session.exitCode = 1;
503
+ session.output += `\n[ops] ${reason}\n`;
504
+ try { session.process.kill(); } catch (_e) { /* noop */ }
505
+ session.listeners.forEach((res) => {
506
+ emitSession(res, { type: "done", status: session.status, exitCode: session.exitCode, output: session.output, projectId: session.projectId });
507
+ res.end();
508
+ });
509
+ session.listeners.clear();
510
+ }
511
+
512
+ function scheduleOrphanTermination(session) {
513
+ if (!session || session.status !== "running" || session.listeners.size > 0) return;
514
+ cleanupSession(session);
515
+ session.killTimer = setTimeout(() => terminateSession(session, "orphan timeout"), ORPHAN_TIMEOUT_MS);
516
+ }
517
+
518
+ function createSession(commandText, project) {
519
+ const id = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
520
+ const session = {
521
+ id, projectId: project.id, projectName: project.name, projectRoot: project.root,
522
+ command: commandText, startedAt: new Date().toISOString(),
523
+ status: "running", exitCode: null, output: "", listeners: new Set(),
524
+ };
525
+
526
+ const shell = process.platform === "win32" ? "powershell.exe" : process.env.SHELL || "/bin/sh";
527
+ const shellArgs = process.platform === "win32"
528
+ ? ["-NoLogo", "-NoProfile", "-Command", commandText]
529
+ : ["-lc", commandText];
530
+
531
+ const child = spawn(shell, shellArgs, { cwd: project.root, env: process.env });
532
+ session.process = child;
533
+ session.killTimer = null;
534
+ session.maxRuntimeTimer = setTimeout(() => terminateSession(session, "max runtime exceeded"), MAX_COMMAND_RUNTIME_MS);
535
+ sessions.set(id, session);
536
+
537
+ function pushChunk(type, chunk) {
538
+ const text = chunk.toString("utf8");
539
+ session.output += text;
540
+ session.listeners.forEach((res) => emitSession(res, { type, chunk: text, status: session.status, projectId: session.projectId }));
541
+ }
542
+
543
+ child.stdout.on("data", (c) => pushChunk("stdout", c));
544
+ child.stderr.on("data", (c) => pushChunk("stderr", c));
545
+ child.on("close", (code) => {
546
+ cleanupSession(session);
547
+ session.status = "completed";
548
+ session.exitCode = code;
549
+ session.listeners.forEach((res) => {
550
+ emitSession(res, { type: "done", status: session.status, exitCode: code, output: session.output, projectId: session.projectId });
551
+ res.end();
552
+ });
553
+ session.listeners.clear();
554
+ });
555
+ child.on("error", (err) => {
556
+ cleanupSession(session);
557
+ session.status = "failed";
558
+ session.exitCode = 1;
559
+ session.output += `${err.message}\n`;
560
+ session.listeners.forEach((res) => {
561
+ emitSession(res, { type: "done", status: session.status, exitCode: 1, output: session.output, projectId: session.projectId });
562
+ res.end();
563
+ });
564
+ session.listeners.clear();
565
+ });
566
+
567
+ return session;
568
+ }
569
+
570
+ function serveSessionStream(res, session) {
571
+ res.writeHead(200, { "Content-Type": "text/event-stream; charset=utf-8", "Cache-Control": "no-store", Connection: "keep-alive" });
572
+ emitSession(res, { type: "snapshot", status: session.status, exitCode: session.exitCode, command: session.command, output: session.output, projectId: session.projectId });
573
+ if (session.status !== "running") { res.end(); return; }
574
+ cleanupSession(session);
575
+ session.listeners.add(res);
576
+ res.on("close", () => { session.listeners.delete(res); scheduleOrphanTermination(session); });
577
+ }
578
+
579
+ /* ── static files ── */
580
+
581
+ function serveStatic(res, pathname) {
582
+ const safePath = pathname === "/" ? "/index.html" : pathname;
583
+ const normalized = path.normalize(safePath).replace(/^(\.\.[\\/])+/, "");
584
+ const filePath = path.join(UI_DIR, normalized);
585
+ if (!filePath.startsWith(UI_DIR)) { sendText(res, 403, "Forbidden."); return; }
586
+ if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory()) { sendText(res, 404, "Not found."); return; }
587
+ const ext = path.extname(filePath).toLowerCase();
588
+ res.writeHead(200, { "Content-Type": MIME_TYPES[ext] || "application/octet-stream", "Cache-Control": "no-store" });
589
+ fs.createReadStream(filePath).pipe(res);
590
+ }
591
+
592
+ /* ── API handler ── */
593
+
594
+ async function handleApi(req, res, url) {
595
+ try {
596
+ if (req.method === "GET" && url.pathname === "/api/projects") {
597
+ const current = ensureCurrentProjectRegistered();
598
+ sendJson(res, 200, { ok: true, currentProjectId: current?.id || null, registryFile: registry.REGISTRY_FILE, projects: registry.listProjects() });
599
+ return;
600
+ }
601
+
602
+ if (req.method === "POST" && url.pathname === "/api/projects/register") {
603
+ const body = await parseBody(req);
604
+ const project = registry.registerProject(body.root || startupRoot || process.cwd());
605
+ sendJson(res, 201, { ok: true, project, projects: registry.listProjects() });
606
+ return;
607
+ }
608
+
609
+ if (req.method === "POST" && url.pathname === "/api/projects/install") {
610
+ const body = await parseBody(req);
611
+ if (!body.root) { sendJson(res, 400, { ok: false, error: "Project path required." }); return; }
612
+ try {
613
+ const initMod = require("./init");
614
+ const result = initMod.initProject(body.root, { locale: body.locale || null });
615
+ if (body.withOpera) {
616
+ const opera = require("./opera");
617
+ await opera.install(result.root, {
618
+ locale: body.locale || null,
619
+ bootstrap: body.bootstrap !== false,
620
+ interactive: false,
621
+ answers: body.bootstrapAnswers || {},
622
+ });
623
+ }
624
+ const project = registry.registerProject(result.root);
625
+ sendJson(res, 201, { ok: true, project, projects: registry.listProjects() });
626
+ } catch (err) {
627
+ sendJson(res, 500, { ok: false, error: err.message });
628
+ }
629
+ return;
630
+ }
631
+
632
+ if (req.method === "GET" && url.pathname === "/api/state") {
633
+ sendJson(res, 200, getStatePayload(url.searchParams.get("project")));
634
+ return;
635
+ }
636
+
637
+ if (req.method === "POST" && url.pathname === "/api/projects/locale") {
638
+ const body = await parseBody(req);
639
+ const project = resolveProjectEntry(body.projectId || body.project || url.searchParams.get("project"));
640
+ const controlState = updateProjectLocale(project.root, body.locale);
641
+ sendJson(res, 200, {
642
+ ok: true,
643
+ locale: config.getLocale(controlState),
644
+ state: getStatePayload(project.id),
645
+ });
646
+ return;
647
+ }
648
+
649
+ if (req.method === "POST" && url.pathname === "/api/tasks") {
650
+ const body = await parseBody(req);
651
+ const project = resolveProjectEntry(body.projectId || body.project || url.searchParams.get("project"));
652
+ const task = createTask(project.root, body);
653
+ sendJson(res, 201, { ok: true, task, state: getStatePayload(project.id) });
654
+ return;
655
+ }
656
+
657
+ const taskMatch = url.pathname.match(/^\/api\/tasks\/([^/]+)$/);
658
+ if (req.method === "PUT" && taskMatch) {
659
+ const body = await parseBody(req);
660
+ const project = resolveProjectEntry(body.projectId || body.project || url.searchParams.get("project"));
661
+ const task = patchTask(project.root, decodeURIComponent(taskMatch[1]), body);
662
+ sendJson(res, 200, { ok: true, task, state: getStatePayload(project.id) });
663
+ return;
664
+ }
665
+
666
+ const actionMatch = url.pathname.match(/^\/api\/tasks\/([^/]+)\/action$/);
667
+ if (req.method === "POST" && actionMatch) {
668
+ const body = await parseBody(req);
669
+ const project = resolveProjectEntry(body.projectId || body.project || url.searchParams.get("project"));
670
+ const action = String(body.action || "").trim();
671
+ if (!action) { sendJson(res, 400, { ok: false, error: "Action required." }); return; }
672
+ const api = loadControlApi(project.root);
673
+ const controlState = api.loadControl();
674
+ api.updateTask(controlState, action, decodeURIComponent(actionMatch[1]), body.note || "");
675
+ sendJson(res, 200, { ok: true, state: getStatePayload(project.id) });
676
+ return;
677
+ }
678
+
364
679
  if (req.method === "POST" && url.pathname === "/api/sync") {
365
- const body = await parseBody(req);
366
- const project = resolveProjectEntry(body.projectId || body.project || url.searchParams.get("project"));
367
- const api = loadControlApi(project.root);
368
- const controlState = api.loadControl();
369
- api.syncDocs(controlState);
370
- api.refreshRepoRuntime({ quiet: true });
371
- sendJson(res, 200, { ok: true, state: getStatePayload(project.id) });
680
+ const body = await parseBody(req);
681
+ const project = resolveProjectEntry(body.projectId || body.project || url.searchParams.get("project"));
682
+ const api = loadControlApi(project.root);
683
+ const controlState = api.loadControl();
684
+ api.syncDocs(controlState);
685
+ api.refreshRepoRuntime({ quiet: true });
686
+ sendJson(res, 200, { ok: true, state: getStatePayload(project.id) });
372
687
  return;
373
688
  }
374
689
 
375
- if (req.method === "POST" && url.pathname === "/api/commands") {
376
- const body = await parseBody(req);
377
- const project = resolveProjectEntry(body.projectId || body.project || url.searchParams.get("project"));
378
- const commandText = String(body.command || "").trim();
379
- if (!commandText) { sendJson(res, 400, { ok: false, error: t("server.commandRequired") }); return; }
380
- const session = createSession(commandText, project);
381
- sendJson(res, 201, { ok: true, session: { id: session.id, command: session.command, startedAt: session.startedAt, status: session.status, projectId: session.projectId, projectName: session.projectName } });
382
- return;
383
- }
384
-
385
- const sessionInfoMatch = url.pathname.match(/^\/api\/commands\/([^/]+)$/);
386
- if (req.method === "GET" && sessionInfoMatch) {
387
- const session = sessions.get(decodeURIComponent(sessionInfoMatch[1]));
388
- if (!session) { sendJson(res, 404, { ok: false, error: t("server.sessionNotFound") }); return; }
389
- sendJson(res, 200, { ok: true, session });
390
- return;
391
- }
392
-
393
- const sessionStreamMatch = url.pathname.match(/^\/api\/commands\/([^/]+)\/stream$/);
394
- if (req.method === "GET" && sessionStreamMatch) {
395
- const session = sessions.get(decodeURIComponent(sessionStreamMatch[1]));
396
- if (!session) { sendText(res, 404, t("server.sessionNotFound")); return; }
397
- serveSessionStream(res, session);
398
- return;
399
- }
400
-
401
- const sessionCancelMatch = url.pathname.match(/^\/api\/commands\/([^/]+)\/cancel$/);
402
- if (req.method === "POST" && sessionCancelMatch) {
403
- const session = sessions.get(decodeURIComponent(sessionCancelMatch[1]));
404
- if (!session) { sendJson(res, 404, { ok: false, error: t("server.sessionNotFound") }); return; }
405
- terminateSession(session, "manually cancelled");
406
- sendJson(res, 200, { ok: true, session });
407
- return;
408
- }
409
-
410
- /* ── Time Tracking ── */
411
-
412
- if (req.method === "GET" && url.pathname === "/api/time") {
690
+ if (req.method === "GET" && url.pathname === "/api/env") {
413
691
  const project = resolveProjectEntry(url.searchParams.get("project"));
414
692
  const api = loadControlApi(project.root);
415
693
  const controlState = api.loadControl();
416
- const entries = controlState.timeEntries || [];
417
- sendJson(res, 200, { ok: true, entries });
418
- return;
419
- }
420
-
421
- if (req.method === "POST" && url.pathname === "/api/time/start") {
422
- const body = await parseBody(req);
423
- const project = resolveProjectEntry(body.projectId || body.project || url.searchParams.get("project"));
424
- const api = loadControlApi(project.root);
425
- const controlState = api.loadControl();
426
- const entryId = `te-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`;
427
- const entry = {
428
- id: entryId,
429
- taskId: String(body.taskId || "").trim(),
430
- taskTitle: String(body.taskTitle || "").trim(),
431
- startedAt: new Date().toISOString(),
432
- stoppedAt: null,
433
- durationMs: 0,
434
- };
435
- if (!controlState.timeEntries) controlState.timeEntries = [];
436
- controlState.timeEntries.push(entry);
437
- api.saveControl(controlState);
438
- sendJson(res, 201, { ok: true, entry });
694
+ sendJson(res, 200, env.auditEnvironment(project.root, controlState));
439
695
  return;
440
696
  }
441
697
 
442
- if (req.method === "POST" && url.pathname === "/api/time/stop") {
698
+ if (req.method === "POST" && url.pathname === "/api/env/sync") {
443
699
  const body = await parseBody(req);
444
700
  const project = resolveProjectEntry(body.projectId || body.project || url.searchParams.get("project"));
445
701
  const api = loadControlApi(project.root);
446
702
  const controlState = api.loadControl();
447
- const entries = controlState.timeEntries || [];
448
- const entry = entries.find(e => e.id === body.entryId);
449
- if (!entry) { sendJson(res, 404, { ok: false, error: "Entry not found." }); return; }
450
- entry.stoppedAt = new Date().toISOString();
451
- entry.durationMs = new Date(entry.stoppedAt) - new Date(entry.startedAt);
452
- api.saveControl(controlState);
453
- sendJson(res, 200, { ok: true, entry });
703
+ const result = env.syncEnvironment(project.root, controlState);
704
+ api.syncDocs(api.loadControl());
705
+ api.refreshRepoRuntime({ quiet: true });
706
+ sendJson(res, 200, result);
454
707
  return;
455
708
  }
456
-
457
- /* ── Skills Hub ── */
458
-
709
+
710
+ if (req.method === "POST" && url.pathname === "/api/commands") {
711
+ const body = await parseBody(req);
712
+ const project = resolveProjectEntry(body.projectId || body.project || url.searchParams.get("project"));
713
+ const commandText = String(body.command || "").trim();
714
+ if (!commandText) { sendJson(res, 400, { ok: false, error: t("server.commandRequired") }); return; }
715
+ const session = createSession(commandText, project);
716
+ sendJson(res, 201, { ok: true, session: { id: session.id, command: session.command, startedAt: session.startedAt, status: session.status, projectId: session.projectId, projectName: session.projectName } });
717
+ return;
718
+ }
719
+
720
+ const sessionInfoMatch = url.pathname.match(/^\/api\/commands\/([^/]+)$/);
721
+ if (req.method === "GET" && sessionInfoMatch) {
722
+ const session = sessions.get(decodeURIComponent(sessionInfoMatch[1]));
723
+ if (!session) { sendJson(res, 404, { ok: false, error: t("server.sessionNotFound") }); return; }
724
+ sendJson(res, 200, { ok: true, session });
725
+ return;
726
+ }
727
+
728
+ const sessionStreamMatch = url.pathname.match(/^\/api\/commands\/([^/]+)\/stream$/);
729
+ if (req.method === "GET" && sessionStreamMatch) {
730
+ const session = sessions.get(decodeURIComponent(sessionStreamMatch[1]));
731
+ if (!session) { sendText(res, 404, t("server.sessionNotFound")); return; }
732
+ serveSessionStream(res, session);
733
+ return;
734
+ }
735
+
736
+ const sessionCancelMatch = url.pathname.match(/^\/api\/commands\/([^/]+)\/cancel$/);
737
+ if (req.method === "POST" && sessionCancelMatch) {
738
+ const session = sessions.get(decodeURIComponent(sessionCancelMatch[1]));
739
+ if (!session) { sendJson(res, 404, { ok: false, error: t("server.sessionNotFound") }); return; }
740
+ terminateSession(session, "manually cancelled");
741
+ sendJson(res, 200, { ok: true, session });
742
+ return;
743
+ }
744
+
745
+ /* ── Time Tracking ── */
746
+
747
+ if (req.method === "GET" && url.pathname === "/api/time") {
748
+ const project = resolveProjectEntry(url.searchParams.get("project"));
749
+ const api = loadControlApi(project.root);
750
+ const controlState = api.loadControl();
751
+ const entries = controlState.timeEntries || [];
752
+ sendJson(res, 200, { ok: true, entries });
753
+ return;
754
+ }
755
+
756
+ if (req.method === "POST" && url.pathname === "/api/time/start") {
757
+ const body = await parseBody(req);
758
+ const project = resolveProjectEntry(body.projectId || body.project || url.searchParams.get("project"));
759
+ const api = loadControlApi(project.root);
760
+ const controlState = api.loadControl();
761
+ const entryId = `te-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`;
762
+ const entry = {
763
+ id: entryId,
764
+ taskId: String(body.taskId || "").trim(),
765
+ taskTitle: String(body.taskTitle || "").trim(),
766
+ startedAt: new Date().toISOString(),
767
+ stoppedAt: null,
768
+ durationMs: 0,
769
+ };
770
+ if (!controlState.timeEntries) controlState.timeEntries = [];
771
+ controlState.timeEntries.push(entry);
772
+ api.saveControl(controlState);
773
+ sendJson(res, 201, { ok: true, entry });
774
+ return;
775
+ }
776
+
777
+ if (req.method === "POST" && url.pathname === "/api/time/stop") {
778
+ const body = await parseBody(req);
779
+ const project = resolveProjectEntry(body.projectId || body.project || url.searchParams.get("project"));
780
+ const api = loadControlApi(project.root);
781
+ const controlState = api.loadControl();
782
+ const entries = controlState.timeEntries || [];
783
+ const entry = entries.find(e => e.id === body.entryId);
784
+ if (!entry) { sendJson(res, 404, { ok: false, error: "Entry not found." }); return; }
785
+ entry.stoppedAt = new Date().toISOString();
786
+ entry.durationMs = new Date(entry.stoppedAt) - new Date(entry.startedAt);
787
+ api.saveControl(controlState);
788
+ sendJson(res, 200, { ok: true, entry });
789
+ return;
790
+ }
791
+
792
+ /* ── Skills Hub ── */
793
+
459
794
  if (req.method === "GET" && url.pathname === "/api/skills/local") {
460
795
  const project = resolveProjectEntry(url.searchParams.get("project"));
461
- const agentsPath = path.join(project.root, ".agents", "skills");
462
- const agentPathFallback = path.join(project.root, ".agent", "skills");
463
- let skillsDir = fs.existsSync(agentsPath) ? agentsPath : (fs.existsSync(agentPathFallback) ? agentPathFallback : null);
464
-
465
- const skills = [];
466
- if (skillsDir) {
467
- try {
468
- const dirs = fs.readdirSync(skillsDir, { withFileTypes: true })
469
- .filter(dirent => dirent.isDirectory())
470
- .map(dirent => dirent.name);
471
-
472
- for (const d of dirs) {
473
- const skillMdPath = path.join(skillsDir, d, "SKILL.md");
474
- let description = "";
475
- let title = d;
476
- if (fs.existsSync(skillMdPath)) {
477
- const content = fs.readFileSync(skillMdPath, "utf-8");
478
- // Parse basic YAML frontmatter for title/description if exists
479
- const titleMatch = content.match(/title:\s*(.+)/i) || content.match(/name:\s*(.+)/i);
480
- const descMatch = content.match(/description:\s*(.+)/i) || content.match(/desc:\s*(.+)/i);
481
- if (titleMatch) title = titleMatch[1].replace(/['"]/g, '');
482
- if (descMatch) description = descMatch[1].replace(/['"]/g, '');
483
- }
484
- skills.push({ id: d, title, description, path: skillMdPath });
485
- }
486
- } catch (err) {
487
- console.error("Error reading skills dir:", err);
488
- }
489
- }
490
- sendJson(res, 200, { ok: true, skills });
491
- return;
492
- }
493
-
494
- if (req.method === "GET" && url.pathname === "/api/skills/discover") {
495
- // Mocked recommendations/catalog for skills.sh integration
496
- // Ideally this calls a raw json from github
497
- const catalog = [
498
- { id: "changelog-updater", title: "Changelog Updater", description: "Mantiene automatizado el CHANGELOG basado en commits.", url: "https://skills.sh/changelog-updater.md" },
499
- { id: "commiter", title: "Git Commiter", description: "Genera mensajes de commit strictos siguiendo Conventional Commits y Emojis.", url: "https://skills.sh/commiter.md" },
500
- { id: "project-starter-skill", title: "Project Starter", description: "Skill para inicializar proyectos usando el protocolo O.P.E.R.A.", url: "https://skills.sh/project-starter.md" },
501
- { id: "tdd-master", title: "TDD Master", description: "Fuerza el ciclo Red-Green-Refactor en las implementaciones.", url: "https://skills.sh/tdd-master.md" },
502
- { id: "e2e-tester", title: "E2E Tester", description: "Plantillas y comandos para frameworks de Test End-to-End.", url: "https://skills.sh/e2e-tester.md" }
503
- ];
504
- // Simulate network wait
505
- setTimeout(() => {
506
- sendJson(res, 200, { ok: true, catalog });
507
- }, 400);
508
- return;
509
- }
510
-
796
+ const context = config.ensureContext(project.root);
797
+ const skillsDir = fs.existsSync(context.paths.skillsDir) ? context.paths.skillsDir : null;
798
+
799
+ const skills = [];
800
+ if (skillsDir) {
801
+ try {
802
+ const dirs = fs.readdirSync(skillsDir, { withFileTypes: true })
803
+ .filter(dirent => dirent.isDirectory())
804
+ .map(dirent => dirent.name);
805
+
806
+ for (const d of dirs) {
807
+ const skillMdPath = path.join(skillsDir, d, "SKILL.md");
808
+ let description = "";
809
+ let title = d;
810
+ if (fs.existsSync(skillMdPath)) {
811
+ const content = fs.readFileSync(skillMdPath, "utf-8");
812
+ // Parse basic YAML frontmatter for title/description if exists
813
+ const titleMatch = content.match(/title:\s*(.+)/i) || content.match(/name:\s*(.+)/i);
814
+ const descMatch = content.match(/description:\s*(.+)/i) || content.match(/desc:\s*(.+)/i);
815
+ if (titleMatch) title = titleMatch[1].replace(/['"]/g, '');
816
+ if (descMatch) description = descMatch[1].replace(/['"]/g, '');
817
+ }
818
+ skills.push({ id: d, title, description, path: skillMdPath });
819
+ }
820
+ } catch (err) {
821
+ console.error("Error reading skills dir:", err);
822
+ }
823
+ }
824
+ sendJson(res, 200, { ok: true, skills });
825
+ return;
826
+ }
827
+
828
+ if (req.method === "GET" && url.pathname === "/api/skills/discover") {
829
+ // Mocked recommendations/catalog for skills.sh integration
830
+ // Ideally this calls a raw json from github
831
+ const catalog = [
832
+ { id: "changelog-updater", title: "Changelog Updater", description: "Mantiene automatizado el CHANGELOG basado en commits.", url: "https://skills.sh/changelog-updater.md" },
833
+ { id: "commiter", title: "Git Commiter", description: "Genera mensajes de commit strictos siguiendo Conventional Commits y Emojis.", url: "https://skills.sh/commiter.md" },
834
+ { id: "project-starter-skill", title: "Project Starter", description: "Skill para inicializar proyectos usando el protocolo O.P.E.R.A.", url: "https://skills.sh/project-starter.md" },
835
+ { id: "tdd-master", title: "TDD Master", description: "Fuerza el ciclo Red-Green-Refactor en las implementaciones.", url: "https://skills.sh/tdd-master.md" },
836
+ { id: "e2e-tester", title: "E2E Tester", description: "Plantillas y comandos para frameworks de Test End-to-End.", url: "https://skills.sh/e2e-tester.md" }
837
+ ];
838
+ // Simulate network wait
839
+ setTimeout(() => {
840
+ sendJson(res, 200, { ok: true, catalog });
841
+ }, 400);
842
+ return;
843
+ }
844
+
511
845
  if (req.method === "POST" && url.pathname === "/api/skills/install") {
512
- const body = await parseBody(req);
513
- const project = resolveProjectEntry(body.projectId || body.project || url.searchParams.get("project"));
514
- const skillId = body.skillId;
515
-
516
- if (!skillId) { sendJson(res, 400, { ok: false, error: "Missing skillId parameter" }); return; }
517
-
518
- // Intentamos usar .agents primariamente
519
- let agentsPath = path.join(project.root, ".agents");
520
- if (!fs.existsSync(agentsPath) && fs.existsSync(path.join(project.root, ".agent"))) {
521
- agentsPath = path.join(project.root, ".agent");
522
- }
523
-
524
- const skillsDir = path.join(agentsPath, "skills");
525
- if (!fs.existsSync(agentsPath)) fs.mkdirSync(agentsPath, { recursive: true });
846
+ const body = await parseBody(req);
847
+ const project = resolveProjectEntry(body.projectId || body.project || url.searchParams.get("project"));
848
+ const skillId = body.skillId;
849
+
850
+ if (!skillId) { sendJson(res, 400, { ok: false, error: "Missing skillId parameter" }); return; }
851
+
852
+ const context = config.ensureContext(project.root);
853
+ const skillsDir = context.paths.skillsDir;
526
854
  if (!fs.existsSync(skillsDir)) fs.mkdirSync(skillsDir, { recursive: true });
527
-
528
- const targetSkillDir = path.join(skillsDir, skillId);
529
- if (!fs.existsSync(targetSkillDir)) fs.mkdirSync(targetSkillDir, { recursive: true });
530
-
531
- const targetMdPath = path.join(targetSkillDir, "SKILL.md");
532
- const templateContent = `---
533
- name: ${skillId}
534
- description: Skill instalada desde skills.sh
535
- ---
536
-
537
- # ${skillId}
538
-
539
- Instructions para el agente relativas a esta skill...
540
- `;
541
-
542
- fs.writeFileSync(targetMdPath, templateContent, "utf-8");
543
- sendJson(res, 201, { ok: true, message: "Instalado correctamente", path: targetMdPath });
544
- return;
545
- }
546
-
547
-
548
- sendJson(res, 404, { ok: false, error: "API route not found." });
549
- } catch (error) {
550
- sendJson(res, 500, { ok: false, error: error.message });
551
- }
552
- }
553
-
554
- /* ── server start ── */
555
-
556
- function run() {
855
+
856
+ const targetSkillDir = path.join(skillsDir, skillId);
857
+ if (!fs.existsSync(targetSkillDir)) fs.mkdirSync(targetSkillDir, { recursive: true });
858
+
859
+ const targetMdPath = path.join(targetSkillDir, "SKILL.md");
860
+ const templateContent = `---
861
+ name: ${skillId}
862
+ description: Skill instalada desde skills.sh
863
+ ---
864
+
865
+ # ${skillId}
866
+
867
+ Instructions para el agente relativas a esta skill...
868
+ `;
869
+
870
+ fs.writeFileSync(targetMdPath, templateContent, "utf-8");
871
+ sendJson(res, 201, { ok: true, message: "Instalado correctamente", path: targetMdPath });
872
+ return;
873
+ }
874
+
875
+
876
+ sendJson(res, 404, { ok: false, error: "API route not found." });
877
+ } catch (error) {
878
+ sendJson(res, 500, { ok: false, error: error.message });
879
+ }
880
+ }
881
+
882
+ /* ── server start ── */
883
+
884
+ async function run(args = []) {
557
885
  startupRoot = config.resolveProjectRoot() || process.cwd();
558
-
559
- try {
560
- const ctrl = config.loadControl(startupRoot);
561
- setLocale(config.getLocale(ctrl));
562
- } catch (_e) {
563
- setLocale("es");
564
- }
565
-
566
- ensureCurrentProjectRegistered();
567
-
568
- const server = http.createServer((req, res) => {
569
- const url = new URL(req.url, `http://${req.headers.host || `${HOST}:${PORT}`}`);
570
- if (url.pathname.startsWith("/api/")) { handleApi(req, res, url); return; }
571
- serveStatic(res, url.pathname);
572
- });
573
-
574
- function shutdown() {
575
- sessions.forEach((s) => { if (s.status === "running") terminateSession(s, "dashboard shutdown"); });
576
- }
577
- process.on("SIGINT", shutdown);
578
- process.on("SIGTERM", shutdown);
579
- process.on("exit", shutdown);
580
-
581
- server.listen(PORT, HOST, () => {
582
- const current = ensureCurrentProjectRegistered();
583
- console.log(t("server.ready", { host: HOST, port: PORT }));
584
- if (current) console.log(t("server.defaultProject", { name: current.name, id: current.id }));
585
- });
586
- }
587
-
588
- if (require.main === module) {
589
- run();
590
- }
591
-
592
- module.exports = { run };
886
+
887
+ try {
888
+ const ctrl = config.loadControl(startupRoot);
889
+ setLocale(config.getLocale(ctrl));
890
+ } catch (_e) {
891
+ setLocale("es");
892
+ }
893
+
894
+ const dashboardConfig = resolveDashboardConfig(args, process.env);
895
+ const portSelection = await findAvailablePort({
896
+ host: dashboardConfig.host,
897
+ startPort: dashboardConfig.startPort,
898
+ strict: dashboardConfig.strictPort,
899
+ });
900
+ const resolvedPort = portSelection.port;
901
+ const fallbackBaseHost = getLocalUrlHost(dashboardConfig.host);
902
+
903
+ const server = http.createServer((req, res) => {
904
+ const url = new URL(req.url, `http://${req.headers.host || `${fallbackBaseHost}:${resolvedPort}`}`);
905
+ if (url.pathname.startsWith("/api/")) { handleApi(req, res, url); return; }
906
+ serveStatic(res, url.pathname);
907
+ });
908
+
909
+ function shutdown() {
910
+ sessions.forEach((s) => { if (s.status === "running") terminateSession(s, "dashboard shutdown"); });
911
+ }
912
+ process.on("SIGINT", shutdown);
913
+ process.on("SIGTERM", shutdown);
914
+ process.on("exit", shutdown);
915
+
916
+ await listenServer(server, dashboardConfig.host, resolvedPort);
917
+ const current = ensureCurrentProjectRegistered();
918
+ const urls = collectReachableUrls({
919
+ host: dashboardConfig.host,
920
+ port: resolvedPort,
921
+ publicMode: dashboardConfig.publicMode,
922
+ });
923
+ const clipboard = copyTextToClipboard(urls.localUrl);
924
+
925
+ console.log(renderStartupBanner({
926
+ port: resolvedPort,
927
+ requestedPort: portSelection.requestedPort,
928
+ fallbackUsed: portSelection.fallbackUsed,
929
+ publicMode: dashboardConfig.publicMode,
930
+ urls,
931
+ clipboard,
932
+ defaultProject: current,
933
+ }));
934
+
935
+ return server;
936
+ }
937
+
938
+ if (require.main === module) {
939
+ run(process.argv.slice(2)).catch((error) => {
940
+ console.error(error.message);
941
+ process.exit(1);
942
+ });
943
+ }
944
+
945
+ module.exports = { run };