@omerrgocmen/crewctl 1.3.0 → 1.3.1

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 (92) hide show
  1. package/README.md +193 -193
  2. package/orchestrator/README.md +473 -473
  3. package/orchestrator/config.default.json +90 -79
  4. package/orchestrator/roles/executor.md +57 -57
  5. package/orchestrator/roles/operator.md +77 -77
  6. package/orchestrator/roles/planner.md +58 -58
  7. package/orchestrator/roles/reviewer.md +63 -63
  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/checkpoints.js +0 -4
  69. package/orchestrator/src/cli-registry.js +848 -740
  70. package/orchestrator/src/cli.js +140 -140
  71. package/orchestrator/src/doctor.js +64 -64
  72. package/orchestrator/src/engine.js +1914 -1735
  73. package/orchestrator/src/schedule.js +124 -126
  74. package/orchestrator/src/server.js +817 -818
  75. package/orchestrator/src/skill-registry.js +272 -272
  76. package/orchestrator/src/store.js +478 -470
  77. package/orchestrator/web/OrbitControls.js +1417 -1417
  78. package/orchestrator/web/board.html +146 -146
  79. package/orchestrator/web/code.html +213 -213
  80. package/orchestrator/web/flow.html +741 -741
  81. package/orchestrator/web/index.html +622 -602
  82. package/orchestrator/web/jsm/postprocessing/EffectComposer.js +231 -231
  83. package/orchestrator/web/jsm/postprocessing/MaskPass.js +104 -104
  84. package/orchestrator/web/jsm/postprocessing/Pass.js +95 -95
  85. package/orchestrator/web/jsm/postprocessing/RenderPass.js +99 -99
  86. package/orchestrator/web/jsm/postprocessing/ShaderPass.js +77 -77
  87. package/orchestrator/web/jsm/postprocessing/UnrealBloomPass.js +415 -415
  88. package/orchestrator/web/jsm/shaders/CopyShader.js +45 -45
  89. package/orchestrator/web/jsm/shaders/LuminosityHighPassShader.js +66 -66
  90. package/orchestrator/web/site.webmanifest +12 -12
  91. package/orchestrator/web/three.module.min.js +6 -6
  92. package/package.json +51 -51
@@ -1,470 +1,478 @@
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
- // Ajan hapsi: "workspace" = her CLI'nin native sandbox'i ile calisma klasoru DISINA yazma/ag
129
- // engellenir (Docker/Git gerektirmez; codex mac/Linux/Windows'ta OS-native zorlar). "off" =
130
- // eski davranis. extraWritableDirs: calisma klasoru disinda ek yazilabilir mutlak yollar.
131
- sandbox: { mode: "workspace", extraWritableDirs: [] },
132
- // Proje context: her calisma klasorunun .crewctl/CONTEXT.md profili gorev acilisinda yuklenir,
133
- // bitiminde operator revize eder. false = eski global hafiza davranisi.
134
- projectContext: true, projectContextCharBudget: 6000,
135
- notify: { webhookUrl: "", onComplete: true, onFailed: true },
136
- operator: { roleFile: "roles/operator.md", maxRounds: 6, maxDelegationsPerRound: 8, maxInfrastructureRecoveryRounds: 2, protocolRetries: 1 },
137
- cliSettings: {
138
- codex: { model: "", reasoningEffort: "medium", serviceTier: "fast" },
139
- opencode: { model: "" },
140
- },
141
- skills: { enabled: [], autoMatch: true, catalogLimit: 12, maxSkillsPerAssignment: 3, charBudget: 2400, referenceCharBudget: 1200 },
142
- agents: {}, riskyPatterns: [], schedules: [],
143
- };
144
- // Eski sema, model ayarlarini operator altina gomuyordu (operator.codexSettings ve
145
- // operator.model). Yeni sema CLI bazlidir: cliSettings[adapter] o CLI'nin operator ve
146
- // uzman kullanimlarinin tumune uygulanir. Saf ve idempotent olmali; loadConfig sicak yoldur.
147
- function normalizeConfig(cfg) {
148
- if (!cfg || typeof cfg !== "object") return cfg;
149
- const current = cfg.cliSettings && typeof cfg.cliSettings === "object" ? cfg.cliSettings : {};
150
- const legacyCodex = cfg.operator && typeof cfg.operator.codexSettings === "object" ? cfg.operator.codexSettings : {};
151
- const legacyOpenCodeModel = typeof cfg.operator?.model === "string" ? cfg.operator.model : "";
152
- const normalized = {
153
- ...cfg,
154
- skills: { enabled: [], autoMatch: true, catalogLimit: 12, maxSkillsPerAssignment: 3, charBudget: 2400, referenceCharBudget: 1200, ...(cfg.skills || {}) },
155
- schedules: Array.isArray(cfg.schedules) ? cfg.schedules : [],
156
- // Her yuklemede hapis semasini garanti et; boylece eski config.json'lar yukseltilince
157
- // varsayilan olarak "workspace" hapsini kazanir. Gecersiz mode "workspace"e duser.
158
- sandbox: {
159
- mode: ["off", "workspace"].includes(cfg.sandbox?.mode) ? cfg.sandbox.mode : "workspace",
160
- extraWritableDirs: Array.isArray(cfg.sandbox?.extraWritableDirs)
161
- ? cfg.sandbox.extraWritableDirs.filter((x) => typeof x === "string" && x.trim()).map(String)
162
- : [],
163
- },
164
- cliSettings: {
165
- codex: { model: "", reasoningEffort: "medium", serviceTier: "fast", ...legacyCodex, ...(current.codex || {}) },
166
- opencode: { model: legacyOpenCodeModel, ...(current.opencode || {}) },
167
- },
168
- };
169
- if (cfg.operator && typeof cfg.operator === "object") {
170
- normalized.operator = { ...cfg.operator };
171
- delete normalized.operator.codexSettings;
172
- delete normalized.operator.model;
173
- }
174
- return normalized;
175
- }
176
- // config.json kisiye ozeldir (gitignore). Yoksa config.default.json sablonundan uretilir;
177
- // boylece kullanici klonlayip `npm start` dedigi anda calisir ve kurulu CLI'lar keşifle eklenir.
178
- // Paketle gelen beceri dosyalarinin slug'lari (dosya adi = frontmatter name, dogrulanir).
179
- // Ilk config uretiminde beceriler VARSAYILAN OLARAK ETKIN gelsin diye kullanilir; boylece
180
- // operator, kullanicinin becerilerini kodlama/planlama/review delegasyonlarinda kullanabilir.
181
- function shippedSkillSlugs() {
182
- try {
183
- return fs.readdirSync(path.join(ASSETS, "skills"))
184
- .filter((f) => f.toLowerCase().endsWith(".md"))
185
- .map((f) => f.replace(/\.md$/i, ""));
186
- } catch { return []; }
187
- }
188
- function loadConfig() {
189
- const file = path.join(ROOT, "config.json");
190
- if (!fs.existsSync(file)) {
191
- const template = path.join(ASSETS, "config.default.json");
192
- const seed = fs.existsSync(template) ? fs.readFileSync(template, "utf8") : JSON.stringify(FALLBACK_CONFIG, null, 2);
193
- let seedObj;
194
- try { seedObj = JSON.parse(seed); } catch { seedObj = { ...FALLBACK_CONFIG }; }
195
- // Ilk kurulumda tum paket becerilerini etkinlestir (kullanici Ayarlar'dan kapatabilir).
196
- // Sonraki yuklemelerde dosya var oldugundan bu blok CALISMAZ; kullanicinin secimi korunur.
197
- seedObj.skills = seedObj.skills || {};
198
- if (!Array.isArray(seedObj.skills.enabled) || !seedObj.skills.enabled.length) {
199
- const slugs = shippedSkillSlugs();
200
- if (slugs.length) seedObj.skills.enabled = slugs;
201
- }
202
- atomicWrite(file, JSON.stringify(seedObj, null, 2));
203
- }
204
- return normalizeConfig(JSON.parse(fs.readFileSync(file, "utf8")));
205
- }
206
- function saveConfig(cfg) {
207
- atomicWrite(path.join(ROOT, "config.json"), JSON.stringify(cfg, null, 2));
208
- }
209
-
210
- // ---- Roller ----
211
- function listRoles() {
212
- if (!fs.existsSync(ROLES)) return [];
213
- return fs.readdirSync(ROLES).filter((f) => f.endsWith(".md"));
214
- }
215
- function readRole(file) {
216
- const p = path.join(ROLES, path.basename(file));
217
- return fs.existsSync(p) ? fs.readFileSync(p, "utf8") : "";
218
- }
219
- function writeRole(file, content) {
220
- fs.writeFileSync(path.join(ROLES, path.basename(file)), content);
221
- }
222
- function deleteRole(file) {
223
- const p = path.join(ROLES, path.basename(file));
224
- if (fs.existsSync(p)) fs.rmSync(p);
225
- }
226
-
227
- // ---- Gorevler ----
228
- function taskPath(state, id) {
229
- return path.join(Q, state, `${id}.json`);
230
- }
231
- function listTasks(state) {
232
- const dir = path.join(Q, state);
233
- if (!fs.existsSync(dir)) return [];
234
- return fs
235
- .readdirSync(dir)
236
- .filter((f) => f.endsWith(".json"))
237
- .map((f) => {
238
- try {
239
- return JSON.parse(fs.readFileSync(path.join(dir, f), "utf8"));
240
- } catch {
241
- return null;
242
- }
243
- })
244
- .filter(Boolean)
245
- .sort((a, b) => (a.id < b.id ? -1 : 1));
246
- }
247
- // Yalnizca en yeni `limit` gorevi okur. Gorev id'si zaman damgasiyla basladigi icin dosya adi
248
- // siralamasi = kronolojik siralama; boylece done/failed gecmisi buyudukce (yuzlerce/binlerce
249
- // dosya) her pano yenilemesinde TUM dosyalari okuyup ayristirma maliyeti sabit N'e iner.
250
- function listRecentTasks(state, limit) {
251
- const dir = path.join(Q, state);
252
- if (!fs.existsSync(dir)) return [];
253
- let names = fs.readdirSync(dir).filter((f) => f.endsWith(".json")).sort();
254
- if (limit && names.length > limit) names = names.slice(-limit);
255
- return names
256
- .map((f) => {
257
- try { return JSON.parse(fs.readFileSync(path.join(dir, f), "utf8")); } catch { return null; }
258
- })
259
- .filter(Boolean);
260
- }
261
- function nextPending() {
262
- return listTasks("pending")[0] || null;
263
- }
264
- function addTask(prompt, targetDir, operatorCli, executionMode) {
265
- const id =
266
- new Date().toISOString().replace(/[-:T.]/g, "").slice(0, 15) +
267
- "-" +
268
- Math.floor(Math.random() * 9000 + 1000);
269
- const task = { id, prompt, status: "pending", createdAt: new Date().toISOString() };
270
- if (targetDir) task.targetDir = targetDir;
271
- if (operatorCli) task.operatorCli = operatorCli;
272
- if (executionMode) task.executionMode = executionMode;
273
- atomicWrite(taskPath("pending", id), JSON.stringify(task, null, 2));
274
- return task;
275
- }
276
- function addChatTask(parentTask, question) {
277
- const task = addTask(question, parentTask.targetDir, parentTask.operatorCli, "chat");
278
- task.kind = "operator-chat";
279
- task.parentTaskId = parentTask.id;
280
- saveTask("pending", task);
281
- return task;
282
- }
283
- // Zamanlanmis bir gorevi kuyruga ekler. Normal gorevle ayni yolu kullanir; yalnizca kaynagini
284
- // isaretlemek icin scheduleId iliştirir (Pano bu görevi "zamanlanmis" rozetiyle gosterebilsin).
285
- function addScheduledTask(schedule) {
286
- const task = addTask(schedule.prompt, schedule.targetDir, schedule.operatorCli, schedule.executionMode || "auto");
287
- task.scheduleId = schedule.id;
288
- saveTask("pending", task);
289
- return task;
290
- }
291
-
292
- // ---- Kalici calisma olaylari ----
293
- function appendRunEvent(taskId, event) {
294
- ensureDirs();
295
- fs.appendFileSync(path.join(EVENTS, `${path.basename(taskId)}.jsonl`), JSON.stringify(event) + "\n");
296
- }
297
- function listRunEvents(taskId, limit = 1000) {
298
- const file = path.join(EVENTS, `${path.basename(taskId)}.jsonl`);
299
- if (!fs.existsSync(file)) return [];
300
- return fs.readFileSync(file, "utf8").split(/\r?\n/).filter(Boolean).slice(-Math.max(1, limit)).map((line) => {
301
- try { return JSON.parse(line); } catch { return null; }
302
- }).filter(Boolean);
303
- }
304
- function hashText(text) {
305
- return crypto.createHash("sha256").update(String(text)).digest("hex");
306
- }
307
- function saveTask(state, task) {
308
- atomicWrite(taskPath(state, task.id), JSON.stringify(task, null, 2));
309
- }
310
- function findTask(id) {
311
- for (const s of STATES) {
312
- const p = taskPath(s, id);
313
- if (fs.existsSync(p)) return { state: s, task: JSON.parse(fs.readFileSync(p, "utf8")) };
314
- }
315
- return null;
316
- }
317
- function moveTask(fromState, toState, task) {
318
- const src = taskPath(fromState, task.id);
319
- // Hedefi once atomik olarak yaz. Surec iki islem arasinda cokse bile gorev kaybolmaz.
320
- saveTask(toState, task);
321
- if (fromState !== toState && fs.existsSync(src)) fs.rmSync(src);
322
- }
323
- function removeTask(state, id) {
324
- const p = taskPath(state, id);
325
- if (fs.existsSync(p)) fs.rmSync(p);
326
- }
327
-
328
- function approveTask(id) {
329
- const found = findTask(id);
330
- if (!found) throw new Error(`Gorev bulunamadi: ${id}`);
331
- if (found.state !== "approval") throw new Error(`Gorev onay beklemiyor: ${id}`);
332
- const task = found.task;
333
- if (task.planHash && task.planPreview && task.planHash !== hashText(task.planPreview)) {
334
- throw new Error("Plan onay beklerken degismis; yeniden planlanmasi gerekiyor.");
335
- }
336
- task.approved = true;
337
- task.status = "pending";
338
- moveTask(found.state, "pending", task);
339
- return task;
340
- }
341
-
342
- function rejectTask(id) {
343
- const found = findTask(id);
344
- if (!found) throw new Error(`Gorev bulunamadi: ${id}`);
345
- if (found.state !== "approval") throw new Error(`Gorev onay beklemiyor: ${id}`);
346
- found.task.status = "rejected";
347
- found.task.finishedAt = new Date().toISOString();
348
- moveTask(found.state, "failed", found.task);
349
- return found.task;
350
- }
351
-
352
- // ---- Hafiza ----
353
- function getMemory(charBudget) {
354
- if (!fs.existsSync(MEM)) return "(hafiza bos)";
355
- const files = fs
356
- .readdirSync(MEM)
357
- .filter((f) => f.endsWith(".md"))
358
- .map((f) => path.join(MEM, f));
359
- if (!files.length) return "(hafiza bos)";
360
- let text = files.map((f) => fs.readFileSync(f, "utf8")).join("\n\n");
361
- if (charBudget && text.length > charBudget) text = text.slice(-charBudget);
362
- return text;
363
- }
364
- function appendMemory(title, body) {
365
- const stamp = new Date().toISOString().slice(0, 16).replace("T", " ");
366
- fs.appendFileSync(path.join(MEM, "log.md"), `\n## ${stamp} — ${title}\n${body}\n`);
367
- }
368
-
369
- // ---- Proje context (path'e ozel) ----
370
- // Global log.md'nin aksine, her calisma klasorunun KENDI birikmis proje profili vardir:
371
- // <cwd>/.crewctl/CONTEXT.md. Gorev acilisinda operatore yuklenir (tum kodu bastan taramaya
372
- // gerek kalmasin), gorev bitiminde operator tarafindan REVIZE edilir (append degil). Calisma
373
- // klasorunde durdugu icin seffaf, elle duzenlenebilir ve git'e girebilir.
374
- function projectContextPath(cwd) {
375
- return path.join(cwd, ".crewctl", "CONTEXT.md");
376
- }
377
- function readProjectContext(cwd) {
378
- if (!cwd) return "";
379
- try { return fs.readFileSync(projectContextPath(cwd), "utf8"); } catch { return ""; }
380
- }
381
- function writeProjectContext(cwd, content) {
382
- if (!cwd) return false;
383
- try {
384
- fs.mkdirSync(path.join(cwd, ".crewctl"), { recursive: true });
385
- atomicWrite(projectContextPath(cwd), String(content == null ? "" : content));
386
- return true;
387
- } catch { return false; }
388
- }
389
- function clearProjectContext(cwd) {
390
- if (!cwd) return false;
391
- try { fs.rmSync(projectContextPath(cwd), { force: true }); return true; } catch { return false; }
392
- }
393
-
394
- // ---- Gunluk cagri butcesi ----
395
- function callFile() {
396
- return path.join(STATE, `calls-${new Date().toISOString().slice(0, 10)}.txt`);
397
- }
398
- function getCallCount() {
399
- const f = callFile();
400
- return fs.existsSync(f) ? parseInt(fs.readFileSync(f, "utf8"), 10) || 0 : 0;
401
- }
402
- function bumpCallCount() {
403
- const n = getCallCount() + 1;
404
- fs.writeFileSync(callFile(), String(n));
405
- return n;
406
- }
407
-
408
- // ---- Gunluk token/maliyet birikimi ----
409
- // Cagri sayacinin yanina gunluk token ve maliyet toplami. Ayri dosyada tutulur ki mevcut
410
- // calls-*.txt bicimi (ve onu okuyan cli.js) hic degismesin. Bozuk/eksik dosya sifir sayilir;
411
- // telemetri hicbir kosulda gorev akisini durdurmamali.
412
- const USAGE_FIELDS = ["input", "output", "reasoning", "cacheRead", "cacheWrite", "cost"];
413
- function usageFile(day) {
414
- return path.join(STATE, `usage-${day || new Date().toISOString().slice(0, 10)}.json`);
415
- }
416
- function getDailyUsage(day) {
417
- const empty = Object.fromEntries(USAGE_FIELDS.map((k) => [k, 0]));
418
- try {
419
- const parsed = JSON.parse(fs.readFileSync(usageFile(day), "utf8"));
420
- for (const key of USAGE_FIELDS) empty[key] = Number(parsed?.[key]) || 0;
421
- empty.calls = Number(parsed?.calls) || 0;
422
- } catch { empty.calls = 0; }
423
- return empty;
424
- }
425
- function addDailyUsage(usage) {
426
- const current = getDailyUsage();
427
- for (const key of USAGE_FIELDS) current[key] += Number(usage?.[key]) || 0;
428
- current.calls += 1;
429
- atomicWrite(usageFile(), JSON.stringify(current));
430
- return current;
431
- }
432
-
433
- module.exports = {
434
- ROOT,
435
- ASSETS,
436
- WORK_BASE,
437
- ensureDirs,
438
- loadConfig,
439
- normalizeConfig,
440
- saveConfig,
441
- listRoles,
442
- readRole,
443
- writeRole,
444
- deleteRole,
445
- listTasks,
446
- listRecentTasks,
447
- nextPending,
448
- addTask,
449
- addChatTask,
450
- addScheduledTask,
451
- saveTask,
452
- findTask,
453
- moveTask,
454
- removeTask,
455
- approveTask,
456
- rejectTask,
457
- getMemory,
458
- appendMemory,
459
- readProjectContext,
460
- writeProjectContext,
461
- clearProjectContext,
462
- projectContextPath,
463
- getCallCount,
464
- bumpCallCount,
465
- getDailyUsage,
466
- addDailyUsage,
467
- appendRunEvent,
468
- listRunEvents,
469
- hashText,
470
- };
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
+ // Ajan hapsi: "workspace" = her CLI'nin native sandbox'i ile calisma klasoru DISINA yazma/ag
129
+ // engellenir (Docker/Git gerektirmez; codex mac/Linux/Windows'ta OS-native zorlar). "off" =
130
+ // eski davranis. extraWritableDirs: calisma klasoru disinda ek yazilabilir mutlak yollar.
131
+ sandbox: { mode: "workspace", extraWritableDirs: [] },
132
+ // Proje context: her calisma klasorunun .crewctl/CONTEXT.md profili gorev acilisinda yuklenir,
133
+ // bitiminde operator revize eder. false = eski global hafiza davranisi.
134
+ projectContext: true, projectContextCharBudget: 6000,
135
+ notify: { webhookUrl: "", onComplete: true, onFailed: true },
136
+ operator: { roleFile: "roles/operator.md", maxRounds: 6, maxDelegationsPerRound: 8, maxInfrastructureRecoveryRounds: 2, protocolRetries: 1 },
137
+ resilience: { transientRetries: 2, retryBaseSeconds: 3, maxFailoverAgents: 1 },
138
+ cliSettings: {
139
+ codex: { model: "", reasoningEffort: "medium", serviceTier: "fast" },
140
+ opencode: { model: "", modelPreferences: ["*deepseek*free*", "*free*", "*"], modelExclude: ["ollama/*", "lmstudio/*", "llamacpp/*", "local/*", "localhost/*"] },
141
+ },
142
+ skills: { enabled: [], autoMatch: true, catalogLimit: 12, maxSkillsPerAssignment: 3, charBudget: 2400, referenceCharBudget: 1200 },
143
+ agents: {}, riskyPatterns: [], schedules: [],
144
+ };
145
+ // Eski sema, model ayarlarini operator altina gomuyordu (operator.codexSettings ve
146
+ // operator.model). Yeni sema CLI bazlidir: cliSettings[adapter] o CLI'nin operator ve
147
+ // uzman kullanimlarinin tumune uygulanir. Saf ve idempotent olmali; loadConfig sicak yoldur.
148
+ function normalizeConfig(cfg) {
149
+ if (!cfg || typeof cfg !== "object") return cfg;
150
+ const current = cfg.cliSettings && typeof cfg.cliSettings === "object" ? cfg.cliSettings : {};
151
+ const legacyCodex = cfg.operator && typeof cfg.operator.codexSettings === "object" ? cfg.operator.codexSettings : {};
152
+ const legacyOpenCodeModel = typeof cfg.operator?.model === "string" ? cfg.operator.model : "";
153
+ const normalized = {
154
+ ...cfg,
155
+ skills: { enabled: [], autoMatch: true, catalogLimit: 12, maxSkillsPerAssignment: 3, charBudget: 2400, referenceCharBudget: 1200, ...(cfg.skills || {}) },
156
+ schedules: Array.isArray(cfg.schedules) ? cfg.schedules : [],
157
+ // Her yuklemede hapis semasini garanti et; boylece eski config.json'lar yukseltilince
158
+ // varsayilan olarak "workspace" hapsini kazanir. Gecersiz mode "workspace"e duser.
159
+ sandbox: {
160
+ mode: ["off", "workspace"].includes(cfg.sandbox?.mode) ? cfg.sandbox.mode : "workspace",
161
+ extraWritableDirs: Array.isArray(cfg.sandbox?.extraWritableDirs)
162
+ ? cfg.sandbox.extraWritableDirs.filter((x) => typeof x === "string" && x.trim()).map(String)
163
+ : [],
164
+ },
165
+ cliSettings: {
166
+ codex: { model: "", reasoningEffort: "medium", serviceTier: "fast", ...legacyCodex, ...(current.codex || {}) },
167
+ // Desenler mevcut config'lere de eklenir ki kullanici bunlari Ayarlar'da gorup
168
+ // kendi aboneligine gore duzenleyebilsin. Kendi degerini yazan kullanicininki korunur.
169
+ opencode: {
170
+ model: legacyOpenCodeModel,
171
+ modelPreferences: ["*deepseek*free*", "*free*", "*"],
172
+ modelExclude: ["ollama/*", "lmstudio/*", "llamacpp/*", "local/*", "localhost/*"],
173
+ ...(current.opencode || {}),
174
+ },
175
+ },
176
+ };
177
+ if (cfg.operator && typeof cfg.operator === "object") {
178
+ normalized.operator = { ...cfg.operator };
179
+ delete normalized.operator.codexSettings;
180
+ delete normalized.operator.model;
181
+ }
182
+ return normalized;
183
+ }
184
+ // config.json kisiye ozeldir (gitignore). Yoksa config.default.json sablonundan uretilir;
185
+ // boylece kullanici klonlayip `npm start` dedigi anda calisir ve kurulu CLI'lar keşifle eklenir.
186
+ // Paketle gelen beceri dosyalarinin slug'lari (dosya adi = frontmatter name, dogrulanir).
187
+ // Ilk config uretiminde beceriler VARSAYILAN OLARAK ETKIN gelsin diye kullanilir; boylece
188
+ // operator, kullanicinin becerilerini kodlama/planlama/review delegasyonlarinda kullanabilir.
189
+ function shippedSkillSlugs() {
190
+ try {
191
+ return fs.readdirSync(path.join(ASSETS, "skills"))
192
+ .filter((f) => f.toLowerCase().endsWith(".md"))
193
+ .map((f) => f.replace(/\.md$/i, ""));
194
+ } catch { return []; }
195
+ }
196
+ function loadConfig() {
197
+ const file = path.join(ROOT, "config.json");
198
+ if (!fs.existsSync(file)) {
199
+ const template = path.join(ASSETS, "config.default.json");
200
+ const seed = fs.existsSync(template) ? fs.readFileSync(template, "utf8") : JSON.stringify(FALLBACK_CONFIG, null, 2);
201
+ let seedObj;
202
+ try { seedObj = JSON.parse(seed); } catch { seedObj = { ...FALLBACK_CONFIG }; }
203
+ // Ilk kurulumda tum paket becerilerini etkinlestir (kullanici Ayarlar'dan kapatabilir).
204
+ // Sonraki yuklemelerde dosya var oldugundan bu blok CALISMAZ; kullanicinin secimi korunur.
205
+ seedObj.skills = seedObj.skills || {};
206
+ if (!Array.isArray(seedObj.skills.enabled) || !seedObj.skills.enabled.length) {
207
+ const slugs = shippedSkillSlugs();
208
+ if (slugs.length) seedObj.skills.enabled = slugs;
209
+ }
210
+ atomicWrite(file, JSON.stringify(seedObj, null, 2));
211
+ }
212
+ return normalizeConfig(JSON.parse(fs.readFileSync(file, "utf8")));
213
+ }
214
+ function saveConfig(cfg) {
215
+ atomicWrite(path.join(ROOT, "config.json"), JSON.stringify(cfg, null, 2));
216
+ }
217
+
218
+ // ---- Roller ----
219
+ function listRoles() {
220
+ if (!fs.existsSync(ROLES)) return [];
221
+ return fs.readdirSync(ROLES).filter((f) => f.endsWith(".md"));
222
+ }
223
+ function readRole(file) {
224
+ const p = path.join(ROLES, path.basename(file));
225
+ return fs.existsSync(p) ? fs.readFileSync(p, "utf8") : "";
226
+ }
227
+ function writeRole(file, content) {
228
+ fs.writeFileSync(path.join(ROLES, path.basename(file)), content);
229
+ }
230
+ function deleteRole(file) {
231
+ const p = path.join(ROLES, path.basename(file));
232
+ if (fs.existsSync(p)) fs.rmSync(p);
233
+ }
234
+
235
+ // ---- Gorevler ----
236
+ function taskPath(state, id) {
237
+ return path.join(Q, state, `${id}.json`);
238
+ }
239
+ function listTasks(state) {
240
+ const dir = path.join(Q, state);
241
+ if (!fs.existsSync(dir)) return [];
242
+ return fs
243
+ .readdirSync(dir)
244
+ .filter((f) => f.endsWith(".json"))
245
+ .map((f) => {
246
+ try {
247
+ return JSON.parse(fs.readFileSync(path.join(dir, f), "utf8"));
248
+ } catch {
249
+ return null;
250
+ }
251
+ })
252
+ .filter(Boolean)
253
+ .sort((a, b) => (a.id < b.id ? -1 : 1));
254
+ }
255
+ // Yalnizca en yeni `limit` gorevi okur. Gorev id'si zaman damgasiyla basladigi icin dosya adi
256
+ // siralamasi = kronolojik siralama; boylece done/failed gecmisi buyudukce (yuzlerce/binlerce
257
+ // dosya) her pano yenilemesinde TUM dosyalari okuyup ayristirma maliyeti sabit N'e iner.
258
+ function listRecentTasks(state, limit) {
259
+ const dir = path.join(Q, state);
260
+ if (!fs.existsSync(dir)) return [];
261
+ let names = fs.readdirSync(dir).filter((f) => f.endsWith(".json")).sort();
262
+ if (limit && names.length > limit) names = names.slice(-limit);
263
+ return names
264
+ .map((f) => {
265
+ try { return JSON.parse(fs.readFileSync(path.join(dir, f), "utf8")); } catch { return null; }
266
+ })
267
+ .filter(Boolean);
268
+ }
269
+ function nextPending() {
270
+ return listTasks("pending")[0] || null;
271
+ }
272
+ function addTask(prompt, targetDir, operatorCli, executionMode) {
273
+ const id =
274
+ new Date().toISOString().replace(/[-:T.]/g, "").slice(0, 15) +
275
+ "-" +
276
+ Math.floor(Math.random() * 9000 + 1000);
277
+ const task = { id, prompt, status: "pending", createdAt: new Date().toISOString() };
278
+ if (targetDir) task.targetDir = targetDir;
279
+ if (operatorCli) task.operatorCli = operatorCli;
280
+ if (executionMode) task.executionMode = executionMode;
281
+ atomicWrite(taskPath("pending", id), JSON.stringify(task, null, 2));
282
+ return task;
283
+ }
284
+ function addChatTask(parentTask, question) {
285
+ const task = addTask(question, parentTask.targetDir, parentTask.operatorCli, "chat");
286
+ task.kind = "operator-chat";
287
+ task.parentTaskId = parentTask.id;
288
+ saveTask("pending", task);
289
+ return task;
290
+ }
291
+ // Zamanlanmis bir gorevi kuyruga ekler. Normal gorevle ayni yolu kullanir; yalnizca kaynagini
292
+ // isaretlemek icin scheduleId iliştirir (Pano bu görevi "zamanlanmis" rozetiyle gosterebilsin).
293
+ function addScheduledTask(schedule) {
294
+ const task = addTask(schedule.prompt, schedule.targetDir, schedule.operatorCli, schedule.executionMode || "auto");
295
+ task.scheduleId = schedule.id;
296
+ saveTask("pending", task);
297
+ return task;
298
+ }
299
+
300
+ // ---- Kalici calisma olaylari ----
301
+ function appendRunEvent(taskId, event) {
302
+ ensureDirs();
303
+ fs.appendFileSync(path.join(EVENTS, `${path.basename(taskId)}.jsonl`), JSON.stringify(event) + "\n");
304
+ }
305
+ function listRunEvents(taskId, limit = 1000) {
306
+ const file = path.join(EVENTS, `${path.basename(taskId)}.jsonl`);
307
+ if (!fs.existsSync(file)) return [];
308
+ return fs.readFileSync(file, "utf8").split(/\r?\n/).filter(Boolean).slice(-Math.max(1, limit)).map((line) => {
309
+ try { return JSON.parse(line); } catch { return null; }
310
+ }).filter(Boolean);
311
+ }
312
+ function hashText(text) {
313
+ return crypto.createHash("sha256").update(String(text)).digest("hex");
314
+ }
315
+ function saveTask(state, task) {
316
+ atomicWrite(taskPath(state, task.id), JSON.stringify(task, null, 2));
317
+ }
318
+ function findTask(id) {
319
+ for (const s of STATES) {
320
+ const p = taskPath(s, id);
321
+ if (fs.existsSync(p)) return { state: s, task: JSON.parse(fs.readFileSync(p, "utf8")) };
322
+ }
323
+ return null;
324
+ }
325
+ function moveTask(fromState, toState, task) {
326
+ const src = taskPath(fromState, task.id);
327
+ // Hedefi once atomik olarak yaz. Surec iki islem arasinda cokse bile gorev kaybolmaz.
328
+ saveTask(toState, task);
329
+ if (fromState !== toState && fs.existsSync(src)) fs.rmSync(src);
330
+ }
331
+ function removeTask(state, id) {
332
+ const p = taskPath(state, id);
333
+ if (fs.existsSync(p)) fs.rmSync(p);
334
+ }
335
+
336
+ function approveTask(id) {
337
+ const found = findTask(id);
338
+ if (!found) throw new Error(`Gorev bulunamadi: ${id}`);
339
+ if (found.state !== "approval") throw new Error(`Gorev onay beklemiyor: ${id}`);
340
+ const task = found.task;
341
+ if (task.planHash && task.planPreview && task.planHash !== hashText(task.planPreview)) {
342
+ throw new Error("Plan onay beklerken degismis; yeniden planlanmasi gerekiyor.");
343
+ }
344
+ task.approved = true;
345
+ task.status = "pending";
346
+ moveTask(found.state, "pending", task);
347
+ return task;
348
+ }
349
+
350
+ function rejectTask(id) {
351
+ const found = findTask(id);
352
+ if (!found) throw new Error(`Gorev bulunamadi: ${id}`);
353
+ if (found.state !== "approval") throw new Error(`Gorev onay beklemiyor: ${id}`);
354
+ found.task.status = "rejected";
355
+ found.task.finishedAt = new Date().toISOString();
356
+ moveTask(found.state, "failed", found.task);
357
+ return found.task;
358
+ }
359
+
360
+ // ---- Hafiza ----
361
+ function getMemory(charBudget) {
362
+ if (!fs.existsSync(MEM)) return "(hafiza bos)";
363
+ const files = fs
364
+ .readdirSync(MEM)
365
+ .filter((f) => f.endsWith(".md"))
366
+ .map((f) => path.join(MEM, f));
367
+ if (!files.length) return "(hafiza bos)";
368
+ let text = files.map((f) => fs.readFileSync(f, "utf8")).join("\n\n");
369
+ if (charBudget && text.length > charBudget) text = text.slice(-charBudget);
370
+ return text;
371
+ }
372
+ function appendMemory(title, body) {
373
+ const stamp = new Date().toISOString().slice(0, 16).replace("T", " ");
374
+ fs.appendFileSync(path.join(MEM, "log.md"), `\n## ${stamp} — ${title}\n${body}\n`);
375
+ }
376
+
377
+ // ---- Proje context (path'e ozel) ----
378
+ // Global log.md'nin aksine, her calisma klasorunun KENDI birikmis proje profili vardir:
379
+ // <cwd>/.crewctl/CONTEXT.md. Gorev acilisinda operatore yuklenir (tum kodu bastan taramaya
380
+ // gerek kalmasin), gorev bitiminde operator tarafindan REVIZE edilir (append degil). Calisma
381
+ // klasorunde durdugu icin seffaf, elle duzenlenebilir ve git'e girebilir.
382
+ function projectContextPath(cwd) {
383
+ return path.join(cwd, ".crewctl", "CONTEXT.md");
384
+ }
385
+ function readProjectContext(cwd) {
386
+ if (!cwd) return "";
387
+ try { return fs.readFileSync(projectContextPath(cwd), "utf8"); } catch { return ""; }
388
+ }
389
+ function writeProjectContext(cwd, content) {
390
+ if (!cwd) return false;
391
+ try {
392
+ fs.mkdirSync(path.join(cwd, ".crewctl"), { recursive: true });
393
+ atomicWrite(projectContextPath(cwd), String(content == null ? "" : content));
394
+ return true;
395
+ } catch { return false; }
396
+ }
397
+ function clearProjectContext(cwd) {
398
+ if (!cwd) return false;
399
+ try { fs.rmSync(projectContextPath(cwd), { force: true }); return true; } catch { return false; }
400
+ }
401
+
402
+ // ---- Gunluk cagri butcesi ----
403
+ function callFile() {
404
+ return path.join(STATE, `calls-${new Date().toISOString().slice(0, 10)}.txt`);
405
+ }
406
+ function getCallCount() {
407
+ const f = callFile();
408
+ return fs.existsSync(f) ? parseInt(fs.readFileSync(f, "utf8"), 10) || 0 : 0;
409
+ }
410
+ function bumpCallCount() {
411
+ const n = getCallCount() + 1;
412
+ fs.writeFileSync(callFile(), String(n));
413
+ return n;
414
+ }
415
+
416
+ // ---- Gunluk token/maliyet birikimi ----
417
+ // Cagri sayacinin yanina gunluk token ve maliyet toplami. Ayri dosyada tutulur ki mevcut
418
+ // calls-*.txt bicimi (ve onu okuyan cli.js) hic degismesin. Bozuk/eksik dosya sifir sayilir;
419
+ // telemetri hicbir kosulda gorev akisini durdurmamali.
420
+ const USAGE_FIELDS = ["input", "output", "reasoning", "cacheRead", "cacheWrite", "cost"];
421
+ function usageFile(day) {
422
+ return path.join(STATE, `usage-${day || new Date().toISOString().slice(0, 10)}.json`);
423
+ }
424
+ function getDailyUsage(day) {
425
+ const empty = Object.fromEntries(USAGE_FIELDS.map((k) => [k, 0]));
426
+ try {
427
+ const parsed = JSON.parse(fs.readFileSync(usageFile(day), "utf8"));
428
+ for (const key of USAGE_FIELDS) empty[key] = Number(parsed?.[key]) || 0;
429
+ empty.calls = Number(parsed?.calls) || 0;
430
+ } catch { empty.calls = 0; }
431
+ return empty;
432
+ }
433
+ function addDailyUsage(usage) {
434
+ const current = getDailyUsage();
435
+ for (const key of USAGE_FIELDS) current[key] += Number(usage?.[key]) || 0;
436
+ current.calls += 1;
437
+ atomicWrite(usageFile(), JSON.stringify(current));
438
+ return current;
439
+ }
440
+
441
+ module.exports = {
442
+ ROOT,
443
+ ASSETS,
444
+ WORK_BASE,
445
+ ensureDirs,
446
+ loadConfig,
447
+ normalizeConfig,
448
+ saveConfig,
449
+ listRoles,
450
+ readRole,
451
+ writeRole,
452
+ deleteRole,
453
+ listTasks,
454
+ listRecentTasks,
455
+ nextPending,
456
+ addTask,
457
+ addChatTask,
458
+ addScheduledTask,
459
+ saveTask,
460
+ findTask,
461
+ moveTask,
462
+ removeTask,
463
+ approveTask,
464
+ rejectTask,
465
+ getMemory,
466
+ appendMemory,
467
+ readProjectContext,
468
+ writeProjectContext,
469
+ clearProjectContext,
470
+ projectContextPath,
471
+ getCallCount,
472
+ bumpCallCount,
473
+ getDailyUsage,
474
+ addDailyUsage,
475
+ appendRunEvent,
476
+ listRunEvents,
477
+ hashText,
478
+ };