@camilyos/codex-antigravity-kit 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1794 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ KNOWN_AGENTS: () => KNOWN_AGENTS,
24
+ RepairLoop: () => RepairLoop,
25
+ ShellAgyAdapter: () => ShellAgyAdapter,
26
+ WorkflowState: () => WorkflowState,
27
+ WorkflowStore: () => WorkflowStore,
28
+ canTransition: () => canTransition,
29
+ defaultState: () => defaultState,
30
+ detectAgent: () => detectAgent,
31
+ parseWorkerResult: () => parseWorkerResult,
32
+ runBrainstorm: () => runBrainstorm,
33
+ runDelegate: () => runDelegate,
34
+ runDelegateWithAdapter: () => runDelegateWithAdapter,
35
+ runDoctor: () => runDoctor,
36
+ runExecute: () => runExecute,
37
+ runExecuteWithAdapter: () => runExecuteWithAdapter,
38
+ runInit: () => runInit,
39
+ runPlan: () => runPlan,
40
+ runReview: () => runReview,
41
+ runStatus: () => runStatus,
42
+ transitionOrThrow: () => transitionOrThrow
43
+ });
44
+ module.exports = __toCommonJS(index_exports);
45
+
46
+ // src/bridge/shell-agy-adapter.ts
47
+ var import_node_child_process = require("child_process");
48
+ var ShellAgyAdapter = class {
49
+ command;
50
+ baseArgs;
51
+ constructor(options) {
52
+ this.command = options.command;
53
+ this.baseArgs = options.baseArgs ?? [];
54
+ }
55
+ async run(request) {
56
+ return new Promise((resolve) => {
57
+ const startedAt = Date.now();
58
+ const args = [
59
+ ...this.baseArgs,
60
+ "--add-dir",
61
+ request.repoPath,
62
+ "--print",
63
+ request.prompt,
64
+ "--output-format",
65
+ "text",
66
+ "--print-timeout",
67
+ `${Math.ceil(request.timeoutMs / 1e3)}s`
68
+ ];
69
+ const child = (0, import_node_child_process.spawn)(this.command, args, {
70
+ cwd: request.repoPath,
71
+ stdio: ["ignore", "pipe", "pipe"]
72
+ });
73
+ let stdout = "";
74
+ let stderr = "";
75
+ let timedOut = false;
76
+ const timer = setTimeout(() => {
77
+ timedOut = true;
78
+ child.kill("SIGTERM");
79
+ }, request.timeoutMs);
80
+ child.stdout.on("data", (chunk) => {
81
+ stdout += chunk.toString("utf8");
82
+ });
83
+ child.stderr.on("data", (chunk) => {
84
+ stderr += chunk.toString("utf8");
85
+ });
86
+ child.on("error", (error) => {
87
+ clearTimeout(timer);
88
+ resolve({
89
+ ok: false,
90
+ timedOut,
91
+ exitCode: null,
92
+ stdout,
93
+ stderr: `${stderr}
94
+ ${error.message}`.trim(),
95
+ durationMs: Date.now() - startedAt
96
+ });
97
+ });
98
+ child.on("close", (exitCode) => {
99
+ clearTimeout(timer);
100
+ resolve({
101
+ ok: !timedOut && exitCode === 0,
102
+ timedOut,
103
+ exitCode,
104
+ stdout,
105
+ stderr,
106
+ durationMs: Date.now() - startedAt
107
+ });
108
+ });
109
+ });
110
+ }
111
+ };
112
+
113
+ // src/core/agent-router.ts
114
+ var import_node_fs = require("fs");
115
+ var import_node_path = require("path");
116
+ var KNOWN_AGENTS = {
117
+ "web-engineer": {
118
+ id: "web-engineer",
119
+ name: "Web Engineer",
120
+ agentFile: "web-engineer.md",
121
+ skillFile: "web-engineering.md",
122
+ description: "Modern web fullstack architecture, frontend, APIs, CSS, and performance",
123
+ keywords: [
124
+ "web",
125
+ "frontend",
126
+ "backend",
127
+ "html",
128
+ "css",
129
+ "react",
130
+ "next.js",
131
+ "nextjs",
132
+ "vue",
133
+ "svelte",
134
+ "angular",
135
+ "rest api",
136
+ "graphql",
137
+ "websocket",
138
+ "http",
139
+ "endpoint",
140
+ "tailwind",
141
+ "responsive",
142
+ "core web vitals",
143
+ "lcp",
144
+ "inp",
145
+ "browser",
146
+ "dom"
147
+ ],
148
+ repoIndicators: [
149
+ "next.config.js",
150
+ "next.config.mjs",
151
+ "next.config.ts",
152
+ "vite.config.ts",
153
+ "vite.config.js",
154
+ "svelte.config.js",
155
+ "angular.json",
156
+ "tsconfig.json"
157
+ ]
158
+ },
159
+ "mobile-engineer": {
160
+ id: "mobile-engineer",
161
+ name: "Mobile Engineer",
162
+ agentFile: "mobile-engineer.md",
163
+ skillFile: "mobile-engineering.md",
164
+ description: "Mobile applications across Native (iOS/Android) and Cross-Platform (Flutter, React Native)",
165
+ keywords: [
166
+ "mobile",
167
+ "ios",
168
+ "android",
169
+ "flutter",
170
+ "dart",
171
+ "react native",
172
+ "react-native",
173
+ "expo",
174
+ "swift",
175
+ "swiftui",
176
+ "uikit",
177
+ "kotlin",
178
+ "jetpack compose",
179
+ "apk",
180
+ "ipa",
181
+ "push notification",
182
+ "biometrics",
183
+ "app store",
184
+ "play store",
185
+ "offline-first",
186
+ "sqlite"
187
+ ],
188
+ repoIndicators: [
189
+ "pubspec.yaml",
190
+ "Podfile",
191
+ "android/build.gradle",
192
+ "ios/Podfile",
193
+ "build.gradle",
194
+ "build.gradle.kts"
195
+ ]
196
+ },
197
+ "game-engineer": {
198
+ id: "game-engineer",
199
+ name: "Game Engineer",
200
+ agentFile: "game-engineer.md",
201
+ skillFile: "game-engineering.md",
202
+ description: "Game architecture and mechanics across Unity, Godot, and Cocos Creator",
203
+ keywords: [
204
+ "game",
205
+ "gameplay",
206
+ "game loop",
207
+ "unity",
208
+ "godot",
209
+ "cocos",
210
+ "cocos creator",
211
+ "physics",
212
+ "rigidbody",
213
+ "collider",
214
+ "collision",
215
+ "sprite",
216
+ "tilemap",
217
+ "prefab",
218
+ "shader",
219
+ "draw call",
220
+ "fps",
221
+ "ecs",
222
+ "fixedupdate",
223
+ "_physics_process",
224
+ "player controller"
225
+ ],
226
+ repoIndicators: [
227
+ "project.godot",
228
+ "ProjectSettings/ProjectVersion.txt",
229
+ "Assets",
230
+ "cocos.config.json",
231
+ "project.json"
232
+ ]
233
+ },
234
+ "researcher": {
235
+ id: "researcher",
236
+ name: "Technical Researcher",
237
+ agentFile: "researcher.md",
238
+ skillFile: "research.md",
239
+ description: "Deep technical research, feasibility studies, spikes, and architecture trade-offs",
240
+ keywords: [
241
+ "research",
242
+ "spike",
243
+ "feasibility",
244
+ "investigate",
245
+ "benchmark",
246
+ "comparison",
247
+ "trade-off",
248
+ "tradeoff",
249
+ "evaluate library",
250
+ "proof of concept",
251
+ "poc",
252
+ "state-of-the-art",
253
+ "options analysis",
254
+ "architectural evaluation"
255
+ ],
256
+ repoIndicators: []
257
+ },
258
+ "business-analyst": {
259
+ id: "business-analyst",
260
+ name: "Business Analyst",
261
+ agentFile: "business-analyst.md",
262
+ skillFile: "requirements-analysis.md",
263
+ description: "Requirements elicitation, user stories, domain modeling, and Gherkin acceptance criteria",
264
+ keywords: [
265
+ "requirements",
266
+ "requirement",
267
+ "user story",
268
+ "user stories",
269
+ "acceptance criteria",
270
+ "given ",
271
+ "when ",
272
+ "then ",
273
+ "persona",
274
+ "personas",
275
+ "business logic",
276
+ "prd",
277
+ "functional requirement",
278
+ "non-functional",
279
+ "workflow diagram",
280
+ "user journey"
281
+ ],
282
+ repoIndicators: []
283
+ },
284
+ "codex": {
285
+ id: "codex",
286
+ name: "Codex Lead",
287
+ agentFile: "codex.md",
288
+ skillFile: "codex-workflow.md",
289
+ description: "General technical lead, architect, and orchestrator",
290
+ keywords: ["orchestration", "workflow", "general", "architecture"],
291
+ repoIndicators: []
292
+ }
293
+ };
294
+ function detectAgent(options) {
295
+ const { root, content = "", explicitAgent } = options;
296
+ if (explicitAgent && explicitAgent.trim().length > 0) {
297
+ const normalized = explicitAgent.trim().toLowerCase();
298
+ const match = KNOWN_AGENTS[normalized];
299
+ if (!match) {
300
+ const valid = Object.keys(KNOWN_AGENTS).join(", ");
301
+ throw new Error(`Unknown agent: "${explicitAgent}". Available agents: ${valid}`);
302
+ }
303
+ return {
304
+ agent: match,
305
+ isExplicit: true,
306
+ confidence: 1,
307
+ reason: `Explicitly requested via --agent ${match.id}`,
308
+ instructions: loadAgentInstructions(root, match.agentFile),
309
+ skillInstructions: loadSkillInstructions(root, match.skillFile)
310
+ };
311
+ }
312
+ const normalizedText = ` ${content.toLowerCase()} `;
313
+ const candidateScores = {
314
+ "game-engineer": { score: 0, reasons: [] },
315
+ "mobile-engineer": { score: 0, reasons: [] },
316
+ "web-engineer": { score: 0, reasons: [] },
317
+ "researcher": { score: 0, reasons: [] },
318
+ "business-analyst": { score: 0, reasons: [] }
319
+ };
320
+ for (const [id, candidate] of Object.entries(candidateScores)) {
321
+ const def = KNOWN_AGENTS[id];
322
+ if (!def) continue;
323
+ for (const kw of def.keywords) {
324
+ if (normalizedText.includes(kw)) {
325
+ candidate.score += 2;
326
+ if (candidate.reasons.length < 3) {
327
+ candidate.reasons.push(`keyword "${kw}"`);
328
+ }
329
+ }
330
+ }
331
+ }
332
+ for (const [id, candidate] of Object.entries(candidateScores)) {
333
+ const def = KNOWN_AGENTS[id];
334
+ if (!def) continue;
335
+ for (const fileIndicator of def.repoIndicators) {
336
+ if ((0, import_node_fs.existsSync)((0, import_node_path.join)(root, fileIndicator))) {
337
+ candidate.score += 3;
338
+ if (candidate.reasons.length < 4) {
339
+ candidate.reasons.push(`repo file "${fileIndicator}"`);
340
+ }
341
+ }
342
+ }
343
+ }
344
+ const packageJsonPath = (0, import_node_path.join)(root, "package.json");
345
+ if ((0, import_node_fs.existsSync)(packageJsonPath)) {
346
+ try {
347
+ const rawPkg = (0, import_node_fs.readFileSync)(packageJsonPath, "utf8");
348
+ if (rawPkg.includes("react-native") || rawPkg.includes("expo")) {
349
+ candidateScores["mobile-engineer"].score += 3;
350
+ candidateScores["mobile-engineer"].reasons.push("package.json (react-native)");
351
+ } else if (rawPkg.includes("react") || rawPkg.includes("next") || rawPkg.includes("vue") || rawPkg.includes("svelte")) {
352
+ candidateScores["web-engineer"].score += 2;
353
+ candidateScores["web-engineer"].reasons.push("package.json (web framework)");
354
+ }
355
+ } catch {
356
+ }
357
+ }
358
+ let bestCandidateId = "codex";
359
+ let maxScore = 0;
360
+ let matchReasons = [];
361
+ for (const [id, data] of Object.entries(candidateScores)) {
362
+ if (data.score > maxScore) {
363
+ maxScore = data.score;
364
+ bestCandidateId = id;
365
+ matchReasons = data.reasons;
366
+ }
367
+ }
368
+ const selectedDef = KNOWN_AGENTS[bestCandidateId] ?? KNOWN_AGENTS["codex"];
369
+ const confidence = Math.min(1, maxScore / 6);
370
+ const reason = maxScore > 0 ? `Auto-detected based on ${matchReasons.join(", ")}` : "Defaulted to Codex General Lead (no specific domain signals found)";
371
+ return {
372
+ agent: selectedDef,
373
+ isExplicit: false,
374
+ confidence,
375
+ reason,
376
+ instructions: loadAgentInstructions(root, selectedDef.agentFile),
377
+ skillInstructions: loadSkillInstructions(root, selectedDef.skillFile)
378
+ };
379
+ }
380
+ function loadAgentInstructions(root, fileName) {
381
+ const customPath = (0, import_node_path.join)(root, ".codex", "agents", fileName);
382
+ if ((0, import_node_fs.existsSync)(customPath)) {
383
+ return (0, import_node_fs.readFileSync)(customPath, "utf8");
384
+ }
385
+ return "";
386
+ }
387
+ function loadSkillInstructions(root, fileName) {
388
+ const customPath = (0, import_node_path.join)(root, ".codex", "skills", fileName);
389
+ if ((0, import_node_fs.existsSync)(customPath)) {
390
+ return (0, import_node_fs.readFileSync)(customPath, "utf8");
391
+ }
392
+ return "";
393
+ }
394
+
395
+ // src/core/repair-loop.ts
396
+ var RepairLoop = class {
397
+ constructor(maxAttempts) {
398
+ this.maxAttempts = maxAttempts;
399
+ if (maxAttempts < 1) {
400
+ throw new Error("maxAttempts must be >= 1");
401
+ }
402
+ }
403
+ maxAttempts;
404
+ canRetry(currentAttempt) {
405
+ return currentAttempt < this.maxAttempts;
406
+ }
407
+ nextAttempt(currentAttempt) {
408
+ return currentAttempt + 1;
409
+ }
410
+ needsEscalation(currentAttempt) {
411
+ return !this.canRetry(currentAttempt);
412
+ }
413
+ };
414
+
415
+ // src/core/result-parser.ts
416
+ var knownStatuses = ["DONE", "BLOCKED", "FAILED"];
417
+ function parseWorkerResult(raw) {
418
+ const lines = raw.split(/\r?\n/).map((line) => line.trim());
419
+ const statusLine = lines.find(
420
+ (line) => knownStatuses.some((status2) => line.toUpperCase().includes(status2))
421
+ );
422
+ const status = knownStatuses.find((value) => statusLine?.toUpperCase().includes(value)) ?? "FAILED";
423
+ const summary = lines.find((line) => line.length > 0 && !line.startsWith("#")) ?? "No summary provided by worker.";
424
+ return { status, summary };
425
+ }
426
+
427
+ // src/core/state-machine.ts
428
+ var WorkflowState = /* @__PURE__ */ ((WorkflowState2) => {
429
+ WorkflowState2["IDLE"] = "IDLE";
430
+ WorkflowState2["DISCOVERY"] = "DISCOVERY";
431
+ WorkflowState2["CLARIFICATION_REQUIRED"] = "CLARIFICATION_REQUIRED";
432
+ WorkflowState2["BRAINSTORMING"] = "BRAINSTORMING";
433
+ WorkflowState2["PLANNING"] = "PLANNING";
434
+ WorkflowState2["READY"] = "READY";
435
+ WorkflowState2["IMPLEMENTING"] = "IMPLEMENTING";
436
+ WorkflowState2["VERIFYING"] = "VERIFYING";
437
+ WorkflowState2["REVIEWING"] = "REVIEWING";
438
+ WorkflowState2["REPAIR_REQUIRED"] = "REPAIR_REQUIRED";
439
+ WorkflowState2["COMPLETED"] = "COMPLETED";
440
+ WorkflowState2["BLOCKED"] = "BLOCKED";
441
+ WorkflowState2["ESCALATION_REQUIRED"] = "ESCALATION_REQUIRED";
442
+ return WorkflowState2;
443
+ })(WorkflowState || {});
444
+ var transitions = {
445
+ ["IDLE" /* IDLE */]: ["DISCOVERY" /* DISCOVERY */],
446
+ ["DISCOVERY" /* DISCOVERY */]: [
447
+ "CLARIFICATION_REQUIRED" /* CLARIFICATION_REQUIRED */,
448
+ "BRAINSTORMING" /* BRAINSTORMING */
449
+ ],
450
+ ["CLARIFICATION_REQUIRED" /* CLARIFICATION_REQUIRED */]: [
451
+ "BRAINSTORMING" /* BRAINSTORMING */,
452
+ "ESCALATION_REQUIRED" /* ESCALATION_REQUIRED */
453
+ ],
454
+ ["BRAINSTORMING" /* BRAINSTORMING */]: ["PLANNING" /* PLANNING */],
455
+ ["PLANNING" /* PLANNING */]: ["READY" /* READY */],
456
+ ["READY" /* READY */]: ["IMPLEMENTING" /* IMPLEMENTING */],
457
+ ["IMPLEMENTING" /* IMPLEMENTING */]: [
458
+ "VERIFYING" /* VERIFYING */,
459
+ "BLOCKED" /* BLOCKED */,
460
+ "ESCALATION_REQUIRED" /* ESCALATION_REQUIRED */
461
+ ],
462
+ ["VERIFYING" /* VERIFYING */]: ["REVIEWING" /* REVIEWING */, "BLOCKED" /* BLOCKED */],
463
+ ["REVIEWING" /* REVIEWING */]: [
464
+ "COMPLETED" /* COMPLETED */,
465
+ "REPAIR_REQUIRED" /* REPAIR_REQUIRED */,
466
+ "ESCALATION_REQUIRED" /* ESCALATION_REQUIRED */,
467
+ "BLOCKED" /* BLOCKED */
468
+ ],
469
+ ["REPAIR_REQUIRED" /* REPAIR_REQUIRED */]: ["IMPLEMENTING" /* IMPLEMENTING */],
470
+ ["COMPLETED" /* COMPLETED */]: ["IDLE" /* IDLE */],
471
+ ["BLOCKED" /* BLOCKED */]: ["ESCALATION_REQUIRED" /* ESCALATION_REQUIRED */],
472
+ ["ESCALATION_REQUIRED" /* ESCALATION_REQUIRED */]: ["IDLE" /* IDLE */]
473
+ };
474
+ function canTransition(from, to) {
475
+ return transitions[from].includes(to);
476
+ }
477
+ function transitionOrThrow(from, to) {
478
+ if (!canTransition(from, to)) {
479
+ throw new Error(`Invalid state transition: ${from} -> ${to}`);
480
+ }
481
+ return to;
482
+ }
483
+
484
+ // src/commands/brainstorm.ts
485
+ var import_node_fs3 = require("fs");
486
+
487
+ // src/fs/workflow-store.ts
488
+ var import_node_fs2 = require("fs");
489
+ var import_node_path2 = require("path");
490
+ var WorkflowStore = class {
491
+ root;
492
+ workflowDir;
493
+ tasksDir;
494
+ statePath;
495
+ configPath;
496
+ constructor(root) {
497
+ this.root = root;
498
+ this.workflowDir = (0, import_node_path2.join)(root, ".agent-workflow");
499
+ this.tasksDir = (0, import_node_path2.join)(this.workflowDir, "tasks");
500
+ this.statePath = (0, import_node_path2.join)(this.workflowDir, "STATE.md");
501
+ this.configPath = (0, import_node_path2.join)(this.workflowDir, "config.json");
502
+ }
503
+ ensureBaseStructure() {
504
+ (0, import_node_fs2.mkdirSync)(this.workflowDir, { recursive: true });
505
+ (0, import_node_fs2.mkdirSync)(this.tasksDir, { recursive: true });
506
+ }
507
+ ensureTask(taskId) {
508
+ const taskDir = (0, import_node_path2.join)(this.tasksDir, taskId);
509
+ (0, import_node_fs2.mkdirSync)(taskDir, { recursive: true });
510
+ return taskDir;
511
+ }
512
+ writeTaskFile(taskId, fileName, content) {
513
+ const taskDir = this.ensureTask(taskId);
514
+ const path = (0, import_node_path2.join)(taskDir, fileName);
515
+ (0, import_node_fs2.writeFileSync)(path, content, "utf8");
516
+ return path;
517
+ }
518
+ readTaskFile(taskId, fileName) {
519
+ const path = (0, import_node_path2.join)(this.tasksDir, taskId, fileName);
520
+ return (0, import_node_fs2.readFileSync)(path, "utf8");
521
+ }
522
+ hasTaskFile(taskId, fileName) {
523
+ const path = (0, import_node_path2.join)(this.tasksDir, taskId, fileName);
524
+ return (0, import_node_fs2.existsSync)(path);
525
+ }
526
+ writeConfig(config) {
527
+ this.ensureBaseStructure();
528
+ (0, import_node_fs2.writeFileSync)(this.configPath, `${JSON.stringify(config, null, 2)}
529
+ `, "utf8");
530
+ }
531
+ readConfig() {
532
+ const raw = (0, import_node_fs2.readFileSync)(this.configPath, "utf8");
533
+ return JSON.parse(raw);
534
+ }
535
+ writeState(snapshot) {
536
+ this.ensureBaseStructure();
537
+ const content = toStateMarkdown(snapshot);
538
+ (0, import_node_fs2.writeFileSync)(this.statePath, content, "utf8");
539
+ }
540
+ readState() {
541
+ if (!(0, import_node_fs2.existsSync)(this.statePath)) {
542
+ return defaultState();
543
+ }
544
+ const raw = (0, import_node_fs2.readFileSync)(this.statePath, "utf8");
545
+ return parseStateMarkdown(raw);
546
+ }
547
+ };
548
+ function defaultState() {
549
+ return {
550
+ state: "IDLE" /* IDLE */,
551
+ currentPhase: "none",
552
+ currentTask: "none",
553
+ reviewAttempt: 0,
554
+ repairAttempt: 0,
555
+ nextAction: "Run init",
556
+ blockingIssues: [],
557
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
558
+ };
559
+ }
560
+ function toStateMarkdown(snapshot) {
561
+ const issues = snapshot.blockingIssues.length === 0 ? "- None" : snapshot.blockingIssues.map((issue) => `- ${issue}`).join("\n");
562
+ return [
563
+ "# Current State",
564
+ "",
565
+ `State: ${snapshot.state}`,
566
+ `Current phase: ${snapshot.currentPhase}`,
567
+ `Current task: ${snapshot.currentTask}`,
568
+ `Review attempt: ${snapshot.reviewAttempt}`,
569
+ `Repair attempt: ${snapshot.repairAttempt}`,
570
+ "",
571
+ "## Blocking Issues",
572
+ issues,
573
+ "",
574
+ "## Next",
575
+ snapshot.nextAction,
576
+ "",
577
+ `Updated at: ${snapshot.updatedAt}`,
578
+ ""
579
+ ].join("\n");
580
+ }
581
+ function parseStateMarkdown(markdown) {
582
+ const line = (prefix) => markdown.split(/\r?\n/).find((item) => item.startsWith(prefix))?.slice(prefix.length).trim();
583
+ const stateValue = line("State: ");
584
+ const currentPhase = line("Current phase: ") ?? "none";
585
+ const currentTask = line("Current task: ") ?? "none";
586
+ const reviewAttempt = Number(line("Review attempt: ") ?? "0");
587
+ const repairAttempt = Number(line("Repair attempt: ") ?? "0");
588
+ const updatedAt = line("Updated at: ") ?? (/* @__PURE__ */ new Date()).toISOString();
589
+ const state = Object.values(WorkflowState).find((value) => value === stateValue) ?? "IDLE" /* IDLE */;
590
+ const nextSection = markdown.split("## Next\n")[1] ?? "";
591
+ const nextAction = (nextSection.split(/\r?\n/)[0] ?? "Run init").trim();
592
+ const blockingSection = markdown.split("## Blocking Issues\n")[1] ?? "";
593
+ const blockingRaw = blockingSection.split("\n## Next")[0] ?? "";
594
+ const blockingIssues = blockingRaw.split(/\r?\n/).map((item) => item.trim()).filter((item) => item.startsWith("- ") && item !== "- None").map((item) => item.slice(2));
595
+ return {
596
+ state,
597
+ currentPhase,
598
+ currentTask,
599
+ reviewAttempt,
600
+ repairAttempt,
601
+ nextAction,
602
+ blockingIssues,
603
+ updatedAt
604
+ };
605
+ }
606
+
607
+ // src/commands/brainstorm.ts
608
+ function runBrainstorm(options) {
609
+ const store = new WorkflowStore(options.root);
610
+ store.ensureBaseStructure();
611
+ let spec = "";
612
+ if (options.spec && (0, import_node_fs3.existsSync)(options.spec)) {
613
+ spec = (0, import_node_fs3.readFileSync)(options.spec, "utf8");
614
+ store.writeTaskFile(options.task, "SPEC.md", spec);
615
+ } else if (options.prompt) {
616
+ spec = options.prompt;
617
+ store.writeTaskFile(options.task, "SPEC.md", spec);
618
+ } else if (store.hasTaskFile(options.task, "SPEC.md")) {
619
+ spec = store.readTaskFile(options.task, "SPEC.md");
620
+ } else {
621
+ throw new Error(
622
+ `Missing spec for task ${options.task}. Provide --spec <path>, --prompt <text>, or create .agent-workflow/tasks/${options.task}/SPEC.md`
623
+ );
624
+ }
625
+ const agentResolution = detectAgent({
626
+ root: options.root,
627
+ content: spec,
628
+ explicitAgent: options.agent
629
+ });
630
+ console.log(`[Agent Router] Assigned: ${agentResolution.agent.name} (${agentResolution.agent.id})`);
631
+ console.log(`[Agent Router] Reason: ${agentResolution.reason}`);
632
+ const brainstorm = buildBrainstormMarkdown(options.task, spec, agentResolution);
633
+ store.writeTaskFile(options.task, "BRAINSTORM.md", brainstorm);
634
+ const state = store.readState();
635
+ state.state = "DISCOVERY" /* DISCOVERY */;
636
+ state.state = "BRAINSTORMING" /* BRAINSTORMING */;
637
+ state.currentTask = options.task;
638
+ state.currentPhase = "brainstorming";
639
+ state.nextAction = "Run plan command to convert brainstorm into phases and tasks";
640
+ state.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
641
+ store.writeState(state);
642
+ console.log(brainstorm);
643
+ }
644
+ function buildBrainstormMarkdown(task, spec, agentResolution) {
645
+ return [
646
+ "# Brainstorm",
647
+ "",
648
+ `Task: ${task}`,
649
+ `Assigned Agent: ${agentResolution.agent.name} (${agentResolution.agent.id})`,
650
+ `Agent Selection: ${agentResolution.reason}`,
651
+ "",
652
+ "## Goal",
653
+ `Task ${task}`,
654
+ "",
655
+ "## Current System",
656
+ "Repository contains an orchestration kit with Codex planning and Antigravity execution boundaries.",
657
+ "",
658
+ "## Requirements",
659
+ spec.trim(),
660
+ "",
661
+ "## Constraints",
662
+ "- Keep context small and deterministic",
663
+ "- Use filesystem artifacts as durable state",
664
+ "- Do not invent requirements",
665
+ "",
666
+ "## Relevant Existing Architecture",
667
+ "- Codex owns clarification, planning, review, and verification",
668
+ "- Antigravity owns implementation",
669
+ "- Agy is the worker CLI bridge",
670
+ "",
671
+ "## Options Considered",
672
+ "### Option A",
673
+ "Pros: Simple artifact-first workflow",
674
+ "Cons: Requires explicit commands",
675
+ "",
676
+ "### Option B",
677
+ "Pros: More automation",
678
+ "Cons: Higher complexity and harder debugging",
679
+ "",
680
+ "## Recommended Approach",
681
+ "Use an artifact-first command flow: brainstorm -> plan -> execute -> review.",
682
+ "",
683
+ "## Why",
684
+ "This keeps the workflow small, inspectable, and easy to recover.",
685
+ "",
686
+ "## Risks",
687
+ "- Incomplete specs can still block execution",
688
+ "- Worker output may need repair",
689
+ "",
690
+ "## Open Questions",
691
+ "None",
692
+ ""
693
+ ].join("\n");
694
+ }
695
+
696
+ // src/commands/plan.ts
697
+ var import_node_fs4 = require("fs");
698
+ function runPlan(options) {
699
+ const store = new WorkflowStore(options.root);
700
+ store.ensureBaseStructure();
701
+ let spec = "";
702
+ if (options.spec && (0, import_node_fs4.existsSync)(options.spec)) {
703
+ spec = (0, import_node_fs4.readFileSync)(options.spec, "utf8");
704
+ store.writeTaskFile(options.task, "SPEC.md", spec);
705
+ } else if (store.hasTaskFile(options.task, "SPEC.md")) {
706
+ spec = store.readTaskFile(options.task, "SPEC.md");
707
+ } else {
708
+ spec = `# Task ${options.task}
709
+ `;
710
+ }
711
+ const brainstormContent = store.hasTaskFile(options.task, "BRAINSTORM.md") ? store.readTaskFile(options.task, "BRAINSTORM.md") : "# Brainstorm\n\nRun brainstorm first.\n";
712
+ const agentResolution = detectAgent({
713
+ root: options.root,
714
+ content: `${spec}
715
+ ${brainstormContent}`,
716
+ explicitAgent: options.agent
717
+ });
718
+ console.log(`[Agent Router] Assigned: ${agentResolution.agent.name} (${agentResolution.agent.id})`);
719
+ console.log(`[Agent Router] Reason: ${agentResolution.reason}`);
720
+ const plan = buildPlanMarkdown(options.task, spec, brainstormContent, agentResolution);
721
+ store.writeTaskFile(options.task, "PLAN.md", plan);
722
+ const state = store.readState();
723
+ state.state = "BRAINSTORMING" /* BRAINSTORMING */;
724
+ state.state = "PLANNING" /* PLANNING */;
725
+ state.currentTask = options.task;
726
+ state.currentPhase = "planning";
727
+ state.nextAction = `Run execute command to implement work described in PLAN.md for task ${options.task}`;
728
+ state.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
729
+ store.writeState(state);
730
+ console.log(plan);
731
+ }
732
+ function buildPlanMarkdown(task, spec, brainstorm, agentResolution) {
733
+ return [
734
+ "# Plan",
735
+ "",
736
+ `Task: ${task}`,
737
+ `Assigned Agent: ${agentResolution.agent.name} (${agentResolution.agent.id})`,
738
+ `Agent Selection: ${agentResolution.reason}`,
739
+ "",
740
+ "## Objective",
741
+ "Convert brainstorm into actionable phases and tasks.",
742
+ "",
743
+ "## Context",
744
+ brainstorm.trim(),
745
+ "",
746
+ "## Requirements",
747
+ spec.trim(),
748
+ "",
749
+ "## Phases",
750
+ "### Phase 1 \u2014 Scope and Contracts",
751
+ "- Confirm task boundaries",
752
+ "- Capture expected behavior",
753
+ "",
754
+ "### Phase 2 \u2014 Worker Execution",
755
+ "- Send spec to Antigravity",
756
+ "- Collect implementation result",
757
+ "",
758
+ "### Phase 3 \u2014 Review and Repair",
759
+ "- Codex reviews diff and output",
760
+ "- Produce repair request if needed",
761
+ "",
762
+ "## Acceptance Criteria",
763
+ "- Brainstorm artifact exists",
764
+ "- Plan artifact exists",
765
+ "- Execute artifact can be generated",
766
+ "- Workflow remains recoverable from disk",
767
+ "",
768
+ "## Verification",
769
+ "- npm test",
770
+ "- npm run build",
771
+ "- npx codex-antigravity-kit doctor",
772
+ ""
773
+ ].join("\n");
774
+ }
775
+
776
+ // src/commands/execute.ts
777
+ var import_node_fs5 = require("fs");
778
+ var import_node_path3 = require("path");
779
+ async function runExecute(options) {
780
+ const store = new WorkflowStore(options.root);
781
+ if (!(0, import_node_fs5.existsSync)(store.configPath)) {
782
+ throw new Error("Missing .agent-workflow/config.json. Run init first.");
783
+ }
784
+ const config = store.readConfig();
785
+ const adapter = new ShellAgyAdapter({
786
+ command: config.agyCommand,
787
+ baseArgs: config.agyArgs
788
+ });
789
+ await runExecuteWithAdapter(options, adapter);
790
+ }
791
+ async function runExecuteWithAdapter(options, adapter) {
792
+ const store = new WorkflowStore(options.root);
793
+ store.ensureBaseStructure();
794
+ const current = store.readState();
795
+ let contextSource = "";
796
+ let contextContent = "";
797
+ if (options.file && (0, import_node_fs5.existsSync)(options.file)) {
798
+ contextSource = options.file;
799
+ contextContent = (0, import_node_fs5.readFileSync)(options.file, "utf8");
800
+ store.writeTaskFile(options.task, "PLAN.md", contextContent);
801
+ } else if (options.plan && (0, import_node_fs5.existsSync)(options.plan)) {
802
+ contextSource = options.plan;
803
+ contextContent = (0, import_node_fs5.readFileSync)(options.plan, "utf8");
804
+ store.writeTaskFile(options.task, "PLAN.md", contextContent);
805
+ } else if (store.hasTaskFile(options.task, "PLAN.md")) {
806
+ contextSource = (0, import_node_path3.join)(store.tasksDir, options.task, "PLAN.md");
807
+ contextContent = store.readTaskFile(options.task, "PLAN.md");
808
+ } else if (options.spec && (0, import_node_fs5.existsSync)(options.spec)) {
809
+ contextSource = options.spec;
810
+ contextContent = (0, import_node_fs5.readFileSync)(options.spec, "utf8");
811
+ store.writeTaskFile(options.task, "SPEC.md", contextContent);
812
+ } else if (store.hasTaskFile(options.task, "SPEC.md")) {
813
+ contextSource = (0, import_node_path3.join)(store.tasksDir, options.task, "SPEC.md");
814
+ contextContent = store.readTaskFile(options.task, "SPEC.md");
815
+ } else {
816
+ throw new Error(
817
+ `No context markdown file found to execute for task ${options.task}. Run 'plan' or provide --plan, --file, or --spec.`
818
+ );
819
+ }
820
+ let repairContent = "";
821
+ if (options.repairRequest && (0, import_node_fs5.existsSync)(options.repairRequest)) {
822
+ repairContent = (0, import_node_fs5.readFileSync)(options.repairRequest, "utf8");
823
+ store.writeTaskFile(options.task, "REPAIR_REQUEST.md", repairContent);
824
+ } else if (store.hasTaskFile(options.task, "REPAIR_REQUEST.md")) {
825
+ repairContent = store.readTaskFile(options.task, "REPAIR_REQUEST.md");
826
+ }
827
+ const agentResolution = detectAgent({
828
+ root: options.root,
829
+ content: contextContent,
830
+ explicitAgent: options.agent
831
+ });
832
+ console.log(`[Agent Router] Assigned: ${agentResolution.agent.name} (${agentResolution.agent.id})`);
833
+ console.log(`[Agent Router] Reason: ${agentResolution.reason}`);
834
+ const executeArtifact = buildExecuteMarkdown(options.task, contextSource, contextContent, agentResolution);
835
+ store.writeTaskFile(options.task, "EXECUTE.md", executeArtifact);
836
+ advanceStateToImplementing(current);
837
+ current.currentTask = options.task;
838
+ current.currentPhase = "implementation";
839
+ current.nextAction = "Wait for worker execution result";
840
+ current.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
841
+ store.writeState(current);
842
+ const workerRulesPath = (0, import_node_path3.join)(options.root, ".antigravity", "WORKER_RULES.md");
843
+ const workerRules = (0, import_node_fs5.existsSync)(workerRulesPath) ? (0, import_node_fs5.readFileSync)(workerRulesPath, "utf8") : "";
844
+ const prompt = buildWorkerPrompt({
845
+ taskId: options.task,
846
+ workerRules,
847
+ context: contextContent,
848
+ repairRequest: repairContent,
849
+ agentResolution
850
+ });
851
+ const timeoutMs = options.timeoutMs ?? 6e5;
852
+ const execution = await adapter.run({
853
+ repoPath: options.root,
854
+ taskId: options.task,
855
+ prompt,
856
+ timeoutMs
857
+ });
858
+ const resultContent = toResultMarkdown(
859
+ execution.stdout,
860
+ execution.stderr,
861
+ execution.exitCode,
862
+ execution.durationMs
863
+ );
864
+ store.writeTaskFile(options.task, "RESULT.md", resultContent);
865
+ current.state = transitionOrThrow(current.state, "VERIFYING" /* VERIFYING */);
866
+ if (!execution.ok) {
867
+ current.state = "BLOCKED" /* BLOCKED */;
868
+ current.blockingIssues = [
869
+ execution.timedOut ? "Worker execution timed out" : `Worker failed with exit code ${execution.exitCode}`
870
+ ];
871
+ current.nextAction = "Inspect RESULT.md and decide escalation or retry";
872
+ current.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
873
+ store.writeState(current);
874
+ console.log("Worker execution failed or timed out. See RESULT.md");
875
+ return;
876
+ }
877
+ const parsed = parseWorkerResult(execution.stdout);
878
+ applyParsedResultState(current, parsed);
879
+ current.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
880
+ store.writeState(current);
881
+ console.log(`Worker status: ${parsed.status}`);
882
+ console.log(`Summary: ${parsed.summary}`);
883
+ }
884
+ function advanceStateToImplementing(snapshot) {
885
+ if (snapshot.state === "IMPLEMENTING" /* IMPLEMENTING */) {
886
+ return;
887
+ }
888
+ if (snapshot.state === "REPAIR_REQUIRED" /* REPAIR_REQUIRED */) {
889
+ snapshot.state = transitionOrThrow(snapshot.state, "IMPLEMENTING" /* IMPLEMENTING */);
890
+ return;
891
+ }
892
+ if (snapshot.state === "READY" /* READY */) {
893
+ snapshot.state = transitionOrThrow(snapshot.state, "IMPLEMENTING" /* IMPLEMENTING */);
894
+ return;
895
+ }
896
+ if (snapshot.state === "PLANNING" /* PLANNING */) {
897
+ snapshot.state = transitionOrThrow(snapshot.state, "READY" /* READY */);
898
+ snapshot.state = transitionOrThrow(snapshot.state, "IMPLEMENTING" /* IMPLEMENTING */);
899
+ return;
900
+ }
901
+ if (snapshot.state === "BRAINSTORMING" /* BRAINSTORMING */) {
902
+ snapshot.state = transitionOrThrow(snapshot.state, "PLANNING" /* PLANNING */);
903
+ snapshot.state = transitionOrThrow(snapshot.state, "READY" /* READY */);
904
+ snapshot.state = transitionOrThrow(snapshot.state, "IMPLEMENTING" /* IMPLEMENTING */);
905
+ return;
906
+ }
907
+ if (snapshot.state === "DISCOVERY" /* DISCOVERY */) {
908
+ snapshot.state = transitionOrThrow(snapshot.state, "BRAINSTORMING" /* BRAINSTORMING */);
909
+ snapshot.state = transitionOrThrow(snapshot.state, "PLANNING" /* PLANNING */);
910
+ snapshot.state = transitionOrThrow(snapshot.state, "READY" /* READY */);
911
+ snapshot.state = transitionOrThrow(snapshot.state, "IMPLEMENTING" /* IMPLEMENTING */);
912
+ return;
913
+ }
914
+ snapshot.state = transitionOrThrow(snapshot.state, "DISCOVERY" /* DISCOVERY */);
915
+ snapshot.state = transitionOrThrow(snapshot.state, "BRAINSTORMING" /* BRAINSTORMING */);
916
+ snapshot.state = transitionOrThrow(snapshot.state, "PLANNING" /* PLANNING */);
917
+ snapshot.state = transitionOrThrow(snapshot.state, "READY" /* READY */);
918
+ snapshot.state = transitionOrThrow(snapshot.state, "IMPLEMENTING" /* IMPLEMENTING */);
919
+ }
920
+ function buildWorkerPrompt(input) {
921
+ const parts = [
922
+ "You are Antigravity implementation worker.",
923
+ "",
924
+ input.workerRules,
925
+ "",
926
+ `# Task ID
927
+ ${input.taskId}`,
928
+ "",
929
+ `# Assigned Role
930
+ Agent: ${input.agentResolution.agent.name} (${input.agentResolution.agent.id})
931
+ Reason: ${input.agentResolution.reason}`
932
+ ];
933
+ if (input.agentResolution.instructions) {
934
+ parts.push("# Agent Operational Guidelines\n" + input.agentResolution.instructions);
935
+ }
936
+ if (input.agentResolution.skillInstructions) {
937
+ parts.push("# Recommended Skill Practices\n" + input.agentResolution.skillInstructions);
938
+ }
939
+ parts.push("# Implementation Context & Specification\n" + input.context);
940
+ if (input.repairRequest) {
941
+ parts.push("# REPAIR REQUEST\n" + input.repairRequest);
942
+ }
943
+ parts.push("Return only concise Implementation Result markdown with status DONE | BLOCKED | FAILED.");
944
+ return parts.filter(Boolean).join("\n\n");
945
+ }
946
+ function applyParsedResultState(state, result) {
947
+ state.state = transitionOrThrow(state.state, "REVIEWING" /* REVIEWING */);
948
+ if (result.status === "DONE") {
949
+ state.nextAction = "Run review and record PASS/FAIL";
950
+ state.blockingIssues = [];
951
+ return;
952
+ }
953
+ if (result.status === "FAILED") {
954
+ state.state = "REPAIR_REQUIRED" /* REPAIR_REQUIRED */;
955
+ state.repairAttempt += 1;
956
+ state.nextAction = "Create repair request and execute again";
957
+ return;
958
+ }
959
+ state.state = "ESCALATION_REQUIRED" /* ESCALATION_REQUIRED */;
960
+ state.blockingIssues = ["Worker returned BLOCKED status"];
961
+ state.nextAction = "Resolve blocking decision with user";
962
+ }
963
+ function buildExecuteMarkdown(task, source, context, agentResolution) {
964
+ return [
965
+ "# Execute",
966
+ "",
967
+ `Task: ${task}`,
968
+ `Source: ${source}`,
969
+ `Assigned Agent: ${agentResolution.agent.name} (${agentResolution.agent.id})`,
970
+ `Agent Selection: ${agentResolution.reason}`,
971
+ "",
972
+ "## Context & Plan Package",
973
+ context.trim(),
974
+ "",
975
+ "## Expected Worker Result",
976
+ "- DONE when implementation and tests complete",
977
+ "- FAILED when implementation needs repair",
978
+ "- BLOCKED when missing context/decision",
979
+ ""
980
+ ].join("\n");
981
+ }
982
+ function toResultMarkdown(stdout, stderr, exitCode, durationMs) {
983
+ return [
984
+ "# Implementation Result",
985
+ "",
986
+ "## Execution",
987
+ `- Exit code: ${String(exitCode)}`,
988
+ `- Duration ms: ${durationMs}`,
989
+ "",
990
+ "## Stdout",
991
+ "```text",
992
+ stdout.trim() || "(empty)",
993
+ "```",
994
+ "",
995
+ "## Stderr",
996
+ "```text",
997
+ stderr.trim() || "(empty)",
998
+ "```",
999
+ ""
1000
+ ].join("\n");
1001
+ }
1002
+
1003
+ // src/commands/delegate.ts
1004
+ var import_node_fs6 = require("fs");
1005
+ var import_node_path4 = require("path");
1006
+ async function runDelegate(options) {
1007
+ const store = new WorkflowStore(options.root);
1008
+ if (!(0, import_node_fs6.existsSync)(store.configPath)) {
1009
+ throw new Error("Missing .agent-workflow/config.json. Run init first.");
1010
+ }
1011
+ const config = store.readConfig();
1012
+ const adapter = new ShellAgyAdapter({
1013
+ command: config.agyCommand,
1014
+ baseArgs: config.agyArgs
1015
+ });
1016
+ await runDelegateWithAdapter(options, adapter);
1017
+ }
1018
+ async function runDelegateWithAdapter(options, adapter) {
1019
+ const store = new WorkflowStore(options.root);
1020
+ store.ensureBaseStructure();
1021
+ const current = store.readState();
1022
+ const specContent = (0, import_node_fs6.readFileSync)(options.spec, "utf8");
1023
+ store.writeTaskFile(options.task, "SPEC.md", specContent);
1024
+ let repairContent = "";
1025
+ if (options.repairRequest) {
1026
+ repairContent = (0, import_node_fs6.readFileSync)(options.repairRequest, "utf8");
1027
+ store.writeTaskFile(options.task, "REPAIR_REQUEST.md", repairContent);
1028
+ }
1029
+ advanceStateToImplementing2(current);
1030
+ current.currentTask = options.task;
1031
+ current.currentPhase = "implementation";
1032
+ current.nextAction = "Wait for worker execution result";
1033
+ current.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1034
+ store.writeState(current);
1035
+ const workerRulesPath = (0, import_node_path4.join)(options.root, ".antigravity", "WORKER_RULES.md");
1036
+ const workerRules = (0, import_node_fs6.existsSync)(workerRulesPath) ? (0, import_node_fs6.readFileSync)(workerRulesPath, "utf8") : "";
1037
+ const prompt = buildWorkerPrompt2({
1038
+ taskId: options.task,
1039
+ workerRules,
1040
+ spec: specContent,
1041
+ repairRequest: repairContent
1042
+ });
1043
+ const execution = await adapter.run({
1044
+ repoPath: options.root,
1045
+ taskId: options.task,
1046
+ prompt,
1047
+ timeoutMs: options.timeoutMs
1048
+ });
1049
+ const resultContent = toResultMarkdown2(execution.stdout, execution.stderr, execution.exitCode, execution.durationMs);
1050
+ store.writeTaskFile(options.task, "RESULT.md", resultContent);
1051
+ current.state = transitionOrThrow(current.state, "VERIFYING" /* VERIFYING */);
1052
+ if (!execution.ok) {
1053
+ current.state = "BLOCKED" /* BLOCKED */;
1054
+ current.blockingIssues = [
1055
+ execution.timedOut ? "Worker execution timed out" : `Worker failed with exit code ${execution.exitCode}`
1056
+ ];
1057
+ current.nextAction = "Inspect RESULT.md and decide escalation or retry";
1058
+ current.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1059
+ store.writeState(current);
1060
+ console.log("Worker execution failed or timed out. See RESULT.md");
1061
+ return;
1062
+ }
1063
+ const parsed = parseWorkerResult(execution.stdout);
1064
+ applyParsedResultState2(current, parsed);
1065
+ current.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1066
+ store.writeState(current);
1067
+ console.log(`Worker status: ${parsed.status}`);
1068
+ console.log(`Summary: ${parsed.summary}`);
1069
+ }
1070
+ function buildWorkerPrompt2(input) {
1071
+ return [
1072
+ "You are Antigravity implementation worker.",
1073
+ "",
1074
+ input.workerRules,
1075
+ "",
1076
+ `# Task ID
1077
+ ${input.taskId}`,
1078
+ "",
1079
+ "# SPEC",
1080
+ input.spec,
1081
+ input.repairRequest ? "# REPAIR REQUEST\n" + input.repairRequest : "",
1082
+ "",
1083
+ "Return only concise Implementation Result markdown with status DONE | BLOCKED | FAILED."
1084
+ ].filter(Boolean).join("\n");
1085
+ }
1086
+ function applyParsedResultState2(state, result) {
1087
+ state.state = transitionOrThrow(state.state, "REVIEWING" /* REVIEWING */);
1088
+ if (result.status === "DONE") {
1089
+ state.nextAction = "Run review and record PASS/FAIL";
1090
+ state.blockingIssues = [];
1091
+ return;
1092
+ }
1093
+ if (result.status === "FAILED") {
1094
+ state.state = "REPAIR_REQUIRED" /* REPAIR_REQUIRED */;
1095
+ state.repairAttempt += 1;
1096
+ state.nextAction = "Create repair request and delegate again";
1097
+ return;
1098
+ }
1099
+ state.state = "ESCALATION_REQUIRED" /* ESCALATION_REQUIRED */;
1100
+ state.blockingIssues = ["Worker returned BLOCKED status"];
1101
+ state.nextAction = "Resolve blocking decision with user";
1102
+ }
1103
+ function toResultMarkdown2(stdout, stderr, exitCode, durationMs) {
1104
+ return [
1105
+ "# Implementation Result",
1106
+ "",
1107
+ "## Execution",
1108
+ `- Exit code: ${String(exitCode)}`,
1109
+ `- Duration ms: ${durationMs}`,
1110
+ "",
1111
+ "## Stdout",
1112
+ "```text",
1113
+ stdout.trim() || "(empty)",
1114
+ "```",
1115
+ "",
1116
+ "## Stderr",
1117
+ "```text",
1118
+ stderr.trim() || "(empty)",
1119
+ "```",
1120
+ ""
1121
+ ].join("\n");
1122
+ }
1123
+ function advanceStateToImplementing2(snapshot) {
1124
+ if (snapshot.state === "IMPLEMENTING" /* IMPLEMENTING */) {
1125
+ return;
1126
+ }
1127
+ if (snapshot.state === "REPAIR_REQUIRED" /* REPAIR_REQUIRED */) {
1128
+ snapshot.state = transitionOrThrow(snapshot.state, "IMPLEMENTING" /* IMPLEMENTING */);
1129
+ return;
1130
+ }
1131
+ if (snapshot.state === "READY" /* READY */) {
1132
+ snapshot.state = transitionOrThrow(snapshot.state, "IMPLEMENTING" /* IMPLEMENTING */);
1133
+ return;
1134
+ }
1135
+ if (snapshot.state === "PLANNING" /* PLANNING */) {
1136
+ snapshot.state = transitionOrThrow(snapshot.state, "READY" /* READY */);
1137
+ snapshot.state = transitionOrThrow(snapshot.state, "IMPLEMENTING" /* IMPLEMENTING */);
1138
+ return;
1139
+ }
1140
+ if (snapshot.state === "BRAINSTORMING" /* BRAINSTORMING */) {
1141
+ snapshot.state = transitionOrThrow(snapshot.state, "PLANNING" /* PLANNING */);
1142
+ snapshot.state = transitionOrThrow(snapshot.state, "READY" /* READY */);
1143
+ snapshot.state = transitionOrThrow(snapshot.state, "IMPLEMENTING" /* IMPLEMENTING */);
1144
+ return;
1145
+ }
1146
+ if (snapshot.state === "DISCOVERY" /* DISCOVERY */) {
1147
+ snapshot.state = transitionOrThrow(snapshot.state, "BRAINSTORMING" /* BRAINSTORMING */);
1148
+ snapshot.state = transitionOrThrow(snapshot.state, "PLANNING" /* PLANNING */);
1149
+ snapshot.state = transitionOrThrow(snapshot.state, "READY" /* READY */);
1150
+ snapshot.state = transitionOrThrow(snapshot.state, "IMPLEMENTING" /* IMPLEMENTING */);
1151
+ return;
1152
+ }
1153
+ snapshot.state = transitionOrThrow(snapshot.state, "DISCOVERY" /* DISCOVERY */);
1154
+ snapshot.state = transitionOrThrow(snapshot.state, "BRAINSTORMING" /* BRAINSTORMING */);
1155
+ snapshot.state = transitionOrThrow(snapshot.state, "PLANNING" /* PLANNING */);
1156
+ snapshot.state = transitionOrThrow(snapshot.state, "READY" /* READY */);
1157
+ snapshot.state = transitionOrThrow(snapshot.state, "IMPLEMENTING" /* IMPLEMENTING */);
1158
+ }
1159
+
1160
+ // src/commands/doctor.ts
1161
+ var import_node_fs7 = require("fs");
1162
+ var import_node_child_process2 = require("child_process");
1163
+ function runDoctor(options) {
1164
+ const store = new WorkflowStore(options.root);
1165
+ const checks = [];
1166
+ const agyCheck = (0, import_node_child_process2.spawnSync)("sh", ["-lc", "command -v agy"], {
1167
+ cwd: options.root,
1168
+ encoding: "utf8"
1169
+ });
1170
+ checks.push({
1171
+ name: "agy command",
1172
+ ok: agyCheck.status === 0,
1173
+ detail: agyCheck.stdout.trim() || agyCheck.stderr.trim()
1174
+ });
1175
+ checks.push({
1176
+ name: ".agent-workflow directory",
1177
+ ok: (0, import_node_fs7.existsSync)(store.workflowDir)
1178
+ });
1179
+ checks.push({
1180
+ name: "STATE.md",
1181
+ ok: (0, import_node_fs7.existsSync)(store.statePath)
1182
+ });
1183
+ checks.push({
1184
+ name: "config.json",
1185
+ ok: (0, import_node_fs7.existsSync)(store.configPath)
1186
+ });
1187
+ checks.push({
1188
+ name: "AGENTS.md",
1189
+ ok: (0, import_node_fs7.existsSync)(`${options.root}/AGENTS.md`)
1190
+ });
1191
+ checks.push({
1192
+ name: ".codex/agents/codex.md",
1193
+ ok: (0, import_node_fs7.existsSync)(`${options.root}/.codex/agents/codex.md`)
1194
+ });
1195
+ checks.push({
1196
+ name: ".codex/agents/brainstormer.md",
1197
+ ok: (0, import_node_fs7.existsSync)(`${options.root}/.codex/agents/brainstormer.md`)
1198
+ });
1199
+ checks.push({
1200
+ name: ".codex/agents/planner.md",
1201
+ ok: (0, import_node_fs7.existsSync)(`${options.root}/.codex/agents/planner.md`)
1202
+ });
1203
+ checks.push({
1204
+ name: ".codex/agents/researcher.md",
1205
+ ok: (0, import_node_fs7.existsSync)(`${options.root}/.codex/agents/researcher.md`)
1206
+ });
1207
+ checks.push({
1208
+ name: ".codex/agents/business-analyst.md",
1209
+ ok: (0, import_node_fs7.existsSync)(`${options.root}/.codex/agents/business-analyst.md`)
1210
+ });
1211
+ checks.push({
1212
+ name: ".codex/agents/web-engineer.md",
1213
+ ok: (0, import_node_fs7.existsSync)(`${options.root}/.codex/agents/web-engineer.md`)
1214
+ });
1215
+ checks.push({
1216
+ name: ".codex/agents/mobile-engineer.md",
1217
+ ok: (0, import_node_fs7.existsSync)(`${options.root}/.codex/agents/mobile-engineer.md`)
1218
+ });
1219
+ checks.push({
1220
+ name: ".codex/agents/game-engineer.md",
1221
+ ok: (0, import_node_fs7.existsSync)(`${options.root}/.codex/agents/game-engineer.md`)
1222
+ });
1223
+ checks.push({
1224
+ name: ".codex/skills/codex-workflow.md",
1225
+ ok: (0, import_node_fs7.existsSync)(`${options.root}/.codex/skills/codex-workflow.md`)
1226
+ });
1227
+ checks.push({
1228
+ name: ".codex/skills/brainstorming.md",
1229
+ ok: (0, import_node_fs7.existsSync)(`${options.root}/.codex/skills/brainstorming.md`)
1230
+ });
1231
+ checks.push({
1232
+ name: ".codex/skills/planning.md",
1233
+ ok: (0, import_node_fs7.existsSync)(`${options.root}/.codex/skills/planning.md`)
1234
+ });
1235
+ checks.push({
1236
+ name: ".codex/skills/research.md",
1237
+ ok: (0, import_node_fs7.existsSync)(`${options.root}/.codex/skills/research.md`)
1238
+ });
1239
+ checks.push({
1240
+ name: ".codex/skills/requirements-analysis.md",
1241
+ ok: (0, import_node_fs7.existsSync)(`${options.root}/.codex/skills/requirements-analysis.md`)
1242
+ });
1243
+ checks.push({
1244
+ name: ".codex/skills/web-engineering.md",
1245
+ ok: (0, import_node_fs7.existsSync)(`${options.root}/.codex/skills/web-engineering.md`)
1246
+ });
1247
+ checks.push({
1248
+ name: ".codex/skills/mobile-engineering.md",
1249
+ ok: (0, import_node_fs7.existsSync)(`${options.root}/.codex/skills/mobile-engineering.md`)
1250
+ });
1251
+ checks.push({
1252
+ name: ".codex/skills/game-engineering.md",
1253
+ ok: (0, import_node_fs7.existsSync)(`${options.root}/.codex/skills/game-engineering.md`)
1254
+ });
1255
+ for (const check of checks) {
1256
+ console.log(`${check.ok ? "PASS" : "FAIL"} - ${check.name}`);
1257
+ if (check.detail) {
1258
+ console.log(` ${check.detail}`);
1259
+ }
1260
+ }
1261
+ const hasFailure = checks.some((check) => !check.ok);
1262
+ if (hasFailure) {
1263
+ process.exitCode = 1;
1264
+ }
1265
+ }
1266
+
1267
+ // src/commands/init.ts
1268
+ var import_node_fs8 = require("fs");
1269
+ var import_node_path5 = require("path");
1270
+ var defaultConfig = {
1271
+ agyCommand: "agy",
1272
+ agyArgs: [],
1273
+ maxRepairAttempts: 3
1274
+ };
1275
+ var defaultAgents = `# Codex Runtime Contract
1276
+
1277
+ Codex role: Technical Lead, Architect, Planner, Orchestrator, Reviewer, Verifier.
1278
+
1279
+ Execution order:
1280
+ Understand -> Inspect -> Clarify -> Brainstorm -> Plan -> Delegate -> Review -> Repair -> Verify -> Complete.
1281
+
1282
+ Rules:
1283
+ 1. Search before asking.
1284
+ 2. If missing context affects architecture/behavior/security/compatibility, stop and ask.
1285
+ 3. Do not invent requirements.
1286
+ 4. Do not delegate before task spec is complete.
1287
+ 5. PASS only after verification and independent review.
1288
+ `;
1289
+ var defaultWorkerRules = `# Antigravity Worker Contract
1290
+
1291
+ You are the implementation worker.
1292
+
1293
+ 1. SPEC is the contract.
1294
+ 2. REPAIR request is the correction contract.
1295
+ 3. Inspect relevant code before editing.
1296
+ 4. Implement minimal correct scope.
1297
+ 5. Add or update tests.
1298
+ 6. Run verification commands.
1299
+ 7. Report using Implementation Result contract.
1300
+ 8. Return BLOCKED if missing decision/context prevents safe completion.
1301
+ `;
1302
+ var defaultCodexAgent = `# Codex Agent Template
1303
+
1304
+ Role: Technical Lead / Planner / Reviewer
1305
+
1306
+ Use this agent for:
1307
+ - clarifying requirements
1308
+ - decomposing work into phases
1309
+ - reviewing implementation output
1310
+ - deciding PASS / FAIL / BLOCKED
1311
+
1312
+ Rules:
1313
+ 1. Keep decisions in markdown artifacts.
1314
+ 2. Do not delegate before the spec is complete.
1315
+ 3. Prefer the smallest safe next action.
1316
+ `;
1317
+ var brainstormAgent = `# Brainstormer Agent
1318
+
1319
+ Role: Discovery and problem framing.
1320
+
1321
+ Use this agent for:
1322
+ - turning a rough request into a clear problem statement
1323
+ - identifying constraints, assumptions, and unknowns
1324
+ - comparing solution options before planning
1325
+ - preparing the input for planning
1326
+
1327
+ Operating rules:
1328
+ 1. Stay in discovery; do not implement.
1329
+ 2. Capture only evidence-backed assumptions.
1330
+ 3. Prefer short, explicit notes.
1331
+ 4. End with concrete questions or a recommendation.
1332
+
1333
+ Output format:
1334
+ - Goal
1335
+ - Context
1336
+ - Constraints
1337
+ - Options
1338
+ - Risks
1339
+ - Open questions
1340
+ - Recommended next step
1341
+ `;
1342
+ var plannerAgent = `# Planner Agent
1343
+
1344
+ Role: Convert a validated brainstorm into an execution plan.
1345
+
1346
+ Use this agent for:
1347
+ - breaking work into phases and tasks
1348
+ - defining acceptance criteria
1349
+ - identifying dependencies and sequencing
1350
+ - preparing the handoff to execution
1351
+
1352
+ Operating rules:
1353
+ 1. Use the brainstorm as the source of truth.
1354
+ 2. Split work into small, ordered steps.
1355
+ 3. Keep the plan testable and recoverable.
1356
+ 4. Call out blockers explicitly.
1357
+
1358
+ Output format:
1359
+ - Objective
1360
+ - Scope
1361
+ - Phases
1362
+ - Tasks
1363
+ - Acceptance criteria
1364
+ - Verification
1365
+ - Blockers
1366
+ `;
1367
+ var defaultCodexSkill = `# Codex Skill Template
1368
+
1369
+ Use this skill when the task must be executed through the Codex flow in this kit.
1370
+
1371
+ Workflow:
1372
+ 1. Brainstorm
1373
+ 2. Plan
1374
+ 3. Execute
1375
+ 4. Delegate
1376
+ 5. Review
1377
+
1378
+ Output artifacts:
1379
+ - BRAINSTORM.md
1380
+ - PLAN.md
1381
+ - EXECUTE.md
1382
+ - RESULT.md
1383
+ - REVIEW.md
1384
+ `;
1385
+ var brainstormingSkill = `# Brainstorming Skill
1386
+
1387
+ Use this skill when you need to transform a vague request into a decision-ready problem statement.
1388
+
1389
+ Workflow:
1390
+ 1. Read the spec or request.
1391
+ 2. Identify goals, constraints, unknowns, and risks.
1392
+ 3. Compare at least two viable approaches.
1393
+ 4. Recommend the safest next step.
1394
+
1395
+ Outputs:
1396
+ - BRAINSTORM.md
1397
+ - Decision notes
1398
+ - Open questions
1399
+
1400
+ Do not implement code in this phase.
1401
+ `;
1402
+ var planningSkill = `# Planning Skill
1403
+
1404
+ Use this skill when the request is ready to be turned into an execution plan.
1405
+
1406
+ Workflow:
1407
+ 1. Consume the brainstorm output.
1408
+ 2. Break the work into phases.
1409
+ 3. Add acceptance criteria and verification steps.
1410
+ 4. Prepare a clear execution handoff.
1411
+
1412
+ Outputs:
1413
+ - PLAN.md
1414
+ - Task breakdown
1415
+ - Verification checklist
1416
+ - Handoff notes
1417
+
1418
+ Do not delegate implementation until the plan is complete.
1419
+ `;
1420
+ var researcherAgent = `# Researcher Agent
1421
+
1422
+ Role: Deep Technical Research, Spikes, Architecture Benchmarks & Feasibility.
1423
+
1424
+ Use this agent for:
1425
+ - investigating unknown technical domains, new libraries, or unfamiliar APIs
1426
+ - conducting technical spikes and feasibility studies before architectural commitment
1427
+ - comparing competing frameworks, protocols, and third-party services
1428
+ - identifying hidden constraints, license obligations, deprecations, and performance bottlenecks
1429
+ - analyzing state-of-the-art implementations and industry best practices
1430
+
1431
+ Operating rules:
1432
+ 1. Search code and documentation before speculating.
1433
+ 2. Provide concrete evidence, benchmarks, or citations for claims.
1434
+ 3. Compare at least 2 viable approaches with explicit trade-offs (pros/cons/risks).
1435
+ 4. Never assume third-party API contracts without verifying current versions.
1436
+ 5. Conclude with a definitive, actionable recommendation and a risk mitigation strategy.
1437
+
1438
+ Output format:
1439
+ - Research Objective & Scope
1440
+ - Background & Current State
1441
+ - Evaluated Options (Trade-off Matrix)
1442
+ - Spike / Proof of Concept Findings
1443
+ - Risks & Breaking Changes
1444
+ - Recommended Architecture / Path Forward
1445
+ `;
1446
+ var businessAnalystAgent = `# Business Analyst (BA) Agent
1447
+
1448
+ Role: Requirements Elicitation, User Story Breakdown, Domain Modeling & Acceptance Criteria Engineering.
1449
+
1450
+ Use this agent for:
1451
+ - turning unstructured business requirements or user requests into precise functional specifications
1452
+ - identifying distinct user personas, user journeys, and role-based permissions
1453
+ - uncovering non-obvious edge cases, error scenarios, and business boundary rules
1454
+ - authoring testable acceptance criteria using Gherkin (Given / When / Then) syntax
1455
+ - mapping domain entities, data dictionaries, and state transition lifecycles
1456
+
1457
+ Operating rules:
1458
+ 1. Do not invent requirements; clarify ambiguities with explicit questions or assumptions.
1459
+ 2. Separate business logic and user intent from technical implementation details.
1460
+ 3. Every functional requirement must have at least one testable acceptance criterion.
1461
+ 4. Always specify happy path, alternative paths, and negative/failure paths.
1462
+ 5. Highlight all dependencies on external systems, legal/compliance rules, and business limits.
1463
+
1464
+ Output format:
1465
+ - Feature Summary & Business Value
1466
+ - User Personas & Permissions
1467
+ - User Stories & Workflows
1468
+ - Functional & Non-Functional Requirements
1469
+ - Edge Cases & Negative Scenarios
1470
+ - Acceptance Criteria (Given/When/Then)
1471
+ - Open Questions & Assumptions
1472
+ `;
1473
+ var webEngineerAgent = `# Web Engineer Agent
1474
+
1475
+ Role: Modern Web Architecture & Engineering Specialist (Frontend, Backend, APIs, Performance).
1476
+
1477
+ Use this agent for:
1478
+ - designing responsive frontend architectures (React, Next.js, Vue, Svelte, Vanilla HTML/CSS/JS)
1479
+ - building resilient backend services and APIs (Node.js/TypeScript, Go, Python, REST, GraphQL, WebSocket)
1480
+ - defining state management, data caching, optimistic UI updates, and server components
1481
+ - enforcing modern web performance (Core Web Vitals: LCP, INP, CLS) and responsive design
1482
+ - securing web applications against XSS, CSRF, SSRF, CORS misconfigurations, and injection attacks
1483
+ - establishing SEO, accessibility (WCAG 2.1 AA, ARIA roles), and progressive enhancement standards
1484
+
1485
+ Operating rules:
1486
+ 1. Adhere to repository coding patterns and modern framework idioms (prefer web standards and composable patterns).
1487
+ 2. Never hardcode sensitive tokens or environment secrets into client-side bundles.
1488
+ 3. Design UI components for responsiveness across mobile, tablet, and desktop breakpoints.
1489
+ 4. Keep network waterfalls minimal: optimize bundle size, leverage code splitting and caching headers.
1490
+ 5. All interactive UI elements must have unique test identifiers and valid keyboard focus management.
1491
+
1492
+ Output format:
1493
+ - Web Architecture & Tech Stack Details
1494
+ - Component Hierarchy & State Flow
1495
+ - API Contracts & Data Schemas
1496
+ - Routing & Navigation Structure
1497
+ - Performance & Security Constraints
1498
+ - Verification & Test Matrix (Unit, Integration, E2E)
1499
+ `;
1500
+ var mobileEngineerAgent = `# Mobile Engineer Agent
1501
+
1502
+ Role: Mobile Application Architecture & Engineering Specialist (Cross-Platform & Native).
1503
+
1504
+ Use this agent for:
1505
+ - architecting cross-platform apps using Flutter/Dart or React Native/Expo
1506
+ - engineering native iOS applications (Swift, SwiftUI, UIKit, Combine/Async-Await)
1507
+ - engineering native Android applications (Kotlin, Jetpack Compose, Coroutines/Flow)
1508
+ - managing mobile lifecycle states (foreground, background, suspended, terminated)
1509
+ - designing offline-first local storage, SQLite/Room/CoreData/WatermelonDB/Hive, and background sync
1510
+ - handling device hardware integrations: Push notifications, Biometrics, Camera, Geolocation, Bluetooth
1511
+ - configuring native build pipelines, signing, permissions, deep linking, and App Store/Play Store readiness
1512
+
1513
+ Operating rules:
1514
+ 1. Respect native operating system guidelines (Apple Human Interface Guidelines and Material Design 3).
1515
+ 2. Handle network flakiness gracefully: implement retries, offline caching, and optimistic local state.
1516
+ 3. Treat app permissions defensively: request at runtime with clear user rationale and fallback states.
1517
+ 4. Avoid main-thread blocking; offload heavy computations and disk I/O to background workers/isolates.
1518
+ 5. Account for device fragmentation: test various screen aspect ratios, safe areas, notches, and dark mode.
1519
+
1520
+ Output format:
1521
+ - Target Platform & Architecture (Native iOS/Android, React Native, or Flutter)
1522
+ - State Management & Navigation Hierarchy
1523
+ - Local Storage & Offline Sync Strategy
1524
+ - Native Capabilities & Permission Handling
1525
+ - Device Lifecycle & Memory Considerations
1526
+ - Build, Verification & Device Testing Strategy
1527
+ `;
1528
+ var gameEngineerAgent = `# Game Engineer Agent
1529
+
1530
+ Role: Game Systems Architecture, Gameplay Mechanics & Engine Specialist (Unity, Godot, Cocos Creator).
1531
+
1532
+ Use this agent for:
1533
+ - architecting game systems across major game engines:
1534
+ - Unity: C#, GameObject/Component lifecycle, ScriptableObjects, DOTS/Burst, Addressables
1535
+ - Godot: GDScript / C#, Node tree hierarchy, Scene inheritance, Signals, Resource system
1536
+ - Cocos Creator: TypeScript, Component lifecycle, Prefabs, Canvas/UI, WebGL/HTML5 packaging
1537
+ - developing core gameplay loops, mechanics, player controllers, and input action maps
1538
+ - designing Entity-Component-System (ECS) and data-driven state machines
1539
+ - configuring 2D/3D physics, collision layers, rigid bodies, raycasting, and triggers
1540
+ - managing asset pipelines: sprites, tilemaps, 3D meshes, particle effects, animations, and audio mixers
1541
+ - profiling and optimizing game performance: frame-rate stability (60/120 FPS), draw calls, texture atlases, garbage collection pauses
1542
+
1543
+ Operating rules:
1544
+ 1. Keep gameplay logic decoupled from rendering and engine-specific editor scripts where feasible.
1545
+ 2. Optimize memory allocations in the hot game loop (Update / _process) to prevent GC spikes.
1546
+ 3. Physics updates must run in fixed timesteps (FixedUpdate / _physics_process).
1547
+ 4. Manage scene and asset lifecycles strictly to eliminate memory leaks and dangling event listeners.
1548
+ 5. Provide deterministic fallback logic and verification tests for core game rules and mathematical calculations.
1549
+
1550
+ Output format:
1551
+ - Game Engine, Version & Render Pipeline Selection
1552
+ - Core Game Loop & Gameplay Mechanics Architecture
1553
+ - Scene / Node Hierarchy & Component Relationships
1554
+ - Physics, Collision Matrix & Input Handling
1555
+ - Asset Management & Performance Budget (Draw calls, Memory, Target FPS)
1556
+ - Verification Checklist & Playtest Strategy
1557
+ `;
1558
+ var researchSkill = `# Technical Research Skill
1559
+
1560
+ Use this skill when tackling technical uncertainty, evaluating new libraries, prototyping spikes, or comparing architectural designs.
1561
+
1562
+ Workflow:
1563
+ 1. Frame the Spike: Define the research question, target hypothesis, constraints, and success criteria.
1564
+ 2. Explore Existing Solutions: Inspect repository codebase, official documentation, ecosystem libraries, and community benchmarks.
1565
+ 3. Compare Alternatives: Benchmark at least 2 distinct approaches across complexity, maintenance, scalability, security, and developer experience.
1566
+ 4. Prototype & Validate: Run minimal proof-of-concept tests or sandbox experiments to verify critical assumptions.
1567
+ 5. Document & Recommend: Synthesize findings into clear architectural guidance, trade-offs, and an actionable implementation path.
1568
+
1569
+ Outputs:
1570
+ - Research findings artifact (RESEARCH.md or section in BRAINSTORM.md)
1571
+ - Technical comparison matrix
1572
+ - Decision record with trade-offs and rationale
1573
+ - Risk assessment and mitigation plan
1574
+ `;
1575
+ var requirementsAnalysisSkill = `# Requirements Analysis Skill
1576
+
1577
+ Use this skill when translating high-level business goals, user feedback, or feature requests into actionable, testable technical requirements.
1578
+
1579
+ Workflow:
1580
+ 1. Clarify Business Intent: Elicit the core user problem, business metrics, and target audience.
1581
+ 2. Deconstruct User Journeys: Map end-to-end flows covering happy path, alternative paths, and error scenarios.
1582
+ 3. Formulate Acceptance Criteria: Write precise, testable criteria using Gherkin syntax (Given [context], When [action], Then [outcome]).
1583
+ 4. Identify Non-Functional Requirements: Specify performance targets, security rules, compliance, and accessibility standards.
1584
+ 5. Surface Unknowns: Flag open questions, unconfirmed business logic, and potential edge cases before planning.
1585
+
1586
+ Outputs:
1587
+ - Business requirements specification (REQUIREMENTS.md or section in SPEC.md)
1588
+ - User stories with Gherkin acceptance criteria
1589
+ - Domain entities & data dictionary definitions
1590
+ - Edge case checklist & business validation rules
1591
+ `;
1592
+ var webEngineeringSkill = `# Web Engineering Skill
1593
+
1594
+ Use this skill when designing, implementing, or optimizing fullstack web applications, frontends, APIs, and modern web architectures.
1595
+
1596
+ Workflow:
1597
+ 1. Analyze Repository & Tech Stack: Inspect active frameworks (React, Next.js, Vue, Node.js, etc.), state stores, design systems, and package dependencies.
1598
+ 2. Design Component & State Flow: Architect clean component boundaries, unidirectional data flow, server/client state segregation, and error boundaries.
1599
+ 3. Specify API Contracts: Define type-safe request/response schemas (TypeScript, Zod, OpenAPI, GraphQL) and error handling codes.
1600
+ 4. Enforce UX, Performance & Accessibility: Apply responsive layouts, Core Web Vitals optimizations (LCP, INP, CLS), keyboard navigation, and ARIA roles.
1601
+ 5. Formulate Verification Matrix: Define unit tests (Vitest/Jest), component tests, and end-to-end integration scenarios (Playwright/Cypress).
1602
+
1603
+ Outputs:
1604
+ - Web implementation plan (PLAN.md with web-specific phase breakdown)
1605
+ - Component hierarchy and data flow diagrams
1606
+ - API schema specifications and endpoint contracts
1607
+ - Performance, security, and accessibility verification checklist
1608
+ `;
1609
+ var mobileEngineeringSkill = `# Mobile Engineering Skill
1610
+
1611
+ Use this skill when developing, refactoring, or optimizing native (iOS Swift, Android Kotlin) and cross-platform (Flutter, React Native) mobile applications.
1612
+
1613
+ Workflow:
1614
+ 1. Target Platform & Framework Audit: Inspect whether the app is Flutter, React Native, Swift/SwiftUI, or Kotlin/Jetpack Compose, plus target SDK versions.
1615
+ 2. Design Navigation & State Hierarchy: Define screen stacks, tabs, modals, deep linking schemes, and application-wide state management.
1616
+ 3. Architect Storage & Offline Capability: Specify local caching, SQLite / Room / CoreData / WatermelonDB schemas, and background sync strategies.
1617
+ 4. Integrate Native Device Capabilities: Structure permission flows, push notifications, hardware access, and platform bridges/plugins defensively.
1618
+ 5. Formulate Verification & Emulation Matrix: Specify unit tests, widget/component tests, and platform-specific simulator/device build commands.
1619
+
1620
+ Outputs:
1621
+ - Mobile technical implementation plan
1622
+ - Screen navigation and state transition map
1623
+ - Local database schema and offline sync rules
1624
+ - Platform permission checklist and native configuration guidelines
1625
+ `;
1626
+ var gameEngineeringSkill = `# Game Engineering Skill
1627
+
1628
+ Use this skill when developing, refactoring, or optimizing games across Unity, Godot, or Cocos Creator engines.
1629
+
1630
+ Workflow:
1631
+ 1. Engine & Architecture Assessment: Identify game engine (Unity C#, Godot GDScript/C#, Cocos Creator TypeScript), rendering pipeline, and target platforms (PC, Mobile, WebGL, Console).
1632
+ 2. Gameplay Loops & Mechanics Design: Structure the primary game loop, player controllers, state machines, and event dispatchers.
1633
+ 3. Scene, Node & Entity Architecture: Establish clean scene hierarchies, prefabs/nodes composition, and decouple gameplay logic from presentation.
1634
+ 4. Physics, Collision & Input Integration: Configure collision layers/masks, rigid body properties, input action maps, and fixed-timestep calculations.
1635
+ 5. Optimization & Performance Profiling: Audit hot loop allocations, draw call batching, texture atlases, object pooling, and target frame rate (60/120 FPS).
1636
+
1637
+ Outputs:
1638
+ - Game architecture & mechanics implementation plan
1639
+ - Scene hierarchy and component relationship specification
1640
+ - Physics collision matrix and input mapping configuration
1641
+ - Object pooling and memory optimization checklist
1642
+ - Verification plan with deterministic math/logic tests and playtest criteria
1643
+ `;
1644
+ function runInit(options) {
1645
+ const store = new WorkflowStore(options.root);
1646
+ store.ensureBaseStructure();
1647
+ const architecturePath = (0, import_node_path5.join)(store.workflowDir, "ARCHITECTURE.md");
1648
+ const projectPath = (0, import_node_path5.join)(store.workflowDir, "PROJECT.md");
1649
+ const decisionsPath = (0, import_node_path5.join)(store.workflowDir, "DECISIONS.md");
1650
+ const agentsPath = (0, import_node_path5.join)(options.root, "AGENTS.md");
1651
+ const codexDir = (0, import_node_path5.join)(options.root, ".codex");
1652
+ const codexAgentsDir = (0, import_node_path5.join)(codexDir, "agents");
1653
+ const codexSkillsDir = (0, import_node_path5.join)(codexDir, "skills");
1654
+ const workerDir = (0, import_node_path5.join)(options.root, ".antigravity");
1655
+ const workerPath = (0, import_node_path5.join)(workerDir, "WORKER_RULES.md");
1656
+ (0, import_node_fs8.mkdirSync)(codexDir, { recursive: true });
1657
+ (0, import_node_fs8.mkdirSync)(codexAgentsDir, { recursive: true });
1658
+ (0, import_node_fs8.mkdirSync)(codexSkillsDir, { recursive: true });
1659
+ if (!(0, import_node_fs8.existsSync)(workerDir)) {
1660
+ (0, import_node_fs8.mkdirSync)(workerDir, { recursive: true });
1661
+ (0, import_node_fs8.writeFileSync)((0, import_node_path5.join)(workerDir, ".gitkeep"), "", "utf8");
1662
+ }
1663
+ writeIfMissing(projectPath, "# Project\n\nDescribe project-level goals and boundaries.\n", options.force);
1664
+ writeIfMissing(
1665
+ architecturePath,
1666
+ "# Architecture\n\nDocument Codex brain, bridge, worker, state, and review loop architecture.\n",
1667
+ options.force
1668
+ );
1669
+ writeIfMissing(decisionsPath, "# Decisions\n\nLog only material architectural/product decisions.\n", options.force);
1670
+ writeIfMissing((0, import_node_path5.join)(codexAgentsDir, "brainstormer.md"), brainstormAgent, options.force);
1671
+ writeIfMissing((0, import_node_path5.join)(codexAgentsDir, "planner.md"), plannerAgent, options.force);
1672
+ writeIfMissing((0, import_node_path5.join)(codexAgentsDir, "codex.md"), defaultCodexAgent, options.force);
1673
+ writeIfMissing((0, import_node_path5.join)(codexAgentsDir, "researcher.md"), researcherAgent, options.force);
1674
+ writeIfMissing((0, import_node_path5.join)(codexAgentsDir, "business-analyst.md"), businessAnalystAgent, options.force);
1675
+ writeIfMissing((0, import_node_path5.join)(codexAgentsDir, "web-engineer.md"), webEngineerAgent, options.force);
1676
+ writeIfMissing((0, import_node_path5.join)(codexAgentsDir, "mobile-engineer.md"), mobileEngineerAgent, options.force);
1677
+ writeIfMissing((0, import_node_path5.join)(codexAgentsDir, "game-engineer.md"), gameEngineerAgent, options.force);
1678
+ writeIfMissing((0, import_node_path5.join)(codexSkillsDir, "brainstorming.md"), brainstormingSkill, options.force);
1679
+ writeIfMissing((0, import_node_path5.join)(codexSkillsDir, "planning.md"), planningSkill, options.force);
1680
+ writeIfMissing((0, import_node_path5.join)(codexSkillsDir, "codex-workflow.md"), defaultCodexSkill, options.force);
1681
+ writeIfMissing((0, import_node_path5.join)(codexSkillsDir, "research.md"), researchSkill, options.force);
1682
+ writeIfMissing((0, import_node_path5.join)(codexSkillsDir, "requirements-analysis.md"), requirementsAnalysisSkill, options.force);
1683
+ writeIfMissing((0, import_node_path5.join)(codexSkillsDir, "web-engineering.md"), webEngineeringSkill, options.force);
1684
+ writeIfMissing((0, import_node_path5.join)(codexSkillsDir, "mobile-engineering.md"), mobileEngineeringSkill, options.force);
1685
+ writeIfMissing((0, import_node_path5.join)(codexSkillsDir, "game-engineering.md"), gameEngineeringSkill, options.force);
1686
+ if (!(0, import_node_fs8.existsSync)(store.statePath) || options.force) {
1687
+ const state = defaultState();
1688
+ state.state = "IDLE" /* IDLE */;
1689
+ state.nextAction = "Start discovery for a feature request";
1690
+ store.writeState(state);
1691
+ }
1692
+ if (!(0, import_node_fs8.existsSync)(store.configPath) || options.force) {
1693
+ store.writeConfig(defaultConfig);
1694
+ }
1695
+ writeIfMissing(agentsPath, defaultAgents, options.force);
1696
+ writeIfMissing(workerPath, defaultWorkerRules, options.force);
1697
+ console.log("Initialized codex-antigravity kit");
1698
+ console.log(`Workflow dir: ${store.workflowDir}`);
1699
+ }
1700
+ function writeIfMissing(path, content, force) {
1701
+ if (!(0, import_node_fs8.existsSync)(path) || force) {
1702
+ (0, import_node_fs8.writeFileSync)(path, content, "utf8");
1703
+ return;
1704
+ }
1705
+ const current = (0, import_node_fs8.readFileSync)(path, "utf8");
1706
+ if (current.trim().length === 0) {
1707
+ (0, import_node_fs8.writeFileSync)(path, content, "utf8");
1708
+ }
1709
+ }
1710
+
1711
+ // src/commands/review.ts
1712
+ var import_node_fs9 = require("fs");
1713
+ function runReview(options) {
1714
+ const store = new WorkflowStore(options.root);
1715
+ const state = store.readState();
1716
+ const config = store.readConfig();
1717
+ const loop = new RepairLoop(config.maxRepairAttempts);
1718
+ const reviewContent = options.reviewFile ? (0, import_node_fs9.readFileSync)(options.reviewFile, "utf8") : `# Review
1719
+
1720
+ Outcome: ${options.outcome}
1721
+ `;
1722
+ store.writeTaskFile(options.task, "REVIEW.md", reviewContent);
1723
+ state.currentTask = options.task;
1724
+ state.reviewAttempt += 1;
1725
+ if (options.outcome === "PASS") {
1726
+ state.state = "COMPLETED" /* COMPLETED */;
1727
+ state.nextAction = "Task completed. Return to IDLE when ready.";
1728
+ state.blockingIssues = [];
1729
+ } else if (options.outcome === "BLOCKED") {
1730
+ state.state = "ESCALATION_REQUIRED" /* ESCALATION_REQUIRED */;
1731
+ state.nextAction = "Escalate blocking issue to user";
1732
+ state.blockingIssues = ["Reviewer marked task as BLOCKED"];
1733
+ } else {
1734
+ state.repairAttempt += 1;
1735
+ if (loop.needsEscalation(state.repairAttempt)) {
1736
+ state.state = "ESCALATION_REQUIRED" /* ESCALATION_REQUIRED */;
1737
+ state.nextAction = "Repair attempts exceeded limit. Escalate to user.";
1738
+ state.blockingIssues = [
1739
+ `Max repair attempts exceeded (${config.maxRepairAttempts})`
1740
+ ];
1741
+ } else {
1742
+ state.state = "REPAIR_REQUIRED" /* REPAIR_REQUIRED */;
1743
+ state.nextAction = "Prepare targeted repair request and delegate again";
1744
+ state.blockingIssues = [];
1745
+ }
1746
+ }
1747
+ state.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1748
+ store.writeState(state);
1749
+ console.log(`Review outcome recorded: ${options.outcome}`);
1750
+ console.log(`State is now: ${state.state}`);
1751
+ }
1752
+
1753
+ // src/commands/status.ts
1754
+ function runStatus(options) {
1755
+ const store = new WorkflowStore(options.root);
1756
+ const state = store.readState();
1757
+ console.log("Current workflow status");
1758
+ console.log(`State: ${state.state}`);
1759
+ console.log(`Current phase: ${state.currentPhase}`);
1760
+ console.log(`Current task: ${state.currentTask}`);
1761
+ console.log(`Review attempt: ${state.reviewAttempt}`);
1762
+ console.log(`Repair attempt: ${state.repairAttempt}`);
1763
+ console.log(`Next action: ${state.nextAction}`);
1764
+ console.log(`Updated at: ${state.updatedAt}`);
1765
+ if (state.blockingIssues.length > 0) {
1766
+ console.log("Blocking issues:");
1767
+ for (const issue of state.blockingIssues) {
1768
+ console.log(`- ${issue}`);
1769
+ }
1770
+ }
1771
+ }
1772
+ // Annotate the CommonJS export names for ESM import in node:
1773
+ 0 && (module.exports = {
1774
+ KNOWN_AGENTS,
1775
+ RepairLoop,
1776
+ ShellAgyAdapter,
1777
+ WorkflowState,
1778
+ WorkflowStore,
1779
+ canTransition,
1780
+ defaultState,
1781
+ detectAgent,
1782
+ parseWorkerResult,
1783
+ runBrainstorm,
1784
+ runDelegate,
1785
+ runDelegateWithAdapter,
1786
+ runDoctor,
1787
+ runExecute,
1788
+ runExecuteWithAdapter,
1789
+ runInit,
1790
+ runPlan,
1791
+ runReview,
1792
+ runStatus,
1793
+ transitionOrThrow
1794
+ });