catenext 0.0.0-stage → 0.1.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.
package/dist/index.js ADDED
@@ -0,0 +1,2719 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { existsSync as existsSync2 } from "node:fs";
5
+ import { dirname as dirname4, resolve as resolve4 } from "node:path";
6
+ import { createInterface } from "node:readline";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ // shared/src/api.ts
10
+ import { z as z4 } from "zod";
11
+
12
+ // shared/src/common.ts
13
+ import { z } from "zod";
14
+ var IdSchema = z.uuid();
15
+ var SlugSchema = z.string().min(1).max(64).regex(/^[a-z0-9]+(?:[-_][a-z0-9]+)*$/, "Harus slug huruf kecil (a-z, 0-9, '-' atau '_')");
16
+ var RepoNameSchema = SlugSchema;
17
+ var RoleSchema = SlugSchema.max(32);
18
+ var AgentAliasSchema = SlugSchema.max(32);
19
+ var IsoDateTimeSchema = z.iso.datetime({ offset: true });
20
+ function estimateTokens(text2) {
21
+ return Math.ceil(text2.length / 4);
22
+ }
23
+ function countWords(text2) {
24
+ const trimmed = text2.trim();
25
+ return trimmed === "" ? 0 : trimmed.split(/\s+/).length;
26
+ }
27
+
28
+ // shared/src/task.ts
29
+ import { z as z3 } from "zod";
30
+
31
+ // shared/src/handoff.ts
32
+ import { z as z2 } from "zod";
33
+ var HANDOFF_LIMITS = {
34
+ maxFilesModified: 15,
35
+ maxPathLength: 200,
36
+ maxKeyDecisions: 5,
37
+ maxKeyDecisionLength: 150,
38
+ maxVerificationCommandLength: 300,
39
+ maxNotesLength: 500,
40
+ maxTokens: 600
41
+ };
42
+ var CODE_FENCE = /```/;
43
+ var FilePathSchema = z2.string().min(1).max(HANDOFF_LIMITS.maxPathLength).regex(/^[^\s]+$/, "Path file tidak boleh berisi spasi atau baris baru (tanpa potongan kode)");
44
+ var NoCodeText = (max) => z2.string().min(1).max(max).refine((s) => !CODE_FENCE.test(s), "Jangan menempelkan blok kode; cukup rujuk path file");
45
+ var HandoffSummarySchema = z2.object({
46
+ files_modified: z2.array(FilePathSchema).max(HANDOFF_LIMITS.maxFilesModified),
47
+ key_decisions: z2.array(NoCodeText(HANDOFF_LIMITS.maxKeyDecisionLength)).max(HANDOFF_LIMITS.maxKeyDecisions),
48
+ verification_command: z2.string().min(1).max(HANDOFF_LIMITS.maxVerificationCommandLength).nullable(),
49
+ notes_for_next_agent: NoCodeText(HANDOFF_LIMITS.maxNotesLength),
50
+ git_branch: z2.string().min(1).max(255),
51
+ last_commit_hash: z2.string().regex(/^[0-9a-f]{7,64}$/, "Hash commit git (hex, 7\u201364 karakter)")
52
+ }).refine((h) => estimateHandoffTokens(h) <= HANDOFF_LIMITS.maxTokens, {
53
+ message: `Ringkasan handoff melebihi ~${HANDOFF_LIMITS.maxTokens} token; ringkas lagi`
54
+ });
55
+ function estimateHandoffTokens(h) {
56
+ return estimateTokens(JSON.stringify(h));
57
+ }
58
+
59
+ // shared/src/task.ts
60
+ var TASK_STATUSES = [
61
+ "DRAFT",
62
+ "TODO",
63
+ "IN_PROGRESS",
64
+ "NEEDS_REVIEW",
65
+ "REVISION_REQUESTED",
66
+ "BLOCKED",
67
+ "DONE"
68
+ ];
69
+ var TaskStatusSchema = z3.enum(TASK_STATUSES);
70
+ var KANBAN_STATUSES = TASK_STATUSES.filter(
71
+ (s) => s !== "DRAFT"
72
+ );
73
+ var TASK_EVENTS = [
74
+ "approve_plan",
75
+ // human: DRAFT -> TODO
76
+ "return_to_draft",
77
+ // human: TODO -> DRAFT
78
+ "claim",
79
+ // agent: TODO | REVISION_REQUESTED -> IN_PROGRESS
80
+ "complete",
81
+ // agent: IN_PROGRESS -> DONE, atau NEEDS_REVIEW bila requires_approval
82
+ "report_blocker",
83
+ // agent: IN_PROGRESS -> BLOCKED
84
+ "release",
85
+ // agent: IN_PROGRESS -> TODO (melepas lock tanpa blocker)
86
+ "lease_expired",
87
+ // system: IN_PROGRESS -> TODO
88
+ "approve",
89
+ // human: NEEDS_REVIEW -> DONE
90
+ "request_revision",
91
+ // human: NEEDS_REVIEW | DONE -> REVISION_REQUESTED
92
+ "unblock"
93
+ // human: BLOCKED -> TODO
94
+ ];
95
+ var TaskEventSchema = z3.enum(TASK_EVENTS);
96
+ var LOCK_LEASE_MS = 30 * 60 * 1e3;
97
+ var TaskSchema = z3.object({
98
+ id: IdSchema,
99
+ /** Diduplikasi dari project agar kebijakan RLS cukup `workspace_id = current_setting(...)`. */
100
+ workspace_id: IdSchema,
101
+ project_id: IdSchema,
102
+ epic_id: IdSchema,
103
+ title: z3.string().min(1).max(200),
104
+ prompt_instruction: z3.string().min(1).max(8e3),
105
+ status: TaskStatusSchema,
106
+ requires_approval: z3.boolean().default(false),
107
+ target_repo: RepoNameSchema.nullable(),
108
+ role: RoleSchema.nullable(),
109
+ assignee_id: IdSchema.nullable(),
110
+ locked_by: z3.string().max(200).nullable(),
111
+ locked_at: IsoDateTimeSchema.nullable(),
112
+ lease_expires_at: IsoDateTimeSchema.nullable(),
113
+ handoff_summary: HandoffSummarySchema.nullable(),
114
+ review_feedback: z3.string().max(2e3).nullable(),
115
+ revision_count: z3.number().int().min(0).default(0),
116
+ blocker_reason: z3.string().max(1e3).nullable(),
117
+ /** Ditandai bila dependensi hulu dibuka ulang setelah task ini berjalan. */
118
+ is_stale: z3.boolean().default(false),
119
+ depends_on: z3.array(IdSchema).default([]),
120
+ created_at: IsoDateTimeSchema,
121
+ updated_at: IsoDateTimeSchema
122
+ });
123
+ var TaskSummarySchema = z3.object({
124
+ id: IdSchema,
125
+ title: z3.string().min(1).max(200),
126
+ depends_on: z3.array(IdSchema),
127
+ role: RoleSchema.optional(),
128
+ target_repo: RepoNameSchema.optional(),
129
+ revision: z3.boolean().optional()
130
+ });
131
+ var BLOCKER_CATEGORIES = [
132
+ "missing_env",
133
+ "ambiguous_requirement",
134
+ "failing_tests",
135
+ "dependency_issue",
136
+ "other"
137
+ ];
138
+ var BlockerCategorySchema = z3.enum(BLOCKER_CATEGORIES);
139
+
140
+ // shared/src/api.ts
141
+ var WorkspaceSchema = z4.object({
142
+ id: IdSchema,
143
+ name: z4.string(),
144
+ slug: z4.string(),
145
+ role: z4.string()
146
+ });
147
+ var ProjectSchema = z4.object({
148
+ id: IdSchema,
149
+ workspace_id: IdSchema,
150
+ name: z4.string().min(1).max(120),
151
+ detected_stack: z4.array(z4.string()),
152
+ agent_connected_at: IsoDateTimeSchema.nullable(),
153
+ created_at: IsoDateTimeSchema,
154
+ updated_at: IsoDateTimeSchema
155
+ });
156
+ var EpicSchema = z4.object({
157
+ id: IdSchema,
158
+ workspace_id: IdSchema,
159
+ project_id: IdSchema,
160
+ title: z4.string().min(1).max(200),
161
+ description: z4.string().max(4e3).nullable(),
162
+ template_used: z4.string().max(80).nullable(),
163
+ created_at: IsoDateTimeSchema,
164
+ updated_at: IsoDateTimeSchema
165
+ });
166
+ var TaskDtoSchema = TaskSchema.extend({
167
+ position: z4.number(),
168
+ lock_repo: RepoNameSchema.nullable(),
169
+ blocker_category: BlockerCategorySchema.nullable(),
170
+ /** Dependensi yang belum DONE. Kosong = tidak tertahan dependensi. */
171
+ blocked_by: z4.array(IdSchema),
172
+ /** TODO/REVISION_REQUESTED dan semua dependensinya DONE: bisa diklaim agen sekarang. */
173
+ is_ready: z4.boolean()
174
+ });
175
+ var AgentPersonaSchema = z4.object({
176
+ id: IdSchema,
177
+ workspace_id: IdSchema,
178
+ project_id: IdSchema.nullable(),
179
+ alias: AgentAliasSchema,
180
+ role: RoleSchema,
181
+ rules: z4.array(z4.string()),
182
+ created_at: IsoDateTimeSchema,
183
+ updated_at: IsoDateTimeSchema
184
+ });
185
+ var ApiKeySchema = z4.object({
186
+ id: IdSchema,
187
+ workspace_id: IdSchema,
188
+ project_id: IdSchema.nullable(),
189
+ name: z4.string(),
190
+ prefix: z4.string(),
191
+ last_used_at: IsoDateTimeSchema.nullable(),
192
+ revoked_at: IsoDateTimeSchema.nullable(),
193
+ created_at: IsoDateTimeSchema
194
+ });
195
+ var ACTIVITY_ACTORS = ["human", "agent", "system"];
196
+ var ActivityLogSchema = z4.object({
197
+ id: IdSchema,
198
+ workspace_id: IdSchema,
199
+ project_id: IdSchema.nullable(),
200
+ task_id: IdSchema.nullable(),
201
+ event_type: z4.string(),
202
+ actor: z4.enum(ACTIVITY_ACTORS),
203
+ persona_alias: z4.string().nullable(),
204
+ /** Nama agen + repo untuk event agen (mis. `claude-code@web`), null untuk manusia/sistem. */
205
+ agent_name: z4.string().nullable(),
206
+ duration_ms: z4.number().int().nullable(),
207
+ metadata: z4.record(z4.string(), z4.unknown()).nullable(),
208
+ created_at: IsoDateTimeSchema
209
+ });
210
+ var ProjectMetricsSchema = z4.object({
211
+ handoffs_7d: z4.number().int(),
212
+ revisions_7d: z4.number().int(),
213
+ blockers_7d: z4.number().int(),
214
+ avg_task_duration_ms: z4.number().int().nullable()
215
+ });
216
+ var CreateProjectInput = z4.object({
217
+ name: z4.string().trim().min(1).max(120),
218
+ detected_stack: z4.array(z4.string().min(1).max(40)).max(20).default([])
219
+ });
220
+ var UpdateProjectInput = CreateProjectInput.partial();
221
+ var CreateEpicInput = z4.object({
222
+ title: z4.string().trim().min(1).max(200),
223
+ description: z4.string().max(4e3).nullish(),
224
+ template_used: z4.string().max(80).nullish()
225
+ });
226
+ var UpdateEpicInput = CreateEpicInput.partial();
227
+ var CreateTaskInput = z4.object({
228
+ title: z4.string().trim().min(1).max(200),
229
+ prompt_instruction: z4.string().min(1).max(8e3),
230
+ target_repo: RepoNameSchema.nullish(),
231
+ role: RoleSchema.nullish(),
232
+ requires_approval: z4.boolean().default(false),
233
+ depends_on: z4.array(IdSchema).max(10).default([]),
234
+ /** Task buatan manusia langsung TODO; DRAFT bila ingin ditinjau bersama rencana agen. */
235
+ status: z4.enum(["DRAFT", "TODO"]).default("TODO")
236
+ });
237
+ var UpdateTaskInput = z4.object({
238
+ title: z4.string().trim().min(1).max(200).optional(),
239
+ prompt_instruction: z4.string().min(1).max(8e3).optional(),
240
+ target_repo: RepoNameSchema.nullable().optional(),
241
+ role: RoleSchema.nullable().optional(),
242
+ requires_approval: z4.boolean().optional(),
243
+ assignee_id: IdSchema.nullable().optional(),
244
+ position: z4.number().finite().optional(),
245
+ /** Hanya boleh false: manusia menandai task stale sudah diperiksa ulang. */
246
+ is_stale: z4.literal(false).optional()
247
+ });
248
+ var SetDependenciesInput = z4.object({
249
+ depends_on: z4.array(IdSchema).max(10)
250
+ });
251
+ var TaskActionInput = z4.discriminatedUnion("event", [
252
+ z4.object({ event: z4.literal("approve_plan") }),
253
+ z4.object({ event: z4.literal("return_to_draft") }),
254
+ z4.object({ event: z4.literal("approve") }),
255
+ z4.object({
256
+ event: z4.literal("request_revision"),
257
+ feedback: z4.string().trim().min(5).max(2e3)
258
+ }),
259
+ z4.object({ event: z4.literal("unblock") })
260
+ ]);
261
+ var PersonaInput = z4.object({
262
+ alias: AgentAliasSchema,
263
+ role: RoleSchema,
264
+ rules: z4.array(z4.string().trim().min(1).max(300)).max(30).default([]),
265
+ project_id: IdSchema.nullish()
266
+ });
267
+ var UpdatePersonaInput = PersonaInput.partial();
268
+ var CreateApiKeyInput = z4.object({
269
+ name: z4.string().trim().min(1).max(80),
270
+ project_id: IdSchema.nullish()
271
+ });
272
+ var CreateApiKeyOutput = z4.object({
273
+ api_key: ApiKeySchema,
274
+ /** Kunci mentah. Hanya dikirim sekali, saat dibuat. */
275
+ secret: z4.string()
276
+ });
277
+ var AGENT_HEADERS = {
278
+ project: "x-catenext-project",
279
+ repo: "x-catenext-repo",
280
+ agent: "x-catenext-agent"
281
+ };
282
+ var API_KEY_PREFIX = "ctnx_";
283
+ var ReleaseTaskInput = z4.object({ task_id: IdSchema });
284
+ var SyncSkillsInput = z4.object({
285
+ skills: z4.array(
286
+ z4.object({
287
+ name: z4.string().min(1).max(48),
288
+ when_to_use: z4.string().min(1).max(160)
289
+ })
290
+ ).max(100)
291
+ });
292
+ var VerifyOutput = z4.object({
293
+ token_valid: z4.literal(true),
294
+ workspace_id: IdSchema,
295
+ project: z4.object({ id: IdSchema, name: z4.string() }),
296
+ repo_name: RepoNameSchema
297
+ });
298
+ var ApiErrorSchema = z4.object({
299
+ error: z4.object({
300
+ code: z4.string(),
301
+ message: z4.string(),
302
+ details: z4.unknown().optional()
303
+ })
304
+ });
305
+
306
+ // shared/src/config.ts
307
+ import { z as z5 } from "zod";
308
+ var CONFIG_SCHEMA_VERSION = 1;
309
+ var CatenextConfigSchema = z5.object({
310
+ schema_version: z5.number().int().positive(),
311
+ project_id: IdSchema,
312
+ repo_name: RepoNameSchema,
313
+ stack: z5.array(z5.string().min(1).max(40)).max(20).default([]),
314
+ /** URL Catenext Cloud API; kosong = default bawaan CLI. */
315
+ api_url: z5.url().optional(),
316
+ overrides: z5.object({
317
+ default_agent_alias: AgentAliasSchema.optional(),
318
+ default_role: RoleSchema.optional(),
319
+ extra_rules: z5.array(z5.string().min(1).max(300)).max(20).optional()
320
+ }).optional()
321
+ });
322
+ function checkConfigCompatibility(schemaVersion, supported = CONFIG_SCHEMA_VERSION) {
323
+ if (schemaVersion > supported) {
324
+ return {
325
+ ok: false,
326
+ reason: "too_new",
327
+ message: `Config memakai schema_version ${schemaVersion}, CLI ini hanya mendukung ${supported}. Perbarui CLI Catenext ke versi terbaru (sementara: git pull lalu pnpm build).`
328
+ };
329
+ }
330
+ if (schemaVersion < supported) {
331
+ return {
332
+ ok: false,
333
+ reason: "too_old",
334
+ message: `Config memakai schema_version ${schemaVersion}. Jalankan \`catenext sync --fix\` untuk memperbaruinya ke ${supported}.`
335
+ };
336
+ }
337
+ return { ok: true };
338
+ }
339
+
340
+ // shared/src/dag.ts
341
+ function findCycle(edges) {
342
+ const graph = /* @__PURE__ */ new Map();
343
+ for (const { task: task2, dependsOn } of edges) {
344
+ const list = graph.get(task2);
345
+ if (list) list.push(dependsOn);
346
+ else graph.set(task2, [dependsOn]);
347
+ if (!graph.has(dependsOn)) graph.set(dependsOn, []);
348
+ }
349
+ const WHITE = 0;
350
+ const GRAY = 1;
351
+ const BLACK = 2;
352
+ const color = /* @__PURE__ */ new Map();
353
+ const stack = [];
354
+ const visit2 = (node) => {
355
+ color.set(node, GRAY);
356
+ stack.push(node);
357
+ for (const next of graph.get(node) ?? []) {
358
+ const c = color.get(next) ?? WHITE;
359
+ if (c === GRAY) {
360
+ return [...stack.slice(stack.indexOf(next)), next];
361
+ }
362
+ if (c === WHITE) {
363
+ const found = visit2(next);
364
+ if (found) return found;
365
+ }
366
+ }
367
+ stack.pop();
368
+ color.set(node, BLACK);
369
+ return null;
370
+ };
371
+ for (const node of graph.keys()) {
372
+ if ((color.get(node) ?? WHITE) === WHITE) {
373
+ const found = visit2(node);
374
+ if (found) return found;
375
+ }
376
+ }
377
+ return null;
378
+ }
379
+
380
+ // shared/src/device.ts
381
+ import { z as z6 } from "zod";
382
+ var UserCodeSchema = z6.string().trim().toUpperCase().regex(/^[A-Z2-9]{4}-?[A-Z2-9]{4}$/, "Kode harus 8 karakter, mis. ABCD-EFGH").transform((s) => s.includes("-") ? s : `${s.slice(0, 4)}-${s.slice(4)}`);
383
+ var DeviceCodeInput = z6.object({
384
+ /** Nama mesin/klien yang ditampilkan saat menyetujui, mis. "catenext CLI @ macbook". */
385
+ client_name: z6.string().trim().min(1).max(80),
386
+ /**
387
+ * Public key X25519 sementara milik CLI (SPKI DER, base64url). API key hasil persetujuan
388
+ * dienkripsi ke kunci ini, jadi baris database saja tidak cukup untuk membacanya.
389
+ */
390
+ public_key: z6.string().min(40).max(200)
391
+ });
392
+ var DeviceCodeOutput = z6.object({
393
+ device_code: z6.string(),
394
+ user_code: z6.string(),
395
+ verification_uri: z6.string(),
396
+ verification_uri_complete: z6.string(),
397
+ expires_in: z6.number().int(),
398
+ interval: z6.number().int()
399
+ });
400
+ var DeviceTokenInput = z6.object({ device_code: z6.string().min(20).max(200) });
401
+ var DeviceTokenOutput = z6.object({
402
+ /** API key terenkripsi ke public_key CLI: <pub efemeral>.<iv>.<tag>.<ciphertext> (base64url). */
403
+ encrypted_key: z6.string(),
404
+ workspace_id: IdSchema,
405
+ project_id: IdSchema.nullable()
406
+ });
407
+ var DeviceLookupOutput = z6.object({
408
+ user_code: z6.string(),
409
+ client_name: z6.string(),
410
+ status: z6.enum(["pending", "approved", "denied"]),
411
+ expires_at: z6.string()
412
+ });
413
+ var DeviceApproveInput = z6.object({
414
+ user_code: UserCodeSchema,
415
+ approve: z6.boolean(),
416
+ /** Batasi API key ke satu proyek (disarankan). null = semua proyek di workspace. */
417
+ project_id: IdSchema.nullish()
418
+ });
419
+
420
+ // shared/src/mcp-tools.ts
421
+ import { z as z8 } from "zod";
422
+
423
+ // shared/src/skill.ts
424
+ import { z as z7 } from "zod";
425
+ var SKILL_LIMITS = {
426
+ maxWords: 500,
427
+ maxWhenToUseLength: 160,
428
+ /** Blok kode pendek (perintah, contoh nama) boleh; code dump tidak. */
429
+ maxCodeBlockLines: 15
430
+ };
431
+ var SkillNameSchema = SlugSchema.max(48);
432
+ var SkillFrontmatterSchema = z7.object({
433
+ name: SkillNameSchema,
434
+ when_to_use: z7.string().min(1).max(SKILL_LIMITS.maxWhenToUseLength),
435
+ updated_at: IsoDateTimeSchema
436
+ });
437
+ function longestCodeBlockLines(markdown) {
438
+ let longest = 0;
439
+ const blocks = markdown.match(/```[\s\S]*?```/g) ?? [];
440
+ for (const block of blocks) {
441
+ const lines = block.split("\n").length - 2;
442
+ if (lines > longest) longest = lines;
443
+ }
444
+ return longest;
445
+ }
446
+ var SkillContentSchema = z7.string().min(1).refine((s) => countWords(s) <= SKILL_LIMITS.maxWords, {
447
+ message: `Skill maksimal ${SKILL_LIMITS.maxWords} kata`
448
+ }).refine((s) => longestCodeBlockLines(s) <= SKILL_LIMITS.maxCodeBlockLines, {
449
+ message: `Blok kode maksimal ${SKILL_LIMITS.maxCodeBlockLines} baris; rujuk path file, jangan menyalin kode`
450
+ });
451
+ var SkillIndexEntrySchema = z7.object({
452
+ name: SkillNameSchema,
453
+ when_to_use: z7.string().min(1).max(SKILL_LIMITS.maxWhenToUseLength),
454
+ repo_name: RepoNameSchema
455
+ });
456
+
457
+ // shared/src/mcp-tools.ts
458
+ var PersonaFilter = {
459
+ agent_alias: AgentAliasSchema.optional(),
460
+ role: RoleSchema.optional()
461
+ };
462
+ var PersonaSchema = z8.object({
463
+ alias: AgentAliasSchema,
464
+ role: RoleSchema,
465
+ rules: z8.array(z8.string().min(1).max(300)).max(30)
466
+ });
467
+ var DependencyHandoffSchema = z8.object({
468
+ task_id: IdSchema,
469
+ title: z8.string(),
470
+ handoff_summary: HandoffSummarySchema
471
+ });
472
+ var GetProjectContextInput = z8.object(PersonaFilter);
473
+ var GetProjectContextOutput = z8.object({
474
+ project: z8.object({
475
+ id: IdSchema,
476
+ name: z8.string(),
477
+ repo_name: RepoNameSchema,
478
+ stack: z8.array(z8.string())
479
+ }),
480
+ /** Aturan keras untuk agen (mis. jangan mengedit config MCP). Statis di atas agar ramah cache. */
481
+ directives: z8.array(z8.string()),
482
+ persona: PersonaSchema.optional(),
483
+ epic_summary: z8.string().max(1e3).optional(),
484
+ /** Tier 1: indeks skill saja, isi lengkap lewat load_skill. */
485
+ skills: z8.array(SkillIndexEntrySchema),
486
+ /**
487
+ * Handoff dari dependensi langsung task aktif (dependency-scoped context). Jika belum ada
488
+ * task aktif: handoff dependensi task yang siap diklaim (maks. 5).
489
+ */
490
+ recent_handoffs: z8.array(DependencyHandoffSchema)
491
+ });
492
+ var GetReadyTasksInput = z8.object({
493
+ ...PersonaFilter,
494
+ limit: z8.number().int().min(1).max(50).default(10)
495
+ });
496
+ var GetReadyTasksOutput = z8.object({
497
+ tasks: z8.array(TaskSummarySchema)
498
+ });
499
+ var ClaimTaskInput = z8.object({
500
+ task_id: IdSchema
501
+ });
502
+ var ClaimTaskOutput = z8.object({
503
+ task: z8.object({
504
+ id: IdSchema,
505
+ title: z8.string(),
506
+ prompt_instruction: z8.string(),
507
+ status: z8.literal("IN_PROGRESS"),
508
+ role: RoleSchema.optional(),
509
+ target_repo: RepoNameSchema.optional(),
510
+ revision_count: z8.number().int().min(0)
511
+ }),
512
+ lease_expires_at: IsoDateTimeSchema,
513
+ dependencies: z8.array(DependencyHandoffSchema),
514
+ /** Diisi bila task diambil dari REVISION_REQUESTED. */
515
+ revision: z8.object({
516
+ review_feedback: z8.string(),
517
+ previous_handoff: HandoffSummarySchema.nullable()
518
+ }).optional(),
519
+ /** Peringatan bila branch lokal berbeda dari git_branch handoff dependensi. */
520
+ warnings: z8.array(z8.string()).default([])
521
+ });
522
+ var CompleteHandoffInput = z8.object({
523
+ task_id: IdSchema,
524
+ handoff_summary: HandoffSummarySchema
525
+ });
526
+ var CompleteHandoffOutput = z8.object({
527
+ task_id: IdSchema,
528
+ status: z8.enum(["DONE", "NEEDS_REVIEW"]),
529
+ unlocked_task_ids: z8.array(IdSchema),
530
+ /** Mis. saran mereset sesi chat (1 Task = 1 Fresh Session). */
531
+ next_step_hint: z8.string()
532
+ });
533
+ var ReportBlockerInput = z8.object({
534
+ task_id: IdSchema,
535
+ category: BlockerCategorySchema,
536
+ reason: z8.string().min(10).max(1e3)
537
+ });
538
+ var ReportBlockerOutput = z8.object({
539
+ task_id: IdSchema,
540
+ status: z8.literal("BLOCKED")
541
+ });
542
+ var MAX_TASKS_PER_PLAN = 30;
543
+ var PlanRefSchema = z8.string().min(1).max(40).regex(/^[a-z0-9][a-z0-9_-]*$/, "ref harus huruf kecil, angka, '-' atau '_'");
544
+ var PlannedTaskSchema = z8.object({
545
+ ref: PlanRefSchema,
546
+ title: z8.string().min(1).max(200),
547
+ prompt_instruction: z8.string().min(1).max(8e3),
548
+ /** Berisi ref task lain dalam rencana ini, atau UUID task yang sudah ada. */
549
+ depends_on: z8.array(z8.union([PlanRefSchema, IdSchema])).max(10).default([]),
550
+ target_repo: RepoNameSchema.optional(),
551
+ role: RoleSchema.optional(),
552
+ requires_approval: z8.boolean().default(false)
553
+ });
554
+ var CreateTasksInput = z8.object({
555
+ epic_id: IdSchema,
556
+ tasks: z8.array(PlannedTaskSchema).min(1).max(MAX_TASKS_PER_PLAN)
557
+ }).superRefine((plan, ctx) => {
558
+ const refs = /* @__PURE__ */ new Set();
559
+ plan.tasks.forEach((t, i) => {
560
+ if (refs.has(t.ref)) {
561
+ ctx.addIssue({
562
+ code: "custom",
563
+ message: `ref "${t.ref}" duplikat`,
564
+ path: ["tasks", i, "ref"]
565
+ });
566
+ }
567
+ refs.add(t.ref);
568
+ });
569
+ const isUuid = (v) => IdSchema.safeParse(v).success;
570
+ plan.tasks.forEach((t, i) => {
571
+ t.depends_on.forEach((dep, j) => {
572
+ if (dep === t.ref) {
573
+ ctx.addIssue({
574
+ code: "custom",
575
+ message: "Task tidak boleh bergantung pada dirinya sendiri",
576
+ path: ["tasks", i, "depends_on", j]
577
+ });
578
+ } else if (!isUuid(dep) && !refs.has(dep)) {
579
+ ctx.addIssue({
580
+ code: "custom",
581
+ message: `depends_on "${dep}" bukan ref di rencana ini maupun UUID task`,
582
+ path: ["tasks", i, "depends_on", j]
583
+ });
584
+ }
585
+ });
586
+ });
587
+ const edges = plan.tasks.flatMap(
588
+ (t) => t.depends_on.filter((d) => refs.has(d)).map((d) => ({ task: t.ref, dependsOn: d }))
589
+ );
590
+ const cycle = findCycle(edges);
591
+ if (cycle) {
592
+ ctx.addIssue({
593
+ code: "custom",
594
+ message: `Dependensi melingkar: ${cycle.join(" -> ")}`,
595
+ path: ["tasks"]
596
+ });
597
+ }
598
+ });
599
+ var CreateTasksOutput = z8.object({
600
+ created: z8.array(
601
+ z8.object({
602
+ ref: z8.string(),
603
+ task_id: IdSchema,
604
+ status: TaskStatusSchema
605
+ })
606
+ )
607
+ });
608
+ var LoadSkillInput = z8.object({
609
+ name: SkillNameSchema
610
+ });
611
+ var LoadSkillOutput = z8.object({
612
+ name: SkillNameSchema,
613
+ when_to_use: z8.string(),
614
+ content: z8.string()
615
+ });
616
+ var SaveRepoSkillInput = z8.object({
617
+ name: SkillNameSchema,
618
+ when_to_use: z8.string().min(1).max(SKILL_LIMITS.maxWhenToUseLength),
619
+ content: SkillContentSchema
620
+ });
621
+ var SaveRepoSkillOutput = z8.object({
622
+ path: z8.string(),
623
+ created: z8.boolean()
624
+ });
625
+ var EpicSummarySchema = z8.object({
626
+ id: IdSchema,
627
+ title: z8.string(),
628
+ description: z8.string().nullable(),
629
+ /** Jumlah task per status, mis. { DRAFT: 3, TODO: 1 }. */
630
+ task_counts: z8.record(z8.string(), z8.number().int().min(0))
631
+ });
632
+ var ListEpicsInput = z8.object({});
633
+ var ListEpicsOutput = z8.object({
634
+ epics: z8.array(EpicSummarySchema)
635
+ });
636
+ var CreateEpicToolInput = z8.object({
637
+ title: z8.string().trim().min(1).max(200),
638
+ description: z8.string().max(4e3).optional()
639
+ });
640
+ var CreateEpicToolOutput = z8.object({
641
+ epic: EpicSummarySchema
642
+ });
643
+ var ListPersonasInput = z8.object({});
644
+ var ListPersonasOutput = z8.object({
645
+ personas: z8.array(
646
+ PersonaSchema.extend({
647
+ /** "project" = khusus proyek ini (bisa diubah agen); "workspace" = global, hanya dari Web. */
648
+ scope: z8.enum(["project", "workspace"])
649
+ })
650
+ )
651
+ });
652
+ var UpsertPersonaInput = PersonaSchema.extend({
653
+ rules: z8.array(z8.string().trim().min(1).max(300)).max(30).default([])
654
+ });
655
+ var UpsertPersonaOutput = z8.object({
656
+ persona: PersonaSchema,
657
+ created: z8.boolean()
658
+ });
659
+ function tool(description, input, output) {
660
+ return { description, input, output };
661
+ }
662
+ var MCP_TOOLS = {
663
+ get_project_context: tool(
664
+ "Baca konteks proyek: identitas repo, aturan persona, indeks skill, dan handoff dependensi langsung.",
665
+ GetProjectContextInput,
666
+ GetProjectContextOutput
667
+ ),
668
+ get_ready_tasks: tool(
669
+ "Daftar ringkas task siap dikerjakan untuk repo ini (semua dependensi DONE).",
670
+ GetReadyTasksInput,
671
+ GetReadyTasksOutput
672
+ ),
673
+ claim_task: tool(
674
+ "Kunci task (lease 30 menit) dan ambil instruksi lengkap beserta handoff dependensinya.",
675
+ ClaimTaskInput,
676
+ ClaimTaskOutput
677
+ ),
678
+ complete_handoff: tool(
679
+ "Selesaikan task dengan ringkasan handoff terstruktur (DONE, atau NEEDS_REVIEW bila ada approval gate).",
680
+ CompleteHandoffInput,
681
+ CompleteHandoffOutput
682
+ ),
683
+ report_blocker: tool(
684
+ "Lepas lock dan tandai task BLOCKED dengan alasan spesifik bila tidak bisa dilanjutkan.",
685
+ ReportBlockerInput,
686
+ ReportBlockerOutput
687
+ ),
688
+ create_tasks: tool(
689
+ "Ajukan rencana task berdependensi untuk sebuah epic (masuk sebagai DRAFT untuk ditinjau manusia).",
690
+ CreateTasksInput,
691
+ CreateTasksOutput
692
+ ),
693
+ list_epics: tool(
694
+ "Daftar epic di proyek ini beserta jumlah task per status. Pakai epic_id-nya untuk create_tasks.",
695
+ ListEpicsInput,
696
+ ListEpicsOutput
697
+ ),
698
+ create_epic: tool(
699
+ "Buat epic baru di proyek ini (mis. 'Fitur login'), lalu pecah dengan create_tasks.",
700
+ CreateEpicToolInput,
701
+ CreateEpicToolOutput
702
+ ),
703
+ list_personas: tool(
704
+ "Daftar persona agen (alias, role, aturan) yang berlaku untuk proyek ini.",
705
+ ListPersonasInput,
706
+ ListPersonasOutput
707
+ ),
708
+ upsert_persona: tool(
709
+ "Buat atau perbarui persona khusus proyek ini (alias unik, role, aturan). Persona tingkat workspace hanya bisa diubah dari Web.",
710
+ UpsertPersonaInput,
711
+ UpsertPersonaOutput
712
+ ),
713
+ load_skill: tool(
714
+ "Muat isi lengkap skill repo dari .catenext/skills/<name>.md saat relevan dengan task aktif.",
715
+ LoadSkillInput,
716
+ LoadSkillOutput
717
+ ),
718
+ save_repo_skill: tool(
719
+ "Buat atau perbarui skill repo (maks. 500 kata, tanpa code dump) di .catenext/skills/<name>.md.",
720
+ SaveRepoSkillInput,
721
+ SaveRepoSkillOutput
722
+ )
723
+ };
724
+ var MCP_TOOL_NAMES = Object.keys(MCP_TOOLS);
725
+
726
+ // shared/src/quota.ts
727
+ import { z as z9 } from "zod";
728
+ var PLANS = ["free", "pro", "team"];
729
+ var PlanSchema = z9.enum(PLANS);
730
+ var QUOTA_DIMENSIONS = [
731
+ /** Jumlah proyek di workspace. */
732
+ "projects",
733
+ /** Epic yang belum semua task-nya DONE. */
734
+ "active_epics",
735
+ /** Task yang dibuat per bulan kalender (Web, CLI, dan create_tasks). */
736
+ "tasks_per_month",
737
+ /** Panggilan agen yang mengubah sesuatu: claim, complete, blocker, release, create_*, sync. */
738
+ "write_calls_per_month",
739
+ /** Panggilan baca agen: get_project_context, get_ready_tasks, list_*. Lebih longgar. */
740
+ "read_calls_per_month",
741
+ /** Persona di workspace (semua proyek). */
742
+ "personas",
743
+ /** Indeks skill per repo yang disinkronkan ke Cloud. */
744
+ "skills"
745
+ ];
746
+ var QuotaDimensionSchema = z9.enum(QUOTA_DIMENSIONS);
747
+ var QUOTA_WARNING_HEADER = "x-catenext-quota-warning";
748
+ var QuotaExceededDetailsSchema = z9.object({
749
+ dimension: QuotaDimensionSchema,
750
+ plan: PlanSchema,
751
+ limit: z9.number().int(),
752
+ used: z9.number().int(),
753
+ /** Kapan kuota bulanan direset; null untuk kuota jumlah (proyek, persona, ...). */
754
+ reset_at: IsoDateTimeSchema.nullable(),
755
+ upgrade_url: z9.string()
756
+ });
757
+ var UsageItemSchema = z9.object({
758
+ dimension: QuotaDimensionSchema,
759
+ label: z9.string(),
760
+ used: z9.number().int().min(0),
761
+ limit: z9.number().int().nullable()
762
+ });
763
+ var UsageOutput = z9.object({
764
+ plan: PlanSchema,
765
+ plans: z9.array(
766
+ z9.object({
767
+ plan: PlanSchema,
768
+ available: z9.boolean(),
769
+ limits: z9.record(z9.string(), z9.number().nullable())
770
+ })
771
+ ),
772
+ period_start: IsoDateTimeSchema,
773
+ reset_at: IsoDateTimeSchema,
774
+ retention_days: z9.number().int().nullable(),
775
+ usage: z9.array(UsageItemSchema)
776
+ });
777
+
778
+ // src/index.ts
779
+ import { Command } from "commander";
780
+
781
+ // src/api-client.ts
782
+ var ApiRequestError = class extends Error {
783
+ constructor(message, status, code, details) {
784
+ super(message);
785
+ this.status = status;
786
+ this.code = code;
787
+ this.details = details;
788
+ this.name = "ApiRequestError";
789
+ }
790
+ };
791
+ var AgentApi = class {
792
+ constructor(opts) {
793
+ this.opts = opts;
794
+ }
795
+ warning;
796
+ /** Ambil (dan hapus) peringatan kuota terakhir, untuk disisipkan ke hasil tool MCP. */
797
+ takeWarning() {
798
+ const w = this.warning;
799
+ this.warning = void 0;
800
+ return w;
801
+ }
802
+ post(path, body = {}) {
803
+ return this.request("POST", path, body);
804
+ }
805
+ put(path, body = {}) {
806
+ return this.request("PUT", path, body);
807
+ }
808
+ async request(method, path, body) {
809
+ const url = `${this.opts.baseUrl}/api/v1/agent/${path}`;
810
+ const doFetch = this.opts.fetch ?? fetch;
811
+ const agent = sanitizeAgentName(this.opts.agentName?.());
812
+ let res;
813
+ try {
814
+ res = await doFetch(url, {
815
+ method,
816
+ headers: {
817
+ "content-type": "application/json",
818
+ authorization: `Bearer ${this.opts.apiKey}`,
819
+ [AGENT_HEADERS.project]: this.opts.projectId,
820
+ [AGENT_HEADERS.repo]: this.opts.repoName,
821
+ [AGENT_HEADERS.agent]: agent
822
+ },
823
+ body: JSON.stringify(body),
824
+ signal: AbortSignal.timeout(this.opts.timeoutMs ?? 15e3)
825
+ });
826
+ } catch (err) {
827
+ throw new ApiRequestError(
828
+ `Tidak bisa menghubungi Catenext API di ${this.opts.baseUrl} (${err.message}). Pastikan API berjalan (pnpm dev) atau periksa api_url.`,
829
+ null,
830
+ "network_error"
831
+ );
832
+ }
833
+ const warning = res.headers.get(QUOTA_WARNING_HEADER);
834
+ if (warning) {
835
+ this.warning = warning;
836
+ this.opts.onWarning?.(warning);
837
+ }
838
+ const text2 = await res.text();
839
+ let json2;
840
+ try {
841
+ json2 = text2 ? JSON.parse(text2) : {};
842
+ } catch {
843
+ json2 = void 0;
844
+ }
845
+ if (!res.ok) {
846
+ const parsed = ApiErrorSchema.safeParse(json2);
847
+ if (parsed.success) {
848
+ throw new ApiRequestError(
849
+ parsed.data.error.message,
850
+ res.status,
851
+ parsed.data.error.code,
852
+ parsed.data.error.details
853
+ );
854
+ }
855
+ throw new ApiRequestError(
856
+ `Catenext API membalas HTTP ${res.status}. Periksa api_url (${this.opts.baseUrl}).`,
857
+ res.status,
858
+ "http_error"
859
+ );
860
+ }
861
+ if (json2 === void 0) {
862
+ throw new ApiRequestError(
863
+ `Respons Catenext API bukan JSON. Periksa api_url (${this.opts.baseUrl}).`,
864
+ res.status,
865
+ "bad_response"
866
+ );
867
+ }
868
+ return json2;
869
+ }
870
+ };
871
+ function sanitizeAgentName(name) {
872
+ const clean = (name ?? "").toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60);
873
+ return clean || "agent";
874
+ }
875
+
876
+ // src/config.ts
877
+ import { access, readFile } from "node:fs/promises";
878
+ import { dirname, join, resolve } from "node:path";
879
+ import { parse } from "yaml";
880
+ var CONFIG_PATH = join(".catenext", "config.yaml");
881
+ var ConfigError = class extends Error {
882
+ constructor(message) {
883
+ super(message);
884
+ this.name = "ConfigError";
885
+ }
886
+ };
887
+ function parseConfig(source) {
888
+ let raw;
889
+ try {
890
+ raw = parse(source);
891
+ } catch (err) {
892
+ throw new ConfigError(`.catenext/config.yaml bukan YAML yang valid: ${err.message}`);
893
+ }
894
+ const result = CatenextConfigSchema.safeParse(raw);
895
+ if (!result.success) {
896
+ const lines = result.error.issues.map(
897
+ (i) => ` - ${i.path.join(".") || "(root)"}: ${i.message}`
898
+ );
899
+ throw new ConfigError(
900
+ `.catenext/config.yaml tidak valid:
901
+ ${lines.join("\n")}
902
+ Perbaiki manual atau jalankan \`catenext init\` ulang.`
903
+ );
904
+ }
905
+ const compat = checkConfigCompatibility(result.data.schema_version);
906
+ if (!compat.ok) throw new ConfigError(compat.message);
907
+ return result.data;
908
+ }
909
+ async function readConfig(cwd = process.cwd()) {
910
+ let source;
911
+ try {
912
+ source = await readFile(join(cwd, CONFIG_PATH), "utf8");
913
+ } catch {
914
+ throw new ConfigError(
915
+ "Belum ada .catenext/config.yaml di folder ini. Jalankan `catenext init --project <project_id>` terlebih dahulu."
916
+ );
917
+ }
918
+ return parseConfig(source);
919
+ }
920
+ async function findProjectRoot(start = process.cwd()) {
921
+ let dir = resolve(start);
922
+ for (; ; ) {
923
+ try {
924
+ await access(join(dir, CONFIG_PATH));
925
+ return dir;
926
+ } catch {
927
+ const parent = dirname(dir);
928
+ if (parent === dir) return null;
929
+ dir = parent;
930
+ }
931
+ }
932
+ }
933
+
934
+ // src/credentials.ts
935
+ import { chmod, mkdir, readFile as readFile2, rename, writeFile } from "node:fs/promises";
936
+ import { homedir } from "node:os";
937
+ import { join as join2 } from "node:path";
938
+ import { z as z10 } from "zod";
939
+ function catenextHome() {
940
+ return process.env.CATENEXT_HOME ?? join2(homedir(), ".catenext");
941
+ }
942
+ function credentialsPath() {
943
+ return join2(catenextHome(), "credentials.json");
944
+ }
945
+ var PRODUCTION_API_URL = "https://catenext.mapan.digital";
946
+ var DEFAULT_API_URL = PRODUCTION_API_URL;
947
+ var CredentialsSchema = z10.object({
948
+ api_key: z10.string().startsWith(API_KEY_PREFIX),
949
+ api_url: z10.url().optional(),
950
+ saved_at: z10.string().optional()
951
+ });
952
+ var CredentialsError = class extends Error {
953
+ constructor(message) {
954
+ super(message);
955
+ this.name = "CredentialsError";
956
+ }
957
+ };
958
+ function validateApiKey(raw) {
959
+ const key = raw.trim();
960
+ if (!key.startsWith(API_KEY_PREFIX) || key.length < API_KEY_PREFIX.length + 16 || /\s/.test(key)) {
961
+ throw new CredentialsError(
962
+ `API key harus diawali "${API_KEY_PREFIX}" tanpa spasi. Salin ulang dari Dashboard > Security.`
963
+ );
964
+ }
965
+ return key;
966
+ }
967
+ async function saveCredentials(creds) {
968
+ const dir = catenextHome();
969
+ await mkdir(dir, { recursive: true, mode: 448 });
970
+ const data = { ...creds, saved_at: (/* @__PURE__ */ new Date()).toISOString() };
971
+ const target = credentialsPath();
972
+ const tmp = `${target}.${process.pid}.tmp`;
973
+ await writeFile(tmp, `${JSON.stringify(data, null, 2)}
974
+ `, { mode: 384 });
975
+ await rename(tmp, target);
976
+ await chmod(target, 384);
977
+ return target;
978
+ }
979
+ async function loadCredentials() {
980
+ const fromEnv = process.env.CATENEXT_API_KEY;
981
+ if (fromEnv) return { api_key: validateApiKey(fromEnv) };
982
+ let raw;
983
+ try {
984
+ raw = await readFile2(credentialsPath(), "utf8");
985
+ } catch {
986
+ throw new CredentialsError(
987
+ "Belum login. Jalankan `catenext login` lalu tempel API key dari Dashboard."
988
+ );
989
+ }
990
+ let json2;
991
+ try {
992
+ json2 = JSON.parse(raw);
993
+ } catch {
994
+ throw new CredentialsError(`${credentialsPath()} rusak. Jalankan \`catenext login\` ulang.`);
995
+ }
996
+ const parsed = CredentialsSchema.safeParse(json2);
997
+ if (!parsed.success) {
998
+ throw new CredentialsError(
999
+ `${credentialsPath()} tidak valid. Jalankan \`catenext login\` ulang.`
1000
+ );
1001
+ }
1002
+ return parsed.data;
1003
+ }
1004
+ function resolveApiUrl(configUrl, credsUrl) {
1005
+ return (process.env.CATENEXT_API_URL ?? configUrl ?? credsUrl ?? DEFAULT_API_URL).replace(
1006
+ /\/+$/,
1007
+ ""
1008
+ );
1009
+ }
1010
+
1011
+ // src/device-login.ts
1012
+ import { spawn } from "node:child_process";
1013
+ import {
1014
+ createDecipheriv,
1015
+ createHash,
1016
+ createPublicKey,
1017
+ diffieHellman,
1018
+ generateKeyPairSync
1019
+ } from "node:crypto";
1020
+ import { hostname } from "node:os";
1021
+ function newKeyPair() {
1022
+ const { publicKey, privateKey } = generateKeyPairSync("x25519");
1023
+ return {
1024
+ publicKey: publicKey.export({ format: "der", type: "spki" }).toString("base64url"),
1025
+ privateKey
1026
+ };
1027
+ }
1028
+ function decryptFromServer(blob, privateKey) {
1029
+ const [pub, iv, tag, data] = blob.split(".").map((p) => Buffer.from(p, "base64url"));
1030
+ if (!pub || !iv || !tag || !data) throw new Error("Balasan login rusak.");
1031
+ const serverKey = createPublicKey({ key: pub, format: "der", type: "spki" });
1032
+ const shared = diffieHellman({ privateKey, publicKey: serverKey });
1033
+ const decipher = createDecipheriv(
1034
+ "aes-256-gcm",
1035
+ createHash("sha256").update(shared).digest(),
1036
+ iv
1037
+ );
1038
+ decipher.setAuthTag(tag);
1039
+ return Buffer.concat([decipher.update(data), decipher.final()]).toString("utf8");
1040
+ }
1041
+ function openBrowser(url) {
1042
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
1043
+ const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
1044
+ try {
1045
+ const child = spawn(cmd, args, { stdio: "ignore", detached: true });
1046
+ child.on("error", () => {
1047
+ });
1048
+ child.unref();
1049
+ return true;
1050
+ } catch {
1051
+ return false;
1052
+ }
1053
+ }
1054
+ async function postJson(fetchImpl, url, body) {
1055
+ let res;
1056
+ try {
1057
+ res = await fetchImpl(url, {
1058
+ method: "POST",
1059
+ headers: { "content-type": "application/json" },
1060
+ body: JSON.stringify(body),
1061
+ signal: AbortSignal.timeout(15e3)
1062
+ });
1063
+ } catch (err) {
1064
+ throw new ApiRequestError(
1065
+ `Tidak bisa menghubungi Catenext API (${err.message}). Periksa --api-url.`,
1066
+ null,
1067
+ "network_error"
1068
+ );
1069
+ }
1070
+ const json2 = await res.json().catch(() => ({}));
1071
+ return { status: res.status, json: json2 };
1072
+ }
1073
+ async function deviceLogin(opts) {
1074
+ const fetchImpl = opts.fetch ?? fetch;
1075
+ const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
1076
+ const log = opts.log ?? ((l) => process.stderr.write(`${l}
1077
+ `));
1078
+ const keys = newKeyPair();
1079
+ const start = await postJson(fetchImpl, `${opts.apiUrl}/api/v1/cli-auth/code`, {
1080
+ client_name: `catenext CLI @ ${hostname()}`.slice(0, 80),
1081
+ public_key: keys.publicKey
1082
+ });
1083
+ const code = DeviceCodeOutput.safeParse(start.json);
1084
+ if (start.status !== 201 || !code.success) {
1085
+ throw new ApiRequestError(
1086
+ start.json.error?.message ?? `Server di ${opts.apiUrl} belum mendukung login lewat browser. Pakai \`catenext login --with-key\`.`,
1087
+ start.status,
1088
+ start.json.error?.code ?? "device_unsupported"
1089
+ );
1090
+ }
1091
+ const { user_code, verification_uri_complete, verification_uri, interval, expires_in } = code.data;
1092
+ log(`Buka ${verification_uri_complete}`);
1093
+ log(`lalu pastikan kodenya sama: ${user_code} (berlaku ${Math.round(expires_in / 60)} menit)`);
1094
+ if (opts.browser && openBrowser(verification_uri_complete)) {
1095
+ log("Browser dibuka. Menunggu persetujuan...");
1096
+ } else {
1097
+ log(`(Tidak membuka browser. Buka ${verification_uri} di perangkat mana pun.)`);
1098
+ }
1099
+ const deadline = Date.now() + expires_in * 1e3;
1100
+ while (Date.now() < deadline) {
1101
+ await sleep(interval * 1e3);
1102
+ const poll = await postJson(fetchImpl, `${opts.apiUrl}/api/v1/cli-auth/token`, {
1103
+ device_code: code.data.device_code
1104
+ });
1105
+ if (poll.status === 200) {
1106
+ const token = DeviceTokenOutput.safeParse(poll.json);
1107
+ if (!token.success)
1108
+ throw new ApiRequestError("Balasan login tidak valid.", 200, "bad_response");
1109
+ return decryptFromServer(token.data.encrypted_key, keys.privateKey);
1110
+ }
1111
+ const errCode = poll.json.error?.code;
1112
+ if (errCode === "authorization_pending") continue;
1113
+ throw new ApiRequestError(
1114
+ poll.json.error?.message ?? `Login gagal (HTTP ${poll.status}).`,
1115
+ poll.status,
1116
+ errCode ?? "device_error"
1117
+ );
1118
+ }
1119
+ throw new ApiRequestError(
1120
+ "Kode login kedaluwarsa. Jalankan `catenext login` lagi.",
1121
+ 410,
1122
+ "expired_token"
1123
+ );
1124
+ }
1125
+
1126
+ // src/fallback.ts
1127
+ import { execFile } from "node:child_process";
1128
+ import { promisify } from "node:util";
1129
+
1130
+ // src/planning.ts
1131
+ import { readFile as readFile3 } from "node:fs/promises";
1132
+
1133
+ // src/scrubber.ts
1134
+ var redact = (kind) => `[REDACTED:${kind}]`;
1135
+ var RULES = [
1136
+ {
1137
+ kind: "private_key",
1138
+ pattern: /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY-----|$)/g
1139
+ },
1140
+ { kind: "catenext_key", pattern: /\bctnx_[A-Za-z0-9_-]{8,}/g },
1141
+ { kind: "aws_key", pattern: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g },
1142
+ {
1143
+ kind: "github_token",
1144
+ pattern: /\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})/g
1145
+ },
1146
+ { kind: "slack_token", pattern: /\bxox[abposr]-[A-Za-z0-9-]{10,}/g },
1147
+ { kind: "stripe_key", pattern: /\b[sr]k_(?:live|test)_[A-Za-z0-9]{10,}/g },
1148
+ { kind: "llm_api_key", pattern: /\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}/g },
1149
+ { kind: "google_api_key", pattern: /\bAIza[0-9A-Za-z_-]{35}/g },
1150
+ { kind: "jwt", pattern: /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g },
1151
+ {
1152
+ kind: "url_password",
1153
+ pattern: /\b([a-z][a-z0-9+.-]*:\/\/[^\s:/@]+:)([^\s@/]+)(@)/gi,
1154
+ replace: (_m, pre, _pw, at) => `${pre}${redact("url_password")}${at}`
1155
+ },
1156
+ {
1157
+ kind: "bearer_token",
1158
+ pattern: /\b(Bearer\s+)([A-Za-z0-9._~+/=-]{16,})/gi,
1159
+ replace: (_m, pre) => `${pre}${redact("bearer_token")}`
1160
+ },
1161
+ {
1162
+ // KEY=value / password: value. Nilai dianggap secret bila >= 12 karakter, atau
1163
+ // >= 6 karakter dan mengandung angka/simbol (agar prosa biasa tidak ikut tersensor).
1164
+ kind: "assignment",
1165
+ pattern: /\b([A-Za-z0-9_.-]*(?:secret|token|passw(?:or)?d|pwd|api[_-]?key|access[_-]?key|private[_-]?key|credentials?|auth)[A-Za-z0-9_.-]*)(\s*[:=]\s*["']?)([^\s"'`,;]*[^\s"'`,;.)])/gi,
1166
+ replace: (m, name, sep, value) => {
1167
+ if (value.startsWith("[REDACTED:")) return m;
1168
+ const looksSecret = value.length >= 12 || value.length >= 6 && /[0-9\W_]/.test(value);
1169
+ return looksSecret ? `${name}${sep}${redact("assignment")}` : m;
1170
+ }
1171
+ }
1172
+ ];
1173
+ function scrubText(text2, counts2 = {}) {
1174
+ let out = text2;
1175
+ for (const rule of RULES) {
1176
+ out = out.replace(rule.pattern, (...args) => {
1177
+ const match = args[0];
1178
+ const groups = args.slice(1, -2);
1179
+ const replaced = rule.replace ? rule.replace(match, ...groups) : redact(rule.kind);
1180
+ if (replaced !== match) counts2[rule.kind] = (counts2[rule.kind] ?? 0) + 1;
1181
+ return replaced;
1182
+ });
1183
+ }
1184
+ return out;
1185
+ }
1186
+ function scrubDeep(value, skipKeys = /* @__PURE__ */ new Set()) {
1187
+ const counts2 = {};
1188
+ const walk = (v, key) => {
1189
+ if (typeof v === "string") return key && skipKeys.has(key) ? v : scrubText(v, counts2);
1190
+ if (Array.isArray(v)) return v.map((item) => walk(item, key));
1191
+ if (v && typeof v === "object") {
1192
+ return Object.fromEntries(Object.entries(v).map(([k, inner]) => [k, walk(inner, k)]));
1193
+ }
1194
+ return v;
1195
+ };
1196
+ const scrubbed = walk(value);
1197
+ const total = Object.values(counts2).reduce((a, b) => a + b, 0);
1198
+ return { value: scrubbed, redactions: counts2, total };
1199
+ }
1200
+ function describeRedactions(r) {
1201
+ const parts = Object.entries(r.redactions).map(([k, n]) => `${k}\xD7${n}`);
1202
+ return `secret-scrubber lokal menyensor ${r.total} potensi secret (${parts.join(", ")}) sebelum dikirim ke Catenext Cloud.`;
1203
+ }
1204
+
1205
+ // src/planning.ts
1206
+ var PlanningInputError = class extends Error {
1207
+ constructor(message) {
1208
+ super(message);
1209
+ this.name = "PlanningInputError";
1210
+ }
1211
+ };
1212
+ async function cliApi(agentName = "catenext-cli") {
1213
+ const root = await findProjectRoot();
1214
+ if (!root) {
1215
+ throw new ConfigError(
1216
+ "Tidak ada .catenext/config.yaml di folder ini atau induknya. Jalankan `catenext init --project <project_id>` dulu."
1217
+ );
1218
+ }
1219
+ const config = await readConfig(root);
1220
+ const creds = await loadCredentials();
1221
+ return new AgentApi({
1222
+ baseUrl: resolveApiUrl(config.api_url, creds.api_url),
1223
+ apiKey: creds.api_key,
1224
+ projectId: config.project_id,
1225
+ repoName: config.repo_name,
1226
+ agentName: () => agentName,
1227
+ onWarning: (m) => console.error(`! Kuota: ${m}`)
1228
+ });
1229
+ }
1230
+ function prepare(schema, input, keep) {
1231
+ const scrubbed = scrubDeep(input, new Set(keep));
1232
+ if (scrubbed.total > 0) console.error(`! ${describeRedactions(scrubbed)}`);
1233
+ const parsed = schema.safeParse(scrubbed.value);
1234
+ if (!parsed.success) {
1235
+ const lines = parsed.error.issues.map(
1236
+ (i) => ` - ${i.path.join(".") || "(root)"}: ${i.message}`
1237
+ );
1238
+ throw new PlanningInputError(`Input tidak valid:
1239
+ ${lines.join("\n")}`);
1240
+ }
1241
+ return parsed.data;
1242
+ }
1243
+ var counts = (c) => Object.entries(c).map(([status, n]) => `${n} ${status}`).join(", ") || "belum ada task";
1244
+ async function epicList(api, asJson) {
1245
+ const res = await api.post("epics/list");
1246
+ if (asJson) return console.log(JSON.stringify(res, null, 2));
1247
+ if (res.epics.length === 0) {
1248
+ return console.log('Belum ada epic. Buat dengan: catenext epic create "<judul>"');
1249
+ }
1250
+ for (const e of res.epics) console.log(`${e.id} ${e.title} (${counts(e.task_counts)})`);
1251
+ }
1252
+ async function epicCreate(api, title, description, asJson) {
1253
+ const body = prepare(CreateEpicToolInput, { title, description }, []);
1254
+ const res = await api.post("epics", body);
1255
+ if (asJson) return console.log(JSON.stringify(res, null, 2));
1256
+ console.log(`\u2713 Epic "${res.epic.title}" dibuat: ${res.epic.id}`);
1257
+ console.log(` Lanjut: catenext task create --epic ${res.epic.id} --file rencana.json`);
1258
+ }
1259
+ async function readJsonInput(file) {
1260
+ let raw;
1261
+ try {
1262
+ raw = file === "-" ? await new Promise((res, rej) => {
1263
+ let data = "";
1264
+ process.stdin.setEncoding("utf8");
1265
+ process.stdin.on("data", (c) => {
1266
+ data += c;
1267
+ });
1268
+ process.stdin.on("end", () => res(data));
1269
+ process.stdin.on("error", rej);
1270
+ }) : await readFile3(file, "utf8");
1271
+ } catch (err) {
1272
+ throw new PlanningInputError(`Tidak bisa membaca ${file}: ${err.message}`);
1273
+ }
1274
+ try {
1275
+ return JSON.parse(raw);
1276
+ } catch {
1277
+ throw new PlanningInputError(`${file} bukan JSON yang valid.`);
1278
+ }
1279
+ }
1280
+ async function taskCreate(api, epicId, file, asJson) {
1281
+ const plan = await readJsonInput(file);
1282
+ const tasks = Array.isArray(plan) ? plan : plan?.tasks;
1283
+ const body = prepare(CreateTasksInput, { epic_id: epicId, tasks }, [
1284
+ "epic_id",
1285
+ "ref",
1286
+ "depends_on",
1287
+ "target_repo",
1288
+ "role"
1289
+ ]);
1290
+ const res = await api.post("tasks", body);
1291
+ if (asJson) return console.log(JSON.stringify(res, null, 2));
1292
+ for (const t of res.created) console.log(`+ ${t.ref.padEnd(16)} ${t.task_id} ${t.status}`);
1293
+ console.log(
1294
+ `
1295
+ \u2713 ${res.created.length} task diajukan sebagai DRAFT. Tinjau & setujui rencananya di Web sebelum agen bisa mengambilnya.`
1296
+ );
1297
+ }
1298
+ async function personaList(api, asJson) {
1299
+ const res = await api.post("personas/list");
1300
+ if (asJson) return console.log(JSON.stringify(res, null, 2));
1301
+ if (res.personas.length === 0) {
1302
+ return console.log(
1303
+ 'Belum ada persona. Buat dengan: catenext persona set <alias> --role <role> --rule "..."'
1304
+ );
1305
+ }
1306
+ for (const p of res.personas) {
1307
+ console.log(`${p.alias} (${p.role}, ${p.scope === "project" ? "proyek" : "workspace"})`);
1308
+ for (const r of p.rules) console.log(` - ${r}`);
1309
+ }
1310
+ }
1311
+ async function personaSet(api, alias, role, rules, asJson) {
1312
+ const body = prepare(UpsertPersonaInput, { alias, role, rules }, ["alias", "role"]);
1313
+ const res = await api.put("personas", body);
1314
+ if (asJson) return console.log(JSON.stringify(res, null, 2));
1315
+ console.log(
1316
+ `\u2713 Persona "${res.persona.alias}" (${res.persona.role}) ${res.created ? "dibuat" : "diperbarui"} untuk proyek ini, ${res.persona.rules.length} aturan.`
1317
+ );
1318
+ }
1319
+
1320
+ // src/fallback.ts
1321
+ var exec = promisify(execFile);
1322
+ async function git(args, cwd) {
1323
+ try {
1324
+ const { stdout } = await exec("git", args, { cwd });
1325
+ return stdout.trim();
1326
+ } catch {
1327
+ return null;
1328
+ }
1329
+ }
1330
+ async function readGitState(cwd = process.cwd()) {
1331
+ const branch = await git(["rev-parse", "--abbrev-ref", "HEAD"], cwd);
1332
+ const commit = await git(["rev-parse", "HEAD"], cwd);
1333
+ const lastCommit = await git(["show", "--name-only", "--format=", "HEAD"], cwd) ?? "";
1334
+ const dirty = await git(["diff", "--name-only", "HEAD"], cwd) ?? "";
1335
+ const changedFiles = [
1336
+ ...new Set([...dirty.split("\n"), ...lastCommit.split("\n")].filter(Boolean))
1337
+ ];
1338
+ return { branch, commit, changedFiles };
1339
+ }
1340
+ async function taskNext(api, opts) {
1341
+ const res = await api.post("ready-tasks", {
1342
+ limit: opts.limit ?? 10
1343
+ });
1344
+ if (opts.json) return console.log(JSON.stringify(res, null, 2));
1345
+ if (res.tasks.length === 0) {
1346
+ return console.log(
1347
+ "Tidak ada task siap untuk repo ini. Cek Dashboard untuk task DRAFT/BLOCKED."
1348
+ );
1349
+ }
1350
+ for (const t of res.tasks) {
1351
+ const tags = [t.role, t.revision ? "revisi" : null].filter(Boolean).join(", ");
1352
+ console.log(`${t.id} ${t.title}${tags ? ` [${tags}]` : ""}`);
1353
+ }
1354
+ console.log(`
1355
+ Ambil satu: catenext claim ${res.tasks[0]?.id}`);
1356
+ }
1357
+ function renderClaim(res) {
1358
+ const out = [];
1359
+ out.push(`# Task: ${res.task.title}`, "");
1360
+ out.push(`- ID: ${res.task.id}`);
1361
+ out.push(`- Lease sampai: ${res.lease_expires_at} (diperpanjang setiap perintah catenext)`);
1362
+ if (res.task.role) out.push(`- Role: ${res.task.role}`);
1363
+ if (res.task.revision_count > 0) out.push(`- Revisi ke-${res.task.revision_count}`);
1364
+ out.push("", "## Instruksi", "", res.task.prompt_instruction.trim(), "");
1365
+ if (res.revision) {
1366
+ out.push("## Feedback revisi dari reviewer", "", res.revision.review_feedback.trim(), "");
1367
+ }
1368
+ if (res.dependencies.length > 0) {
1369
+ out.push("## Handoff dari task dependensi", "");
1370
+ for (const d of res.dependencies) {
1371
+ const h = d.handoff_summary;
1372
+ out.push(`### ${d.title}`, "");
1373
+ out.push(`- Branch/commit: ${h.git_branch} @ ${h.last_commit_hash}`);
1374
+ if (h.files_modified.length) out.push(`- File: ${h.files_modified.join(", ")}`);
1375
+ for (const k of h.key_decisions) out.push(`- Keputusan: ${k}`);
1376
+ if (h.verification_command) out.push(`- Verifikasi: \`${h.verification_command}\``);
1377
+ out.push(`- Catatan: ${h.notes_for_next_agent}`, "");
1378
+ }
1379
+ }
1380
+ for (const w of res.warnings) out.push(`! ${w}`);
1381
+ out.push(
1382
+ "## Setelah selesai",
1383
+ "",
1384
+ `catenext done ${res.task.id} --notes "<ringkasan untuk agen berikutnya>" --verify "<perintah tes>"`,
1385
+ `Bila buntu: catenext block ${res.task.id} --category <kategori> --reason "<alasan spesifik>"`
1386
+ );
1387
+ return out.join("\n");
1388
+ }
1389
+ async function taskClaim(api, taskId, opts) {
1390
+ const res = await api.post("claim", { task_id: taskId });
1391
+ if (opts.json) return console.log(JSON.stringify(res, null, 2));
1392
+ console.log(renderClaim(res));
1393
+ }
1394
+ function buildHandoff(opts, gitState) {
1395
+ if (!opts.notes) {
1396
+ throw new PlanningInputError(
1397
+ "--notes wajib: tulis ringkasan untuk agen berikutnya (atau pakai --handoff <file.json>)."
1398
+ );
1399
+ }
1400
+ if (!gitState.branch || !gitState.commit) {
1401
+ throw new PlanningInputError(
1402
+ "Tidak bisa membaca branch/commit git. Jalankan di dalam repo git dan commit pekerjaan Anda dulu."
1403
+ );
1404
+ }
1405
+ const files = opts.file.length ? opts.file : gitState.changedFiles;
1406
+ return {
1407
+ files_modified: files.slice(0, HANDOFF_LIMITS.maxFilesModified),
1408
+ key_decisions: opts.decision,
1409
+ verification_command: opts.verify ?? null,
1410
+ notes_for_next_agent: opts.notes,
1411
+ git_branch: gitState.branch,
1412
+ last_commit_hash: gitState.commit
1413
+ };
1414
+ }
1415
+ async function taskDone(api, taskId, opts) {
1416
+ const summary = opts.handoff ? await readJsonInput(opts.handoff) : buildHandoff(opts, await readGitState());
1417
+ const body = prepare(CompleteHandoffInput, { task_id: taskId, handoff_summary: summary }, [
1418
+ "task_id",
1419
+ "last_commit_hash"
1420
+ ]);
1421
+ const res = await api.post("complete", body);
1422
+ if (opts.json) return console.log(JSON.stringify(res, null, 2));
1423
+ console.log(
1424
+ res.status === "DONE" ? `\u2713 Task selesai (DONE). ${res.unlocked_task_ids.length} task hilir terbuka.` : "\u2713 Handoff terkirim, menunggu review manusia (NEEDS_REVIEW)."
1425
+ );
1426
+ console.log(` ${res.next_step_hint}`);
1427
+ }
1428
+ async function taskBlock(api, taskId, opts) {
1429
+ const body = prepare(
1430
+ ReportBlockerInput,
1431
+ { task_id: taskId, category: opts.category, reason: opts.reason },
1432
+ ["task_id", "category"]
1433
+ );
1434
+ const res = await api.post("blocker", body);
1435
+ if (opts.json) return console.log(JSON.stringify(res, null, 2));
1436
+ console.log("\u2713 Task ditandai BLOCKED dan lock dilepas. Manusia akan meninjau di Dashboard.");
1437
+ }
1438
+
1439
+ // src/init/index.ts
1440
+ import { mkdir as mkdir2, readFile as readFile5, rename as rename2, writeFile as writeFile2 } from "node:fs/promises";
1441
+ import { basename, dirname as dirname2, join as join4, resolve as resolve2 } from "node:path";
1442
+ import { createTwoFilesPatch } from "diff";
1443
+
1444
+ // src/init/agents-md.ts
1445
+ var AGENTS_MD = "AGENTS.md";
1446
+ var BLOCK_START = "<!-- catenext:start -->";
1447
+ var BLOCK_END = "<!-- catenext:end -->";
1448
+ function renderAgentsBlock() {
1449
+ return [
1450
+ BLOCK_START,
1451
+ "## Catenext: estafet task antar-agen",
1452
+ "",
1453
+ "Repo ini memakai Catenext. Bila Anda punya tool MCP `catenext`, pakai tool itu",
1454
+ "(`get_project_context` -> `get_ready_tasks` -> `claim_task` -> `complete_handoff`).",
1455
+ "Bila tidak, pakai CLI berikut:",
1456
+ "",
1457
+ "1. `catenext next`: lihat task yang siap untuk repo ini.",
1458
+ "2. `catenext claim <task_id>`: kunci task dan baca instruksi + handoff dependensinya.",
1459
+ "3. Kerjakan, jalankan tes, lalu commit.",
1460
+ '4. `catenext done <task_id> --notes "<ringkasan>" --verify "<perintah tes>" [--decision "..."]`',
1461
+ '5. Bila buntu: `catenext block <task_id> --category <missing_env|ambiguous_requirement|failing_tests|dependency_issue|other> --reason "..."`',
1462
+ "",
1463
+ "Aturan: satu task per sesi; jangan menyalin kode atau secret ke handoff (rujuk path file);",
1464
+ "jangan mengedit `.catenext/config.yaml`. Skill repo ada di `.catenext/skills/`.",
1465
+ BLOCK_END
1466
+ ].join("\n");
1467
+ }
1468
+ var BLOCK_RE = new RegExp(`${BLOCK_START}[\\s\\S]*?${BLOCK_END}`);
1469
+ function upsertAgentsBlock(source) {
1470
+ const block = renderAgentsBlock();
1471
+ if (source === null || source.trim() === "") return `# AGENTS.md
1472
+
1473
+ ${block}
1474
+ `;
1475
+ const eol = source.includes("\r\n") ? "\r\n" : "\n";
1476
+ const normalized = eol === "\n" ? block : block.replace(/\n/g, eol);
1477
+ if (BLOCK_RE.test(source)) return source.replace(BLOCK_RE, normalized);
1478
+ const sep = source.endsWith(`${eol}${eol}`) ? "" : source.endsWith(eol) ? eol : `${eol}${eol}`;
1479
+ return `${source}${sep}${normalized}${eol}`;
1480
+ }
1481
+ function removeAgentsBlock(source) {
1482
+ if (!BLOCK_RE.test(source)) return source;
1483
+ const out = source.replace(new RegExp(`(\\r?\\n)*${BLOCK_RE.source}(\\r?\\n)?`), "\n");
1484
+ const rest = out.trim();
1485
+ if (rest === "" || rest === "# AGENTS.md") return null;
1486
+ return `${out.replace(/\s+$/, "")}
1487
+ `;
1488
+ }
1489
+
1490
+ // src/init/config-file.ts
1491
+ import { parseDocument } from "yaml";
1492
+ function renderNewConfig(f) {
1493
+ const lines = [
1494
+ "# Identitas repo ini di Catenext. File milik manusia: agen tidak boleh mengubahnya.",
1495
+ "# Aman di-commit (tidak berisi secret). API key ada di ~/.catenext/credentials.json.",
1496
+ `schema_version: ${CONFIG_SCHEMA_VERSION}`,
1497
+ `project_id: ${f.project_id}`,
1498
+ `repo_name: ${f.repo_name}`,
1499
+ `stack: [${f.stack.join(", ")}]`
1500
+ ];
1501
+ if (f.api_url) lines.push(`api_url: ${f.api_url}`);
1502
+ lines.push(
1503
+ "# overrides:",
1504
+ "# default_agent_alias: adel",
1505
+ "# default_role: backend",
1506
+ "# extra_rules: []"
1507
+ );
1508
+ const out = `${lines.join("\n")}
1509
+ `;
1510
+ parseConfig(out);
1511
+ return out;
1512
+ }
1513
+ function updateConfig(source, changes) {
1514
+ const doc = parseDocument(source);
1515
+ for (const [key, value] of Object.entries(changes)) {
1516
+ if (value === void 0) continue;
1517
+ if (JSON.stringify(doc.get(key)) === JSON.stringify(value)) continue;
1518
+ doc.set(key, value);
1519
+ }
1520
+ const out = doc.toString();
1521
+ if (out === parseDocument(source).toString()) return source;
1522
+ parseConfig(out);
1523
+ return out;
1524
+ }
1525
+
1526
+ // src/init/detect.ts
1527
+ import { readFile as readFile4 } from "node:fs/promises";
1528
+ import { join as join3 } from "node:path";
1529
+ var exists = async (p) => readFile4(p, "utf8").then(
1530
+ (s) => s,
1531
+ () => null
1532
+ );
1533
+ async function detectStack(root) {
1534
+ const stack = /* @__PURE__ */ new Set();
1535
+ const goMod = await exists(join3(root, "go.mod"));
1536
+ if (goMod !== null) stack.add("go");
1537
+ const pkg = await exists(join3(root, "package.json"));
1538
+ if (pkg !== null) {
1539
+ stack.add("node");
1540
+ try {
1541
+ const json2 = JSON.parse(pkg);
1542
+ const deps = { ...json2.dependencies, ...json2.devDependencies };
1543
+ const known = {
1544
+ typescript: "typescript",
1545
+ next: "nextjs",
1546
+ react: "react",
1547
+ vue: "vue",
1548
+ svelte: "svelte",
1549
+ hono: "hono",
1550
+ express: "express",
1551
+ "@nestjs/core": "nestjs",
1552
+ "drizzle-orm": "drizzle",
1553
+ prisma: "prisma"
1554
+ };
1555
+ for (const [dep, label] of Object.entries(known)) if (deps[dep]) stack.add(label);
1556
+ } catch {
1557
+ }
1558
+ }
1559
+ const composer = await exists(join3(root, "composer.json"));
1560
+ if (composer !== null) {
1561
+ stack.add("php");
1562
+ if (composer.includes('"laravel/framework"')) stack.add("laravel");
1563
+ }
1564
+ if (await exists(join3(root, "pyproject.toml")) !== null) stack.add("python");
1565
+ else if (await exists(join3(root, "requirements.txt")) !== null) stack.add("python");
1566
+ if (await exists(join3(root, "Cargo.toml")) !== null) stack.add("rust");
1567
+ return [...stack].slice(0, 20);
1568
+ }
1569
+
1570
+ // src/init/gitignore.ts
1571
+ var CACHE_IGNORE = ".catenext/cache.json";
1572
+ var COVERS = /* @__PURE__ */ new Set([
1573
+ CACHE_IGNORE,
1574
+ `/${CACHE_IGNORE}`,
1575
+ ".catenext/cache.json",
1576
+ ".catenext/*.json"
1577
+ ]);
1578
+ function ensureGitignore(source) {
1579
+ const text2 = source ?? "";
1580
+ const lines = text2.split(/\r?\n/).map((l) => l.trim());
1581
+ if (lines.some((l) => COVERS.has(l))) return text2;
1582
+ const eol = text2.includes("\r\n") ? "\r\n" : "\n";
1583
+ const prefix = text2 === "" ? "" : text2.endsWith("\n") ? eol : `${eol}${eol}`;
1584
+ return `${text2}${prefix}# Catenext: cache lokal, jangan di-commit${eol}${CACHE_IGNORE}${eol}`;
1585
+ }
1586
+
1587
+ // src/init/mcp-config.ts
1588
+ import { applyEdits, modify, parse as parse2 } from "jsonc-parser";
1589
+ var MCP_SERVER_KEY = "catenext";
1590
+ var CURSOR_WORKSPACE_FOLDER = "${workspaceFolder}";
1591
+ var ADAPTERS = [
1592
+ { id: "claude-code", label: "Claude Code", path: ".mcp.json", extraArgs: [] },
1593
+ {
1594
+ id: "cursor",
1595
+ label: "Cursor",
1596
+ path: ".cursor/mcp.json",
1597
+ // Cursor mengganti variabel ini dengan root workspace saat menjalankan server.
1598
+ extraArgs: ["--root", CURSOR_WORKSPACE_FOLDER]
1599
+ }
1600
+ ];
1601
+ var McpConfigError = class extends Error {
1602
+ constructor(message) {
1603
+ super(message);
1604
+ this.name = "McpConfigError";
1605
+ }
1606
+ };
1607
+ function detectFormatting(source) {
1608
+ const indent = /^([ \t]+)\S/m.exec(source)?.[1];
1609
+ return {
1610
+ insertSpaces: !indent?.startsWith(" "),
1611
+ tabSize: indent && !indent.startsWith(" ") ? indent.length : 2,
1612
+ eol: source.includes("\r\n") ? "\r\n" : "\n"
1613
+ };
1614
+ }
1615
+ function upsertMcpEntry(source, entry, file) {
1616
+ const base = source && source.trim() !== "" ? source : "{}\n";
1617
+ const errors = [];
1618
+ const doc = parse2(base, errors, { allowTrailingComma: true, disallowComments: false });
1619
+ if (errors.length > 0 || doc === null || typeof doc !== "object" || Array.isArray(doc)) {
1620
+ throw new McpConfigError(
1621
+ `${file} bukan JSON/JSONC objek yang valid, jadi tidak disentuh. Perbaiki manual lalu jalankan ulang \`catenext init\`.`
1622
+ );
1623
+ }
1624
+ const servers = doc.mcpServers;
1625
+ if (servers !== void 0 && (servers === null || typeof servers !== "object" || Array.isArray(servers))) {
1626
+ throw new McpConfigError(`${file}: "mcpServers" harus berupa objek. Perbaiki manual dulu.`);
1627
+ }
1628
+ const current = servers?.[MCP_SERVER_KEY];
1629
+ if (current !== void 0 && JSON.stringify(current) === JSON.stringify(entry)) return base;
1630
+ const edits = modify(base, ["mcpServers", MCP_SERVER_KEY], entry, {
1631
+ formattingOptions: detectFormatting(base)
1632
+ });
1633
+ let out = applyEdits(base, edits);
1634
+ if (!out.endsWith("\n")) out += "\n";
1635
+ return out;
1636
+ }
1637
+ function readMcpEntry(source) {
1638
+ const errors = [];
1639
+ const doc = parse2(source, errors, { allowTrailingComma: true });
1640
+ if (errors.length > 0) return null;
1641
+ const entry = doc?.mcpServers?.[MCP_SERVER_KEY];
1642
+ return entry && typeof entry.command === "string" && Array.isArray(entry.args) ? entry : null;
1643
+ }
1644
+
1645
+ // src/init/index.ts
1646
+ var readOrNull = (p) => readFile5(p, "utf8").then(
1647
+ (s) => s,
1648
+ () => null
1649
+ );
1650
+ function slugifyRepoName(name) {
1651
+ return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 64) || "repo";
1652
+ }
1653
+ async function planInit(opts) {
1654
+ const root = resolve2(opts.root);
1655
+ if (opts.projectId !== void 0 && !IdSchema.safeParse(opts.projectId).success) {
1656
+ throw new ConfigError("--project harus UUID project_id dari Dashboard.");
1657
+ }
1658
+ if (opts.repoName !== void 0 && !RepoNameSchema.safeParse(opts.repoName).success) {
1659
+ throw new ConfigError(
1660
+ "--repo harus slug huruf kecil (a-z, 0-9, '-' atau '_'), mis. backend atau frontend."
1661
+ );
1662
+ }
1663
+ const changes = [];
1664
+ const configBefore = await readOrNull(join4(root, CONFIG_PATH));
1665
+ let configAfter;
1666
+ if (configBefore === null) {
1667
+ if (!opts.projectId) {
1668
+ throw new ConfigError(
1669
+ "Belum ada .catenext/config.yaml. Buat proyek di Dashboard lalu jalankan: catenext init --project <project_id>"
1670
+ );
1671
+ }
1672
+ configAfter = renderNewConfig({
1673
+ project_id: opts.projectId,
1674
+ repo_name: opts.repoName ?? slugifyRepoName(basename(root)),
1675
+ stack: await detectStack(root),
1676
+ ...opts.apiUrl ? { api_url: opts.apiUrl } : {}
1677
+ });
1678
+ } else {
1679
+ parseConfig(configBefore);
1680
+ configAfter = updateConfig(configBefore, {
1681
+ project_id: opts.projectId,
1682
+ repo_name: opts.repoName,
1683
+ api_url: opts.apiUrl
1684
+ });
1685
+ }
1686
+ changes.push({ path: CONFIG_PATH, before: configBefore, after: configAfter });
1687
+ for (const adapter of ADAPTERS) {
1688
+ const before = await readOrNull(join4(root, adapter.path));
1689
+ const entry = {
1690
+ command: opts.mcpCommand.command,
1691
+ args: [...opts.mcpCommand.args, "mcp", ...adapter.extraArgs]
1692
+ };
1693
+ changes.push({
1694
+ path: adapter.path,
1695
+ before,
1696
+ after: upsertMcpEntry(before, entry, adapter.path)
1697
+ });
1698
+ }
1699
+ const gitignoreBefore = await readOrNull(join4(root, ".gitignore"));
1700
+ changes.push({
1701
+ path: ".gitignore",
1702
+ before: gitignoreBefore,
1703
+ after: ensureGitignore(gitignoreBefore)
1704
+ });
1705
+ if (opts.agentsMd !== false) {
1706
+ const before = await readOrNull(join4(root, AGENTS_MD));
1707
+ changes.push({ path: AGENTS_MD, before, after: upsertAgentsBlock(before) });
1708
+ }
1709
+ return changes.filter((c) => c.before !== c.after);
1710
+ }
1711
+ function renderDiff(changes) {
1712
+ return changes.map(
1713
+ (c) => createTwoFilesPatch(
1714
+ c.before === null ? "/dev/null" : `a/${c.path}`,
1715
+ `b/${c.path}`,
1716
+ c.before ?? "",
1717
+ c.after,
1718
+ void 0,
1719
+ void 0,
1720
+ { context: 3 }
1721
+ )
1722
+ ).join("\n");
1723
+ }
1724
+ async function applyInit(root, changes) {
1725
+ for (const c of changes) {
1726
+ const target = join4(resolve2(root), c.path);
1727
+ await mkdir2(dirname2(target), { recursive: true });
1728
+ const tmp = `${target}.catenext-${process.pid}.tmp`;
1729
+ await writeFile2(tmp, c.after);
1730
+ await rename2(tmp, target);
1731
+ }
1732
+ }
1733
+
1734
+ // src/maintenance.ts
1735
+ import { existsSync } from "node:fs";
1736
+ import { copyFile, mkdir as mkdir4, readFile as readFile7, rename as rename4, rm, rmdir, writeFile as writeFile4 } from "node:fs/promises";
1737
+ import { dirname as dirname3, isAbsolute, join as join6, resolve as resolve3 } from "node:path";
1738
+ import { applyEdits as applyEdits2, modify as modify2, parse as parse4, visit } from "jsonc-parser";
1739
+
1740
+ // src/skills.ts
1741
+ import { mkdir as mkdir3, readdir, readFile as readFile6, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
1742
+ import { join as join5 } from "node:path";
1743
+ import { parse as parse3, stringify } from "yaml";
1744
+ var SKILLS_DIR = join5(".catenext", "skills");
1745
+ var SkillError = class extends Error {
1746
+ constructor(message) {
1747
+ super(message);
1748
+ this.name = "SkillError";
1749
+ }
1750
+ };
1751
+ var FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;
1752
+ function parseSkill(source, fileName) {
1753
+ const m = FRONTMATTER.exec(source);
1754
+ if (!m) throw new SkillError(`${fileName}: tidak punya frontmatter YAML (--- ... ---).`);
1755
+ let raw;
1756
+ try {
1757
+ raw = parse3(m[1] ?? "");
1758
+ } catch (err) {
1759
+ throw new SkillError(`${fileName}: frontmatter bukan YAML valid: ${err.message}`);
1760
+ }
1761
+ const fm = SkillFrontmatterSchema.safeParse(raw);
1762
+ if (!fm.success) {
1763
+ const issues = fm.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ");
1764
+ throw new SkillError(`${fileName}: frontmatter tidak valid (${issues}).`);
1765
+ }
1766
+ return { ...fm.data, content: (m[2] ?? "").trim() };
1767
+ }
1768
+ function renderSkill(skill) {
1769
+ const fm = stringify({
1770
+ name: skill.name,
1771
+ when_to_use: skill.when_to_use,
1772
+ updated_at: skill.updated_at
1773
+ }).trimEnd();
1774
+ return `---
1775
+ ${fm}
1776
+ ---
1777
+
1778
+ ${skill.content.trim()}
1779
+ `;
1780
+ }
1781
+ async function listSkills(root) {
1782
+ let files;
1783
+ try {
1784
+ files = await readdir(join5(root, SKILLS_DIR));
1785
+ } catch {
1786
+ return { skills: [], invalid: [] };
1787
+ }
1788
+ const skills = [];
1789
+ const invalid = [];
1790
+ for (const file of files.filter((f) => f.endsWith(".md")).sort()) {
1791
+ try {
1792
+ const skill = parseSkill(await readFile6(join5(root, SKILLS_DIR, file), "utf8"), file);
1793
+ if (`${skill.name}.md` !== file) {
1794
+ throw new SkillError(`${file}: name "${skill.name}" harus sama dengan nama file.`);
1795
+ }
1796
+ skills.push(skill);
1797
+ } catch (err) {
1798
+ invalid.push({ file, error: err.message });
1799
+ }
1800
+ }
1801
+ return { skills, invalid };
1802
+ }
1803
+ function skillIndex(skills) {
1804
+ return skills.map((s) => ({ name: s.name, when_to_use: s.when_to_use }));
1805
+ }
1806
+ async function loadSkill(root, name) {
1807
+ const parsedName = SkillNameSchema.safeParse(name);
1808
+ if (!parsedName.success) throw new SkillError(`Nama skill "${name}" tidak valid.`);
1809
+ const file = `${parsedName.data}.md`;
1810
+ let source;
1811
+ try {
1812
+ source = await readFile6(join5(root, SKILLS_DIR, file), "utf8");
1813
+ } catch {
1814
+ const { skills } = await listSkills(root);
1815
+ const names = skills.map((s) => s.name).join(", ") || "(belum ada)";
1816
+ throw new SkillError(`Skill "${name}" tidak ada. Skill tersedia: ${names}.`);
1817
+ }
1818
+ return parseSkill(source, file);
1819
+ }
1820
+ async function saveSkill(root, input, now = /* @__PURE__ */ new Date()) {
1821
+ const name = SkillNameSchema.parse(input.name);
1822
+ const content = SkillContentSchema.parse(input.content.trim());
1823
+ const when = input.when_to_use.trim();
1824
+ if (!when || when.length > SKILL_LIMITS.maxWhenToUseLength) {
1825
+ throw new SkillError(`when_to_use wajib, maks ${SKILL_LIMITS.maxWhenToUseLength} karakter.`);
1826
+ }
1827
+ const dir = join5(root, SKILLS_DIR);
1828
+ await mkdir3(dir, { recursive: true });
1829
+ const target = join5(dir, `${name}.md`);
1830
+ let created = true;
1831
+ try {
1832
+ await readFile6(target);
1833
+ created = false;
1834
+ } catch {
1835
+ }
1836
+ const skill = { name, when_to_use: when, updated_at: now.toISOString(), content };
1837
+ const tmp = `${target}.${process.pid}.tmp`;
1838
+ await writeFile3(tmp, renderSkill(skill), "utf8");
1839
+ await rename3(tmp, target);
1840
+ return { path: join5(SKILLS_DIR, `${name}.md`), created, skill };
1841
+ }
1842
+
1843
+ // src/maintenance.ts
1844
+ var readOrNull2 = (p) => readFile7(p, "utf8").then(
1845
+ (s) => s,
1846
+ () => null
1847
+ );
1848
+ function countEntries(source) {
1849
+ let count = 0;
1850
+ let depth = 0;
1851
+ let inServers = -1;
1852
+ let pendingServers = false;
1853
+ visit(
1854
+ source,
1855
+ {
1856
+ onObjectBegin: () => {
1857
+ depth++;
1858
+ if (pendingServers) {
1859
+ inServers = depth;
1860
+ pendingServers = false;
1861
+ }
1862
+ },
1863
+ onObjectEnd: () => {
1864
+ if (depth === inServers) inServers = -1;
1865
+ depth--;
1866
+ },
1867
+ onObjectProperty: (name) => {
1868
+ if (depth === 1 && name === "mcpServers") pendingServers = true;
1869
+ else if (depth === inServers && name === MCP_SERVER_KEY) count++;
1870
+ }
1871
+ },
1872
+ { allowTrailingComma: true, disallowComments: false }
1873
+ );
1874
+ return count;
1875
+ }
1876
+ function removeMcpEntries(source) {
1877
+ let out = source;
1878
+ for (let i = 0; i < 20 && countEntries(out) > 0; i++) {
1879
+ out = applyEdits2(out, modify2(out, ["mcpServers", MCP_SERVER_KEY], void 0, {}));
1880
+ }
1881
+ return out;
1882
+ }
1883
+ function isValidJsonObject(source) {
1884
+ const errors = [];
1885
+ const doc = parse4(source, errors, { allowTrailingComma: true, disallowComments: false });
1886
+ return errors.length === 0 && doc !== null && typeof doc === "object" && !Array.isArray(doc);
1887
+ }
1888
+ function entryIsStale(entry) {
1889
+ if (isAbsolute(entry.command) && !existsSync(entry.command)) return true;
1890
+ const script = entry.args[0];
1891
+ return Boolean(script && isAbsolute(script) && /\.[cm]?js$/.test(script) && !existsSync(script));
1892
+ }
1893
+ function baseCommand(entry, adapter) {
1894
+ const suffix = ["mcp", ...adapter.extraArgs];
1895
+ const args = [...entry.args];
1896
+ if (args.slice(-suffix.length).join("\0") === suffix.join("\0")) args.splice(-suffix.length);
1897
+ return { command: entry.command, args };
1898
+ }
1899
+ async function planSync(opts) {
1900
+ const root = resolve3(opts.root);
1901
+ const edits = [];
1902
+ const findings = [];
1903
+ for (const adapter of ADAPTERS) {
1904
+ const before = await readOrNull2(join6(root, adapter.path));
1905
+ if (before !== null && before.trim() !== "" && !isValidJsonObject(before)) {
1906
+ if (!opts.fix) {
1907
+ findings.push({
1908
+ level: "fixable",
1909
+ message: `${adapter.path} bukan JSON valid. \`catenext sync --fix\` akan membuatnya ulang (salinan lama ke .bak).`
1910
+ });
1911
+ continue;
1912
+ }
1913
+ const cmd = opts.defaultCommand();
1914
+ edits.push({
1915
+ path: adapter.path,
1916
+ before,
1917
+ backup: true,
1918
+ after: upsertMcpEntry(
1919
+ null,
1920
+ { command: cmd.command, args: [...cmd.args, "mcp", ...adapter.extraArgs] },
1921
+ adapter.path
1922
+ )
1923
+ });
1924
+ findings.push({ level: "ok", message: `${adapter.path} dibuat ulang (rusak).` });
1925
+ continue;
1926
+ }
1927
+ const entry = before ? readMcpEntry(before) : null;
1928
+ const dupes = before ? countEntries(before) : 0;
1929
+ const stale = entry ? entryIsStale(entry) : false;
1930
+ let base = entry && !stale ? baseCommand(entry, adapter) : opts.defaultCommand();
1931
+ let source = before;
1932
+ if (dupes > 1) {
1933
+ if (opts.fix) {
1934
+ source = removeMcpEntries(before ?? "");
1935
+ findings.push({
1936
+ level: "ok",
1937
+ message: `${adapter.path}: ${dupes} entri "catenext" disatukan.`
1938
+ });
1939
+ } else {
1940
+ findings.push({
1941
+ level: "fixable",
1942
+ message: `${adapter.path}: entri "catenext" muncul ${dupes} kali. Jalankan \`catenext sync --fix\`.`
1943
+ });
1944
+ continue;
1945
+ }
1946
+ }
1947
+ if (stale) {
1948
+ if (!opts.fix) {
1949
+ findings.push({
1950
+ level: "fixable",
1951
+ message: `${adapter.path}: entri "catenext" menunjuk ke path yang tidak ada (${entry?.command} ${entry?.args[0] ?? ""}). Jalankan \`catenext sync --fix\`.`
1952
+ });
1953
+ continue;
1954
+ }
1955
+ base = opts.defaultCommand();
1956
+ findings.push({ level: "ok", message: `${adapter.path}: path server MCP diperbarui.` });
1957
+ }
1958
+ if (!entry)
1959
+ findings.push({ level: "ok", message: `${adapter.path}: entri "catenext" ditambahkan.` });
1960
+ const after = upsertMcpEntry(
1961
+ source,
1962
+ { command: base.command, args: [...base.args, "mcp", ...adapter.extraArgs] },
1963
+ adapter.path
1964
+ );
1965
+ if (after !== before) edits.push({ path: adapter.path, before, after });
1966
+ }
1967
+ const gitignore = await readOrNull2(join6(root, ".gitignore"));
1968
+ const gitignoreAfter = ensureGitignore(gitignore);
1969
+ if (gitignoreAfter !== gitignore) {
1970
+ edits.push({ path: ".gitignore", before: gitignore, after: gitignoreAfter });
1971
+ }
1972
+ const agents = await readOrNull2(join6(root, AGENTS_MD));
1973
+ if (agents?.includes(BLOCK_START)) {
1974
+ const after = upsertAgentsBlock(agents);
1975
+ if (after !== agents) edits.push({ path: AGENTS_MD, before: agents, after });
1976
+ }
1977
+ return { edits, findings };
1978
+ }
1979
+ async function syncSkills(root, api) {
1980
+ const { skills, invalid } = await listSkills(root);
1981
+ if (api) await api.put("skills", { skills: skillIndex(skills) });
1982
+ return { count: skills.length, invalid };
1983
+ }
1984
+ async function planRemove(opts) {
1985
+ const root = resolve3(opts.root);
1986
+ const edits = [];
1987
+ for (const adapter of ADAPTERS) {
1988
+ const before = await readOrNull2(join6(root, adapter.path));
1989
+ if (before === null || countEntries(before) === 0) continue;
1990
+ const stripped = removeMcpEntries(before);
1991
+ const doc = parse4(stripped, [], { allowTrailingComma: true });
1992
+ const servers = doc?.mcpServers;
1993
+ const emptyDoc = Object.keys(doc ?? {}).every((k) => k === "mcpServers") && Object.keys(servers ?? {}).length === 0 && !/\/\/|\/\*/.test(stripped);
1994
+ edits.push({ path: adapter.path, before, after: emptyDoc ? null : stripped });
1995
+ }
1996
+ const gitignore = await readOrNull2(join6(root, ".gitignore"));
1997
+ if (gitignore !== null) {
1998
+ const eol = gitignore.includes("\r\n") ? "\r\n" : "\n";
1999
+ const lines = gitignore.split(/\r?\n/);
2000
+ const kept = lines.filter(
2001
+ (l, i) => l.trim() !== CACHE_IGNORE && !(l.startsWith("# Catenext:") && lines[i + 1]?.trim() === CACHE_IGNORE)
2002
+ );
2003
+ if (kept.length !== lines.length) {
2004
+ const text2 = kept.join(eol).replace(/(\r?\n)+$/, "");
2005
+ edits.push({ path: ".gitignore", before: gitignore, after: text2 ? `${text2}${eol}` : null });
2006
+ }
2007
+ }
2008
+ const agents = await readOrNull2(join6(root, AGENTS_MD));
2009
+ if (agents?.includes(BLOCK_START)) {
2010
+ edits.push({ path: AGENTS_MD, before: agents, after: removeAgentsBlock(agents) });
2011
+ }
2012
+ for (const p of [CONFIG_PATH, join6(".catenext", "cache.json")]) {
2013
+ const before = await readOrNull2(join6(root, p));
2014
+ if (before !== null) edits.push({ path: p, before, after: null });
2015
+ }
2016
+ if (opts.all) {
2017
+ const { skills, invalid } = await listSkills(root);
2018
+ for (const f of [...skills.map((s) => `${s.name}.md`), ...invalid.map((i) => i.file)]) {
2019
+ const p = join6(SKILLS_DIR, f);
2020
+ edits.push({ path: p, before: await readOrNull2(join6(root, p)), after: null });
2021
+ }
2022
+ }
2023
+ return edits;
2024
+ }
2025
+ async function applyFileEdits(root, edits) {
2026
+ const base = resolve3(root);
2027
+ for (const e of edits) {
2028
+ const target = join6(base, e.path);
2029
+ if (e.after === null) {
2030
+ await rm(target, { force: true });
2031
+ continue;
2032
+ }
2033
+ await mkdir4(dirname3(target), { recursive: true });
2034
+ if (e.backup && e.before !== null) await copyFile(target, `${target}.bak`);
2035
+ const tmp = `${target}.catenext-${process.pid}.tmp`;
2036
+ await writeFile4(tmp, e.after);
2037
+ await rename4(tmp, target);
2038
+ }
2039
+ for (const dir of [SKILLS_DIR, ".catenext", ".cursor"]) {
2040
+ await rmdir(join6(base, dir)).catch(() => {
2041
+ });
2042
+ }
2043
+ }
2044
+ function summarize(edits) {
2045
+ return edits.map(
2046
+ (e) => e.after === null ? `- dihapus ${e.path}` : e.before === null ? `+ dibuat ${e.path}` : `~ diubah ${e.path}${e.backup ? " (salinan lama: .bak)" : ""}`
2047
+ );
2048
+ }
2049
+
2050
+ // src/mcp/run.ts
2051
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
2052
+
2053
+ // src/mcp/server.ts
2054
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2055
+ var SERVER_INSTRUCTIONS = [
2056
+ "Catenext mengatur estafet task antar-agen AI untuk repo ini.",
2057
+ "Alur: get_project_context -> get_ready_tasks -> claim_task -> kerjakan & tes -> complete_handoff.",
2058
+ "Merencanakan: list_epics/create_epic -> create_tasks (masuk DRAFT, disetujui manusia di Web sebelum bisa dikerjakan).",
2059
+ "Persona: list_personas/upsert_persona untuk alias, role, dan aturan agen di proyek ini.",
2060
+ "Skill repo: indeksnya ada di get_project_context; panggil load_skill hanya bila relevan, dan save_repo_skill untuk mencatat konvensi/pitfall yang ditemukan (maks. 500 kata, tanpa code dump).",
2061
+ "Bila buntu, panggil report_blocker. Jangan menyalin kode atau secret ke handoff; rujuk path file.",
2062
+ "Jangan mengedit .catenext/config.yaml atau file konfigurasi MCP IDE."
2063
+ ].join(" ");
2064
+ var text = (body, isError = false) => ({
2065
+ content: [{ type: "text", text: body }],
2066
+ ...isError ? { isError: true } : {}
2067
+ });
2068
+ var json = (data, notes = []) => ({
2069
+ content: [
2070
+ { type: "text", text: JSON.stringify(data, null, 2) },
2071
+ ...notes.map((n) => ({ type: "text", text: n }))
2072
+ ]
2073
+ });
2074
+ function errorResult(err) {
2075
+ if (err instanceof SkillError) return text(`Catenext: ${err.message}`, true);
2076
+ if (err instanceof ApiRequestError) {
2077
+ const detail = err.details ? `
2078
+ Detail: ${JSON.stringify(err.details)}` : "";
2079
+ return text(`Catenext: ${err.message} [${err.code}]${detail}`, true);
2080
+ }
2081
+ return text(`Catenext: ${err.message ?? String(err)}`, true);
2082
+ }
2083
+ function zodIssues(error) {
2084
+ return error.issues.map((i) => `- ${i.path.join(".") || "(root)"}: ${i.message}`).join("\n");
2085
+ }
2086
+ function createCatenextMcpServer(opts) {
2087
+ const log = opts.log ?? ((m) => process.stderr.write(`[catenext] ${m}
2088
+ `));
2089
+ const server = new McpServer(
2090
+ { name: "catenext", version: opts.version },
2091
+ { instructions: SERVER_INSTRUCTIONS }
2092
+ );
2093
+ const call = async (run) => {
2094
+ const ctx = await opts.context();
2095
+ if (!ctx.ok) return text(`Catenext belum siap: ${ctx.error}`, true);
2096
+ let result;
2097
+ try {
2098
+ result = await run(ctx);
2099
+ } catch (err) {
2100
+ result = errorResult(err);
2101
+ }
2102
+ const warning = ctx.api.takeWarning();
2103
+ if (warning) {
2104
+ result.content.push({
2105
+ type: "text",
2106
+ text: `Peringatan kuota Catenext: ${warning} Beri tahu pengguna; board tetap bisa dibaca bila kuota habis.`
2107
+ });
2108
+ }
2109
+ return result;
2110
+ };
2111
+ server.registerTool(
2112
+ "get_project_context",
2113
+ {
2114
+ description: MCP_TOOLS.get_project_context.description,
2115
+ inputSchema: MCP_TOOLS.get_project_context.input
2116
+ },
2117
+ (input) => call(
2118
+ async ({ api, config }) => json(
2119
+ await api.post("context", {
2120
+ agent_alias: input.agent_alias ?? config.overrides?.default_agent_alias,
2121
+ role: input.role ?? config.overrides?.default_role
2122
+ })
2123
+ )
2124
+ )
2125
+ );
2126
+ server.registerTool(
2127
+ "get_ready_tasks",
2128
+ {
2129
+ description: MCP_TOOLS.get_ready_tasks.description,
2130
+ inputSchema: MCP_TOOLS.get_ready_tasks.input
2131
+ },
2132
+ (input) => call(
2133
+ async ({ api, config }) => json(
2134
+ await api.post("ready-tasks", {
2135
+ agent_alias: input.agent_alias ?? config.overrides?.default_agent_alias,
2136
+ role: input.role ?? config.overrides?.default_role,
2137
+ limit: input.limit
2138
+ })
2139
+ )
2140
+ )
2141
+ );
2142
+ server.registerTool(
2143
+ "claim_task",
2144
+ { description: MCP_TOOLS.claim_task.description, inputSchema: MCP_TOOLS.claim_task.input },
2145
+ (input) => call(async ({ api }) => json(await api.post("claim", { task_id: input.task_id })))
2146
+ );
2147
+ server.registerTool(
2148
+ "complete_handoff",
2149
+ {
2150
+ description: `${MCP_TOOLS.complete_handoff.description} Teks disensor secret-scrubber lokal sebelum dikirim.`,
2151
+ inputSchema: MCP_TOOLS.complete_handoff.input
2152
+ },
2153
+ (input) => call(async ({ api }) => {
2154
+ const scrubbed = scrubDeep(input, /* @__PURE__ */ new Set(["task_id", "last_commit_hash"]));
2155
+ const parsed = CompleteHandoffInput.safeParse(scrubbed.value);
2156
+ if (!parsed.success) {
2157
+ return text(
2158
+ `Handoff ditolak sebelum dikirim (batas ukuran/format):
2159
+ ${zodIssues(parsed.error)}
2160
+ Ringkas lalu panggil complete_handoff lagi.`,
2161
+ true
2162
+ );
2163
+ }
2164
+ const notes = [];
2165
+ if (scrubbed.total > 0) {
2166
+ const note = describeRedactions(scrubbed);
2167
+ log(note);
2168
+ notes.push(note);
2169
+ }
2170
+ return json(await api.post("complete", parsed.data), notes);
2171
+ })
2172
+ );
2173
+ server.registerTool(
2174
+ "report_blocker",
2175
+ {
2176
+ description: MCP_TOOLS.report_blocker.description,
2177
+ inputSchema: MCP_TOOLS.report_blocker.input
2178
+ },
2179
+ (input) => call(async ({ api }) => {
2180
+ const scrubbed = scrubDeep(input, /* @__PURE__ */ new Set(["task_id", "category"]));
2181
+ const parsed = ReportBlockerInput.safeParse(scrubbed.value);
2182
+ if (!parsed.success) {
2183
+ return text(`Laporan blocker tidak valid:
2184
+ ${zodIssues(parsed.error)}`, true);
2185
+ }
2186
+ const notes = [];
2187
+ if (scrubbed.total > 0) {
2188
+ const note = describeRedactions(scrubbed);
2189
+ log(note);
2190
+ notes.push(note);
2191
+ }
2192
+ return json(await api.post("blocker", parsed.data), notes);
2193
+ })
2194
+ );
2195
+ const scrubbedWrite = (schema, keep, send) => (input) => call(async ({ api }) => {
2196
+ const scrubbed = scrubDeep(input, new Set(keep));
2197
+ const parsed = schema.safeParse(scrubbed.value);
2198
+ if (!parsed.success) {
2199
+ return text(`Input ditolak sebelum dikirim:
2200
+ ${zodIssues(parsed.error)}`, true);
2201
+ }
2202
+ const notes = [];
2203
+ if (scrubbed.total > 0) {
2204
+ const note = describeRedactions(scrubbed);
2205
+ log(note);
2206
+ notes.push(note);
2207
+ }
2208
+ return json(await send(api, parsed.data), notes);
2209
+ });
2210
+ server.registerTool(
2211
+ "list_epics",
2212
+ { description: MCP_TOOLS.list_epics.description, inputSchema: MCP_TOOLS.list_epics.input },
2213
+ () => call(async ({ api }) => json(await api.post("epics/list")))
2214
+ );
2215
+ server.registerTool(
2216
+ "create_epic",
2217
+ { description: MCP_TOOLS.create_epic.description, inputSchema: MCP_TOOLS.create_epic.input },
2218
+ scrubbedWrite(CreateEpicToolInput, [], (api, body) => api.post("epics", body))
2219
+ );
2220
+ server.registerTool(
2221
+ "create_tasks",
2222
+ {
2223
+ description: `${MCP_TOOLS.create_tasks.description} Task baru tidak bisa diklaim sebelum disetujui.`,
2224
+ inputSchema: MCP_TOOLS.create_tasks.input
2225
+ },
2226
+ scrubbedWrite(
2227
+ CreateTasksInput,
2228
+ ["epic_id", "ref", "depends_on", "target_repo", "role"],
2229
+ (api, body) => api.post("tasks", body)
2230
+ )
2231
+ );
2232
+ server.registerTool(
2233
+ "list_personas",
2234
+ {
2235
+ description: MCP_TOOLS.list_personas.description,
2236
+ inputSchema: MCP_TOOLS.list_personas.input
2237
+ },
2238
+ () => call(async ({ api }) => json(await api.post("personas/list")))
2239
+ );
2240
+ server.registerTool(
2241
+ "upsert_persona",
2242
+ {
2243
+ description: MCP_TOOLS.upsert_persona.description,
2244
+ inputSchema: MCP_TOOLS.upsert_persona.input
2245
+ },
2246
+ scrubbedWrite(UpsertPersonaInput, ["alias", "role"], (api, body) => api.put("personas", body))
2247
+ );
2248
+ server.registerTool(
2249
+ "load_skill",
2250
+ { description: MCP_TOOLS.load_skill.description, inputSchema: MCP_TOOLS.load_skill.input },
2251
+ (input) => call(async ({ root }) => {
2252
+ const skill = await loadSkill(root, input.name);
2253
+ return json({ name: skill.name, when_to_use: skill.when_to_use, content: skill.content });
2254
+ })
2255
+ );
2256
+ server.registerTool(
2257
+ "save_repo_skill",
2258
+ {
2259
+ description: `${MCP_TOOLS.save_repo_skill.description} Isi tetap di repo; hanya indeks (nama + when_to_use) yang dikirim ke Cloud.`,
2260
+ inputSchema: MCP_TOOLS.save_repo_skill.input
2261
+ },
2262
+ (input) => call(async ({ api, root }) => {
2263
+ const scrubbed = scrubDeep(input, /* @__PURE__ */ new Set(["name"]));
2264
+ const parsed = SaveRepoSkillInput.safeParse(scrubbed.value);
2265
+ if (!parsed.success) {
2266
+ return text(
2267
+ `Skill ditolak:
2268
+ ${zodIssues(parsed.error)}
2269
+ Ringkas (rujuk path file, jangan menyalin kode) lalu coba lagi.`,
2270
+ true
2271
+ );
2272
+ }
2273
+ const notes = [];
2274
+ if (scrubbed.total > 0) {
2275
+ const note = describeRedactions(scrubbed);
2276
+ log(note);
2277
+ notes.push(note);
2278
+ }
2279
+ const saved = await saveSkill(root, parsed.data);
2280
+ try {
2281
+ const { skills } = await listSkills(root);
2282
+ await api.put("skills", { skills: skillIndex(skills) });
2283
+ } catch (err) {
2284
+ notes.push(
2285
+ `Skill tersimpan lokal, tetapi indeks belum tersinkron ke Cloud (${err.message}). Jalankan \`catenext sync\` nanti.`
2286
+ );
2287
+ }
2288
+ return json({ path: saved.path, created: saved.created }, notes);
2289
+ })
2290
+ );
2291
+ return server;
2292
+ }
2293
+
2294
+ // src/mcp/run.ts
2295
+ async function runMcpServer(opts) {
2296
+ let agentName;
2297
+ let cached;
2298
+ const load = async () => {
2299
+ try {
2300
+ const start = opts.root && !opts.root.includes("${") ? opts.root : process.cwd();
2301
+ const root = await findProjectRoot(start);
2302
+ if (!root) {
2303
+ return {
2304
+ ok: false,
2305
+ error: `Tidak ada .catenext/config.yaml di ${start} atau folder induknya. Jalankan \`catenext init\` di root repo.`
2306
+ };
2307
+ }
2308
+ const config = await readConfig(root);
2309
+ const creds = await loadCredentials();
2310
+ const api = new AgentApi({
2311
+ baseUrl: resolveApiUrl(config.api_url, creds.api_url),
2312
+ apiKey: creds.api_key,
2313
+ projectId: config.project_id,
2314
+ repoName: config.repo_name,
2315
+ agentName: () => agentName
2316
+ });
2317
+ process.stderr.write(
2318
+ `[catenext] repo "${config.repo_name}" (project ${config.project_id}) dari ${root}
2319
+ `
2320
+ );
2321
+ return { ok: true, api, config, root };
2322
+ } catch (err) {
2323
+ if (err instanceof ConfigError || err instanceof CredentialsError) {
2324
+ return { ok: false, error: err.message };
2325
+ }
2326
+ throw err;
2327
+ }
2328
+ };
2329
+ const server = createCatenextMcpServer({
2330
+ version: opts.version,
2331
+ context: () => {
2332
+ cached ??= load();
2333
+ return cached.then((ctx) => {
2334
+ if (!ctx.ok) cached = void 0;
2335
+ return ctx;
2336
+ });
2337
+ }
2338
+ });
2339
+ server.server.oninitialized = () => {
2340
+ agentName = server.server.getClientVersion()?.name;
2341
+ };
2342
+ await server.connect(new StdioServerTransport());
2343
+ }
2344
+
2345
+ // src/node-command.ts
2346
+ import { accessSync, constants, realpathSync } from "node:fs";
2347
+ import { delimiter, join as join7 } from "node:path";
2348
+ function stableNodeCommand(execPath, pathEnv, resolveReal = realpathSync, isExecutable = defaultIsExecutable) {
2349
+ const target = safeReal(execPath, resolveReal);
2350
+ for (const dir of (pathEnv ?? "").split(delimiter)) {
2351
+ if (!dir) continue;
2352
+ for (const name of process.platform === "win32" ? ["node.exe", "node"] : ["node"]) {
2353
+ const candidate = join7(dir, name);
2354
+ if (!isExecutable(candidate)) continue;
2355
+ return safeReal(candidate, resolveReal) === target ? "node" : execPath;
2356
+ }
2357
+ }
2358
+ return execPath;
2359
+ }
2360
+ function hasVersionedSegment(path) {
2361
+ return /[\\/]v?\d+\.\d+\.\d+[\\/]/.test(path);
2362
+ }
2363
+ function safeReal(p, resolveReal) {
2364
+ try {
2365
+ return resolveReal(p);
2366
+ } catch {
2367
+ return p;
2368
+ }
2369
+ }
2370
+ function defaultIsExecutable(p) {
2371
+ try {
2372
+ accessSync(p, constants.X_OK);
2373
+ return true;
2374
+ } catch {
2375
+ return false;
2376
+ }
2377
+ }
2378
+
2379
+ // src/verify.ts
2380
+ import { readFile as readFile8 } from "node:fs/promises";
2381
+ import { join as join8 } from "node:path";
2382
+ async function verifySetup(root, config) {
2383
+ const lines = [];
2384
+ let tokenLine;
2385
+ let projectLine;
2386
+ try {
2387
+ const creds = await loadCredentials();
2388
+ const api = new AgentApi({
2389
+ baseUrl: resolveApiUrl(config.api_url, creds.api_url),
2390
+ apiKey: creds.api_key,
2391
+ projectId: config.project_id,
2392
+ repoName: config.repo_name,
2393
+ agentName: () => "catenext-cli"
2394
+ });
2395
+ const res = await api.post("verify");
2396
+ tokenLine = { ok: true, label: "Token API valid" };
2397
+ projectLine = {
2398
+ ok: true,
2399
+ label: `Akses proyek "${res.project.name}" aktif (repo ${config.repo_name})`
2400
+ };
2401
+ } catch (err) {
2402
+ if (err instanceof CredentialsError) {
2403
+ tokenLine = { ok: false, label: "Token API valid", hint: err.message };
2404
+ projectLine = { ok: false, label: "Akses baca proyek aktif", hint: "Butuh token API dulu." };
2405
+ } else if (err instanceof ApiRequestError && (err.status === 401 || err.status === null)) {
2406
+ tokenLine = { ok: false, label: "Token API valid", hint: err.message };
2407
+ projectLine = { ok: false, label: "Akses baca proyek aktif", hint: "Butuh token API dulu." };
2408
+ } else {
2409
+ tokenLine = { ok: true, label: "Token API valid" };
2410
+ projectLine = {
2411
+ ok: false,
2412
+ label: "Akses baca proyek aktif",
2413
+ hint: `${err.message} Periksa project_id di .catenext/config.yaml.`
2414
+ };
2415
+ }
2416
+ }
2417
+ const found = [];
2418
+ const missing = [];
2419
+ const stale = [];
2420
+ for (const adapter of ADAPTERS) {
2421
+ const src = await readFile8(join8(root, adapter.path), "utf8").catch(() => null);
2422
+ const entry = src ? readMcpEntry(src) : null;
2423
+ if (!entry) missing.push(adapter.label);
2424
+ else if (entryIsStale(entry)) stale.push(adapter.label);
2425
+ else found.push(adapter.label);
2426
+ }
2427
+ const mcpLine = missing.length > 0 ? {
2428
+ ok: false,
2429
+ label: "Konfigurasi MCP terbaca",
2430
+ hint: `Entri "catenext" belum ada untuk ${missing.join(", ")}. Jalankan \`catenext init\`.`
2431
+ } : stale.length > 0 ? {
2432
+ ok: false,
2433
+ label: "Konfigurasi MCP terbaca",
2434
+ hint: `Entri "catenext" untuk ${stale.join(", ")} menunjuk ke path yang sudah tidak ada. Jalankan \`catenext sync --fix\`.`
2435
+ } : { ok: true, label: `Konfigurasi MCP terbaca (${found.join(", ")})` };
2436
+ lines.push(tokenLine, mcpLine, projectLine);
2437
+ return lines;
2438
+ }
2439
+ function formatChecks(lines) {
2440
+ return lines.map((l) => `${l.ok ? "\u2713" : "\u2717"} ${l.label}${l.hint && !l.ok ? `
2441
+ \u2192 ${l.hint}` : ""}`).join("\n");
2442
+ }
2443
+
2444
+ // src/index.ts
2445
+ var VERSION = "0.1.1";
2446
+ var program = new Command();
2447
+ program.name("catenext").description("Estafet tugas & konteks antar-agen AI coding").version(VERSION);
2448
+ async function friendly(fn) {
2449
+ try {
2450
+ await fn();
2451
+ } catch (err) {
2452
+ if (err instanceof ConfigError || err instanceof CredentialsError || err instanceof McpConfigError || err instanceof PlanningInputError) {
2453
+ console.error(`\u2717 ${err.message}`);
2454
+ process.exitCode = 1;
2455
+ return;
2456
+ }
2457
+ if (err instanceof ApiRequestError) {
2458
+ const detail = err.details ? `
2459
+ ${JSON.stringify(err.details)}` : "";
2460
+ console.error(`\u2717 ${err.message} [${err.code}]${detail}`);
2461
+ process.exitCode = 1;
2462
+ return;
2463
+ }
2464
+ throw err;
2465
+ }
2466
+ }
2467
+ function defaultMcpCommand() {
2468
+ const self = fileURLToPath(import.meta.url);
2469
+ const entry = self.endsWith(".ts") ? resolve4(dirname4(self), "../dist/index.js") : self;
2470
+ if (!existsSync2(entry)) {
2471
+ console.error(
2472
+ `! ${entry} belum ada. Jalankan \`pnpm --filter catenext build\` agar IDE bisa menjalankan server MCP.`
2473
+ );
2474
+ }
2475
+ const command = stableNodeCommand(process.execPath, process.env.PATH);
2476
+ if (command !== "node" && hasVersionedSegment(command)) {
2477
+ console.error(
2478
+ `! Entri MCP memakai ${command}, path berversi yang akan rusak saat Node di-update. Tambahkan node ke PATH lalu jalankan ulang, atau pakai --mcp-command.`
2479
+ );
2480
+ }
2481
+ return { command, args: [entry] };
2482
+ }
2483
+ function readSecret(prompt) {
2484
+ if (!process.stdin.isTTY) {
2485
+ return new Promise((res, rej) => {
2486
+ let data = "";
2487
+ process.stdin.setEncoding("utf8");
2488
+ process.stdin.on("data", (c) => {
2489
+ data += c;
2490
+ });
2491
+ process.stdin.on("end", () => res(data));
2492
+ process.stdin.on("error", rej);
2493
+ });
2494
+ }
2495
+ return new Promise((res) => {
2496
+ const rl = createInterface({ input: process.stdin, output: process.stderr, terminal: true });
2497
+ process.stderr.write(prompt);
2498
+ rl._writeToOutput = () => {
2499
+ };
2500
+ rl.question("", (answer) => {
2501
+ rl.close();
2502
+ process.stderr.write("\n");
2503
+ res(answer);
2504
+ });
2505
+ });
2506
+ }
2507
+ program.command("login").description("Login lewat browser dan simpan API key baru (atau tempel key dengan --with-key)").option("--api-url <url>", "URL Catenext API, mis. https://catenext.mapan.digital").option("--with-key", "Tempel API key dari Dashboard alih-alih login lewat browser").option("--no-browser", "Jangan buka browser otomatis (mis. lewat SSH); tampilkan tautan saja").action(
2508
+ (opts) => friendly(async () => {
2509
+ let explicitUrl;
2510
+ if (opts.apiUrl) {
2511
+ try {
2512
+ explicitUrl = new URL(opts.apiUrl).toString().replace(/\/+$/, "");
2513
+ } catch {
2514
+ throw new CredentialsError("--api-url bukan URL yang valid.");
2515
+ }
2516
+ }
2517
+ const root = await findProjectRoot();
2518
+ const config = root ? await readConfig(root).catch(() => null) : null;
2519
+ const previous = await loadCredentials().catch(() => null);
2520
+ const apiUrl = explicitUrl ?? resolveApiUrl(config?.api_url, previous?.api_url);
2521
+ const key = opts.withKey || !process.stdin.isTTY ? validateApiKey(
2522
+ await readSecret("Tempel API key (ctnx_...) dari Dashboard > Keamanan & Akses: ")
2523
+ ) : validateApiKey(await deviceLogin({ apiUrl, browser: opts.browser }));
2524
+ const path = await saveCredentials({
2525
+ api_key: key,
2526
+ ...apiUrl !== DEFAULT_API_URL ? { api_url: apiUrl } : {}
2527
+ });
2528
+ console.log(
2529
+ `\u2713 Login berhasil. API key tersimpan di ${path} (izin 0600, di luar folder proyek).`
2530
+ );
2531
+ if (root) console.log(formatChecks(await verifySetup(root, await readConfig(root))));
2532
+ })
2533
+ );
2534
+ program.command("init").description("Tulis .catenext/config.yaml dan pasang entri MCP untuk Claude Code & Cursor").option("--project <id>", "project_id dari Dashboard (wajib saat pertama kali)").option("--repo <name>", "repo_name untuk repo ini (default: nama folder)").option("--api-url <url>", "Simpan api_url di config (opsional)").option("--mcp-command <cmd>", 'Perintah untuk menjalankan CLI ini, mis. "catenext"').option("--no-agents-md", "Jangan tulis blok Catenext di AGENTS.md").option("--dry-run", "Tampilkan diff tanpa menulis ke disk").action(
2535
+ (opts) => friendly(async () => {
2536
+ const root = process.cwd();
2537
+ const custom = opts.mcpCommand?.trim().split(/\s+/).filter(Boolean);
2538
+ const mcpCommand = custom?.[0] ? { command: custom[0], args: custom.slice(1) } : defaultMcpCommand();
2539
+ const changes = await planInit({
2540
+ root,
2541
+ projectId: opts.project,
2542
+ repoName: opts.repo,
2543
+ apiUrl: opts.apiUrl,
2544
+ mcpCommand,
2545
+ agentsMd: opts.agentsMd
2546
+ });
2547
+ if (changes.length === 0) {
2548
+ console.log("\u2713 Tidak ada perubahan: Catenext sudah terpasang di repo ini.");
2549
+ } else if (opts.dryRun) {
2550
+ console.log(renderDiff(changes));
2551
+ console.log(`(dry-run) ${changes.length} file akan berubah. Tidak ada yang ditulis.`);
2552
+ return;
2553
+ } else {
2554
+ await applyInit(root, changes);
2555
+ for (const c of changes)
2556
+ console.log(`${c.before === null ? "+ dibuat " : "~ diubah "} ${c.path}`);
2557
+ }
2558
+ if (opts.dryRun) return;
2559
+ console.log("");
2560
+ console.log(formatChecks(await verifySetup(root, await readConfig(root))));
2561
+ console.log(
2562
+ `
2563
+ Mulai ulang Claude Code / Cursor agar server MCP "catenext" terbaca. Log server: stderr \`catenext mcp\`.`
2564
+ );
2565
+ })
2566
+ );
2567
+ var epic = program.command("epic").description("Kelola epic proyek ini dari terminal");
2568
+ epic.command("list").description("Daftar epic beserta jumlah task per status").option("--json", "Keluaran JSON").action(
2569
+ (opts) => friendly(async () => epicList(await cliApi(), Boolean(opts.json)))
2570
+ );
2571
+ epic.command("create").description("Buat epic baru").argument("<title>", 'Judul epic, mis. "Fitur login"').option("-d, --description <text>", "Deskripsi / kriteria selesai").option("--json", "Keluaran JSON").action(
2572
+ (title, opts) => friendly(async () => epicCreate(await cliApi(), title, opts.description, Boolean(opts.json)))
2573
+ );
2574
+ var task = program.command("task").description("Ajukan rencana task (masuk DRAFT)");
2575
+ task.command("create").description(
2576
+ "Ajukan task berdependensi dari file JSON (array task atau { tasks: [...] }); pakai '-' untuk stdin"
2577
+ ).requiredOption("--epic <id>", "epic_id tujuan (lihat `catenext epic list`)").requiredOption("-f, --file <path>", "File rencana JSON, atau '-' untuk stdin").option("--json", "Keluaran JSON").action(
2578
+ (opts) => friendly(async () => taskCreate(await cliApi(), opts.epic, opts.file, Boolean(opts.json)))
2579
+ );
2580
+ var persona = program.command("persona").description("Kelola persona agen untuk proyek ini");
2581
+ persona.command("list").description("Daftar persona (alias, role, aturan) yang berlaku di proyek ini").option("--json", "Keluaran JSON").action(
2582
+ (opts) => friendly(async () => personaList(await cliApi(), Boolean(opts.json)))
2583
+ );
2584
+ persona.command("set").description("Buat atau perbarui persona khusus proyek ini (aturan lama diganti)").argument("<alias>", "Nama panggilan, mis. bambang").requiredOption("--role <role>", "Role, mis. backend, ui, architect").option(
2585
+ "--rule <text>",
2586
+ "Aturan kerja (boleh diulang)",
2587
+ (v, prev) => [...prev, v],
2588
+ []
2589
+ ).option("--json", "Keluaran JSON").action(
2590
+ (alias, opts) => friendly(
2591
+ async () => personaSet(await cliApi(), alias, opts.role, opts.rule, Boolean(opts.json))
2592
+ )
2593
+ );
2594
+ var collect = (v, prev) => [...prev, v];
2595
+ var AGENT_OPT = [
2596
+ "--agent <name>",
2597
+ "Nama agen untuk log aktivitas, mis. codex",
2598
+ "catenext-cli"
2599
+ ];
2600
+ program.command("next").description("Daftar task siap untuk repo ini (setara get_ready_tasks)").option("-n, --limit <n>", "Jumlah maksimal", (v) => Number.parseInt(v, 10), 10).option(...AGENT_OPT).option("--json", "Keluaran JSON").action(
2601
+ (opts) => friendly(async () => taskNext(await cliApi(opts.agent), opts))
2602
+ );
2603
+ program.command("claim").description("Kunci task dan cetak instruksi + handoff dependensinya (setara claim_task)").argument("<task_id>").option(...AGENT_OPT).option("--json", "Keluaran JSON").action(
2604
+ (taskId, opts) => friendly(async () => taskClaim(await cliApi(opts.agent), taskId, opts))
2605
+ );
2606
+ program.command("done").description("Selesaikan task dengan handoff terstruktur (setara complete_handoff)").argument("<task_id>").option("--notes <text>", "Ringkasan untuk agen berikutnya (maks. 500 karakter)").option(
2607
+ "--decision <text>",
2608
+ "Keputusan penting (boleh diulang, maks. 5)",
2609
+ collect,
2610
+ []
2611
+ ).option(
2612
+ "--file <path>",
2613
+ "File yang diubah (boleh diulang; default dari git)",
2614
+ collect,
2615
+ []
2616
+ ).option("--verify <cmd>", "Perintah verifikasi, mis. pnpm test").option("--handoff <file>", "File JSON handoff_summary lengkap, atau '-' untuk stdin").option(...AGENT_OPT).option("--json", "Keluaran JSON").action(
2617
+ (taskId, opts) => friendly(async () => taskDone(await cliApi(opts.agent), taskId, opts))
2618
+ );
2619
+ program.command("block").description("Lepas lock dan tandai task BLOCKED (setara report_blocker)").argument("<task_id>").requiredOption("--category <category>", `Salah satu: ${BLOCKER_CATEGORIES.join(", ")}`).requiredOption("--reason <text>", "Alasan spesifik (min. 10 karakter)").option(...AGENT_OPT).option("--json", "Keluaran JSON").action(
2620
+ (taskId, opts) => friendly(async () => taskBlock(await cliApi(opts.agent), taskId, opts))
2621
+ );
2622
+ async function requireRoot() {
2623
+ const root = await findProjectRoot();
2624
+ if (!root) {
2625
+ throw new ConfigError(
2626
+ "Tidak ada .catenext/config.yaml di folder ini atau induknya. Jalankan `catenext init --project <project_id>` dulu."
2627
+ );
2628
+ }
2629
+ return root;
2630
+ }
2631
+ function confirm(question) {
2632
+ if (!process.stdin.isTTY) return Promise.resolve(false);
2633
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
2634
+ return new Promise(
2635
+ (res) => rl.question(question, (a) => {
2636
+ rl.close();
2637
+ res(/^(y|ya|yes)$/i.test(a.trim()));
2638
+ })
2639
+ );
2640
+ }
2641
+ program.command("sync").description("Selaraskan entri MCP, .gitignore, blok AGENTS.md, dan indeks skill dengan Cloud").option("--dry-run", "Tampilkan perubahan tanpa menulis atau mengirim apa pun").option("--fix", "Perbaiki entri MCP yang duplikat, basi (path hilang), atau file yang rusak").action(
2642
+ (opts) => friendly(async () => {
2643
+ const root = await requireRoot();
2644
+ const config = await readConfig(root);
2645
+ const plan = await planSync({
2646
+ root,
2647
+ fix: Boolean(opts.fix),
2648
+ defaultCommand: defaultMcpCommand
2649
+ });
2650
+ for (const f of plan.findings) console.log(`${f.level === "ok" ? "\u2022" : "!"} ${f.message}`);
2651
+ if (opts.dryRun) {
2652
+ for (const l of summarize(plan.edits)) console.log(l);
2653
+ const { count, invalid } = await syncSkills(root, null);
2654
+ console.log(
2655
+ `(dry-run) ${plan.edits.length} file akan berubah; indeks ${count} skill akan dikirim.`
2656
+ );
2657
+ for (const i of invalid) console.log(`! Skill dilewati: ${i.error}`);
2658
+ return;
2659
+ }
2660
+ await applyFileEdits(root, plan.edits);
2661
+ for (const l of summarize(plan.edits)) console.log(l);
2662
+ const fixable = plan.findings.some((f) => f.level === "fixable");
2663
+ if (plan.edits.length === 0 && !fixable) console.log("\u2713 File lokal sudah selaras.");
2664
+ try {
2665
+ const { count, invalid } = await syncSkills(root, await cliApi());
2666
+ console.log(`\u2713 Indeks ${count} skill tersinkron ke Cloud (isi skill tetap lokal).`);
2667
+ for (const i of invalid) console.log(`! Skill dilewati: ${i.error}`);
2668
+ } catch (err) {
2669
+ if (!(err instanceof CredentialsError || err instanceof ApiRequestError)) throw err;
2670
+ console.log(`! Indeks skill belum tersinkron: ${err.message}`);
2671
+ }
2672
+ console.log("");
2673
+ console.log(formatChecks(await verifySetup(root, config)));
2674
+ if (fixable) process.exitCode = 1;
2675
+ })
2676
+ );
2677
+ program.command("remove").description("Hapus Catenext dari repo ini secara bersih (entri MCP, config, blok AGENTS.md)").option("--all", "Hapus juga skill repo di .catenext/skills/").option("--dry-run", "Tampilkan yang akan dihapus tanpa menulis").option("-y, --yes", "Jangan minta konfirmasi").action(
2678
+ (opts) => friendly(async () => {
2679
+ const root = await findProjectRoot() ?? process.cwd();
2680
+ const edits = await planRemove({ root, all: Boolean(opts.all) });
2681
+ if (edits.length === 0) {
2682
+ console.log("\u2713 Tidak ada jejak Catenext di repo ini.");
2683
+ return;
2684
+ }
2685
+ for (const l of summarize(edits)) console.log(l);
2686
+ if (!opts.all)
2687
+ console.log(" (skill di .catenext/skills/ disimpan; tambah --all untuk ikut menghapus)");
2688
+ if (opts.dryRun) {
2689
+ console.log(`(dry-run) ${edits.length} file akan berubah. Tidak ada yang ditulis.`);
2690
+ return;
2691
+ }
2692
+ if (!opts.yes && !await confirm(`Lanjutkan di ${root}? [y/N] `)) {
2693
+ console.log("Dibatalkan. (Tanpa terminal interaktif, pakai --yes.)");
2694
+ process.exitCode = 1;
2695
+ return;
2696
+ }
2697
+ await applyFileEdits(root, edits);
2698
+ console.log(
2699
+ "\u2713 Catenext dihapus dari repo ini. Kredensial global (~/.catenext) tidak disentuh."
2700
+ );
2701
+ console.log(" Mulai ulang Claude Code / Cursor agar server MCP berhenti dimuat.");
2702
+ })
2703
+ );
2704
+ program.command("mcp").description("Jalankan server MCP lokal (stdio)").option("--root <path>", "Root repo (default: cari .catenext/config.yaml dari folder saat ini)").action((opts) => runMcpServer({ root: opts.root, version: VERSION }));
2705
+ program.command("config").description("Validasi .catenext/config.yaml di folder ini").action(async () => {
2706
+ try {
2707
+ const cfg = await readConfig();
2708
+ console.log(`\u2713 Config valid: repo "${cfg.repo_name}" (project ${cfg.project_id})`);
2709
+ } catch (err) {
2710
+ if (err instanceof ConfigError) {
2711
+ console.error(`\u2717 ${err.message}`);
2712
+ process.exitCode = 1;
2713
+ return;
2714
+ }
2715
+ throw err;
2716
+ }
2717
+ });
2718
+ await program.parseAsync();
2719
+ //# sourceMappingURL=index.js.map