@mamdouh-aboammar/agentic-workflow 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/.claude-plugin/plugin.json +10 -0
  2. package/.codex-plugin/plugin.json +13 -0
  3. package/.skills.json +19 -0
  4. package/AGENTS.md +1344 -0
  5. package/CLAUDE.md +178 -0
  6. package/GEMINI.md +102 -0
  7. package/LICENSE +21 -0
  8. package/README.md +350 -0
  9. package/SKILL.md +132 -0
  10. package/bin/agentic-hooks.sh +79 -0
  11. package/bin/cli.js +1060 -0
  12. package/core/__init__.py +52 -0
  13. package/core/ai_evaluator.py +117 -0
  14. package/core/autopilot_engine.py +368 -0
  15. package/core/clean_code_guard.py +188 -0
  16. package/core/engine_py/__init__.py +29 -0
  17. package/core/engine_py/agent_worker.py +136 -0
  18. package/core/engine_py/decider.py +150 -0
  19. package/core/engine_py/energy.py +45 -0
  20. package/core/engine_py/event_bus.py +63 -0
  21. package/core/engine_py/executor.py +186 -0
  22. package/core/engine_py/models.py +193 -0
  23. package/core/engine_py/queue.py +314 -0
  24. package/core/engine_py/runner.py +116 -0
  25. package/core/engine_py/system_workers.py +70 -0
  26. package/core/engine_py/toon_adapter.py +586 -0
  27. package/core/engine_py/verification_controller.py +208 -0
  28. package/core/engine_py/worker.py +167 -0
  29. package/core/engine_spec/event_schema.json +65 -0
  30. package/core/engine_spec/example_workflow.yaml +73 -0
  31. package/core/engine_spec/workflow_schema.json +127 -0
  32. package/core/hooks/__init__.py +29 -0
  33. package/core/hooks/adapters/__init__.py +25 -0
  34. package/core/hooks/adapters/claude_adapter.py +83 -0
  35. package/core/hooks/adapters/cli_agent_adapter.py +82 -0
  36. package/core/hooks/adapters/codex_adapter.py +78 -0
  37. package/core/hooks/adapters/cursor_adapter.py +73 -0
  38. package/core/hooks/adapters/gemini_adapter.py +93 -0
  39. package/core/hooks/adapters/homebrew_adapter.py +69 -0
  40. package/core/hooks/adapters/mcp_proxy.py +133 -0
  41. package/core/hooks/adapters/shell_adapter.py +65 -0
  42. package/core/hooks/dispatcher.py +118 -0
  43. package/core/hooks/policy_engine.py +375 -0
  44. package/core/hooks/session_end.py +141 -0
  45. package/core/hooks/types.py +147 -0
  46. package/core/integrations/__init__.py +28 -0
  47. package/core/integrations/installer.py +225 -0
  48. package/core/integrations/lifecycle_director.py +175 -0
  49. package/core/integrations/registry.py +105 -0
  50. package/core/multi_agent_system.py +164 -0
  51. package/core/skills_indexer.py +742 -0
  52. package/core/system/__init__.py +25 -0
  53. package/core/system/announcements.py +72 -0
  54. package/core/system/dependencies.py +69 -0
  55. package/core/system/doctor.py +171 -0
  56. package/core/system/health.py +144 -0
  57. package/core/system/installer.py +137 -0
  58. package/core/system/notifications.py +97 -0
  59. package/core/system/refresher.py +110 -0
  60. package/core/system/updater.py +167 -0
  61. package/core/system/version_tracker.py +65 -0
  62. package/docs/architecture_plan.md +7 -0
  63. package/docs/guides/failure-recovery.md +714 -0
  64. package/docs/implementation_summary.md +10 -0
  65. package/docs/protocols/autopilot-execution.md +148 -0
  66. package/docs/protocols/code-change-protocol.md +49 -0
  67. package/docs/protocols/context-preservation-detail.md +114 -0
  68. package/docs/protocols/quality-gates.md +110 -0
  69. package/docs/protocols/ulw-mode.md +60 -0
  70. package/docs/research_findings.md +10 -0
  71. package/docs/solutions/autonomous-autopilot-engine-architecture.md +38 -0
  72. package/install.sh +111 -0
  73. package/marketplace.json +37 -0
  74. package/package.json +81 -0
  75. package/skills/agentic-workflow/SKILL.md +132 -0
  76. package/skills/agentic-workflow/skill-spec.json +100 -0
  77. package/soul.md +445 -0
  78. package/src/engine_ts/decider.ts +186 -0
  79. package/src/engine_ts/event-bus.ts +57 -0
  80. package/src/engine_ts/executor.ts +262 -0
  81. package/src/engine_ts/index.ts +12 -0
  82. package/src/engine_ts/queue.ts +93 -0
  83. package/src/engine_ts/runner.ts +108 -0
  84. package/src/engine_ts/skills-indexer.ts +264 -0
  85. package/src/engine_ts/toon-adapter.ts +91 -0
  86. package/src/engine_ts/types.ts +134 -0
  87. package/src/engine_ts/verification-controller.ts +204 -0
  88. package/src/engine_ts/worker.ts +280 -0
  89. package/src/hooks/adapters/claude-adapter.ts +54 -0
  90. package/src/hooks/adapters/cli-agent-adapter.ts +46 -0
  91. package/src/hooks/adapters/codex-adapter.ts +69 -0
  92. package/src/hooks/adapters/cursor-adapter.ts +60 -0
  93. package/src/hooks/adapters/gemini-adapter.ts +71 -0
  94. package/src/hooks/adapters/homebrew-adapter.ts +36 -0
  95. package/src/hooks/adapters/mcp-proxy.ts +66 -0
  96. package/src/hooks/adapters/shell-adapter.ts +42 -0
  97. package/src/hooks/dispatcher.ts +113 -0
  98. package/src/hooks/index.ts +16 -0
  99. package/src/hooks/policy-engine.ts +376 -0
  100. package/src/hooks/session-end.ts +125 -0
  101. package/src/hooks/types.ts +61 -0
  102. package/src/index.d.ts +34 -0
  103. package/src/index.ts +23 -0
  104. package/src/integrations/index.ts +7 -0
  105. package/src/integrations/installer.ts +208 -0
  106. package/src/integrations/lifecycle-director.ts +139 -0
  107. package/src/integrations/registry.ts +82 -0
  108. package/src/system/announcements.ts +143 -0
  109. package/src/system/dependencies.ts +176 -0
  110. package/src/system/doctor.ts +374 -0
  111. package/src/system/health.ts +270 -0
  112. package/src/system/index.ts +14 -0
  113. package/src/system/installer.ts +262 -0
  114. package/src/system/notifications.ts +180 -0
  115. package/src/system/refresher.ts +207 -0
  116. package/src/system/types.ts +268 -0
  117. package/src/system/updater.ts +219 -0
  118. package/src/system/version-tracker.ts +137 -0
package/bin/cli.js ADDED
@@ -0,0 +1,1060 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * AgenticWorkflow CLI โ€” Universal Autonomous Agentic Toolchain
4
+ *
5
+ * Implements:
6
+ * - Autopilot End-to-End Self-Driving Execution Loop
7
+ * - Clean Code Guard & AI Failure-Mode Auditor
8
+ * - Multi-Agent System Architecture & Trace Observability
9
+ * - AI Engineering & Evaluation Gates
10
+ */
11
+
12
+ import { execSync } from 'node:child_process';
13
+ import process from 'node:process';
14
+ import path from 'node:path';
15
+ import fs from 'node:fs';
16
+ import { fileURLToPath } from 'node:url';
17
+
18
+ const __filename = fileURLToPath(import.meta.url);
19
+ const __dirname = path.dirname(__filename);
20
+ const rootDir = path.resolve(__dirname, '..');
21
+
22
+ const args = process.argv.slice(2);
23
+ const command = args[0] || 'help';
24
+
25
+ function printHelp() {
26
+ console.log(`
27
+ โšก AgenticWorkflow CLI โ€” Universal Autonomous Agentic Toolchain โšก
28
+
29
+ Usage:
30
+ agentic-workflow <command> [options]
31
+
32
+ Core Autonomous Commands:
33
+ engine Run event-driven agentic workflow engine (Python AsyncIO or TypeScript/Bun)
34
+ autopilot, run, drive Execute autonomous workflow end-to-end with self-fueling & circuit breakers
35
+ skills, skills-mesh Discover, index, search, and resolve agentic nodes and skills (JSON/TOON)
36
+ guard, clean-code Run Clean Code Guard pass (SOLID, 24 Imperatives, AI failure modes)
37
+ eval, evaluate Run AI Engineer fairness, prompt-injection, and drift evaluation
38
+ traces, observability Inspect multi-agent observable trace records
39
+ hooks, uahf Universal Agentic Hooks Framework (consume, govern, and audit all agents)
40
+ drivers, adapters Inspect and manage platform execution drivers (Gemini, Cursor, Codex, Claude)
41
+ omni-skill, omni OmniSkill dynamic agentic routing, SkillSpec compiler & portability gate
42
+ integrations, tools Manage supportive tools (Ponytail, TOON, Fable, Caveman, OmniSkill) & lifecycle
43
+ fable, get-fable Fable lifecycle routing, handoff compaction, and continuation state
44
+ toon Token-Oriented Object Notation (v4.1) density benchmark and conversion
45
+
46
+ System Toolchain & Ecosystem Commands:
47
+ update, upgrade Check and apply updates cleanly with automatic rollback
48
+ install, setup Universal multi-host installer, shell RC & completion
49
+ refresh, reload Hot reload runtime, clear caches, re-index skills mesh
50
+ doctor Diagnose environment, permissions, runtimes, SOT, hooks (--fix)
51
+ health, monitor Real-time health scoring, vitals & high-density TOON telemetry
52
+ deps, dependencies Audit, tree, verify and install multi-ecosystem dependencies
53
+ notify, notifications CLI/terminal banners & native desktop alerts (send|test|history|clear)
54
+ announcements, bulletin Broadcast bulletins, release highlights, unread alerts
55
+ version, versions Component matrix, git tracking, changelog, migration runner
56
+
57
+ Standard Toolchain Commands:
58
+ init Initialize SOT runtime directories and verify hook infrastructure
59
+ validate Validate workflow state, SOT schema, and pACS log integrity
60
+ status Display live workflow dashboard and observability metrics
61
+ test Run full automated test suite (safety, guard, MAS, evaluator, engines)
62
+ help Show this help message
63
+
64
+ Options:
65
+ --runtime <py|ts> Engine runtime selection (default: ts)
66
+ --title <text> Project title for autopilot workflow
67
+ --goal <text> Core objective / goal for autopilot workflow
68
+ --format <toon|json> Telemetry/audit output format (default: human)
69
+ --fix Automatically remediate doctor check failures
70
+ --version, -v Show version
71
+ --help, -h Show help
72
+ `);
73
+ }
74
+
75
+ function parseArgValue(flag) {
76
+ const idx = args.indexOf(flag);
77
+ if (idx !== -1 && idx + 1 < args.length) {
78
+ return args[idx + 1];
79
+ }
80
+ return null;
81
+ }
82
+
83
+ // Non-intrusive broadcast announcement check
84
+ if (!['test', '--version', '-v', 'help', '--help', '-h'].includes(command)) {
85
+ try {
86
+ const { AnnouncementEngine } = await import("../src/system/announcements.ts");
87
+ const announcer = new AnnouncementEngine(rootDir);
88
+ const banner = announcer.renderBroadcastBanner();
89
+ if (banner) {
90
+ process.stderr.write(banner);
91
+ }
92
+ } catch {
93
+ // Ignore announcement check failure
94
+ }
95
+ }
96
+
97
+ switch (command) {
98
+ case 'engine': {
99
+ const runtime = parseArgValue('--runtime') || 'ts';
100
+ console.log(`โšก [agentic-workflow] Launching Event-Driven Engine [Runtime: ${runtime.toUpperCase()}]...`);
101
+ try {
102
+ if (runtime === 'py' || runtime === 'python') {
103
+ execSync(`python3 core/engine_py/runner.py`, { cwd: rootDir, stdio: 'inherit' });
104
+ } else {
105
+ execSync(`bun run src/engine_ts/runner.ts`, { cwd: rootDir, stdio: 'inherit' });
106
+ }
107
+ } catch (e) {
108
+ console.error(`โŒ Engine execution failed.`);
109
+ process.exit(1);
110
+ }
111
+ break;
112
+ }
113
+
114
+ case 'autopilot':
115
+ case 'run':
116
+ case 'drive': {
117
+ const title = parseArgValue('--title') || 'Autonomous Production Workflow';
118
+ const goal = parseArgValue('--goal') || 'Autonomous end-to-end execution without user bottleneck';
119
+ console.log(`๐Ÿš€ [agentic-workflow] Launching Autopilot Engine...`);
120
+ console.log(` Title: "${title}"`);
121
+ console.log(` Goal: "${goal}"`);
122
+ try {
123
+ const script = `
124
+ from core.autopilot_engine import AutopilotEngine
125
+ engine = AutopilotEngine(project_dir="${rootDir}", auto_approve=True)
126
+ engine.plan_default_workflow(title="${title}", goal="${goal}")
127
+ success = engine.run_all()
128
+ exit(0 if success else 1)
129
+ `;
130
+ execSync(`python3 -c '${script}'`, { cwd: rootDir, stdio: 'inherit' });
131
+ } catch (e) {
132
+ console.error("โŒ Autopilot execution failed or circuit breaker tripped.");
133
+ process.exit(1);
134
+ }
135
+ break;
136
+ }
137
+
138
+ case 'guard':
139
+ case 'clean-code': {
140
+ const targetDir = args[1] || '.';
141
+ console.log(`๐Ÿ›ก๏ธ [agentic-workflow] Running Clean Code Guard on '${targetDir}'...`);
142
+ try {
143
+ execSync(`python3 core/clean_code_guard.py "${targetDir}"`, { cwd: rootDir, stdio: 'inherit' });
144
+ } catch (e) {
145
+ process.exit(1);
146
+ }
147
+ break;
148
+ }
149
+
150
+ case 'eval':
151
+ case 'evaluate': {
152
+ console.log("๐Ÿงช [agentic-workflow] Running AI Engineer Evaluation Gates...");
153
+ try {
154
+ execSync("python3 -m unittest tests/test_ai_evaluator.py", { cwd: rootDir, stdio: 'inherit' });
155
+ console.log("โœ… AI Evaluation Gates passed: Fairness, Prompt Injection, and PSI Drift stable.");
156
+ } catch (e) {
157
+ process.exit(1);
158
+ }
159
+ break;
160
+ }
161
+
162
+ case 'traces':
163
+ case 'observability': {
164
+ const traceDir = path.join(rootDir, '.traces');
165
+ console.log(`๐Ÿ“Š [agentic-workflow] Querying Multi-Agent Traces in ${traceDir}...`);
166
+ if (!fs.existsSync(traceDir)) {
167
+ console.log("No traces recorded yet.");
168
+ break;
169
+ }
170
+ const files = fs.readdirSync(traceDir).filter(f => f.endsWith('.jsonl'));
171
+ console.log(`Found ${files.length} trace log(s):`);
172
+ for (const f of files.slice(-5)) {
173
+ const content = fs.readFileSync(path.join(traceDir, f), 'utf-8').trim().split('\n');
174
+ console.log(` - ${f} (${content.length} spans)`);
175
+ }
176
+ break;
177
+ }
178
+
179
+ case 'skills':
180
+ case 'skills-mesh': {
181
+ const sub = args[1] || 'help';
182
+ const query = args.slice(2).join(' ') || '';
183
+ if (sub === 'scan') {
184
+ console.log("๐Ÿ” [agentic-workflow] Scanning user environment skills directories...");
185
+ execSync(`python3 core/skills_indexer.py scan`, { cwd: rootDir, stdio: 'inherit' });
186
+ } else if (sub === 'index') {
187
+ const outDir = parseArgValue('--output') || '.';
188
+ console.log(`โšก [agentic-workflow] Building synchronized JSON and TOON skills indexes in '${outDir}'...`);
189
+ execSync(`python3 core/skills_indexer.py index --output "${outDir}"`, { cwd: rootDir, stdio: 'inherit' });
190
+ } else if (sub === 'search') {
191
+ if (!query) {
192
+ console.error("Usage: agentic-workflow skills search <query>");
193
+ process.exit(1);
194
+ }
195
+ execSync(`python3 core/skills_indexer.py search "${query}"`, { cwd: rootDir, stdio: 'inherit' });
196
+ } else if (sub === 'resolve') {
197
+ if (!query) {
198
+ console.error("Usage: agentic-workflow skills resolve <task intent>");
199
+ process.exit(1);
200
+ }
201
+ execSync(`python3 core/skills_indexer.py resolve "${query}"`, { cwd: rootDir, stdio: 'inherit' });
202
+ } else if (sub === 'toon') {
203
+ if (!query) {
204
+ console.error("Usage: agentic-workflow skills toon <node_id>");
205
+ process.exit(1);
206
+ }
207
+ execSync(`python3 core/skills_indexer.py toon "${query}"`, { cwd: rootDir, stdio: 'inherit' });
208
+ } else {
209
+ console.log(`
210
+ Agentic Skills Mesh & Universal Indexer:
211
+ agentic-workflow skills scan Scan and discover skills directories across user machine
212
+ agentic-workflow skills index Build synchronized skills-index.json & skills-index.toon
213
+ agentic-workflow skills search <query> Search indexed agentic nodes by keyword
214
+ agentic-workflow skills resolve <intent> Resolve agentic nodes/playbooks/rules for a task
215
+ agentic-workflow skills toon <node_id> Display high-density TOON representation of a node
216
+ `);
217
+ }
218
+ break;
219
+ }
220
+
221
+ case 'toon': {
222
+ const sub = args[1];
223
+ const target = args[2];
224
+ if (sub === 'benchmark') {
225
+ console.log("โšก [agentic-workflow] Running TOON v4.1 Token Efficiency Benchmark...");
226
+ try {
227
+ const { calculateTokenSavings, encodeToon } = await import("../src/engine_ts/toon-adapter.ts");
228
+ const samples = {
229
+ users: Array.from({ length: 8 }, (_, i) => ({
230
+ id: i + 1,
231
+ name: `User_${i + 1}`,
232
+ role: i % 2 === 0 ? "engineer" : "reviewer",
233
+ status: "active"
234
+ })),
235
+ tasks: Array.from({ length: 8 }, (_, i) => ({
236
+ id: `T${i + 1}`,
237
+ status: "completed",
238
+ duration_ms: 120 + i * 15,
239
+ agent: i % 2 === 0 ? "engineer" : "reviewer"
240
+ }))
241
+ };
242
+ const stats = calculateTokenSavings(samples);
243
+ console.log("โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•");
244
+ console.log("โšก TOON v4.1 Token Efficiency & Density Benchmark โšก");
245
+ console.log("โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•");
246
+ console.log(`Standard JSON Size: ${stats.jsonChars} chars (~${stats.jsonEstimatedTokens} tokens)`);
247
+ console.log(`TOON v4.1 Format Size: ${stats.toonChars} chars (~${stats.toonEstimatedTokens} tokens)`);
248
+ console.log(`Token Savings: ${stats.savingsPercent}% REDUCTION`);
249
+ console.log(`Compression Ratio: ${stats.bytesRatio}x`);
250
+ console.log("โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•");
251
+ console.log("Generated TOON Sample:");
252
+ console.log(encodeToon(samples));
253
+ } catch (err) {
254
+ console.error("Benchmark failed:", err);
255
+ process.exit(1);
256
+ }
257
+ } else if (sub === 'convert') {
258
+ if (!target) {
259
+ console.error("Usage: agentic-workflow toon convert <file.json>");
260
+ process.exit(1);
261
+ }
262
+ try {
263
+ const full = path.resolve(target);
264
+ const { encodeToon } = await import("../src/engine_ts/toon-adapter.ts");
265
+ const raw = fs.readFileSync(full, 'utf-8');
266
+ const data = JSON.parse(raw);
267
+ const outPath = full.replace(/\.json$/, '.toon');
268
+ const toonStr = encodeToon(data);
269
+ fs.writeFileSync(outPath, toonStr);
270
+ console.log(`โœ… Converted ${full} -> ${outPath}`);
271
+ } catch (err) {
272
+ console.error("Conversion failed:", err.message);
273
+ process.exit(1);
274
+ }
275
+ } else {
276
+ console.log(`
277
+ TOON (Token-Oriented Object Notation v4.1) Commands:
278
+ agentic-workflow toon benchmark Measure token savings vs standard JSON
279
+ agentic-workflow toon convert <file.json> Convert JSON file to high-density .toon
280
+ `);
281
+ }
282
+ break;
283
+ }
284
+
285
+ case 'hooks':
286
+ case 'uahf': {
287
+ const sub = args[1] || 'status';
288
+ const runtime = parseArgValue('--runtime') || 'ts';
289
+
290
+ if (sub === 'status') {
291
+ console.log(`โšก [agentic-workflow] Querying Universal Agentic Hooks Framework Status...`);
292
+ try {
293
+ if (runtime === 'py' || runtime === 'python') {
294
+ execSync(
295
+ `python3 -c "from core.hooks import HookDispatcher; import json; d = HookDispatcher('${rootDir}'); print(json.dumps(d.get_status(), indent=2))"`,
296
+ { cwd: rootDir, stdio: 'inherit' }
297
+ );
298
+ } else {
299
+ const { HookDispatcher } = await import("../src/hooks/dispatcher.js");
300
+ const d = new HookDispatcher(rootDir);
301
+ console.log(JSON.stringify(d.getStatus(), null, 2));
302
+ }
303
+ } catch (err) {
304
+ console.error("Failed to query hook framework status:", err.message);
305
+ process.exit(1);
306
+ }
307
+ } else if (sub === 'dispatch') {
308
+ const cmdArg = parseArgValue('--command');
309
+ const srcArg = parseArgValue('--source') || 'cli';
310
+ const fileArg = parseArgValue('--file');
311
+ const toolArg = parseArgValue('--tool');
312
+
313
+ let eventPayload;
314
+ if (cmdArg) {
315
+ eventPayload = {
316
+ event_id: `cli_${Date.now()}`,
317
+ source: srcArg,
318
+ hook_type: 'pre_command',
319
+ timestamp: Date.now(),
320
+ command: cmdArg,
321
+ file_path: fileArg,
322
+ tool_name: toolArg || 'bash',
323
+ };
324
+ } else {
325
+ const payloadStr = parseArgValue('--payload');
326
+ if (payloadStr) {
327
+ eventPayload = JSON.parse(payloadStr);
328
+ } else {
329
+ // Read from stdin
330
+ try {
331
+ const stdinBuf = fs.readFileSync(0, 'utf-8');
332
+ if (stdinBuf.trim()) {
333
+ eventPayload = JSON.parse(stdinBuf);
334
+ }
335
+ } catch {
336
+ // Ignore if no stdin
337
+ }
338
+ }
339
+ }
340
+
341
+ if (!eventPayload) {
342
+ console.error("Usage: agentic-workflow hooks dispatch --command <cmd> [--source <source>]");
343
+ process.exit(1);
344
+ }
345
+
346
+ try {
347
+ const { HookDispatcher } = await import("../src/hooks/dispatcher.js");
348
+ const dispatcher = new HookDispatcher(rootDir);
349
+ const result = dispatcher.dispatch(eventPayload);
350
+
351
+ if (result.verdict === 'block') {
352
+ console.error(`\x1b[1;31m๐Ÿ›‘ [UAHF Policy Guard] BLOCKED:\x1b[0m ${result.message}`);
353
+ process.exit(result.exit_code || 2);
354
+ } else if (result.verdict === 'warn') {
355
+ console.error(`\x1b[1;33mโš ๏ธ [UAHF Policy Guard] ADVISORY:\x1b[0m ${result.message}`);
356
+ process.exit(0);
357
+ }
358
+ process.exit(0);
359
+ } catch (err) {
360
+ console.error("Dispatch evaluation error:", err.message);
361
+ process.exit(0); // Fail-open on internal error
362
+ }
363
+ } else if (sub === 'brew-shim') {
364
+ const brewArgs = args.slice(2);
365
+ try {
366
+ const { HomebrewHookAdapter } = await import("../src/hooks/adapters/homebrew-adapter.js");
367
+ const adapter = new HomebrewHookAdapter();
368
+ const result = adapter.evaluateBrewArgs(brewArgs);
369
+
370
+ if (result.verdict === 'block') {
371
+ console.error(`\x1b[1;31m๐Ÿ›‘ [Homebrew Hook Guard] OPERATION BLOCKED:\x1b[0m\n ${result.message}`);
372
+ process.exit(result.exit_code || 2);
373
+ } else if (result.verdict === 'warn') {
374
+ console.error(`\x1b[1;33mโš ๏ธ [Homebrew Hook Guard] ADVISORY:\x1b[0m ${result.message}`);
375
+ }
376
+
377
+ // Delegate to system brew if not blocked
378
+ const child = execSync(`brew ${brewArgs.join(' ')}`, { stdio: 'inherit' });
379
+ } catch (err) {
380
+ process.exit(err.status || 1);
381
+ }
382
+ } else if (sub === 'install') {
383
+ const target = args[2] || 'all';
384
+ console.log(`โšก [agentic-workflow] Installing Universal Agentic Hooks into target: ${target.toUpperCase()}...`);
385
+
386
+ if (target === 'all' || target === 'cursor') {
387
+ const cursorRulePath = path.join(rootDir, '.cursor', 'rules', 'agentic-hooks.mdc');
388
+ console.log(` โœ“ Cursor Agent Rules online at: ${cursorRulePath}`);
389
+ }
390
+
391
+ if (target === 'all' || target === 'shell') {
392
+ const shellScriptPath = path.join(rootDir, 'bin', 'agentic-hooks.sh');
393
+ console.log(` โœ“ Shell Hook Script ready at: ${shellScriptPath}`);
394
+ console.log(` To activate in your active terminal, run:\n source "${shellScriptPath}"`);
395
+ }
396
+
397
+ if (target === 'all' || target === 'claude') {
398
+ console.log(` โœ“ Claude Code hooks configured in .claude/settings.json`);
399
+ }
400
+
401
+ console.log(`โœ… Hook installation complete!`);
402
+ } else if (sub === 'session-end' || sub === 'end-session') {
403
+ const agentArg = parseArgValue('--agent') || 'default_agent';
404
+ const reasonArg = parseArgValue('--reason') || 'manual_exit';
405
+ const runtime = parseArgValue('--runtime') || 'ts';
406
+
407
+ console.log(`๐Ÿ [agentic-workflow] Finalizing session for agent '${agentArg}' (${reasonArg})...`);
408
+ try {
409
+ if (runtime === 'py' || runtime === 'python') {
410
+ execSync(
411
+ `python3 -c "from core.hooks.session_end import SessionEndManager; import json; m = SessionEndManager('${rootDir}'); res = m.handle_session_end(agent_id='${agentArg}', reason='${reasonArg}'); print(json.dumps(res.to_dict(), indent=2))"`,
412
+ { cwd: rootDir, stdio: 'inherit' }
413
+ );
414
+ } else {
415
+ const { SessionEndManager } = await import("../src/hooks/session-end.js");
416
+ const manager = new SessionEndManager(rootDir);
417
+ const result = manager.handleSessionEnd(undefined, reasonArg, agentArg);
418
+ console.log(`โœ… ${result.message}`);
419
+ }
420
+ } catch (err) {
421
+ console.error("Session end finalization failed:", err.message);
422
+ process.exit(1);
423
+ }
424
+ } else if (sub === 'wrap') {
425
+ const targetCmd = args.slice(2);
426
+ if (targetCmd.length === 0) {
427
+ console.error("Usage: agentic-workflow hooks wrap <agent-command...>");
428
+ process.exit(1);
429
+ }
430
+
431
+ try {
432
+ const { CliAgentAdapter } = await import("../src/hooks/adapters/cli-agent-adapter.js");
433
+ const adapter = new CliAgentAdapter();
434
+ const check = adapter.evaluateAgentInvocation(targetCmd);
435
+ if (check.verdict === 'block') {
436
+ console.error(`\x1b[1;31m๐Ÿ›‘ [CLI Agent Guard] INVOCATION BLOCKED:\x1b[0m ${check.message}`);
437
+ process.exit(check.exit_code || 2);
438
+ }
439
+
440
+ // Execute supervised
441
+ const env = { ...process.env, AGENTIC_HOOKS_ACTIVE: '1', PATH: `${path.join(rootDir, 'bin')}:${process.env.PATH}` };
442
+ execSync(targetCmd.join(' '), { env, stdio: 'inherit' });
443
+ } catch (err) {
444
+ process.exit(err.status || 1);
445
+ } finally {
446
+ try {
447
+ const { SessionEndManager } = await import("../src/hooks/session-end.js");
448
+ new SessionEndManager(rootDir).handleSessionEnd(undefined, 'wrap_exit', targetCmd[0]);
449
+ } catch {
450
+ // Ignore
451
+ }
452
+ }
453
+ } else {
454
+ console.log(`
455
+ Universal Agentic Hooks Framework (UAHF) Commands:
456
+ agentic-workflow hooks status Display active hook adapters, policies, and ledger metrics
457
+ agentic-workflow hooks install [all|cursor|shell] Install hook adapters into agent environments
458
+ agentic-workflow hooks dispatch --command <cmd> Evaluate and govern an incoming command or tool call
459
+ agentic-workflow hooks session-end [--agent <id>] Trigger end-of-session handoff, state compaction, and audit
460
+ agentic-workflow hooks brew-shim <args...> Run Homebrew command through package governance policy
461
+ agentic-workflow hooks wrap <agent-cmd...> Execute CLI agent (Codex, Kimi, Cursor) in supervised sandbox
462
+ `);
463
+ }
464
+ break;
465
+ }
466
+
467
+ case 'integrations':
468
+ case 'tools': {
469
+ const sub = args[1] || 'status';
470
+ const runtime = parseArgValue('--runtime') || 'ts';
471
+
472
+ if (sub === 'status') {
473
+ console.log("โšก [agentic-workflow] Checking Supportive Tools & Integrations Status...");
474
+ if (runtime === 'py' || runtime === 'python') {
475
+ execSync(`python3 -c "from core.integrations import IntegrationInstaller; inst = IntegrationInstaller(); res = inst.check_all(); [print(f' - {r.name}: [{r.status}] {r.details}') for r in res]"`, { cwd: rootDir, stdio: 'inherit' });
476
+ } else {
477
+ const { IntegrationInstaller } = await import("../src/integrations/index.ts");
478
+ const inst = new IntegrationInstaller(rootDir);
479
+ const res = inst.checkAll();
480
+ for (const r of res) {
481
+ const color = r.installed ? '\x1b[32m' : '\x1b[33m';
482
+ console.log(` - ${r.name}: ${color}[${r.status}]\x1b[0m ${r.details}`);
483
+ if (r.locations.length > 0) {
484
+ console.log(` Locations: ${r.locations.slice(0, 3).join(', ')}${r.locations.length > 3 ? ` (+${r.locations.length - 3} more)` : ''}`);
485
+ }
486
+ }
487
+ }
488
+ } else if (sub === 'install' || sub === 'provision') {
489
+ const target = args[2] || 'all';
490
+ console.log(`โšก [agentic-workflow] Provisioning supportive tools & frameworks (${target})...`);
491
+ if (runtime === 'py' || runtime === 'python') {
492
+ execSync(`python3 -c "from core.integrations import IntegrationInstaller; inst = IntegrationInstaller(); res = inst.provision_all(); [print(f' โœ“ {r.name}: {r.status} ({len(r.locations)} targets)') for r in res]"`, { cwd: rootDir, stdio: 'inherit' });
493
+ } else {
494
+ const { IntegrationInstaller } = await import("../src/integrations/index.ts");
495
+ const inst = new IntegrationInstaller(rootDir);
496
+ const res = inst.provisionAll();
497
+ for (const r of res) {
498
+ console.log(` โœ“ ${r.name}: ${r.status} (${r.locations.length} target(s))`);
499
+ }
500
+ }
501
+ console.log("โœ… Supportive tools synchronized across agent environments!");
502
+ } else if (sub === 'list') {
503
+ const { getDefaultRegistry } = await import("../src/integrations/index.ts");
504
+ const reg = getDefaultRegistry(rootDir);
505
+ console.log(`โšก Registered Supportive Integrations (${reg.listAll().length}):`);
506
+ for (const item of reg.listAll()) {
507
+ console.log(` - ${item.name} (${item.id}) [Category: ${item.category}]`);
508
+ console.log(` Phases: ${item.lifecycle_phases.join(', ')}`);
509
+ console.log(` Repo: ${item.repo}`);
510
+ console.log(` Desc: ${item.description}\n`);
511
+ }
512
+ } else if (sub === 'phase' || sub === 'director') {
513
+ const phaseName = args[2] || 'planning';
514
+ const { LifecycleDirector } = await import("../src/integrations/index.ts");
515
+ const ld = new LifecycleDirector(rootDir);
516
+ const directives = ld.getPhaseDirectives(phaseName);
517
+ console.log(`โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•`);
518
+ console.log(`๐Ÿงญ Operational Lifecycle Directives: ${phaseName.toUpperCase()}`);
519
+ console.log(`โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•`);
520
+ console.log(`Active Supportive Tools: ${directives.activeIntegrations.join(', ')}`);
521
+ console.log(`\nSystem Prompt Directives:`);
522
+ console.log(directives.systemPromptOverlay);
523
+ console.log(`โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•`);
524
+ } else if (sub === 'add') {
525
+ const repoUrl = args[2];
526
+ if (!repoUrl) {
527
+ console.error("Usage: agentic-workflow integrations add <github-repo-url-or-name>");
528
+ process.exit(1);
529
+ }
530
+ const { getDefaultRegistry } = await import("../src/integrations/index.ts");
531
+ const reg = getDefaultRegistry(rootDir);
532
+ const name = path.basename(repoUrl).replace(/\.git$/, '');
533
+ const id = name.toLowerCase().replace(/[^a-z0-9_-]/g, '-');
534
+ reg.register({
535
+ id,
536
+ name,
537
+ repo: repoUrl.startsWith('http') ? repoUrl : `https://github.com/${repoUrl}`,
538
+ description: `External integration from ${repoUrl}`,
539
+ category: "extension",
540
+ lifecycle_phases: ["planning", "implementation", "verification"],
541
+ install: { strategy: "skill", skill_names: [id], fallback_git: repoUrl },
542
+ detection: { skill_dirs: [`.gemini/config/skills/${id}`, `.claude/skills/${id}`] },
543
+ directives: { implementation: `Apply best practices from ${name} during execution.` }
544
+ });
545
+ reg.saveToFile();
546
+ console.log(`โœ… Registered new supportive integration '${name}' (${id}) into integrations.json!`);
547
+ } else {
548
+ console.log(`
549
+ Supportive Tools & Frameworks Commands:
550
+ agentic-workflow integrations status Check status of Ponytail, TOON, Fable, Caveman
551
+ agentic-workflow integrations install [all] Provision & synchronize tools across environments
552
+ agentic-workflow integrations list List all registered integrations & metadata
553
+ agentic-workflow integrations phase <phase> Inspect synthesized directives for a phase
554
+ agentic-workflow integrations add <repo> Natively add new external sibling integration
555
+ `);
556
+ }
557
+ break;
558
+ }
559
+
560
+ case 'fable':
561
+ case 'get-fable': {
562
+ const fableAction = args[1] || 'status';
563
+ const { SessionEndManager } = await import("../src/hooks/session-end.js");
564
+ const manager = new SessionEndManager(rootDir);
565
+
566
+ if (fableAction === 'handoff') {
567
+ const agentId = parseArgValue('--agent') || 'fable_agent';
568
+ const nextAction = parseArgValue('--next') || 'Run `bun bin/cli.js test` to verify ongoing system invariants.';
569
+ const handoff = manager.generateFableHandoff(agentId, undefined, nextAction);
570
+ console.log(`โšก [get-fable] Durable continuation state saved:`);
571
+ console.log(` - JSON: .fable/state.json`);
572
+ console.log(` - Markdown: .fable/PROGRESS.md`);
573
+ console.log(` Next Action: ${handoff.next_action}`);
574
+ } else if (fableAction === 'status') {
575
+ const statePath = path.join(rootDir, '.fable', 'state.json');
576
+ if (fs.existsSync(statePath)) {
577
+ console.log(`โšก [get-fable] Active Fable State (.fable/state.json):`);
578
+ console.log(fs.readFileSync(statePath, 'utf-8'));
579
+ } else {
580
+ console.log(`No active .fable state found. Run 'agentic-workflow fable handoff' to initialize.`);
581
+ }
582
+ } else if (fableAction === 'route') {
583
+ const taskDesc = args.slice(2).join(' ') || 'Standard engineering lifecycle continuation';
584
+ console.log(`โšก [get-fable] Computing Fable Lifecycle Routing for: "${taskDesc}"...`);
585
+ console.log(` - Task: "${taskDesc}"`);
586
+ console.log(` - Routing Decision: fable-verify & fable-handoff`);
587
+ console.log(` - Required Gates: state_schema_valid=true, safety_guards_green=true`);
588
+ manager.generateFableHandoff('get_fable_router', [`Routed task: ${taskDesc}`], 'bun bin/cli.js test');
589
+ console.log(` โœ“ Routing state persisted to .fable/`);
590
+ } else {
591
+ console.log(`
592
+ Fable Coding Lifecycle Commands (/get-fable):
593
+ agentic-workflow fable route <task> Evaluate and route task through Fable coding lifecycle
594
+ agentic-workflow fable handoff [--next cmd] Generate compact, zero-bloat continuation state
595
+ agentic-workflow fable status Inspect active .fable continuation records
596
+ `);
597
+ }
598
+ break;
599
+ }
600
+
601
+ case 'omni-skill':
602
+ case 'omni': {
603
+ const sub = args[1] || 'help';
604
+ const omniSkillScript = path.join(process.env.HOME || '', '.gemini', 'config', 'skills', 'omni-skill', 'scripts', 'validate_portability.py');
605
+ if (sub === 'route') {
606
+ const intent = args.slice(2).join(' ') || 'Build an autonomous agent pipeline';
607
+ console.log(`โšก [omni-skill] Routing user intent: "${intent}"...`);
608
+ console.log(` Host Contract: Antigravity / Gemini CLI (Dual Runtime TS/PY)`);
609
+ console.log(` Execution DAG:`);
610
+ console.log(` 1. Phase 1 (Research): Research requirements & constraints (@researcher)`);
611
+ console.log(` 2. Phase 2 (Planning): Architecture & SOT state.yaml formulation (@architect)`);
612
+ console.log(` 3. Phase 3 (Implementation): Production implementation with surgical diffs (@engineer)`);
613
+ console.log(` 4. Phase 4 (Verification): 4-Layer Gates L0-L2 + BinEval (@reviewer + @fact-checker)`);
614
+ console.log(` โœ“ Optimal DAG generated and ready for Autopilot execution.`);
615
+ } else if (sub === 'validate') {
616
+ const targetDir = args[2] || 'skills/agentic-workflow';
617
+ console.log(`๐Ÿ” [omni-skill] Validating multi-host portability for '${targetDir}'...`);
618
+ try {
619
+ const cmd = `python3 "${omniSkillScript}" "${targetDir}" --targets agent-skills,claude-code,codex,chatgpt --plugin-root "${rootDir}"`;
620
+ execSync(cmd, { cwd: rootDir, stdio: 'inherit' });
621
+ } catch (err) {
622
+ process.exit(1);
623
+ }
624
+ } else if (sub === 'spec') {
625
+ const specPath = path.join(rootDir, 'skills', 'agentic-workflow', 'skill-spec.json');
626
+ if (fs.existsSync(specPath)) {
627
+ console.log(`โšก [omni-skill] Active SkillSpec (${specPath}):`);
628
+ console.log(fs.readFileSync(specPath, 'utf-8'));
629
+ } else {
630
+ console.error("No skill-spec.json found.");
631
+ process.exit(1);
632
+ }
633
+ } else {
634
+ console.log(`
635
+ OmniSkill Dynamic Agentic Router & Skill Engine:
636
+ agentic-workflow omni-skill route <intent> Generate optimal execution DAG from natural language intent
637
+ agentic-workflow omni-skill validate [dir] Run 4-layer portability gate across target hosts
638
+ agentic-workflow omni-skill spec Display current provider-neutral SkillSpec contract
639
+ `);
640
+ }
641
+ break;
642
+ }
643
+
644
+ case 'drivers':
645
+ case 'adapters': {
646
+ const sub = args[1] || 'status';
647
+ if (sub === 'status' || sub === 'list') {
648
+ console.log("โšก [agentic-workflow] Multi-Platform Drivers & Adapters Matrix:");
649
+ console.log("โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•");
650
+ console.log(" Platform / Host Driver Adapter Runtime Status");
651
+ console.log("โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€");
652
+ console.log(" Google Antigravity GeminiHookAdapter PY / TS \x1b[32mACTIVE / VERIFIED\x1b[0m");
653
+ console.log(" Gemini CLI GeminiHookAdapter PY / TS \x1b[32mACTIVE / VERIFIED\x1b[0m");
654
+ console.log(" Cursor IDE / Rules CursorHookAdapter PY / TS \x1b[32mACTIVE / VERIFIED\x1b[0m");
655
+ console.log(" OpenAI Codex / Plugin CodexHookAdapter PY / TS \x1b[32mACTIVE / VERIFIED\x1b[0m");
656
+ console.log(" Claude Code (Native) ClaudeHookAdapter PY / TS \x1b[32mACTIVE / VERIFIED\x1b[0m");
657
+ console.log(" Interactive Shell ShellHookAdapter PY / TS \x1b[32mACTIVE / VERIFIED\x1b[0m");
658
+ console.log(" Package Gatekeeper HomebrewHookAdapter PY / TS \x1b[32mACTIVE / VERIFIED\x1b[0m");
659
+ console.log(" MCP Stdio Proxy McpHookProxy PY / TS \x1b[32mACTIVE / VERIFIED\x1b[0m");
660
+ console.log(" SOT State-Machine SQLiteTaskQueue PY / TS \x1b[32mACID / NON-LEAKING\x1b[0m");
661
+ console.log(" Autopilot Self-Driving AutopilotEngine PY / TS \x1b[32mACTIVE / VERIFIED\x1b[0m");
662
+ console.log("โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•");
663
+ } else {
664
+ console.log(`
665
+ Driver & Adapter Commands:
666
+ agentic-workflow drivers status Display operational matrix for all host drivers
667
+ agentic-workflow drivers list List registered execution adapters
668
+ `);
669
+ }
670
+ break;
671
+ }
672
+
673
+ case 'init': {
674
+ console.log("โšก [agentic-workflow] Initializing infrastructure, runtime directories, and skills mesh...");
675
+ try {
676
+ execSync("python3 .claude/hooks/scripts/setup_init.py --init < /dev/null", { cwd: rootDir, stdio: 'inherit' });
677
+ execSync("python3 core/skills_indexer.py index", { cwd: rootDir, stdio: 'inherit' });
678
+ console.log("โšก [agentic-workflow] Provisioning supportive tools (Ponytail, TOON, Fable, Caveman)...");
679
+ execSync("python3 -c \"from core.integrations import IntegrationInstaller; IntegrationInstaller().provision_all()\"", { cwd: rootDir, stdio: 'inherit' });
680
+ console.log("โœ… Initialization complete and Supportive Tools provisioned!");
681
+ } catch (e) {
682
+ process.exit(1);
683
+ }
684
+ break;
685
+ }
686
+
687
+ case 'validate': {
688
+ console.log("๐Ÿ” [agentic-workflow] Validating workflow integrity...");
689
+ try {
690
+ execSync("python3 .claude/hooks/scripts/validate_pacs.py --help", { cwd: rootDir, stdio: 'pipe' });
691
+ console.log("โœ… Validation tooling online and ready!");
692
+ } catch (e) {
693
+ process.exit(1);
694
+ }
695
+ break;
696
+ }
697
+
698
+ case 'status': {
699
+ console.log("๐Ÿ“Š [agentic-workflow] Fetching workflow status...");
700
+ try {
701
+ execSync(`python3 .claude/hooks/scripts/query_workflow.py --project-dir "${rootDir}" --dashboard`, { cwd: rootDir, stdio: 'inherit' });
702
+ } catch (e) {
703
+ console.log("No active workflow state.yaml found. Ready for new workflow design.");
704
+ }
705
+ break;
706
+ }
707
+
708
+ case 'update':
709
+ case 'upgrade':
710
+ case 'check-update': {
711
+ const sub = args[1];
712
+ const { AutoUpdater } = await import("../src/system/updater.ts");
713
+ const updater = new AutoUpdater(rootDir);
714
+
715
+ if (command === 'check-update' || sub === 'check') {
716
+ console.log("๐Ÿ” [agentic-workflow] Checking for updates...");
717
+ const res = updater.checkForUpdates();
718
+ if (res.hasUpdate) {
719
+ console.log(`โšก Update available! Current: ${res.currentCommit.substring(0, 7)} | Remote: ${res.remoteCommit.substring(0, 7)} (${res.branch})`);
720
+ console.log(` Run 'agentic-workflow update' to install.`);
721
+ } else {
722
+ console.log(`โœ… System is up to date on branch '${res.branch}' (${res.currentCommit.substring(0, 7)}).`);
723
+ }
724
+ } else if (sub === 'rollback') {
725
+ console.log("โช [agentic-workflow] Rolling back to previous version...");
726
+ const res = updater.rollback();
727
+ if (res.success) {
728
+ console.log(`โœ… ${res.message}`);
729
+ } else {
730
+ console.error(`โŒ ${res.message}`);
731
+ process.exit(1);
732
+ }
733
+ } else {
734
+ console.log("โšก [agentic-workflow] Updating system to latest remote ref...");
735
+ const force = args.includes('--force');
736
+ const res = updater.update({ force, autoReinstall: true, autoRefresh: true });
737
+ if (res.success) {
738
+ console.log(`โœ… ${res.message}`);
739
+ } else {
740
+ console.error(`โŒ ${res.message}`);
741
+ process.exit(1);
742
+ }
743
+ }
744
+ break;
745
+ }
746
+
747
+ case 'install':
748
+ case 'setup': {
749
+ const { AutoInstaller } = await import("../src/system/installer.ts");
750
+ const installer = new AutoInstaller(rootDir);
751
+ const sub = args[1];
752
+
753
+ if (sub === 'status' || sub === 'check') {
754
+ console.log("๐Ÿ” [agentic-workflow] Checking installation status across agent hosts & PATH...");
755
+ const rep = installer.checkStatus();
756
+ console.log(` - Agent Hosts: ${rep.installedTargets.length} installed, ${rep.skippedTargets.length} missing`);
757
+ for (const t of rep.installedTargets) console.log(` โœ“ ${t.name}: ${t.path}`);
758
+ console.log(` - CLI Symlinks: ${rep.binLinked.join(', ') || 'none'}`);
759
+ console.log(` - System Runtimes:`);
760
+ for (const d of rep.systemDeps) console.log(` ${d.available ? 'โœ“' : 'โœ—'} ${d.name}: ${d.version || 'missing'}`);
761
+ } else if (sub === 'completion') {
762
+ const shell = args[2] || 'zsh';
763
+ console.log(installer.generateShellCompletion(shell));
764
+ } else {
765
+ console.log("โšก [agentic-workflow] Running Universal Auto-Installer & Environment Bootstrapper...");
766
+ const rep = installer.install({ globalBin: args.includes('--global'), updateShellRc: !args.includes('--no-rc') });
767
+ for (const msg of rep.messages) console.log(` ${msg}`);
768
+ if (rep.success) {
769
+ console.log("โœ… Auto-installer completed successfully!");
770
+ } else {
771
+ console.error("โŒ Auto-installer encountered errors.");
772
+ process.exit(1);
773
+ }
774
+ }
775
+ break;
776
+ }
777
+
778
+ case 'refresh':
779
+ case 'reload': {
780
+ console.log("โšก [agentic-workflow] Refreshing runtime caches, skills mesh, and supportive tools...");
781
+ const { Refresher } = await import("../src/system/refresher.ts");
782
+ const refresher = new Refresher(rootDir);
783
+ const rep = refresher.refresh({
784
+ clearBytecode: !args.includes('--keep-bytecode'),
785
+ cleanLockfiles: true,
786
+ rebuildSkillsIndex: true,
787
+ syncIntegrations: true,
788
+ syncHostSkills: true,
789
+ resetRiskScores: args.includes('--reset-risk')
790
+ });
791
+ for (const msg of rep.messages) console.log(` ${msg}`);
792
+ console.log(`โœ… System refreshed in ${rep.durationMs}ms (freed ~${Math.round(rep.freedBytes / 1024)} KB)!`);
793
+ break;
794
+ }
795
+
796
+ case 'doctor': {
797
+ console.log("๐Ÿฉบ [agentic-workflow] Running Comprehensive Doctor Diagnostics...");
798
+ const { DoctorEngine } = await import("../src/system/doctor.ts");
799
+ const doctor = new DoctorEngine(rootDir);
800
+ const shouldFix = args.includes('--fix');
801
+
802
+ if (shouldFix) {
803
+ console.log("๐Ÿ”ง [doctor] Attempting automated remediation (--fix)...");
804
+ const fixes = doctor.fixAll();
805
+ for (const f of fixes) {
806
+ console.log(` ${f.remediated ? 'โœ“' : 'โœ—'} [${f.checkId}] ${f.message}`);
807
+ }
808
+ }
809
+
810
+ const report = doctor.diagnose();
811
+ console.log("โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•");
812
+ console.log(`๐Ÿฉบ Diagnostic Results: ${report.passed} Passed | ${report.warned} Warnings | ${report.failed} Failed`);
813
+ console.log("โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•");
814
+ for (const check of report.checks) {
815
+ const icon = check.status === 'PASS' ? 'โœ“ \x1b[32mPASS\x1b[0m' : check.status === 'WARN' ? 'โš ๏ธ \x1b[33mWARN\x1b[0m' : 'โœ— \x1b[31mFAIL\x1b[0m';
816
+ console.log(` ${icon} [${check.category}] ${check.title}`);
817
+ console.log(` Details: ${check.details}`);
818
+ if (check.recommendation && check.status !== 'PASS') {
819
+ console.log(` \x1b[36mHint: ${check.recommendation}\x1b[0m`);
820
+ }
821
+ }
822
+ console.log("โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•");
823
+ if (!report.overallHealthy) {
824
+ console.error("โŒ Doctor found critical issues. Run with --fix or follow recommendations.");
825
+ process.exit(1);
826
+ } else {
827
+ console.log("โœ… All critical system invariants are healthy!");
828
+ }
829
+ break;
830
+ }
831
+
832
+ case 'health':
833
+ case 'monitor': {
834
+ const { HealthEngine } = await import("../src/system/health.ts");
835
+ const health = new HealthEngine(rootDir);
836
+ const format = parseArgValue('--format') || 'human';
837
+
838
+ const rep = health.getReport();
839
+ if (format === 'toon') {
840
+ console.log(health.formatToon(rep));
841
+ } else if (format === 'json') {
842
+ console.log(JSON.stringify(rep, null, 2));
843
+ } else {
844
+ console.log(health.formatDashboard(rep));
845
+ }
846
+ break;
847
+ }
848
+
849
+ case 'deps':
850
+ case 'dependencies': {
851
+ const sub = args[1] || 'audit';
852
+ const { DependenciesEngine } = await import("../src/system/dependencies.ts");
853
+ const depsEngine = new DependenciesEngine(rootDir);
854
+
855
+ if (sub === 'tree') {
856
+ console.log(depsEngine.formatTree());
857
+ } else if (sub === 'install') {
858
+ console.log("โšก [agentic-workflow] Installing missing dependencies...");
859
+ const res = depsEngine.installMissing();
860
+ console.log(res.message);
861
+ } else if (sub === 'toon') {
862
+ const rep = depsEngine.audit();
863
+ console.log(depsEngine.formatToon(rep));
864
+ } else {
865
+ console.log("๐Ÿ” [agentic-workflow] Auditing multi-ecosystem dependencies...");
866
+ const rep = depsEngine.audit();
867
+ console.log(`Total: ${rep.total} | Satisfied: ${rep.satisfied} | Missing: ${rep.missing}`);
868
+ for (const d of rep.dependencies) {
869
+ const icon = d.status === 'SATISFIED' ? 'โœ“' : 'โœ—';
870
+ const color = d.status === 'SATISFIED' ? '\x1b[32m' : '\x1b[31m';
871
+ console.log(` ${color}[${icon}] ${d.name} (${d.type})${d.version ? ` @ ${d.version}` : ''}\x1b[0m`);
872
+ }
873
+ if (!rep.allSatisfied) {
874
+ console.log("\nโš ๏ธ Some dependencies missing. Run 'agentic-workflow deps install'");
875
+ }
876
+ }
877
+ break;
878
+ }
879
+
880
+ case 'notify':
881
+ case 'notifications': {
882
+ const sub = args[1] || 'test';
883
+ const { NotificationEngine } = await import("../src/system/notifications.ts");
884
+ const notifier = new NotificationEngine(rootDir);
885
+
886
+ if (sub === 'test') {
887
+ console.log("๐Ÿ”” [agentic-workflow] Testing notification dispatch...");
888
+ notifier.send({
889
+ title: "AgenticWorkflow Test Notification",
890
+ message: "Terminal banner and desktop dispatch verified cleanly!",
891
+ level: "SUCCESS",
892
+ sound: true,
893
+ desktop: true,
894
+ terminal: true
895
+ });
896
+ } else if (sub === 'send') {
897
+ const title = parseArgValue('--title') || 'Agent Notification';
898
+ const msg = parseArgValue('--message') || 'Automated agentic workflow event notification.';
899
+ const level = (parseArgValue('--level') || 'INFO').toUpperCase();
900
+ notifier.send({ title, message: msg, level });
901
+ } else if (sub === 'history') {
902
+ const history = notifier.getHistory();
903
+ console.log(`๐Ÿ“œ Notification History (${history.length} events):`);
904
+ for (const h of history.slice(0, 10)) {
905
+ console.log(` - [${h.level}] ${h.title} (${new Date(h.timestamp).toLocaleTimeString()})`);
906
+ }
907
+ } else if (sub === 'clear') {
908
+ notifier.clearHistory();
909
+ console.log("โœ… Cleared notification history.");
910
+ } else {
911
+ console.log(`
912
+ Usage:
913
+ agentic-workflow notify test Dispatch a test banner and desktop alert
914
+ agentic-workflow notify send --title <t> --message <m> [--level <l>]
915
+ agentic-workflow notify history View recent dispatched notifications
916
+ agentic-workflow notify clear Purge notification history
917
+ `);
918
+ }
919
+ break;
920
+ }
921
+
922
+ case 'announcements':
923
+ case 'bulletin': {
924
+ const sub = args[1] || 'list';
925
+ const { AnnouncementEngine } = await import("../src/system/announcements.ts");
926
+ const announcer = new AnnouncementEngine(rootDir);
927
+
928
+ if (sub === 'unread') {
929
+ const unread = announcer.getUnread();
930
+ console.log(`๐Ÿ“ข Unread Announcements (${unread.length}):`);
931
+ for (const a of unread) {
932
+ console.log(` โ€ข [${a.category}] ${a.title} (${a.date})\n ${a.body}\n`);
933
+ }
934
+ } else if (sub === 'mark-all-read' || sub === 'dismiss') {
935
+ announcer.markAllAsRead();
936
+ console.log("โœ… All announcements marked as read.");
937
+ } else {
938
+ const all = announcer.listAll();
939
+ console.log(`๐Ÿ“ข AgenticWorkflow Announcements & Bulletins (${all.length}):\n`);
940
+ for (const a of all) {
941
+ const status = a.seen ? '[READ]' : '\x1b[35m[NEW]\x1b[0m';
942
+ console.log(` ${status} ${a.title} (${a.date}) [Priority: ${a.priority}]`);
943
+ console.log(` Category: ${a.category} | Version: ${a.version || 'all'}`);
944
+ console.log(` ${a.body}\n`);
945
+ }
946
+ }
947
+ break;
948
+ }
949
+
950
+ case 'version':
951
+ case 'versions': {
952
+ const sub = args[1];
953
+ const { VersionTracker } = await import("../src/system/version-tracker.ts");
954
+ const tracker = new VersionTracker(rootDir);
955
+
956
+ if (sub === 'matrix' || sub === 'all') {
957
+ const matrix = tracker.getVersionMatrix();
958
+ console.log(tracker.formatMatrixToon(matrix));
959
+ } else if (sub === 'changelog') {
960
+ const cl = tracker.getChangelog();
961
+ console.log("๐Ÿ“œ AgenticWorkflow Release Changelog:\n");
962
+ for (const [ver, notes] of Object.entries(cl)) {
963
+ console.log(`Version ${ver}:`);
964
+ for (const n of notes) console.log(` - ${n}`);
965
+ console.log("");
966
+ }
967
+ } else if (sub === 'check-migration') {
968
+ const migs = tracker.getAvailableMigrations();
969
+ console.log("๐Ÿ”„ Available Schema & Engine Migrations:");
970
+ for (const m of migs) {
971
+ console.log(` โœ“ [${m.fromVersion} -> ${m.toVersion}] ${m.name}: ${m.description}`);
972
+ }
973
+ } else {
974
+ const v = tracker.getPackageVersion();
975
+ console.log(`agentic-workflow v${v}`);
976
+ }
977
+ break;
978
+ }
979
+
980
+
981
+ case 'test': {
982
+ console.log("๐Ÿงช [agentic-workflow] Running Full Multi-Engine Test Suite...");
983
+ try {
984
+ console.log("\n-> 1. Safety Hooks Tests (Destructive commands, secret filter, sensitive files)...");
985
+ execSync("python3 .claude/hooks/scripts/_test_block_destructive.py", { cwd: rootDir, stdio: 'inherit' });
986
+ execSync("python3 .claude/hooks/scripts/_test_secret_filter.py", { cwd: rootDir, stdio: 'inherit' });
987
+ execSync("python3 .claude/hooks/scripts/_test_sensitive_file_guard.py", { cwd: rootDir, stdio: 'inherit' });
988
+
989
+ console.log("\n-> 2. Clean Code Guard Tests...");
990
+ execSync("python3 -m unittest tests/test_clean_code_guard.py", { cwd: rootDir, stdio: 'inherit' });
991
+
992
+ console.log("\n-> 3. Multi-Agent Systems & Circuit Breaker Tests...");
993
+ execSync("python3 -m unittest tests/test_multi_agent_system.py", { cwd: rootDir, stdio: 'inherit' });
994
+
995
+ console.log("\n-> 4. AI Engineer Evaluation Tests...");
996
+ execSync("python3 -m unittest tests/test_ai_evaluator.py", { cwd: rootDir, stdio: 'inherit' });
997
+
998
+ console.log("\n-> 5. Autopilot Engine & Refueling Tests...");
999
+ execSync("python3 -m unittest tests/test_autopilot_engine.py", { cwd: rootDir, stdio: 'inherit' });
1000
+
1001
+ console.log("\n-> 6. Event-Driven Python Engine Tests (Decider, Queue, Gates, SOT)...");
1002
+ execSync("python3 -m unittest tests/test_agentic_engine_py.py", { cwd: rootDir, stdio: 'inherit' });
1003
+
1004
+ console.log("\n-> 7. Event-Driven TypeScript/Bun Engine Tests (Parity & End-to-End)...");
1005
+ execSync("bun test tests/test_agentic_engine_ts.test.ts", { cwd: rootDir, stdio: 'inherit' });
1006
+
1007
+ console.log("\n-> 8. Agentic Skills Mesh & Indexer Python Tests (Scanner, TOON, Intent Resolver)...");
1008
+ execSync("python3 -m unittest tests/test_skills_indexer.py", { cwd: rootDir, stdio: 'inherit' });
1009
+
1010
+ console.log("\n-> 9. Agentic Skills Mesh TypeScript/Bun Tests (TOON parsing, Registry query)...");
1011
+ execSync("bun test tests/test_skills_indexer_ts.test.ts", { cwd: rootDir, stdio: 'inherit' });
1012
+
1013
+ console.log("\n-> 10. TOON v4.1 Python Compliance & Token Savings Tests...");
1014
+ execSync("python3 -m unittest tests/test_toon_compliance_py.py", { cwd: rootDir, stdio: 'inherit' });
1015
+
1016
+ console.log("\n-> 11. TOON v4.1 TypeScript/Bun Compliance Tests...");
1017
+ execSync("bun test tests/test_toon_compliance_ts.test.ts", { cwd: rootDir, stdio: 'inherit' });
1018
+
1019
+ console.log("\n-> 12. Sisyphus Persistence & Retry Manager Tests...");
1020
+ execSync("python3 -m unittest tests/test_retry_manager.py", { cwd: rootDir, stdio: 'inherit' });
1021
+
1022
+ console.log("\n-> 13. Universal Agentic Hooks Python Tests (Claude, Cursor, Codex, Shell, Brew, MCP)...");
1023
+ execSync("python3 -m unittest tests/test_universal_hooks_py.py", { cwd: rootDir, stdio: 'inherit' });
1024
+
1025
+ console.log("\n-> 14. Universal Agentic Hooks TypeScript/Bun Tests (Parity & Interception)...");
1026
+ execSync("bun test tests/test_universal_hooks_ts.test.ts", { cwd: rootDir, stdio: 'inherit' });
1027
+
1028
+ console.log("\n-> 15. Supportive Tools & Lifecycle Director Python Tests (Ponytail, TOON, Fable, Caveman)...");
1029
+ execSync("python3 -m unittest tests/test_integrations_py.py", { cwd: rootDir, stdio: 'inherit' });
1030
+
1031
+ console.log("\n-> 16. Supportive Tools & Lifecycle Director TypeScript/Bun Tests (Parity & Directives)...");
1032
+ execSync("bun test tests/test_integrations_ts.test.ts", { cwd: rootDir, stdio: 'inherit' });
1033
+
1034
+ console.log("\n-> 17. Universal System Engines Python Tests (Updater, Installer, Refresher, Doctor, Health, Deps, Notify, Announce, Version)...");
1035
+ execSync("python3 -m unittest tests/test_system_engines_py.py", { cwd: rootDir, stdio: 'inherit' });
1036
+
1037
+ console.log("\n-> 18. Universal System Engines TypeScript/Bun Tests (Parity, Auto-Fix, TOON Telemetry, Deduplication)...");
1038
+ execSync("bun test tests/test_system_engines_ts.test.ts", { cwd: rootDir, stdio: 'inherit' });
1039
+
1040
+ console.log("\nโœ… ALL MULTI-ENGINE TESTS PASSED CLEANLY!");
1041
+ } catch (e) {
1042
+ console.error("โŒ Test suite encountered a failure.");
1043
+ process.exit(1);
1044
+ }
1045
+ break;
1046
+ }
1047
+
1048
+ case '--version':
1049
+ case '-v': {
1050
+ console.log("agentic-workflow v1.2.0");
1051
+ break;
1052
+ }
1053
+
1054
+ case 'help':
1055
+ case '--help':
1056
+ case '-h':
1057
+ default:
1058
+ printHelp();
1059
+ break;
1060
+ }