trackops 1.0.0 → 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 (72) hide show
  1. package/README.md +341 -232
  2. package/bin/trackops.js +102 -70
  3. package/lib/config.js +260 -35
  4. package/lib/control.js +518 -475
  5. package/lib/env.js +227 -0
  6. package/lib/i18n.js +61 -53
  7. package/lib/init.js +146 -55
  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 +912 -418
  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 +14 -3
  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/etapa/agent.md +2 -2
  32. package/templates/etapa/references/etapa-cycle.md +1 -1
  33. package/templates/opera/agent.md +1 -1
  34. package/templates/opera/en/agent.md +26 -0
  35. package/templates/opera/en/genesis.md +79 -0
  36. package/templates/opera/en/references/autonomy-and-recovery.md +23 -0
  37. package/templates/opera/en/references/opera-cycle.md +62 -0
  38. package/templates/opera/en/registry.md +28 -0
  39. package/templates/opera/en/router.md +39 -0
  40. package/templates/opera/genesis.md +79 -94
  41. package/templates/skills/changelog-updater/locales/en/SKILL.md +11 -0
  42. package/templates/skills/commiter/locales/en/SKILL.md +11 -0
  43. package/templates/skills/project-starter-skill/SKILL.md +5 -3
  44. package/templates/skills/project-starter-skill/locales/en/SKILL.md +24 -0
  45. package/ui/css/base.css +266 -0
  46. package/ui/css/charts.css +327 -0
  47. package/ui/css/components.css +570 -0
  48. package/ui/css/panels.css +956 -0
  49. package/ui/css/tokens.css +227 -0
  50. package/ui/favicon.svg +5 -0
  51. package/ui/index.html +91 -351
  52. package/ui/js/api.js +220 -0
  53. package/ui/js/app.js +200 -0
  54. package/ui/js/console-logger.js +172 -0
  55. package/ui/js/i18n.js +14 -0
  56. package/ui/js/icons.js +104 -0
  57. package/ui/js/onboarding.js +439 -0
  58. package/ui/js/router.js +125 -0
  59. package/ui/js/state.js +130 -0
  60. package/ui/js/theme.js +100 -0
  61. package/ui/js/time-tracker.js +248 -0
  62. package/ui/js/utils.js +175 -0
  63. package/ui/js/views/board.js +255 -0
  64. package/ui/js/views/execution.js +256 -0
  65. package/ui/js/views/flash.js +47 -0
  66. package/ui/js/views/insights.js +340 -0
  67. package/ui/js/views/overview.js +365 -0
  68. package/ui/js/views/settings.js +381 -0
  69. package/ui/js/views/sidebar.js +131 -0
  70. package/ui/js/views/skills.js +163 -0
  71. package/ui/js/views/tasks.js +406 -0
  72. package/ui/js/views/topbar.js +239 -0
package/lib/server.js CHANGED
@@ -1,451 +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
- ".json": "application/json; charset=utf-8",
25
- ".svg": "image/svg+xml",
26
- };
27
-
28
- /* ── helpers ── */
29
-
30
- function sendJson(res, statusCode, payload) {
31
- res.writeHead(statusCode, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
32
- res.end(JSON.stringify(payload));
33
- }
34
-
35
- function sendText(res, statusCode, message) {
36
- res.writeHead(statusCode, { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" });
37
- res.end(message);
38
- }
39
-
40
- function parseBody(req) {
41
- return new Promise((resolve, reject) => {
42
- const chunks = [];
43
- let size = 0;
44
- req.on("data", (chunk) => {
45
- size += chunk.length;
46
- if (size > 1024 * 1024) { reject(new Error(t("server.payloadTooLarge", { limit: "1 MB" }))); req.destroy(); return; }
47
- chunks.push(chunk);
48
- });
49
- req.on("end", () => {
50
- if (!chunks.length) { resolve({}); return; }
51
- try { resolve(JSON.parse(Buffer.concat(chunks).toString("utf8"))); }
52
- catch (_e) { reject(new Error(t("server.invalidJson"))); }
53
- });
54
- req.on("error", reject);
55
- });
56
- }
57
-
58
- function slugify(value) {
59
- return String(value || "").normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48);
60
- }
61
-
62
- function toList(value) {
63
- if (Array.isArray(value)) return value.map((i) => String(i).trim()).filter(Boolean);
64
- return String(value || "").split(/\r?\n|,/).map((i) => i.trim()).filter(Boolean);
65
- }
66
-
67
- /* ── project resolution ── */
68
-
69
- let startupRoot = null;
70
-
71
- function ensureCurrentProjectRegistered() {
72
- if (!startupRoot) return null;
73
- try { return registry.registerProject(startupRoot); }
74
- catch (_e) { return null; }
75
- }
76
-
77
- function resolveProjectEntry(projectRef) {
78
- const current = ensureCurrentProjectRegistered();
79
- const entry = registry.resolveProject(projectRef, startupRoot) || current;
80
- if (!entry) throw new Error(t("server.projectNotResolved"));
81
- return entry;
82
- }
83
-
84
- function loadControlApi(projectRoot) {
85
- return control.forProject(projectRoot);
86
- }
87
-
88
- function buildI18nPayload(controlState) {
89
- const phases = config.getPhases(controlState);
90
- const locale = config.getLocale(controlState);
91
- const statusLabels = {};
92
- for (const s of control.STATUS_ORDER) {
93
- statusLabels[s] = control.statusLabel(s);
94
- }
95
- return { locale, statusLabels, phases };
96
- }
97
-
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
+
98
368
  function getStatePayload(projectRef) {
99
369
  const project = resolveProjectEntry(projectRef);
100
370
  const api = loadControlApi(project.root);
101
371
  const controlState = api.loadControl();
102
372
  const runtime = api.refreshRepoRuntime({ quiet: true });
373
+ const envState = env.auditEnvironment(project.root, controlState);
103
374
 
104
375
  return {
105
376
  project,
106
377
  control: controlState,
107
378
  derived: api.derive(controlState),
108
379
  runtime,
380
+ env: envState,
109
381
  docsDirty: api.getDocDrift(controlState),
110
382
  i18n: buildI18nPayload(controlState),
111
383
  generatedAt: new Date().toISOString(),
112
- };
113
- }
114
-
115
- function persist(projectRoot) {
116
- const api = loadControlApi(projectRoot);
117
- const controlState = api.loadControl();
118
- api.saveControl(controlState);
119
- api.syncDocs(controlState);
120
- api.refreshRepoRuntime({ quiet: true });
121
- }
122
-
123
- /* ── task operations ── */
124
-
125
- function makeTaskId(controlState, seed) {
126
- const base = slugify(seed) || `task-${Date.now()}`;
127
- const existing = new Set(controlState.tasks.map((t) => t.id));
128
- if (!existing.has(base)) return base;
129
- let idx = 2;
130
- while (existing.has(`${base}-${idx}`)) idx += 1;
131
- return `${base}-${idx}`;
132
- }
133
-
134
- function createTask(projectRoot, payload) {
135
- const api = loadControlApi(projectRoot);
136
- const controlState = api.loadControl();
137
- const title = String(payload.title || "").trim();
138
- if (!title) throw new Error(t("server.titleRequired"));
139
-
140
- const task = {
141
- id: makeTaskId(controlState, payload.id || title),
142
- title,
143
- phase: payload.phase || config.getPhases(controlState)[0]?.id || "E",
144
- stream: String(payload.stream || "Operations").trim(),
145
- priority: payload.priority || "P1",
146
- status: payload.status || "pending",
147
- required: payload.required !== false,
148
- dependsOn: toList(payload.dependsOn),
149
- summary: String(payload.summary || "").trim(),
150
- acceptance: toList(payload.acceptance),
151
- history: [{ at: new Date().toISOString(), action: "create", note: t("server.taskCreatedNote") }],
152
- };
153
-
154
- const blocker = String(payload.blocker || "").trim();
155
- if (blocker) task.blocker = blocker;
156
- controlState.tasks.push(task);
157
- api.saveControl(controlState);
158
- api.syncDocs(controlState);
159
- api.refreshRepoRuntime({ quiet: true });
160
- return task;
161
- }
162
-
163
- function patchTask(projectRoot, taskId, payload) {
164
- const api = loadControlApi(projectRoot);
165
- const controlState = api.loadControl();
166
- const task = controlState.tasks.find((t) => t.id === taskId);
167
- if (!task) throw new Error(t("cli.taskNotFound", { taskId }));
168
-
169
- if (typeof payload.title === "string") task.title = payload.title.trim() || task.title;
170
- if (typeof payload.phase === "string") task.phase = payload.phase;
171
- if (typeof payload.stream === "string") task.stream = payload.stream.trim() || task.stream;
172
- if (typeof payload.priority === "string") task.priority = payload.priority;
173
- if (typeof payload.status === "string") task.status = payload.status;
174
- if (typeof payload.required === "boolean") task.required = payload.required;
175
- if (payload.summary !== undefined) task.summary = String(payload.summary || "").trim();
176
- if (payload.dependsOn !== undefined) task.dependsOn = toList(payload.dependsOn);
177
- if (payload.acceptance !== undefined) task.acceptance = toList(payload.acceptance);
178
-
179
- const blocker = String(payload.blocker || "").trim();
180
- if (blocker) task.blocker = blocker;
181
- else delete task.blocker;
182
-
183
- task.history = task.history || [];
184
- task.history.push({ at: new Date().toISOString(), action: "edit", note: String(payload.note || t("server.taskEditedNote")).trim() });
185
-
186
- api.saveControl(controlState);
187
- api.syncDocs(controlState);
188
- api.refreshRepoRuntime({ quiet: true });
189
- return task;
190
- }
191
-
192
- /* ── sessions (command execution) ── */
193
-
194
- function emitSession(res, payload) { res.write(`data: ${JSON.stringify(payload)}\n\n`); }
195
-
196
- function cleanupSession(session) {
197
- if (session.killTimer) { clearTimeout(session.killTimer); session.killTimer = null; }
198
- if (session.maxRuntimeTimer) { clearTimeout(session.maxRuntimeTimer); session.maxRuntimeTimer = null; }
199
- }
200
-
201
- function terminateSession(session, reason) {
202
- if (!session || session.status !== "running" || !session.process) return;
203
- cleanupSession(session);
204
- session.status = "terminated";
205
- session.exitCode = 1;
206
- session.output += `\n[ops] ${reason}\n`;
207
- try { session.process.kill(); } catch (_e) { /* noop */ }
208
- session.listeners.forEach((res) => {
209
- emitSession(res, { type: "done", status: session.status, exitCode: session.exitCode, output: session.output, projectId: session.projectId });
210
- res.end();
211
- });
212
- session.listeners.clear();
213
- }
214
-
215
- function scheduleOrphanTermination(session) {
216
- if (!session || session.status !== "running" || session.listeners.size > 0) return;
217
- cleanupSession(session);
218
- session.killTimer = setTimeout(() => terminateSession(session, "orphan timeout"), ORPHAN_TIMEOUT_MS);
219
- }
220
-
221
- function createSession(commandText, project) {
222
- const id = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
223
- const session = {
224
- id, projectId: project.id, projectName: project.name, projectRoot: project.root,
225
- command: commandText, startedAt: new Date().toISOString(),
226
- status: "running", exitCode: null, output: "", listeners: new Set(),
227
- };
228
-
229
- const shell = process.platform === "win32" ? "powershell.exe" : process.env.SHELL || "/bin/sh";
230
- const shellArgs = process.platform === "win32"
231
- ? ["-NoLogo", "-NoProfile", "-Command", commandText]
232
- : ["-lc", commandText];
233
-
234
- const child = spawn(shell, shellArgs, { cwd: project.root, env: process.env });
235
- session.process = child;
236
- session.killTimer = null;
237
- session.maxRuntimeTimer = setTimeout(() => terminateSession(session, "max runtime exceeded"), MAX_COMMAND_RUNTIME_MS);
238
- sessions.set(id, session);
239
-
240
- function pushChunk(type, chunk) {
241
- const text = chunk.toString("utf8");
242
- session.output += text;
243
- session.listeners.forEach((res) => emitSession(res, { type, chunk: text, status: session.status, projectId: session.projectId }));
244
- }
245
-
246
- child.stdout.on("data", (c) => pushChunk("stdout", c));
247
- child.stderr.on("data", (c) => pushChunk("stderr", c));
248
- child.on("close", (code) => {
249
- cleanupSession(session);
250
- session.status = "completed";
251
- session.exitCode = code;
252
- session.listeners.forEach((res) => {
253
- emitSession(res, { type: "done", status: session.status, exitCode: code, output: session.output, projectId: session.projectId });
254
- res.end();
255
- });
256
- session.listeners.clear();
257
- });
258
- child.on("error", (err) => {
259
- cleanupSession(session);
260
- session.status = "failed";
261
- session.exitCode = 1;
262
- session.output += `${err.message}\n`;
263
- session.listeners.forEach((res) => {
264
- emitSession(res, { type: "done", status: session.status, exitCode: 1, output: session.output, projectId: session.projectId });
265
- res.end();
266
- });
267
- session.listeners.clear();
268
- });
269
-
270
- return session;
271
- }
272
-
273
- function serveSessionStream(res, session) {
274
- res.writeHead(200, { "Content-Type": "text/event-stream; charset=utf-8", "Cache-Control": "no-store", Connection: "keep-alive" });
275
- emitSession(res, { type: "snapshot", status: session.status, exitCode: session.exitCode, command: session.command, output: session.output, projectId: session.projectId });
276
- if (session.status !== "running") { res.end(); return; }
277
- cleanupSession(session);
278
- session.listeners.add(res);
279
- res.on("close", () => { session.listeners.delete(res); scheduleOrphanTermination(session); });
280
- }
281
-
282
- /* ── static files ── */
283
-
284
- function serveStatic(res, pathname) {
285
- const safePath = pathname === "/" ? "/index.html" : pathname;
286
- const normalized = path.normalize(safePath).replace(/^(\.\.[\\/])+/, "");
287
- const filePath = path.join(UI_DIR, normalized);
288
- if (!filePath.startsWith(UI_DIR)) { sendText(res, 403, "Forbidden."); return; }
289
- if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory()) { sendText(res, 404, "Not found."); return; }
290
- const ext = path.extname(filePath).toLowerCase();
291
- res.writeHead(200, { "Content-Type": MIME_TYPES[ext] || "application/octet-stream", "Cache-Control": "no-store" });
292
- fs.createReadStream(filePath).pipe(res);
293
- }
294
-
295
- /* ── API handler ── */
296
-
297
- async function handleApi(req, res, url) {
298
- try {
299
- if (req.method === "GET" && url.pathname === "/api/projects") {
300
- const current = ensureCurrentProjectRegistered();
301
- sendJson(res, 200, { ok: true, currentProjectId: current?.id || null, registryFile: registry.REGISTRY_FILE, projects: registry.listProjects() });
302
- return;
303
- }
304
-
305
- if (req.method === "POST" && url.pathname === "/api/projects/register") {
306
- const body = await parseBody(req);
307
- const project = registry.registerProject(body.root || startupRoot || process.cwd());
308
- sendJson(res, 201, { ok: true, project, projects: registry.listProjects() });
309
- return;
310
- }
311
-
312
- if (req.method === "POST" && url.pathname === "/api/projects/install") {
313
- const body = await parseBody(req);
314
- if (!body.root) { sendJson(res, 400, { ok: false, error: "Project path required." }); return; }
315
- try {
316
- const initMod = require("./init");
317
- const result = initMod.initProject(body.root, {});
318
- const project = registry.registerProject(result.root);
319
- sendJson(res, 201, { ok: true, project, projects: registry.listProjects() });
320
- } catch (err) {
321
- sendJson(res, 500, { ok: false, error: err.message });
322
- }
323
- return;
324
- }
325
-
326
- if (req.method === "GET" && url.pathname === "/api/state") {
327
- sendJson(res, 200, getStatePayload(url.searchParams.get("project")));
328
- return;
329
- }
330
-
331
- if (req.method === "POST" && url.pathname === "/api/tasks") {
332
- const body = await parseBody(req);
333
- const project = resolveProjectEntry(body.projectId || body.project || url.searchParams.get("project"));
334
- const task = createTask(project.root, body);
335
- sendJson(res, 201, { ok: true, task, state: getStatePayload(project.id) });
336
- return;
337
- }
338
-
339
- const taskMatch = url.pathname.match(/^\/api\/tasks\/([^/]+)$/);
340
- if (req.method === "PUT" && taskMatch) {
341
- const body = await parseBody(req);
342
- const project = resolveProjectEntry(body.projectId || body.project || url.searchParams.get("project"));
343
- const task = patchTask(project.root, decodeURIComponent(taskMatch[1]), body);
344
- sendJson(res, 200, { ok: true, task, state: getStatePayload(project.id) });
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
+
679
+ if (req.method === "POST" && url.pathname === "/api/sync") {
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) });
345
687
  return;
346
688
  }
347
689
 
348
- const actionMatch = url.pathname.match(/^\/api\/tasks\/([^/]+)\/action$/);
349
- if (req.method === "POST" && actionMatch) {
350
- const body = await parseBody(req);
351
- const project = resolveProjectEntry(body.projectId || body.project || url.searchParams.get("project"));
352
- const action = String(body.action || "").trim();
353
- if (!action) { sendJson(res, 400, { ok: false, error: "Action required." }); return; }
690
+ if (req.method === "GET" && url.pathname === "/api/env") {
691
+ const project = resolveProjectEntry(url.searchParams.get("project"));
354
692
  const api = loadControlApi(project.root);
355
693
  const controlState = api.loadControl();
356
- api.updateTask(controlState, action, decodeURIComponent(actionMatch[1]), body.note || "");
357
- sendJson(res, 200, { ok: true, state: getStatePayload(project.id) });
694
+ sendJson(res, 200, env.auditEnvironment(project.root, controlState));
358
695
  return;
359
696
  }
360
697
 
361
- if (req.method === "POST" && url.pathname === "/api/sync") {
698
+ if (req.method === "POST" && url.pathname === "/api/env/sync") {
362
699
  const body = await parseBody(req);
363
700
  const project = resolveProjectEntry(body.projectId || body.project || url.searchParams.get("project"));
364
701
  const api = loadControlApi(project.root);
365
702
  const controlState = api.loadControl();
366
- api.syncDocs(controlState);
703
+ const result = env.syncEnvironment(project.root, controlState);
704
+ api.syncDocs(api.loadControl());
367
705
  api.refreshRepoRuntime({ quiet: true });
368
- sendJson(res, 200, { ok: true, state: getStatePayload(project.id) });
706
+ sendJson(res, 200, result);
369
707
  return;
370
708
  }
371
-
372
- if (req.method === "POST" && url.pathname === "/api/commands") {
373
- const body = await parseBody(req);
374
- const project = resolveProjectEntry(body.projectId || body.project || url.searchParams.get("project"));
375
- const commandText = String(body.command || "").trim();
376
- if (!commandText) { sendJson(res, 400, { ok: false, error: t("server.commandRequired") }); return; }
377
- const session = createSession(commandText, project);
378
- sendJson(res, 201, { ok: true, session: { id: session.id, command: session.command, startedAt: session.startedAt, status: session.status, projectId: session.projectId, projectName: session.projectName } });
379
- return;
380
- }
381
-
382
- const sessionInfoMatch = url.pathname.match(/^\/api\/commands\/([^/]+)$/);
383
- if (req.method === "GET" && sessionInfoMatch) {
384
- const session = sessions.get(decodeURIComponent(sessionInfoMatch[1]));
385
- if (!session) { sendJson(res, 404, { ok: false, error: t("server.sessionNotFound") }); return; }
386
- sendJson(res, 200, { ok: true, session });
387
- return;
388
- }
389
-
390
- const sessionStreamMatch = url.pathname.match(/^\/api\/commands\/([^/]+)\/stream$/);
391
- if (req.method === "GET" && sessionStreamMatch) {
392
- const session = sessions.get(decodeURIComponent(sessionStreamMatch[1]));
393
- if (!session) { sendText(res, 404, t("server.sessionNotFound")); return; }
394
- serveSessionStream(res, session);
395
- return;
396
- }
397
-
398
- const sessionCancelMatch = url.pathname.match(/^\/api\/commands\/([^/]+)\/cancel$/);
399
- if (req.method === "POST" && sessionCancelMatch) {
400
- const session = sessions.get(decodeURIComponent(sessionCancelMatch[1]));
401
- if (!session) { sendJson(res, 404, { ok: false, error: t("server.sessionNotFound") }); return; }
402
- terminateSession(session, "manually cancelled");
403
- sendJson(res, 200, { ok: true, session });
404
- return;
405
- }
406
-
407
- sendJson(res, 404, { ok: false, error: "API route not found." });
408
- } catch (error) {
409
- sendJson(res, 500, { ok: false, error: error.message });
410
- }
411
- }
412
-
413
- /* ── server start ── */
414
-
415
- function run() {
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
+
794
+ if (req.method === "GET" && url.pathname === "/api/skills/local") {
795
+ const project = resolveProjectEntry(url.searchParams.get("project"));
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
+
845
+ if (req.method === "POST" && url.pathname === "/api/skills/install") {
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;
854
+ if (!fs.existsSync(skillsDir)) fs.mkdirSync(skillsDir, { recursive: true });
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 = []) {
416
885
  startupRoot = config.resolveProjectRoot() || process.cwd();
417
-
418
- try {
419
- const ctrl = config.loadControl(startupRoot);
420
- setLocale(config.getLocale(ctrl));
421
- } catch (_e) {
422
- setLocale("es");
423
- }
424
-
425
- ensureCurrentProjectRegistered();
426
-
427
- const server = http.createServer((req, res) => {
428
- const url = new URL(req.url, `http://${req.headers.host || `${HOST}:${PORT}`}`);
429
- if (url.pathname.startsWith("/api/")) { handleApi(req, res, url); return; }
430
- serveStatic(res, url.pathname);
431
- });
432
-
433
- function shutdown() {
434
- sessions.forEach((s) => { if (s.status === "running") terminateSession(s, "dashboard shutdown"); });
435
- }
436
- process.on("SIGINT", shutdown);
437
- process.on("SIGTERM", shutdown);
438
- process.on("exit", shutdown);
439
-
440
- server.listen(PORT, HOST, () => {
441
- const current = ensureCurrentProjectRegistered();
442
- console.log(t("server.ready", { host: HOST, port: PORT }));
443
- if (current) console.log(t("server.defaultProject", { name: current.name, id: current.id }));
444
- });
445
- }
446
-
447
- if (require.main === module) {
448
- run();
449
- }
450
-
451
- 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 };