@omerrgocmen/crewctl 1.0.1 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.md +2 -0
  2. package/orchestrator/README.md +429 -427
  3. package/orchestrator/config.default.json +71 -65
  4. package/orchestrator/roles/executor.md +26 -18
  5. package/orchestrator/roles/operator.md +77 -75
  6. package/orchestrator/roles/planner.md +5 -0
  7. package/orchestrator/roles/reviewer.md +63 -54
  8. package/orchestrator/skills/acceptance-criteria.md +18 -18
  9. package/orchestrator/skills/accessibility-audit.md +16 -16
  10. package/orchestrator/skills/accessible-forms.md +16 -16
  11. package/orchestrator/skills/api-design.md +27 -27
  12. package/orchestrator/skills/api-documentation.md +16 -16
  13. package/orchestrator/skills/architecture-decision-record.md +18 -18
  14. package/orchestrator/skills/authentication-design.md +16 -16
  15. package/orchestrator/skills/authorization-review.md +16 -16
  16. package/orchestrator/skills/backward-compatibility.md +17 -17
  17. package/orchestrator/skills/changelog-writing.md +16 -16
  18. package/orchestrator/skills/ci-pipeline-design.md +16 -16
  19. package/orchestrator/skills/cli-design.md +16 -16
  20. package/orchestrator/skills/code-review.md +27 -27
  21. package/orchestrator/skills/configuration-management.md +16 -16
  22. package/orchestrator/skills/container-review.md +16 -16
  23. package/orchestrator/skills/contract-testing.md +16 -16
  24. package/orchestrator/skills/dashboard-design.md +16 -16
  25. package/orchestrator/skills/database-migration.md +16 -16
  26. package/orchestrator/skills/database-schema-design.md +16 -16
  27. package/orchestrator/skills/debugging.md +26 -26
  28. package/orchestrator/skills/dependency-review.md +16 -16
  29. package/orchestrator/skills/design-review.md +29 -29
  30. package/orchestrator/skills/design-system.md +16 -16
  31. package/orchestrator/skills/docs-api-reference.md +16 -16
  32. package/orchestrator/skills/docs-troubleshooting.md +16 -16
  33. package/orchestrator/skills/docs-tutorial.md +16 -16
  34. package/orchestrator/skills/docs-writing.md +25 -25
  35. package/orchestrator/skills/empty-error-loading-states.md +16 -16
  36. package/orchestrator/skills/end-to-end-testing.md +16 -16
  37. package/orchestrator/skills/error-handling.md +16 -16
  38. package/orchestrator/skills/frontend-design.md +28 -28
  39. package/orchestrator/skills/git-commit-writing.md +16 -16
  40. package/orchestrator/skills/graphql-design.md +16 -16
  41. package/orchestrator/skills/incident-runbook.md +18 -18
  42. package/orchestrator/skills/input-validation.md +16 -16
  43. package/orchestrator/skills/integration-testing.md +16 -16
  44. package/orchestrator/skills/interaction-design.md +16 -16
  45. package/orchestrator/skills/landing-page-design.md +16 -16
  46. package/orchestrator/skills/observability-design.md +16 -16
  47. package/orchestrator/skills/openapi-contract.md +16 -16
  48. package/orchestrator/skills/performance-profiling.md +16 -16
  49. package/orchestrator/skills/privacy-review.md +16 -16
  50. package/orchestrator/skills/property-based-testing.md +16 -16
  51. package/orchestrator/skills/pull-request-writing.md +16 -16
  52. package/orchestrator/skills/refactoring.md +16 -16
  53. package/orchestrator/skills/release-readiness.md +16 -16
  54. package/orchestrator/skills/responsive-design.md +16 -16
  55. package/orchestrator/skills/secrets-management.md +16 -16
  56. package/orchestrator/skills/secure-file-upload.md +16 -16
  57. package/orchestrator/skills/security-review.md +26 -26
  58. package/orchestrator/skills/semantic-versioning.md +17 -17
  59. package/orchestrator/skills/seo-on-page.md +16 -16
  60. package/orchestrator/skills/seo-structured-data.md +16 -16
  61. package/orchestrator/skills/seo-technical-audit.md +16 -16
  62. package/orchestrator/skills/sql-query-review.md +16 -16
  63. package/orchestrator/skills/supply-chain-security.md +16 -16
  64. package/orchestrator/skills/test-strategy.md +16 -16
  65. package/orchestrator/skills/threat-modeling.md +16 -16
  66. package/orchestrator/skills/unit-testing.md +16 -16
  67. package/orchestrator/skills/write-tests.md +28 -28
  68. package/orchestrator/src/cli-registry.js +616 -613
  69. package/orchestrator/src/cli.js +131 -131
  70. package/orchestrator/src/doctor.js +64 -64
  71. package/orchestrator/src/engine.js +216 -32
  72. package/orchestrator/src/server.js +766 -733
  73. package/orchestrator/src/skill-registry.js +272 -272
  74. package/orchestrator/src/store.js +399 -379
  75. package/orchestrator/web/OrbitControls.js +1417 -1417
  76. package/orchestrator/web/android-chrome-192x192.png +0 -0
  77. package/orchestrator/web/android-chrome-512x512.png +0 -0
  78. package/orchestrator/web/apple-touch-icon.png +0 -0
  79. package/orchestrator/web/board.html +5 -0
  80. package/orchestrator/web/code.html +5 -0
  81. package/orchestrator/web/favicon-16x16.png +0 -0
  82. package/orchestrator/web/favicon-32x32.png +0 -0
  83. package/orchestrator/web/favicon.ico +0 -0
  84. package/orchestrator/web/flow.html +741 -736
  85. package/orchestrator/web/index.html +588 -539
  86. package/orchestrator/web/jsm/postprocessing/EffectComposer.js +231 -231
  87. package/orchestrator/web/jsm/postprocessing/MaskPass.js +104 -104
  88. package/orchestrator/web/jsm/postprocessing/Pass.js +95 -95
  89. package/orchestrator/web/jsm/postprocessing/RenderPass.js +99 -99
  90. package/orchestrator/web/jsm/postprocessing/ShaderPass.js +77 -77
  91. package/orchestrator/web/jsm/postprocessing/UnrealBloomPass.js +415 -415
  92. package/orchestrator/web/jsm/shaders/CopyShader.js +45 -45
  93. package/orchestrator/web/jsm/shaders/LuminosityHighPassShader.js +66 -66
  94. package/orchestrator/web/site.webmanifest +12 -0
  95. package/orchestrator/web/three.module.min.js +6 -6
  96. package/package.json +1 -1
@@ -1,379 +1,399 @@
1
- // store.js — dosya tabanli kuyruk, config, hafiza, butce (sifir bagimlilik)
2
- const fs = require("fs");
3
- const path = require("path");
4
- const crypto = require("crypto");
5
- const os = require("os");
6
-
7
- const isWin = process.platform === "win32";
8
- // ASSETS: paket dizini (salt-okunur varlıklar: web/, config.default.json, varsayilan roles/+skills/).
9
- // __dirname/.. daima paketin gercek yeridir (npm global/npx onbellegi dahil).
10
- const ASSETS = path.join(__dirname, "..");
11
- // ROOT: yazilabilir VERI koku (config.json, queue/, state/, memory/, kullanicinin roles/+skills/).
12
- // Oncelik: CLI_TEAM_ROOT (izole test/CI) > CREWCTL_HOME (kullanici override) > mod tespiti.
13
- // Gelistirme kopyasinda test/ klasoru bulunur ve paket dizini yazilabilirdir; o zaman ROOT=ASSETS
14
- // (mevcut npm start/npm test davranisi aynen korunur). Yayinlanan pakette test/ gonderilmez, bu
15
- // yuzden kurulu modda veri ~/.crewctl'e yazilir (npm onbelleğine degil).
16
- const isDevCheckout = fs.existsSync(path.join(ASSETS, "test"));
17
- const ROOT = path.resolve(
18
- process.env.CLI_TEAM_ROOT ||
19
- process.env.CREWCTL_HOME ||
20
- (isDevCheckout ? ASSETS : path.join(os.homedir(), ".crewctl"))
21
- );
22
- // WORK_BASE: agent'larin uzerinde calisacagi klasorun goreli cozumleme tabani. Kurulu modda
23
- // kullanici komutu nerede calistirdiysa orasidir (cwd); mutlak yol secilirse zaten o kullanilir.
24
- const WORK_BASE = process.cwd();
25
- const Q = path.join(ROOT, "queue");
26
- const STATES = ["pending", "done", "failed", "approval"];
27
- const MEM = path.join(ROOT, "memory");
28
- const STATE = path.join(ROOT, "state");
29
- const EVENTS = path.join(STATE, "events");
30
- const ROLES = path.join(ROOT, "roles");
31
- const SKILLS = path.join(ROOT, "skills");
32
-
33
- // Windows'ta rename/unlink; antivirus, arama dizinleyici veya kuyrugu ayni anda tarayan
34
- // canli sunucu dosyada kisa sureli bir handle tuttugunda gecici olarak EPERM/EACCES/EBUSY
35
- // verir. Tek seferlik cagri bu durumda tum gorevi coldururdu; kisa artan beklemelerle yeniden
36
- // deneriz. Bu kod yolu tum saveTask/saveConfig/addTask cagrilarinin sicak yolu.
37
- const TRANSIENT_FS_CODES = new Set(["EPERM", "EACCES", "EBUSY", "ENOENT", "EEXIST"]);
38
- function sleepSync(ms) {
39
- try { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); } catch {}
40
- }
41
- function isTransientFsError(error) {
42
- return isWin && error && TRANSIENT_FS_CODES.has(error.code);
43
- }
44
-
45
- function sweepStaleTemp(dir, maxAgeMs = 5 * 60 * 1000) {
46
- // Kalici olarak yeniden adlandirilamamis eski .tmp dosyalarini birak birikmesin diye temizle.
47
- let entries;
48
- try { entries = fs.readdirSync(dir); } catch { return; }
49
- const now = Date.now();
50
- for (const name of entries) {
51
- if (!name.endsWith(".tmp")) continue;
52
- const full = path.join(dir, name);
53
- try {
54
- if (now - fs.statSync(full).mtimeMs > maxAgeMs) fs.rmSync(full, { force: true });
55
- } catch {}
56
- }
57
- }
58
-
59
- // Kurulu modda (ROOT != ASSETS) veri kokundeki roles/ ve skills/ bos ise paketle gelen
60
- // varsayilanlari BIR KEZ kopyala. Kullanicinin duzenlemeleri korunur (yalnizca bos dizine seed).
61
- let seededAssets = false;
62
- function seedDefaults() {
63
- if (seededAssets) return;
64
- seededAssets = true;
65
- if (ROOT === ASSETS) return;
66
- for (const [srcDir, dstDir] of [[path.join(ASSETS, "roles"), ROLES], [path.join(ASSETS, "skills"), SKILLS]]) {
67
- try {
68
- const existing = fs.existsSync(dstDir) ? fs.readdirSync(dstDir).filter((f) => f.toLowerCase().endsWith(".md")) : [];
69
- if (existing.length) continue;
70
- const defaults = fs.existsSync(srcDir) ? fs.readdirSync(srcDir).filter((f) => f.toLowerCase().endsWith(".md")) : [];
71
- for (const f of defaults) fs.copyFileSync(path.join(srcDir, f), path.join(dstDir, f));
72
- } catch {}
73
- }
74
- }
75
-
76
- // ensureDirs, olay akisinda cok sik cagrilir; temizligi dakikada bir defayla sinirla ki
77
- // her stdout parcasinda dizin taramasi yapmayalim.
78
- let lastSweepAt = 0;
79
- function ensureDirs() {
80
- const dirs = [...STATES.map((s) => path.join(Q, s)), MEM, STATE, EVENTS, ROLES, SKILLS];
81
- dirs.forEach((d) => fs.mkdirSync(d, { recursive: true }));
82
- seedDefaults();
83
- if (Date.now() - lastSweepAt > 60 * 1000) {
84
- lastSweepAt = Date.now();
85
- for (const s of STATES) sweepStaleTemp(path.join(Q, s));
86
- }
87
- }
88
-
89
- // Atomik yazma: once .tmp'ye yaz, sonra rename et. Rename ayni disk uzerinde atomiktir;
90
- // boylece surec ortasinda cokme olsa bile yarim/bozuk JSON dosyasi kalmaz (her PC'de guvenli).
91
- // Windows'ta rename gecici olarak kilitlenebildigi icin (bkz. TRANSIENT_FS_CODES) yeniden dener.
92
- function atomicWrite(file, data) {
93
- const tmp = `${file}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}.tmp`;
94
- fs.writeFileSync(tmp, data);
95
- let lastError;
96
- for (let attempt = 0; attempt < 10; attempt++) {
97
- try {
98
- fs.renameSync(tmp, file);
99
- return;
100
- } catch (error) {
101
- lastError = error;
102
- if (!isTransientFsError(error)) break;
103
- sleepSync(20 * (attempt + 1));
104
- }
105
- }
106
- // Rename kalici olarak basarisiz. Gorevi tamamen kaybetmektense hedefe dogrudan (atomik
107
- // olmayan) yazmayi son care olarak dene; sonra gecici dosyayi temizle.
108
- try {
109
- fs.writeFileSync(file, data);
110
- try { fs.rmSync(tmp, { force: true }); } catch {}
111
- return;
112
- } catch {}
113
- try { fs.rmSync(tmp, { force: true }); } catch {}
114
- throw lastError;
115
- }
116
-
117
- // ---- Config ----
118
- // Minimal geri-donus varsayilani (config.default.json de yoksa kullanilir) — sistem her
119
- // zaman calisir durumda acilsin diye.
120
- const FALLBACK_CONFIG = {
121
- approvalMode: "auto", workingDir: "..", dailyCallBudget: 150,
122
- autonomousConsentAcceptedAt: null,
123
- pollSeconds: 15, memoryCharBudget: 8000, teamContextCharBudget: 30000, agentTimeoutSeconds: 900,
124
- cliSilenceTimeoutSeconds: 300,
125
- discoveryIgnoredAdapters: [],
126
- liveDiff: true, liveDiffIntervalMs: 2500,
127
- versioning: true, versioningRetention: 20,
128
- operator: { roleFile: "roles/operator.md", maxRounds: 6, maxDelegationsPerRound: 8, maxInfrastructureRecoveryRounds: 2, protocolRetries: 1 },
129
- cliSettings: {
130
- codex: { model: "", reasoningEffort: "medium", serviceTier: "fast" },
131
- opencode: { model: "" },
132
- },
133
- skills: { enabled: [], autoMatch: true, catalogLimit: 12, maxSkillsPerAssignment: 3, charBudget: 2400, referenceCharBudget: 1200 },
134
- agents: {}, riskyPatterns: [], schedules: [],
135
- };
136
- // Eski sema, model ayarlarini operator altina gomuyordu (operator.codexSettings ve
137
- // operator.model). Yeni sema CLI bazlidir: cliSettings[adapter] o CLI'nin operator ve
138
- // uzman kullanimlarinin tumune uygulanir. Saf ve idempotent olmali; loadConfig sicak yoldur.
139
- function normalizeConfig(cfg) {
140
- if (!cfg || typeof cfg !== "object") return cfg;
141
- const current = cfg.cliSettings && typeof cfg.cliSettings === "object" ? cfg.cliSettings : {};
142
- const legacyCodex = cfg.operator && typeof cfg.operator.codexSettings === "object" ? cfg.operator.codexSettings : {};
143
- const legacyOpenCodeModel = typeof cfg.operator?.model === "string" ? cfg.operator.model : "";
144
- const normalized = {
145
- ...cfg,
146
- skills: { enabled: [], autoMatch: true, catalogLimit: 12, maxSkillsPerAssignment: 3, charBudget: 2400, referenceCharBudget: 1200, ...(cfg.skills || {}) },
147
- schedules: Array.isArray(cfg.schedules) ? cfg.schedules : [],
148
- cliSettings: {
149
- codex: { model: "", reasoningEffort: "medium", serviceTier: "fast", ...legacyCodex, ...(current.codex || {}) },
150
- opencode: { model: legacyOpenCodeModel, ...(current.opencode || {}) },
151
- },
152
- };
153
- if (cfg.operator && typeof cfg.operator === "object") {
154
- normalized.operator = { ...cfg.operator };
155
- delete normalized.operator.codexSettings;
156
- delete normalized.operator.model;
157
- }
158
- return normalized;
159
- }
160
- // config.json kisiye ozeldir (gitignore). Yoksa config.default.json sablonundan uretilir;
161
- // boylece kullanici klonlayip `npm start` dedigi anda calisir ve kurulu CLI'lar keşifle eklenir.
162
- function loadConfig() {
163
- const file = path.join(ROOT, "config.json");
164
- if (!fs.existsSync(file)) {
165
- const template = path.join(ASSETS, "config.default.json");
166
- const seed = fs.existsSync(template) ? fs.readFileSync(template, "utf8") : JSON.stringify(FALLBACK_CONFIG, null, 2);
167
- atomicWrite(file, seed);
168
- }
169
- return normalizeConfig(JSON.parse(fs.readFileSync(file, "utf8")));
170
- }
171
- function saveConfig(cfg) {
172
- atomicWrite(path.join(ROOT, "config.json"), JSON.stringify(cfg, null, 2));
173
- }
174
-
175
- // ---- Roller ----
176
- function listRoles() {
177
- if (!fs.existsSync(ROLES)) return [];
178
- return fs.readdirSync(ROLES).filter((f) => f.endsWith(".md"));
179
- }
180
- function readRole(file) {
181
- const p = path.join(ROLES, path.basename(file));
182
- return fs.existsSync(p) ? fs.readFileSync(p, "utf8") : "";
183
- }
184
- function writeRole(file, content) {
185
- fs.writeFileSync(path.join(ROLES, path.basename(file)), content);
186
- }
187
- function deleteRole(file) {
188
- const p = path.join(ROLES, path.basename(file));
189
- if (fs.existsSync(p)) fs.rmSync(p);
190
- }
191
-
192
- // ---- Gorevler ----
193
- function taskPath(state, id) {
194
- return path.join(Q, state, `${id}.json`);
195
- }
196
- function listTasks(state) {
197
- const dir = path.join(Q, state);
198
- if (!fs.existsSync(dir)) return [];
199
- return fs
200
- .readdirSync(dir)
201
- .filter((f) => f.endsWith(".json"))
202
- .map((f) => {
203
- try {
204
- return JSON.parse(fs.readFileSync(path.join(dir, f), "utf8"));
205
- } catch {
206
- return null;
207
- }
208
- })
209
- .filter(Boolean)
210
- .sort((a, b) => (a.id < b.id ? -1 : 1));
211
- }
212
- // Yalnizca en yeni `limit` gorevi okur. Gorev id'si zaman damgasiyla basladigi icin dosya adi
213
- // siralamasi = kronolojik siralama; boylece done/failed gecmisi buyudukce (yuzlerce/binlerce
214
- // dosya) her pano yenilemesinde TUM dosyalari okuyup ayristirma maliyeti sabit N'e iner.
215
- function listRecentTasks(state, limit) {
216
- const dir = path.join(Q, state);
217
- if (!fs.existsSync(dir)) return [];
218
- let names = fs.readdirSync(dir).filter((f) => f.endsWith(".json")).sort();
219
- if (limit && names.length > limit) names = names.slice(-limit);
220
- return names
221
- .map((f) => {
222
- try { return JSON.parse(fs.readFileSync(path.join(dir, f), "utf8")); } catch { return null; }
223
- })
224
- .filter(Boolean);
225
- }
226
- function nextPending() {
227
- return listTasks("pending")[0] || null;
228
- }
229
- function addTask(prompt, targetDir, operatorCli, executionMode) {
230
- const id =
231
- new Date().toISOString().replace(/[-:T.]/g, "").slice(0, 15) +
232
- "-" +
233
- Math.floor(Math.random() * 9000 + 1000);
234
- const task = { id, prompt, status: "pending", createdAt: new Date().toISOString() };
235
- if (targetDir) task.targetDir = targetDir;
236
- if (operatorCli) task.operatorCli = operatorCli;
237
- if (executionMode) task.executionMode = executionMode;
238
- atomicWrite(taskPath("pending", id), JSON.stringify(task, null, 2));
239
- return task;
240
- }
241
- function addChatTask(parentTask, question) {
242
- const task = addTask(question, parentTask.targetDir, parentTask.operatorCli, "chat");
243
- task.kind = "operator-chat";
244
- task.parentTaskId = parentTask.id;
245
- saveTask("pending", task);
246
- return task;
247
- }
248
- // Zamanlanmis bir gorevi kuyruga ekler. Normal gorevle ayni yolu kullanir; yalnizca kaynagini
249
- // isaretlemek icin scheduleId iliştirir (Pano bu görevi "zamanlanmis" rozetiyle gosterebilsin).
250
- function addScheduledTask(schedule) {
251
- const task = addTask(schedule.prompt, schedule.targetDir, schedule.operatorCli, schedule.executionMode || "auto");
252
- task.scheduleId = schedule.id;
253
- saveTask("pending", task);
254
- return task;
255
- }
256
-
257
- // ---- Kalici calisma olaylari ----
258
- function appendRunEvent(taskId, event) {
259
- ensureDirs();
260
- fs.appendFileSync(path.join(EVENTS, `${path.basename(taskId)}.jsonl`), JSON.stringify(event) + "\n");
261
- }
262
- function listRunEvents(taskId, limit = 1000) {
263
- const file = path.join(EVENTS, `${path.basename(taskId)}.jsonl`);
264
- if (!fs.existsSync(file)) return [];
265
- return fs.readFileSync(file, "utf8").split(/\r?\n/).filter(Boolean).slice(-Math.max(1, limit)).map((line) => {
266
- try { return JSON.parse(line); } catch { return null; }
267
- }).filter(Boolean);
268
- }
269
- function hashText(text) {
270
- return crypto.createHash("sha256").update(String(text)).digest("hex");
271
- }
272
- function saveTask(state, task) {
273
- atomicWrite(taskPath(state, task.id), JSON.stringify(task, null, 2));
274
- }
275
- function findTask(id) {
276
- for (const s of STATES) {
277
- const p = taskPath(s, id);
278
- if (fs.existsSync(p)) return { state: s, task: JSON.parse(fs.readFileSync(p, "utf8")) };
279
- }
280
- return null;
281
- }
282
- function moveTask(fromState, toState, task) {
283
- const src = taskPath(fromState, task.id);
284
- // Hedefi once atomik olarak yaz. Surec iki islem arasinda cokse bile gorev kaybolmaz.
285
- saveTask(toState, task);
286
- if (fromState !== toState && fs.existsSync(src)) fs.rmSync(src);
287
- }
288
- function removeTask(state, id) {
289
- const p = taskPath(state, id);
290
- if (fs.existsSync(p)) fs.rmSync(p);
291
- }
292
-
293
- function approveTask(id) {
294
- const found = findTask(id);
295
- if (!found) throw new Error(`Gorev bulunamadi: ${id}`);
296
- if (found.state !== "approval") throw new Error(`Gorev onay beklemiyor: ${id}`);
297
- const task = found.task;
298
- if (task.planHash && task.planPreview && task.planHash !== hashText(task.planPreview)) {
299
- throw new Error("Plan onay beklerken degismis; yeniden planlanmasi gerekiyor.");
300
- }
301
- task.approved = true;
302
- task.status = "pending";
303
- moveTask(found.state, "pending", task);
304
- return task;
305
- }
306
-
307
- function rejectTask(id) {
308
- const found = findTask(id);
309
- if (!found) throw new Error(`Gorev bulunamadi: ${id}`);
310
- if (found.state !== "approval") throw new Error(`Gorev onay beklemiyor: ${id}`);
311
- found.task.status = "rejected";
312
- found.task.finishedAt = new Date().toISOString();
313
- moveTask(found.state, "failed", found.task);
314
- return found.task;
315
- }
316
-
317
- // ---- Hafiza ----
318
- function getMemory(charBudget) {
319
- if (!fs.existsSync(MEM)) return "(hafiza bos)";
320
- const files = fs
321
- .readdirSync(MEM)
322
- .filter((f) => f.endsWith(".md"))
323
- .map((f) => path.join(MEM, f));
324
- if (!files.length) return "(hafiza bos)";
325
- let text = files.map((f) => fs.readFileSync(f, "utf8")).join("\n\n");
326
- if (charBudget && text.length > charBudget) text = text.slice(-charBudget);
327
- return text;
328
- }
329
- function appendMemory(title, body) {
330
- const stamp = new Date().toISOString().slice(0, 16).replace("T", " ");
331
- fs.appendFileSync(path.join(MEM, "log.md"), `\n## ${stamp} — ${title}\n${body}\n`);
332
- }
333
-
334
- // ---- Gunluk cagri butcesi ----
335
- function callFile() {
336
- return path.join(STATE, `calls-${new Date().toISOString().slice(0, 10)}.txt`);
337
- }
338
- function getCallCount() {
339
- const f = callFile();
340
- return fs.existsSync(f) ? parseInt(fs.readFileSync(f, "utf8"), 10) || 0 : 0;
341
- }
342
- function bumpCallCount() {
343
- const n = getCallCount() + 1;
344
- fs.writeFileSync(callFile(), String(n));
345
- return n;
346
- }
347
-
348
- module.exports = {
349
- ROOT,
350
- ASSETS,
351
- WORK_BASE,
352
- ensureDirs,
353
- loadConfig,
354
- normalizeConfig,
355
- saveConfig,
356
- listRoles,
357
- readRole,
358
- writeRole,
359
- deleteRole,
360
- listTasks,
361
- listRecentTasks,
362
- nextPending,
363
- addTask,
364
- addChatTask,
365
- addScheduledTask,
366
- saveTask,
367
- findTask,
368
- moveTask,
369
- removeTask,
370
- approveTask,
371
- rejectTask,
372
- getMemory,
373
- appendMemory,
374
- getCallCount,
375
- bumpCallCount,
376
- appendRunEvent,
377
- listRunEvents,
378
- hashText,
379
- };
1
+ // store.js — dosya tabanli kuyruk, config, hafiza, butce (sifir bagimlilik)
2
+ const fs = require("fs");
3
+ const path = require("path");
4
+ const crypto = require("crypto");
5
+ const os = require("os");
6
+
7
+ const isWin = process.platform === "win32";
8
+ // ASSETS: paket dizini (salt-okunur varlıklar: web/, config.default.json, varsayilan roles/+skills/).
9
+ // __dirname/.. daima paketin gercek yeridir (npm global/npx onbellegi dahil).
10
+ const ASSETS = path.join(__dirname, "..");
11
+ // ROOT: yazilabilir VERI koku (config.json, queue/, state/, memory/, kullanicinin roles/+skills/).
12
+ // Oncelik: CLI_TEAM_ROOT (izole test/CI) > CREWCTL_HOME (kullanici override) > mod tespiti.
13
+ // Gelistirme kopyasinda test/ klasoru bulunur ve paket dizini yazilabilirdir; o zaman ROOT=ASSETS
14
+ // (mevcut npm start/npm test davranisi aynen korunur). Yayinlanan pakette test/ gonderilmez, bu
15
+ // yuzden kurulu modda veri ~/.crewctl'e yazilir (npm onbelleğine degil).
16
+ const isDevCheckout = fs.existsSync(path.join(ASSETS, "test"));
17
+ const ROOT = path.resolve(
18
+ process.env.CLI_TEAM_ROOT ||
19
+ process.env.CREWCTL_HOME ||
20
+ (isDevCheckout ? ASSETS : path.join(os.homedir(), ".crewctl"))
21
+ );
22
+ // WORK_BASE: agent'larin uzerinde calisacagi klasorun goreli cozumleme tabani. Kurulu modda
23
+ // kullanici komutu nerede calistirdiysa orasidir (cwd); mutlak yol secilirse zaten o kullanilir.
24
+ const WORK_BASE = process.cwd();
25
+ const Q = path.join(ROOT, "queue");
26
+ const STATES = ["pending", "done", "failed", "approval"];
27
+ const MEM = path.join(ROOT, "memory");
28
+ const STATE = path.join(ROOT, "state");
29
+ const EVENTS = path.join(STATE, "events");
30
+ const ROLES = path.join(ROOT, "roles");
31
+ const SKILLS = path.join(ROOT, "skills");
32
+
33
+ // Windows'ta rename/unlink; antivirus, arama dizinleyici veya kuyrugu ayni anda tarayan
34
+ // canli sunucu dosyada kisa sureli bir handle tuttugunda gecici olarak EPERM/EACCES/EBUSY
35
+ // verir. Tek seferlik cagri bu durumda tum gorevi coldururdu; kisa artan beklemelerle yeniden
36
+ // deneriz. Bu kod yolu tum saveTask/saveConfig/addTask cagrilarinin sicak yolu.
37
+ const TRANSIENT_FS_CODES = new Set(["EPERM", "EACCES", "EBUSY", "ENOENT", "EEXIST"]);
38
+ function sleepSync(ms) {
39
+ try { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); } catch {}
40
+ }
41
+ function isTransientFsError(error) {
42
+ return isWin && error && TRANSIENT_FS_CODES.has(error.code);
43
+ }
44
+
45
+ function sweepStaleTemp(dir, maxAgeMs = 5 * 60 * 1000) {
46
+ // Kalici olarak yeniden adlandirilamamis eski .tmp dosyalarini birak birikmesin diye temizle.
47
+ let entries;
48
+ try { entries = fs.readdirSync(dir); } catch { return; }
49
+ const now = Date.now();
50
+ for (const name of entries) {
51
+ if (!name.endsWith(".tmp")) continue;
52
+ const full = path.join(dir, name);
53
+ try {
54
+ if (now - fs.statSync(full).mtimeMs > maxAgeMs) fs.rmSync(full, { force: true });
55
+ } catch {}
56
+ }
57
+ }
58
+
59
+ // Kurulu modda (ROOT != ASSETS) veri kokundeki roles/ ve skills/ bos ise paketle gelen
60
+ // varsayilanlari BIR KEZ kopyala. Kullanicinin duzenlemeleri korunur (yalnizca bos dizine seed).
61
+ let seededAssets = false;
62
+ function seedDefaults() {
63
+ if (seededAssets) return;
64
+ seededAssets = true;
65
+ if (ROOT === ASSETS) return;
66
+ for (const [srcDir, dstDir] of [[path.join(ASSETS, "roles"), ROLES], [path.join(ASSETS, "skills"), SKILLS]]) {
67
+ try {
68
+ const existing = fs.existsSync(dstDir) ? fs.readdirSync(dstDir).filter((f) => f.toLowerCase().endsWith(".md")) : [];
69
+ if (existing.length) continue;
70
+ const defaults = fs.existsSync(srcDir) ? fs.readdirSync(srcDir).filter((f) => f.toLowerCase().endsWith(".md")) : [];
71
+ for (const f of defaults) fs.copyFileSync(path.join(srcDir, f), path.join(dstDir, f));
72
+ } catch {}
73
+ }
74
+ }
75
+
76
+ // ensureDirs, olay akisinda cok sik cagrilir; temizligi dakikada bir defayla sinirla ki
77
+ // her stdout parcasinda dizin taramasi yapmayalim.
78
+ let lastSweepAt = 0;
79
+ function ensureDirs() {
80
+ const dirs = [...STATES.map((s) => path.join(Q, s)), MEM, STATE, EVENTS, ROLES, SKILLS];
81
+ dirs.forEach((d) => fs.mkdirSync(d, { recursive: true }));
82
+ seedDefaults();
83
+ if (Date.now() - lastSweepAt > 60 * 1000) {
84
+ lastSweepAt = Date.now();
85
+ for (const s of STATES) sweepStaleTemp(path.join(Q, s));
86
+ }
87
+ }
88
+
89
+ // Atomik yazma: once .tmp'ye yaz, sonra rename et. Rename ayni disk uzerinde atomiktir;
90
+ // boylece surec ortasinda cokme olsa bile yarim/bozuk JSON dosyasi kalmaz (her PC'de guvenli).
91
+ // Windows'ta rename gecici olarak kilitlenebildigi icin (bkz. TRANSIENT_FS_CODES) yeniden dener.
92
+ function atomicWrite(file, data) {
93
+ const tmp = `${file}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}.tmp`;
94
+ fs.writeFileSync(tmp, data);
95
+ let lastError;
96
+ for (let attempt = 0; attempt < 10; attempt++) {
97
+ try {
98
+ fs.renameSync(tmp, file);
99
+ return;
100
+ } catch (error) {
101
+ lastError = error;
102
+ if (!isTransientFsError(error)) break;
103
+ sleepSync(20 * (attempt + 1));
104
+ }
105
+ }
106
+ // Rename kalici olarak basarisiz. Gorevi tamamen kaybetmektense hedefe dogrudan (atomik
107
+ // olmayan) yazmayi son care olarak dene; sonra gecici dosyayi temizle.
108
+ try {
109
+ fs.writeFileSync(file, data);
110
+ try { fs.rmSync(tmp, { force: true }); } catch {}
111
+ return;
112
+ } catch {}
113
+ try { fs.rmSync(tmp, { force: true }); } catch {}
114
+ throw lastError;
115
+ }
116
+
117
+ // ---- Config ----
118
+ // Minimal geri-donus varsayilani (config.default.json de yoksa kullanilir) — sistem her
119
+ // zaman calisir durumda acilsin diye.
120
+ const FALLBACK_CONFIG = {
121
+ approvalMode: "auto", workingDir: "..", dailyCallBudget: 150,
122
+ autonomousConsentAcceptedAt: null,
123
+ pollSeconds: 15, memoryCharBudget: 8000, teamContextCharBudget: 30000, agentTimeoutSeconds: 900,
124
+ cliSilenceTimeoutSeconds: 300,
125
+ discoveryIgnoredAdapters: [],
126
+ liveDiff: true, liveDiffIntervalMs: 2500,
127
+ versioning: true, versioningRetention: 20,
128
+ notify: { webhookUrl: "", onComplete: true, onFailed: true },
129
+ operator: { roleFile: "roles/operator.md", maxRounds: 6, maxDelegationsPerRound: 8, maxInfrastructureRecoveryRounds: 2, protocolRetries: 1 },
130
+ cliSettings: {
131
+ codex: { model: "", reasoningEffort: "medium", serviceTier: "fast" },
132
+ opencode: { model: "" },
133
+ },
134
+ skills: { enabled: [], autoMatch: true, catalogLimit: 12, maxSkillsPerAssignment: 3, charBudget: 2400, referenceCharBudget: 1200 },
135
+ agents: {}, riskyPatterns: [], schedules: [],
136
+ };
137
+ // Eski sema, model ayarlarini operator altina gomuyordu (operator.codexSettings ve
138
+ // operator.model). Yeni sema CLI bazlidir: cliSettings[adapter] o CLI'nin operator ve
139
+ // uzman kullanimlarinin tumune uygulanir. Saf ve idempotent olmali; loadConfig sicak yoldur.
140
+ function normalizeConfig(cfg) {
141
+ if (!cfg || typeof cfg !== "object") return cfg;
142
+ const current = cfg.cliSettings && typeof cfg.cliSettings === "object" ? cfg.cliSettings : {};
143
+ const legacyCodex = cfg.operator && typeof cfg.operator.codexSettings === "object" ? cfg.operator.codexSettings : {};
144
+ const legacyOpenCodeModel = typeof cfg.operator?.model === "string" ? cfg.operator.model : "";
145
+ const normalized = {
146
+ ...cfg,
147
+ skills: { enabled: [], autoMatch: true, catalogLimit: 12, maxSkillsPerAssignment: 3, charBudget: 2400, referenceCharBudget: 1200, ...(cfg.skills || {}) },
148
+ schedules: Array.isArray(cfg.schedules) ? cfg.schedules : [],
149
+ cliSettings: {
150
+ codex: { model: "", reasoningEffort: "medium", serviceTier: "fast", ...legacyCodex, ...(current.codex || {}) },
151
+ opencode: { model: legacyOpenCodeModel, ...(current.opencode || {}) },
152
+ },
153
+ };
154
+ if (cfg.operator && typeof cfg.operator === "object") {
155
+ normalized.operator = { ...cfg.operator };
156
+ delete normalized.operator.codexSettings;
157
+ delete normalized.operator.model;
158
+ }
159
+ return normalized;
160
+ }
161
+ // config.json kisiye ozeldir (gitignore). Yoksa config.default.json sablonundan uretilir;
162
+ // boylece kullanici klonlayip `npm start` dedigi anda calisir ve kurulu CLI'lar keşifle eklenir.
163
+ // Paketle gelen beceri dosyalarinin slug'lari (dosya adi = frontmatter name, dogrulanir).
164
+ // Ilk config uretiminde beceriler VARSAYILAN OLARAK ETKIN gelsin diye kullanilir; boylece
165
+ // operator, kullanicinin becerilerini kodlama/planlama/review delegasyonlarinda kullanabilir.
166
+ function shippedSkillSlugs() {
167
+ try {
168
+ return fs.readdirSync(path.join(ASSETS, "skills"))
169
+ .filter((f) => f.toLowerCase().endsWith(".md"))
170
+ .map((f) => f.replace(/\.md$/i, ""));
171
+ } catch { return []; }
172
+ }
173
+ function loadConfig() {
174
+ const file = path.join(ROOT, "config.json");
175
+ if (!fs.existsSync(file)) {
176
+ const template = path.join(ASSETS, "config.default.json");
177
+ const seed = fs.existsSync(template) ? fs.readFileSync(template, "utf8") : JSON.stringify(FALLBACK_CONFIG, null, 2);
178
+ let seedObj;
179
+ try { seedObj = JSON.parse(seed); } catch { seedObj = { ...FALLBACK_CONFIG }; }
180
+ // Ilk kurulumda tum paket becerilerini etkinlestir (kullanici Ayarlar'dan kapatabilir).
181
+ // Sonraki yuklemelerde dosya var oldugundan bu blok CALISMAZ; kullanicinin secimi korunur.
182
+ seedObj.skills = seedObj.skills || {};
183
+ if (!Array.isArray(seedObj.skills.enabled) || !seedObj.skills.enabled.length) {
184
+ const slugs = shippedSkillSlugs();
185
+ if (slugs.length) seedObj.skills.enabled = slugs;
186
+ }
187
+ atomicWrite(file, JSON.stringify(seedObj, null, 2));
188
+ }
189
+ return normalizeConfig(JSON.parse(fs.readFileSync(file, "utf8")));
190
+ }
191
+ function saveConfig(cfg) {
192
+ atomicWrite(path.join(ROOT, "config.json"), JSON.stringify(cfg, null, 2));
193
+ }
194
+
195
+ // ---- Roller ----
196
+ function listRoles() {
197
+ if (!fs.existsSync(ROLES)) return [];
198
+ return fs.readdirSync(ROLES).filter((f) => f.endsWith(".md"));
199
+ }
200
+ function readRole(file) {
201
+ const p = path.join(ROLES, path.basename(file));
202
+ return fs.existsSync(p) ? fs.readFileSync(p, "utf8") : "";
203
+ }
204
+ function writeRole(file, content) {
205
+ fs.writeFileSync(path.join(ROLES, path.basename(file)), content);
206
+ }
207
+ function deleteRole(file) {
208
+ const p = path.join(ROLES, path.basename(file));
209
+ if (fs.existsSync(p)) fs.rmSync(p);
210
+ }
211
+
212
+ // ---- Gorevler ----
213
+ function taskPath(state, id) {
214
+ return path.join(Q, state, `${id}.json`);
215
+ }
216
+ function listTasks(state) {
217
+ const dir = path.join(Q, state);
218
+ if (!fs.existsSync(dir)) return [];
219
+ return fs
220
+ .readdirSync(dir)
221
+ .filter((f) => f.endsWith(".json"))
222
+ .map((f) => {
223
+ try {
224
+ return JSON.parse(fs.readFileSync(path.join(dir, f), "utf8"));
225
+ } catch {
226
+ return null;
227
+ }
228
+ })
229
+ .filter(Boolean)
230
+ .sort((a, b) => (a.id < b.id ? -1 : 1));
231
+ }
232
+ // Yalnizca en yeni `limit` gorevi okur. Gorev id'si zaman damgasiyla basladigi icin dosya adi
233
+ // siralamasi = kronolojik siralama; boylece done/failed gecmisi buyudukce (yuzlerce/binlerce
234
+ // dosya) her pano yenilemesinde TUM dosyalari okuyup ayristirma maliyeti sabit N'e iner.
235
+ function listRecentTasks(state, limit) {
236
+ const dir = path.join(Q, state);
237
+ if (!fs.existsSync(dir)) return [];
238
+ let names = fs.readdirSync(dir).filter((f) => f.endsWith(".json")).sort();
239
+ if (limit && names.length > limit) names = names.slice(-limit);
240
+ return names
241
+ .map((f) => {
242
+ try { return JSON.parse(fs.readFileSync(path.join(dir, f), "utf8")); } catch { return null; }
243
+ })
244
+ .filter(Boolean);
245
+ }
246
+ function nextPending() {
247
+ return listTasks("pending")[0] || null;
248
+ }
249
+ function addTask(prompt, targetDir, operatorCli, executionMode) {
250
+ const id =
251
+ new Date().toISOString().replace(/[-:T.]/g, "").slice(0, 15) +
252
+ "-" +
253
+ Math.floor(Math.random() * 9000 + 1000);
254
+ const task = { id, prompt, status: "pending", createdAt: new Date().toISOString() };
255
+ if (targetDir) task.targetDir = targetDir;
256
+ if (operatorCli) task.operatorCli = operatorCli;
257
+ if (executionMode) task.executionMode = executionMode;
258
+ atomicWrite(taskPath("pending", id), JSON.stringify(task, null, 2));
259
+ return task;
260
+ }
261
+ function addChatTask(parentTask, question) {
262
+ const task = addTask(question, parentTask.targetDir, parentTask.operatorCli, "chat");
263
+ task.kind = "operator-chat";
264
+ task.parentTaskId = parentTask.id;
265
+ saveTask("pending", task);
266
+ return task;
267
+ }
268
+ // Zamanlanmis bir gorevi kuyruga ekler. Normal gorevle ayni yolu kullanir; yalnizca kaynagini
269
+ // isaretlemek icin scheduleId iliştirir (Pano bu görevi "zamanlanmis" rozetiyle gosterebilsin).
270
+ function addScheduledTask(schedule) {
271
+ const task = addTask(schedule.prompt, schedule.targetDir, schedule.operatorCli, schedule.executionMode || "auto");
272
+ task.scheduleId = schedule.id;
273
+ saveTask("pending", task);
274
+ return task;
275
+ }
276
+
277
+ // ---- Kalici calisma olaylari ----
278
+ function appendRunEvent(taskId, event) {
279
+ ensureDirs();
280
+ fs.appendFileSync(path.join(EVENTS, `${path.basename(taskId)}.jsonl`), JSON.stringify(event) + "\n");
281
+ }
282
+ function listRunEvents(taskId, limit = 1000) {
283
+ const file = path.join(EVENTS, `${path.basename(taskId)}.jsonl`);
284
+ if (!fs.existsSync(file)) return [];
285
+ return fs.readFileSync(file, "utf8").split(/\r?\n/).filter(Boolean).slice(-Math.max(1, limit)).map((line) => {
286
+ try { return JSON.parse(line); } catch { return null; }
287
+ }).filter(Boolean);
288
+ }
289
+ function hashText(text) {
290
+ return crypto.createHash("sha256").update(String(text)).digest("hex");
291
+ }
292
+ function saveTask(state, task) {
293
+ atomicWrite(taskPath(state, task.id), JSON.stringify(task, null, 2));
294
+ }
295
+ function findTask(id) {
296
+ for (const s of STATES) {
297
+ const p = taskPath(s, id);
298
+ if (fs.existsSync(p)) return { state: s, task: JSON.parse(fs.readFileSync(p, "utf8")) };
299
+ }
300
+ return null;
301
+ }
302
+ function moveTask(fromState, toState, task) {
303
+ const src = taskPath(fromState, task.id);
304
+ // Hedefi once atomik olarak yaz. Surec iki islem arasinda cokse bile gorev kaybolmaz.
305
+ saveTask(toState, task);
306
+ if (fromState !== toState && fs.existsSync(src)) fs.rmSync(src);
307
+ }
308
+ function removeTask(state, id) {
309
+ const p = taskPath(state, id);
310
+ if (fs.existsSync(p)) fs.rmSync(p);
311
+ }
312
+
313
+ function approveTask(id) {
314
+ const found = findTask(id);
315
+ if (!found) throw new Error(`Gorev bulunamadi: ${id}`);
316
+ if (found.state !== "approval") throw new Error(`Gorev onay beklemiyor: ${id}`);
317
+ const task = found.task;
318
+ if (task.planHash && task.planPreview && task.planHash !== hashText(task.planPreview)) {
319
+ throw new Error("Plan onay beklerken degismis; yeniden planlanmasi gerekiyor.");
320
+ }
321
+ task.approved = true;
322
+ task.status = "pending";
323
+ moveTask(found.state, "pending", task);
324
+ return task;
325
+ }
326
+
327
+ function rejectTask(id) {
328
+ const found = findTask(id);
329
+ if (!found) throw new Error(`Gorev bulunamadi: ${id}`);
330
+ if (found.state !== "approval") throw new Error(`Gorev onay beklemiyor: ${id}`);
331
+ found.task.status = "rejected";
332
+ found.task.finishedAt = new Date().toISOString();
333
+ moveTask(found.state, "failed", found.task);
334
+ return found.task;
335
+ }
336
+
337
+ // ---- Hafiza ----
338
+ function getMemory(charBudget) {
339
+ if (!fs.existsSync(MEM)) return "(hafiza bos)";
340
+ const files = fs
341
+ .readdirSync(MEM)
342
+ .filter((f) => f.endsWith(".md"))
343
+ .map((f) => path.join(MEM, f));
344
+ if (!files.length) return "(hafiza bos)";
345
+ let text = files.map((f) => fs.readFileSync(f, "utf8")).join("\n\n");
346
+ if (charBudget && text.length > charBudget) text = text.slice(-charBudget);
347
+ return text;
348
+ }
349
+ function appendMemory(title, body) {
350
+ const stamp = new Date().toISOString().slice(0, 16).replace("T", " ");
351
+ fs.appendFileSync(path.join(MEM, "log.md"), `\n## ${stamp} — ${title}\n${body}\n`);
352
+ }
353
+
354
+ // ---- Gunluk cagri butcesi ----
355
+ function callFile() {
356
+ return path.join(STATE, `calls-${new Date().toISOString().slice(0, 10)}.txt`);
357
+ }
358
+ function getCallCount() {
359
+ const f = callFile();
360
+ return fs.existsSync(f) ? parseInt(fs.readFileSync(f, "utf8"), 10) || 0 : 0;
361
+ }
362
+ function bumpCallCount() {
363
+ const n = getCallCount() + 1;
364
+ fs.writeFileSync(callFile(), String(n));
365
+ return n;
366
+ }
367
+
368
+ module.exports = {
369
+ ROOT,
370
+ ASSETS,
371
+ WORK_BASE,
372
+ ensureDirs,
373
+ loadConfig,
374
+ normalizeConfig,
375
+ saveConfig,
376
+ listRoles,
377
+ readRole,
378
+ writeRole,
379
+ deleteRole,
380
+ listTasks,
381
+ listRecentTasks,
382
+ nextPending,
383
+ addTask,
384
+ addChatTask,
385
+ addScheduledTask,
386
+ saveTask,
387
+ findTask,
388
+ moveTask,
389
+ removeTask,
390
+ approveTask,
391
+ rejectTask,
392
+ getMemory,
393
+ appendMemory,
394
+ getCallCount,
395
+ bumpCallCount,
396
+ appendRunEvent,
397
+ listRunEvents,
398
+ hashText,
399
+ };